1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSectionXCOFF.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 122 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 123 124 static cl::opt<bool> 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 STATISTIC(NumTailCalls, "Number of tail calls"); 135 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 136 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 137 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 138 139 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 140 141 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 142 143 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word"; 144 145 // FIXME: Remove this once the bug has been fixed! 146 extern cl::opt<bool> ANDIGlueBug; 147 148 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 149 const PPCSubtarget &STI) 150 : TargetLowering(TM), Subtarget(STI) { 151 // Initialize map that relates the PPC addressing modes to the computed flags 152 // of a load/store instruction. The map is used to determine the optimal 153 // addressing mode when selecting load and stores. 154 initializeAddrModeMap(); 155 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 156 // arguments are at least 4/8 bytes aligned. 157 bool isPPC64 = Subtarget.isPPC64(); 158 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 159 160 // Set up the register classes. 161 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 162 if (!useSoftFloat()) { 163 if (hasSPE()) { 164 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 165 // EFPU2 APU only supports f32 166 if (!Subtarget.hasEFPU2()) 167 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 168 } else { 169 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 170 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 171 } 172 } 173 174 // Match BITREVERSE to customized fast code sequence in the td file. 175 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 176 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 177 178 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 179 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 180 181 // Custom lower inline assembly to check for special registers. 182 setOperationAction(ISD::INLINEASM, MVT::Other, Custom); 183 setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom); 184 185 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 186 for (MVT VT : MVT::integer_valuetypes()) { 187 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 188 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 189 } 190 191 if (Subtarget.isISA3_0()) { 192 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 193 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 194 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 195 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 196 } else { 197 // No extending loads from f16 or HW conversions back and forth. 198 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 199 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 200 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 201 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 202 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 203 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 204 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 205 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 206 } 207 208 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 209 210 // PowerPC has pre-inc load and store's. 211 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 212 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 213 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 214 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 215 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 216 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 217 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 218 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 219 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 220 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 221 if (!Subtarget.hasSPE()) { 222 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 223 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 224 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 225 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 226 } 227 228 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 229 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 230 for (MVT VT : ScalarIntVTs) { 231 setOperationAction(ISD::ADDC, VT, Legal); 232 setOperationAction(ISD::ADDE, VT, Legal); 233 setOperationAction(ISD::SUBC, VT, Legal); 234 setOperationAction(ISD::SUBE, VT, Legal); 235 } 236 237 if (Subtarget.useCRBits()) { 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 239 240 if (isPPC64 || Subtarget.hasFPCVT()) { 241 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 242 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 243 isPPC64 ? MVT::i64 : MVT::i32); 244 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 245 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 246 isPPC64 ? MVT::i64 : MVT::i32); 247 248 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 249 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 250 isPPC64 ? MVT::i64 : MVT::i32); 251 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 252 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 253 isPPC64 ? MVT::i64 : MVT::i32); 254 255 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 256 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 257 isPPC64 ? MVT::i64 : MVT::i32); 258 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 259 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 260 isPPC64 ? MVT::i64 : MVT::i32); 261 262 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 263 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 264 isPPC64 ? MVT::i64 : MVT::i32); 265 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 266 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 267 isPPC64 ? MVT::i64 : MVT::i32); 268 } else { 269 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 270 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 271 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 272 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 273 } 274 275 // PowerPC does not support direct load/store of condition registers. 276 setOperationAction(ISD::LOAD, MVT::i1, Custom); 277 setOperationAction(ISD::STORE, MVT::i1, Custom); 278 279 // FIXME: Remove this once the ANDI glue bug is fixed: 280 if (ANDIGlueBug) 281 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 282 283 for (MVT VT : MVT::integer_valuetypes()) { 284 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 285 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 286 setTruncStoreAction(VT, MVT::i1, Expand); 287 } 288 289 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 290 } 291 292 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 293 // PPC (the libcall is not available). 294 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 295 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 296 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 297 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 298 299 // We do not currently implement these libm ops for PowerPC. 300 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 301 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 302 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 303 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 304 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 305 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 306 307 // PowerPC has no SREM/UREM instructions unless we are on P9 308 // On P9 we may use a hardware instruction to compute the remainder. 309 // When the result of both the remainder and the division is required it is 310 // more efficient to compute the remainder from the result of the division 311 // rather than use the remainder instruction. The instructions are legalized 312 // directly because the DivRemPairsPass performs the transformation at the IR 313 // level. 314 if (Subtarget.isISA3_0()) { 315 setOperationAction(ISD::SREM, MVT::i32, Legal); 316 setOperationAction(ISD::UREM, MVT::i32, Legal); 317 setOperationAction(ISD::SREM, MVT::i64, Legal); 318 setOperationAction(ISD::UREM, MVT::i64, Legal); 319 } else { 320 setOperationAction(ISD::SREM, MVT::i32, Expand); 321 setOperationAction(ISD::UREM, MVT::i32, Expand); 322 setOperationAction(ISD::SREM, MVT::i64, Expand); 323 setOperationAction(ISD::UREM, MVT::i64, Expand); 324 } 325 326 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 327 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 328 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 329 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 330 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 331 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 332 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 333 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 334 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 335 336 // Handle constrained floating-point operations of scalar. 337 // TODO: Handle SPE specific operation. 338 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 339 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 340 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 341 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 342 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 343 344 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 345 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 346 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 347 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 348 349 if (!Subtarget.hasSPE()) { 350 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 351 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 352 } 353 354 if (Subtarget.hasVSX()) { 355 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 356 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 357 } 358 359 if (Subtarget.hasFSQRT()) { 360 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 361 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 362 } 363 364 if (Subtarget.hasFPRND()) { 365 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 366 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 367 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 368 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 369 370 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 371 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 372 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 373 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 374 } 375 376 // We don't support sin/cos/sqrt/fmod/pow 377 setOperationAction(ISD::FSIN , MVT::f64, Expand); 378 setOperationAction(ISD::FCOS , MVT::f64, Expand); 379 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 380 setOperationAction(ISD::FREM , MVT::f64, Expand); 381 setOperationAction(ISD::FPOW , MVT::f64, Expand); 382 setOperationAction(ISD::FSIN , MVT::f32, Expand); 383 setOperationAction(ISD::FCOS , MVT::f32, Expand); 384 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 385 setOperationAction(ISD::FREM , MVT::f32, Expand); 386 setOperationAction(ISD::FPOW , MVT::f32, Expand); 387 388 // MASS transformation for LLVM intrinsics with replicating fast-math flag 389 // to be consistent to PPCGenScalarMASSEntries pass 390 if (TM.getOptLevel() == CodeGenOpt::Aggressive && 391 TM.Options.PPCGenScalarMASSEntries) { 392 setOperationAction(ISD::FSIN , MVT::f64, Custom); 393 setOperationAction(ISD::FCOS , MVT::f64, Custom); 394 setOperationAction(ISD::FPOW , MVT::f64, Custom); 395 setOperationAction(ISD::FLOG, MVT::f64, Custom); 396 setOperationAction(ISD::FLOG10, MVT::f64, Custom); 397 setOperationAction(ISD::FEXP, MVT::f64, Custom); 398 setOperationAction(ISD::FSIN , MVT::f32, Custom); 399 setOperationAction(ISD::FCOS , MVT::f32, Custom); 400 setOperationAction(ISD::FPOW , MVT::f32, Custom); 401 setOperationAction(ISD::FLOG, MVT::f32, Custom); 402 setOperationAction(ISD::FLOG10, MVT::f32, Custom); 403 setOperationAction(ISD::FEXP, MVT::f32, Custom); 404 } 405 406 if (Subtarget.hasSPE()) { 407 setOperationAction(ISD::FMA , MVT::f64, Expand); 408 setOperationAction(ISD::FMA , MVT::f32, Expand); 409 } else { 410 setOperationAction(ISD::FMA , MVT::f64, Legal); 411 setOperationAction(ISD::FMA , MVT::f32, Legal); 412 } 413 414 if (Subtarget.hasSPE()) 415 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 416 417 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 418 419 // If we're enabling GP optimizations, use hardware square root 420 if (!Subtarget.hasFSQRT() && 421 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 422 Subtarget.hasFRE())) 423 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 424 425 if (!Subtarget.hasFSQRT() && 426 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 427 Subtarget.hasFRES())) 428 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 429 430 if (Subtarget.hasFCPSGN()) { 431 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 432 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 433 } else { 434 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 435 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 436 } 437 438 if (Subtarget.hasFPRND()) { 439 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 440 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 441 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 442 setOperationAction(ISD::FROUND, MVT::f64, Legal); 443 444 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 445 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 446 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 447 setOperationAction(ISD::FROUND, MVT::f32, Legal); 448 } 449 450 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 451 // to speed up scalar BSWAP64. 452 // CTPOP or CTTZ were introduced in P8/P9 respectively 453 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 454 if (Subtarget.hasP9Vector() && Subtarget.isPPC64()) 455 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 456 else 457 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 458 if (Subtarget.isISA3_0()) { 459 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 460 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 461 } else { 462 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 463 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 464 } 465 466 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 467 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 468 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 469 } else { 470 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 471 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 472 } 473 474 // PowerPC does not have ROTR 475 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 476 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 477 478 if (!Subtarget.useCRBits()) { 479 // PowerPC does not have Select 480 setOperationAction(ISD::SELECT, MVT::i32, Expand); 481 setOperationAction(ISD::SELECT, MVT::i64, Expand); 482 setOperationAction(ISD::SELECT, MVT::f32, Expand); 483 setOperationAction(ISD::SELECT, MVT::f64, Expand); 484 } 485 486 // PowerPC wants to turn select_cc of FP into fsel when possible. 487 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 488 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 489 490 // PowerPC wants to optimize integer setcc a bit 491 if (!Subtarget.useCRBits()) 492 setOperationAction(ISD::SETCC, MVT::i32, Custom); 493 494 if (Subtarget.hasFPU()) { 495 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 496 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 497 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 498 499 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 500 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 501 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 502 } 503 504 // PowerPC does not have BRCOND which requires SetCC 505 if (!Subtarget.useCRBits()) 506 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 507 508 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 509 510 if (Subtarget.hasSPE()) { 511 // SPE has built-in conversions 512 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 513 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 514 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 515 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 516 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 517 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 518 519 // SPE supports signaling compare of f32/f64. 520 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 521 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 522 } else { 523 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 524 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 525 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 526 527 // PowerPC does not have [U|S]INT_TO_FP 528 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 529 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 530 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 531 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 532 } 533 534 if (Subtarget.hasDirectMove() && isPPC64) { 535 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 536 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 537 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 538 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 539 if (TM.Options.UnsafeFPMath) { 540 setOperationAction(ISD::LRINT, MVT::f64, Legal); 541 setOperationAction(ISD::LRINT, MVT::f32, Legal); 542 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 543 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 544 setOperationAction(ISD::LROUND, MVT::f64, Legal); 545 setOperationAction(ISD::LROUND, MVT::f32, Legal); 546 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 547 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 548 } 549 } else { 550 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 551 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 552 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 553 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 554 } 555 556 // We cannot sextinreg(i1). Expand to shifts. 557 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 558 559 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 560 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 561 // support continuation, user-level threading, and etc.. As a result, no 562 // other SjLj exception interfaces are implemented and please don't build 563 // your own exception handling based on them. 564 // LLVM/Clang supports zero-cost DWARF exception handling. 565 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 566 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 567 568 // We want to legalize GlobalAddress and ConstantPool nodes into the 569 // appropriate instructions to materialize the address. 570 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 571 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 572 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 573 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 574 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 575 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 576 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 577 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 578 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 579 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 580 581 // TRAP is legal. 582 setOperationAction(ISD::TRAP, MVT::Other, Legal); 583 584 // TRAMPOLINE is custom lowered. 585 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 586 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 587 588 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 589 setOperationAction(ISD::VASTART , MVT::Other, Custom); 590 591 if (Subtarget.is64BitELFABI()) { 592 // VAARG always uses double-word chunks, so promote anything smaller. 593 setOperationAction(ISD::VAARG, MVT::i1, Promote); 594 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 595 setOperationAction(ISD::VAARG, MVT::i8, Promote); 596 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 597 setOperationAction(ISD::VAARG, MVT::i16, Promote); 598 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 599 setOperationAction(ISD::VAARG, MVT::i32, Promote); 600 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 601 setOperationAction(ISD::VAARG, MVT::Other, Expand); 602 } else if (Subtarget.is32BitELFABI()) { 603 // VAARG is custom lowered with the 32-bit SVR4 ABI. 604 setOperationAction(ISD::VAARG, MVT::Other, Custom); 605 setOperationAction(ISD::VAARG, MVT::i64, Custom); 606 } else 607 setOperationAction(ISD::VAARG, MVT::Other, Expand); 608 609 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 610 if (Subtarget.is32BitELFABI()) 611 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 612 else 613 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 614 615 // Use the default implementation. 616 setOperationAction(ISD::VAEND , MVT::Other, Expand); 617 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 618 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 619 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 620 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 621 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 622 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 623 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 624 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 625 626 // We want to custom lower some of our intrinsics. 627 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 628 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom); 629 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom); 630 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 631 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom); 632 633 // To handle counter-based loop conditions. 634 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 635 636 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 637 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 638 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 639 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 640 641 // Comparisons that require checking two conditions. 642 if (Subtarget.hasSPE()) { 643 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 644 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 645 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 646 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 647 } 648 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 649 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 650 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 651 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 652 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 653 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 654 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 655 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 656 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 657 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 658 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 659 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 660 661 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 662 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 663 664 if (Subtarget.has64BitSupport()) { 665 // They also have instructions for converting between i64 and fp. 666 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 667 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 668 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 669 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 670 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 671 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 672 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 673 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 674 // This is just the low 32 bits of a (signed) fp->i64 conversion. 675 // We cannot do this with Promote because i64 is not a legal type. 676 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 677 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 678 679 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 680 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 681 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 682 } 683 } else { 684 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 685 if (Subtarget.hasSPE()) { 686 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 687 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 688 } else { 689 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 690 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 691 } 692 } 693 694 // With the instructions enabled under FPCVT, we can do everything. 695 if (Subtarget.hasFPCVT()) { 696 if (Subtarget.has64BitSupport()) { 697 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 698 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 699 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 700 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 701 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 702 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 703 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 704 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 705 } 706 707 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 708 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 709 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 710 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 711 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 712 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 713 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 714 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 715 } 716 717 if (Subtarget.use64BitRegs()) { 718 // 64-bit PowerPC implementations can support i64 types directly 719 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 720 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 721 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 722 // 64-bit PowerPC wants to expand i128 shifts itself. 723 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 724 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 725 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 726 } else { 727 // 32-bit PowerPC wants to expand i64 shifts itself. 728 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 729 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 730 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 731 } 732 733 // PowerPC has better expansions for funnel shifts than the generic 734 // TargetLowering::expandFunnelShift. 735 if (Subtarget.has64BitSupport()) { 736 setOperationAction(ISD::FSHL, MVT::i64, Custom); 737 setOperationAction(ISD::FSHR, MVT::i64, Custom); 738 } 739 setOperationAction(ISD::FSHL, MVT::i32, Custom); 740 setOperationAction(ISD::FSHR, MVT::i32, Custom); 741 742 if (Subtarget.hasVSX()) { 743 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 744 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 745 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 746 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 747 } 748 749 if (Subtarget.hasAltivec()) { 750 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 751 setOperationAction(ISD::SADDSAT, VT, Legal); 752 setOperationAction(ISD::SSUBSAT, VT, Legal); 753 setOperationAction(ISD::UADDSAT, VT, Legal); 754 setOperationAction(ISD::USUBSAT, VT, Legal); 755 } 756 // First set operation action for all vector types to expand. Then we 757 // will selectively turn on ones that can be effectively codegen'd. 758 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 759 // add/sub are legal for all supported vector VT's. 760 setOperationAction(ISD::ADD, VT, Legal); 761 setOperationAction(ISD::SUB, VT, Legal); 762 763 // For v2i64, these are only valid with P8Vector. This is corrected after 764 // the loop. 765 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 766 setOperationAction(ISD::SMAX, VT, Legal); 767 setOperationAction(ISD::SMIN, VT, Legal); 768 setOperationAction(ISD::UMAX, VT, Legal); 769 setOperationAction(ISD::UMIN, VT, Legal); 770 } 771 else { 772 setOperationAction(ISD::SMAX, VT, Expand); 773 setOperationAction(ISD::SMIN, VT, Expand); 774 setOperationAction(ISD::UMAX, VT, Expand); 775 setOperationAction(ISD::UMIN, VT, Expand); 776 } 777 778 if (Subtarget.hasVSX()) { 779 setOperationAction(ISD::FMAXNUM, VT, Legal); 780 setOperationAction(ISD::FMINNUM, VT, Legal); 781 } 782 783 // Vector instructions introduced in P8 784 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 785 setOperationAction(ISD::CTPOP, VT, Legal); 786 setOperationAction(ISD::CTLZ, VT, Legal); 787 } 788 else { 789 setOperationAction(ISD::CTPOP, VT, Expand); 790 setOperationAction(ISD::CTLZ, VT, Expand); 791 } 792 793 // Vector instructions introduced in P9 794 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 795 setOperationAction(ISD::CTTZ, VT, Legal); 796 else 797 setOperationAction(ISD::CTTZ, VT, Expand); 798 799 // We promote all shuffles to v16i8. 800 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 801 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 802 803 // We promote all non-typed operations to v4i32. 804 setOperationAction(ISD::AND , VT, Promote); 805 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 806 setOperationAction(ISD::OR , VT, Promote); 807 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 808 setOperationAction(ISD::XOR , VT, Promote); 809 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 810 setOperationAction(ISD::LOAD , VT, Promote); 811 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 812 setOperationAction(ISD::SELECT, VT, Promote); 813 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 814 setOperationAction(ISD::VSELECT, VT, Legal); 815 setOperationAction(ISD::SELECT_CC, VT, Promote); 816 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 817 setOperationAction(ISD::STORE, VT, Promote); 818 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 819 820 // No other operations are legal. 821 setOperationAction(ISD::MUL , VT, Expand); 822 setOperationAction(ISD::SDIV, VT, Expand); 823 setOperationAction(ISD::SREM, VT, Expand); 824 setOperationAction(ISD::UDIV, VT, Expand); 825 setOperationAction(ISD::UREM, VT, Expand); 826 setOperationAction(ISD::FDIV, VT, Expand); 827 setOperationAction(ISD::FREM, VT, Expand); 828 setOperationAction(ISD::FNEG, VT, Expand); 829 setOperationAction(ISD::FSQRT, VT, Expand); 830 setOperationAction(ISD::FLOG, VT, Expand); 831 setOperationAction(ISD::FLOG10, VT, Expand); 832 setOperationAction(ISD::FLOG2, VT, Expand); 833 setOperationAction(ISD::FEXP, VT, Expand); 834 setOperationAction(ISD::FEXP2, VT, Expand); 835 setOperationAction(ISD::FSIN, VT, Expand); 836 setOperationAction(ISD::FCOS, VT, Expand); 837 setOperationAction(ISD::FABS, VT, Expand); 838 setOperationAction(ISD::FFLOOR, VT, Expand); 839 setOperationAction(ISD::FCEIL, VT, Expand); 840 setOperationAction(ISD::FTRUNC, VT, Expand); 841 setOperationAction(ISD::FRINT, VT, Expand); 842 setOperationAction(ISD::FNEARBYINT, VT, Expand); 843 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 844 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 845 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 846 setOperationAction(ISD::MULHU, VT, Expand); 847 setOperationAction(ISD::MULHS, VT, Expand); 848 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 849 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 850 setOperationAction(ISD::UDIVREM, VT, Expand); 851 setOperationAction(ISD::SDIVREM, VT, Expand); 852 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 853 setOperationAction(ISD::FPOW, VT, Expand); 854 setOperationAction(ISD::BSWAP, VT, Expand); 855 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 856 setOperationAction(ISD::ROTL, VT, Expand); 857 setOperationAction(ISD::ROTR, VT, Expand); 858 859 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 860 setTruncStoreAction(VT, InnerVT, Expand); 861 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 862 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 863 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 864 } 865 } 866 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 867 if (!Subtarget.hasP8Vector()) { 868 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 869 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 870 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 871 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 872 } 873 874 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 875 // with merges, splats, etc. 876 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 877 878 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 879 // are cheap, so handle them before they get expanded to scalar. 880 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 881 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 882 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 883 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 884 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 885 886 setOperationAction(ISD::AND , MVT::v4i32, Legal); 887 setOperationAction(ISD::OR , MVT::v4i32, Legal); 888 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 889 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 890 setOperationAction(ISD::SELECT, MVT::v4i32, 891 Subtarget.useCRBits() ? Legal : Expand); 892 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 893 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 894 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 895 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 896 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 897 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 898 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 899 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 900 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 901 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 902 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 903 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 904 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 905 906 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 907 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 908 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 909 if (Subtarget.hasAltivec()) 910 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 911 setOperationAction(ISD::ROTL, VT, Legal); 912 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 913 if (Subtarget.hasP8Altivec()) 914 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 915 916 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 917 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 918 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 919 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 920 921 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 922 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 923 924 if (Subtarget.hasVSX()) { 925 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 926 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 927 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 928 } 929 930 if (Subtarget.hasP8Altivec()) 931 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 932 else 933 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 934 935 if (Subtarget.isISA3_1()) { 936 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 937 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 938 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 939 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 940 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 941 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 942 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 943 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 944 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 945 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 946 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 947 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 948 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 949 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 950 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 951 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 952 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 953 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 954 } 955 956 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 957 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 958 959 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 960 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 961 962 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 963 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 964 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 965 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 966 967 // Altivec does not contain unordered floating-point compare instructions 968 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 969 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 970 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 971 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 972 973 if (Subtarget.hasVSX()) { 974 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 975 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 976 if (Subtarget.hasP8Vector()) { 977 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 979 } 980 if (Subtarget.hasDirectMove() && isPPC64) { 981 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 982 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 983 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 984 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 985 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 986 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 987 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 989 } 990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 991 992 // The nearbyint variants are not allowed to raise the inexact exception 993 // so we can only code-gen them with unsafe math. 994 if (TM.Options.UnsafeFPMath) { 995 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 996 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 997 } 998 999 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 1000 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 1001 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 1002 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 1003 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 1004 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 1005 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1006 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1007 1008 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 1009 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 1010 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1011 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1012 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1013 1014 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 1015 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 1016 1017 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 1018 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 1019 1020 // Share the Altivec comparison restrictions. 1021 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 1022 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 1023 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 1024 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 1025 1026 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 1027 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 1028 1029 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 1030 1031 if (Subtarget.hasP8Vector()) 1032 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 1033 1034 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 1035 1036 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 1037 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 1038 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 1039 1040 if (Subtarget.hasP8Altivec()) { 1041 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 1042 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 1043 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 1044 1045 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1046 // SRL, but not for SRA because of the instructions available: 1047 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1048 // doing 1049 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1050 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1051 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1052 1053 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1054 } 1055 else { 1056 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1057 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1058 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1059 1060 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1061 1062 // VSX v2i64 only supports non-arithmetic operations. 1063 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1064 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1065 } 1066 1067 if (Subtarget.isISA3_1()) 1068 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1069 else 1070 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1071 1072 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1073 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1074 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1075 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1076 1077 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 1078 1079 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1080 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1081 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1082 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1083 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1084 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1085 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1086 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1087 1088 // Custom handling for partial vectors of integers converted to 1089 // floating point. We already have optimal handling for v2i32 through 1090 // the DAG combine, so those aren't necessary. 1091 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1092 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1093 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1094 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1095 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1096 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1097 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1098 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1099 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1100 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1101 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1102 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1103 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1104 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1105 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1106 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1107 1108 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1109 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1110 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1111 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1112 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1113 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1114 1115 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1116 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1117 1118 // Handle constrained floating-point operations of vector. 1119 // The predictor is `hasVSX` because altivec instruction has 1120 // no exception but VSX vector instruction has. 1121 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1122 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1123 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1124 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1125 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1126 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1127 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1128 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1129 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1130 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1131 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1132 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1133 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1134 1135 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1136 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1137 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1138 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1139 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1140 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1141 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1142 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1143 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1144 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1145 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1146 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1147 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1148 1149 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1150 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1151 1152 for (MVT FPT : MVT::fp_valuetypes()) 1153 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1154 1155 // Expand the SELECT to SELECT_CC 1156 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1157 1158 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1159 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1160 1161 // No implementation for these ops for PowerPC. 1162 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1163 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1164 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1165 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1166 setOperationAction(ISD::FREM, MVT::f128, Expand); 1167 } 1168 1169 if (Subtarget.hasP8Altivec()) { 1170 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1171 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1172 } 1173 1174 if (Subtarget.hasP9Vector()) { 1175 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1176 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1177 1178 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1179 // SRL, but not for SRA because of the instructions available: 1180 // VS{RL} and VS{RL}O. 1181 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1182 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1183 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1184 1185 setOperationAction(ISD::FADD, MVT::f128, Legal); 1186 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1187 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1188 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1189 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1190 1191 setOperationAction(ISD::FMA, MVT::f128, Legal); 1192 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1193 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1194 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1195 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1196 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1197 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1198 1199 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1200 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1201 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1202 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1203 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1204 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1205 1206 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1207 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1208 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1209 1210 // Handle constrained floating-point operations of fp128 1211 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1212 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1213 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1214 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1215 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1216 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1217 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1218 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1219 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1220 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1221 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1222 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1223 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1224 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1225 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1226 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1227 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1228 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1229 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1230 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1231 } else if (Subtarget.hasVSX()) { 1232 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1233 setOperationAction(ISD::STORE, MVT::f128, Promote); 1234 1235 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1236 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1237 1238 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1239 // fp_to_uint and int_to_fp. 1240 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1241 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1242 1243 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1244 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1245 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1246 setOperationAction(ISD::FABS, MVT::f128, Expand); 1247 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1248 setOperationAction(ISD::FMA, MVT::f128, Expand); 1249 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1250 1251 // Expand the fp_extend if the target type is fp128. 1252 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1253 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1254 1255 // Expand the fp_round if the source type is fp128. 1256 for (MVT VT : {MVT::f32, MVT::f64}) { 1257 setOperationAction(ISD::FP_ROUND, VT, Custom); 1258 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1259 } 1260 1261 setOperationAction(ISD::SETCC, MVT::f128, Custom); 1262 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 1263 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 1264 setOperationAction(ISD::BR_CC, MVT::f128, Expand); 1265 1266 // Lower following f128 select_cc pattern: 1267 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE 1268 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1269 1270 // We need to handle f128 SELECT_CC with integer result type. 1271 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1272 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand); 1273 } 1274 1275 if (Subtarget.hasP9Altivec()) { 1276 if (Subtarget.isISA3_1()) { 1277 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 1278 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal); 1279 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal); 1280 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal); 1281 } else { 1282 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1283 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1284 } 1285 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1286 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1287 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1288 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1289 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1290 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1291 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1292 } 1293 1294 if (Subtarget.hasP10Vector()) { 1295 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1296 } 1297 } 1298 1299 if (Subtarget.pairedVectorMemops()) { 1300 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1301 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1302 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1303 } 1304 if (Subtarget.hasMMA()) { 1305 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1306 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1307 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1308 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1309 } 1310 1311 if (Subtarget.has64BitSupport()) 1312 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1313 1314 if (Subtarget.isISA3_1()) 1315 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1316 1317 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1318 1319 if (!isPPC64) { 1320 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1321 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1322 } 1323 1324 if (shouldInlineQuadwordAtomics()) { 1325 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom); 1326 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom); 1327 setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom); 1328 } 1329 1330 setBooleanContents(ZeroOrOneBooleanContent); 1331 1332 if (Subtarget.hasAltivec()) { 1333 // Altivec instructions set fields to all zeros or all ones. 1334 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1335 } 1336 1337 setLibcallName(RTLIB::MULO_I128, nullptr); 1338 if (!isPPC64) { 1339 // These libcalls are not available in 32-bit. 1340 setLibcallName(RTLIB::SHL_I128, nullptr); 1341 setLibcallName(RTLIB::SRL_I128, nullptr); 1342 setLibcallName(RTLIB::SRA_I128, nullptr); 1343 setLibcallName(RTLIB::MUL_I128, nullptr); 1344 setLibcallName(RTLIB::MULO_I64, nullptr); 1345 } 1346 1347 if (!isPPC64) 1348 setMaxAtomicSizeInBitsSupported(32); 1349 else if (shouldInlineQuadwordAtomics()) 1350 setMaxAtomicSizeInBitsSupported(128); 1351 else 1352 setMaxAtomicSizeInBitsSupported(64); 1353 1354 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1355 1356 // We have target-specific dag combine patterns for the following nodes: 1357 setTargetDAGCombine({ISD::ADD, ISD::SHL, ISD::SRA, ISD::SRL, ISD::MUL, 1358 ISD::FMA, ISD::SINT_TO_FP, ISD::BUILD_VECTOR}); 1359 if (Subtarget.hasFPCVT()) 1360 setTargetDAGCombine(ISD::UINT_TO_FP); 1361 setTargetDAGCombine({ISD::LOAD, ISD::STORE, ISD::BR_CC}); 1362 if (Subtarget.useCRBits()) 1363 setTargetDAGCombine(ISD::BRCOND); 1364 setTargetDAGCombine({ISD::BSWAP, ISD::INTRINSIC_WO_CHAIN, 1365 ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}); 1366 1367 setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND, ISD::ANY_EXTEND}); 1368 1369 setTargetDAGCombine({ISD::TRUNCATE, ISD::VECTOR_SHUFFLE}); 1370 1371 if (Subtarget.useCRBits()) { 1372 setTargetDAGCombine({ISD::TRUNCATE, ISD::SETCC, ISD::SELECT_CC}); 1373 } 1374 1375 if (Subtarget.hasP9Altivec()) { 1376 setTargetDAGCombine({ISD::ABS, ISD::VSELECT}); 1377 } 1378 1379 setLibcallName(RTLIB::LOG_F128, "logf128"); 1380 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1381 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1382 setLibcallName(RTLIB::EXP_F128, "expf128"); 1383 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1384 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1385 setLibcallName(RTLIB::COS_F128, "cosf128"); 1386 setLibcallName(RTLIB::POW_F128, "powf128"); 1387 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1388 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1389 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1390 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1391 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1392 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1393 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1394 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1395 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1396 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1397 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1398 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1399 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1400 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1401 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1402 1403 // With 32 condition bits, we don't need to sink (and duplicate) compares 1404 // aggressively in CodeGenPrep. 1405 if (Subtarget.useCRBits()) { 1406 setHasMultipleConditionRegisters(); 1407 setJumpIsExpensive(); 1408 } 1409 1410 setMinFunctionAlignment(Align(4)); 1411 1412 switch (Subtarget.getCPUDirective()) { 1413 default: break; 1414 case PPC::DIR_970: 1415 case PPC::DIR_A2: 1416 case PPC::DIR_E500: 1417 case PPC::DIR_E500mc: 1418 case PPC::DIR_E5500: 1419 case PPC::DIR_PWR4: 1420 case PPC::DIR_PWR5: 1421 case PPC::DIR_PWR5X: 1422 case PPC::DIR_PWR6: 1423 case PPC::DIR_PWR6X: 1424 case PPC::DIR_PWR7: 1425 case PPC::DIR_PWR8: 1426 case PPC::DIR_PWR9: 1427 case PPC::DIR_PWR10: 1428 case PPC::DIR_PWR_FUTURE: 1429 setPrefLoopAlignment(Align(16)); 1430 setPrefFunctionAlignment(Align(16)); 1431 break; 1432 } 1433 1434 if (Subtarget.enableMachineScheduler()) 1435 setSchedulingPreference(Sched::Source); 1436 else 1437 setSchedulingPreference(Sched::Hybrid); 1438 1439 computeRegisterProperties(STI.getRegisterInfo()); 1440 1441 // The Freescale cores do better with aggressive inlining of memcpy and 1442 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1443 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1444 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1445 MaxStoresPerMemset = 32; 1446 MaxStoresPerMemsetOptSize = 16; 1447 MaxStoresPerMemcpy = 32; 1448 MaxStoresPerMemcpyOptSize = 8; 1449 MaxStoresPerMemmove = 32; 1450 MaxStoresPerMemmoveOptSize = 8; 1451 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1452 // The A2 also benefits from (very) aggressive inlining of memcpy and 1453 // friends. The overhead of a the function call, even when warm, can be 1454 // over one hundred cycles. 1455 MaxStoresPerMemset = 128; 1456 MaxStoresPerMemcpy = 128; 1457 MaxStoresPerMemmove = 128; 1458 MaxLoadsPerMemcmp = 128; 1459 } else { 1460 MaxLoadsPerMemcmp = 8; 1461 MaxLoadsPerMemcmpOptSize = 4; 1462 } 1463 1464 IsStrictFPEnabled = true; 1465 1466 // Let the subtarget (CPU) decide if a predictable select is more expensive 1467 // than the corresponding branch. This information is used in CGP to decide 1468 // when to convert selects into branches. 1469 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1470 } 1471 1472 // *********************************** NOTE ************************************ 1473 // For selecting load and store instructions, the addressing modes are defined 1474 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD 1475 // patterns to match the load the store instructions. 1476 // 1477 // The TD definitions for the addressing modes correspond to their respective 1478 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely 1479 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the 1480 // address mode flags of a particular node. Afterwards, the computed address 1481 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal 1482 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement 1483 // accordingly, based on the preferred addressing mode. 1484 // 1485 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode. 1486 // MemOpFlags contains all the possible flags that can be used to compute the 1487 // optimal addressing mode for load and store instructions. 1488 // AddrMode contains all the possible load and store addressing modes available 1489 // on Power (such as DForm, DSForm, DQForm, XForm, etc.) 1490 // 1491 // When adding new load and store instructions, it is possible that new address 1492 // flags may need to be added into MemOpFlags, and a new addressing mode will 1493 // need to be added to AddrMode. An entry of the new addressing mode (consisting 1494 // of the minimal and main distinguishing address flags for the new load/store 1495 // instructions) will need to be added into initializeAddrModeMap() below. 1496 // Finally, when adding new addressing modes, the getAddrModeForFlags() will 1497 // need to be updated to account for selecting the optimal addressing mode. 1498 // ***************************************************************************** 1499 /// Initialize the map that relates the different addressing modes of the load 1500 /// and store instructions to a set of flags. This ensures the load/store 1501 /// instruction is correctly matched during instruction selection. 1502 void PPCTargetLowering::initializeAddrModeMap() { 1503 AddrModesMap[PPC::AM_DForm] = { 1504 // LWZ, STW 1505 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt, 1506 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt, 1507 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1508 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1509 // LBZ, LHZ, STB, STH 1510 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1511 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1512 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1513 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1514 // LHA 1515 PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1516 PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1517 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1518 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1519 // LFS, LFD, STFS, STFD 1520 PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1521 PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1522 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1523 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1524 }; 1525 AddrModesMap[PPC::AM_DSForm] = { 1526 // LWA 1527 PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt, 1528 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1529 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1530 // LD, STD 1531 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt, 1532 PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt, 1533 PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt, 1534 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64 1535 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1536 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1537 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1538 }; 1539 AddrModesMap[PPC::AM_DQForm] = { 1540 // LXV, STXV 1541 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1542 PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1543 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1544 }; 1545 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 | 1546 PPC::MOF_SubtargetP10}; 1547 // TODO: Add mapping for quadword load/store. 1548 } 1549 1550 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1551 /// the desired ByVal argument alignment. 1552 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1553 if (MaxAlign == MaxMaxAlign) 1554 return; 1555 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1556 if (MaxMaxAlign >= 32 && 1557 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1558 MaxAlign = Align(32); 1559 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1560 MaxAlign < 16) 1561 MaxAlign = Align(16); 1562 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1563 Align EltAlign; 1564 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1565 if (EltAlign > MaxAlign) 1566 MaxAlign = EltAlign; 1567 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1568 for (auto *EltTy : STy->elements()) { 1569 Align EltAlign; 1570 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1571 if (EltAlign > MaxAlign) 1572 MaxAlign = EltAlign; 1573 if (MaxAlign == MaxMaxAlign) 1574 break; 1575 } 1576 } 1577 } 1578 1579 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1580 /// function arguments in the caller parameter area. 1581 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1582 const DataLayout &DL) const { 1583 // 16byte and wider vectors are passed on 16byte boundary. 1584 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1585 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1586 if (Subtarget.hasAltivec()) 1587 getMaxByValAlign(Ty, Alignment, Align(16)); 1588 return Alignment.value(); 1589 } 1590 1591 bool PPCTargetLowering::useSoftFloat() const { 1592 return Subtarget.useSoftFloat(); 1593 } 1594 1595 bool PPCTargetLowering::hasSPE() const { 1596 return Subtarget.hasSPE(); 1597 } 1598 1599 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1600 return VT.isScalarInteger(); 1601 } 1602 1603 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1604 switch ((PPCISD::NodeType)Opcode) { 1605 case PPCISD::FIRST_NUMBER: break; 1606 case PPCISD::FSEL: return "PPCISD::FSEL"; 1607 case PPCISD::XSMAXC: return "PPCISD::XSMAXC"; 1608 case PPCISD::XSMINC: return "PPCISD::XSMINC"; 1609 case PPCISD::FCFID: return "PPCISD::FCFID"; 1610 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1611 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1612 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1613 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1614 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1615 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1616 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1617 case PPCISD::FP_TO_UINT_IN_VSR: 1618 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1619 case PPCISD::FP_TO_SINT_IN_VSR: 1620 return "PPCISD::FP_TO_SINT_IN_VSR"; 1621 case PPCISD::FRE: return "PPCISD::FRE"; 1622 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1623 case PPCISD::FTSQRT: 1624 return "PPCISD::FTSQRT"; 1625 case PPCISD::FSQRT: 1626 return "PPCISD::FSQRT"; 1627 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1628 case PPCISD::VPERM: return "PPCISD::VPERM"; 1629 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1630 case PPCISD::XXSPLTI_SP_TO_DP: 1631 return "PPCISD::XXSPLTI_SP_TO_DP"; 1632 case PPCISD::XXSPLTI32DX: 1633 return "PPCISD::XXSPLTI32DX"; 1634 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1635 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1636 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1637 case PPCISD::CMPB: return "PPCISD::CMPB"; 1638 case PPCISD::Hi: return "PPCISD::Hi"; 1639 case PPCISD::Lo: return "PPCISD::Lo"; 1640 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1641 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1642 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1643 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1644 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1645 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1646 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1647 case PPCISD::SRL: return "PPCISD::SRL"; 1648 case PPCISD::SRA: return "PPCISD::SRA"; 1649 case PPCISD::SHL: return "PPCISD::SHL"; 1650 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1651 case PPCISD::CALL: return "PPCISD::CALL"; 1652 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1653 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1654 case PPCISD::CALL_RM: 1655 return "PPCISD::CALL_RM"; 1656 case PPCISD::CALL_NOP_RM: 1657 return "PPCISD::CALL_NOP_RM"; 1658 case PPCISD::CALL_NOTOC_RM: 1659 return "PPCISD::CALL_NOTOC_RM"; 1660 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1661 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1662 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1663 case PPCISD::BCTRL_RM: 1664 return "PPCISD::BCTRL_RM"; 1665 case PPCISD::BCTRL_LOAD_TOC_RM: 1666 return "PPCISD::BCTRL_LOAD_TOC_RM"; 1667 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1668 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1669 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1670 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1671 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1672 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1673 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1674 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1675 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1676 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1677 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1678 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1679 case PPCISD::ANDI_rec_1_EQ_BIT: 1680 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1681 case PPCISD::ANDI_rec_1_GT_BIT: 1682 return "PPCISD::ANDI_rec_1_GT_BIT"; 1683 case PPCISD::VCMP: return "PPCISD::VCMP"; 1684 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1685 case PPCISD::LBRX: return "PPCISD::LBRX"; 1686 case PPCISD::STBRX: return "PPCISD::STBRX"; 1687 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1688 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1689 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1690 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1691 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1692 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1693 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1694 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1695 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1696 case PPCISD::ST_VSR_SCAL_INT: 1697 return "PPCISD::ST_VSR_SCAL_INT"; 1698 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1699 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1700 case PPCISD::BDZ: return "PPCISD::BDZ"; 1701 case PPCISD::MFFS: return "PPCISD::MFFS"; 1702 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1703 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1704 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1705 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1706 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1707 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1708 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1709 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1710 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1711 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1712 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1713 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1714 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1715 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX"; 1716 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1717 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1718 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1719 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1720 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1721 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1722 case PPCISD::PADDI_DTPREL: 1723 return "PPCISD::PADDI_DTPREL"; 1724 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1725 case PPCISD::SC: return "PPCISD::SC"; 1726 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1727 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1728 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1729 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1730 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1731 case PPCISD::VABSD: return "PPCISD::VABSD"; 1732 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1733 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1734 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1735 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1736 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1737 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1738 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1739 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1740 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1741 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1742 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1743 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1744 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1745 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1746 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1747 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1748 case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT"; 1749 case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT"; 1750 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1751 case PPCISD::STRICT_FADDRTZ: 1752 return "PPCISD::STRICT_FADDRTZ"; 1753 case PPCISD::STRICT_FCTIDZ: 1754 return "PPCISD::STRICT_FCTIDZ"; 1755 case PPCISD::STRICT_FCTIWZ: 1756 return "PPCISD::STRICT_FCTIWZ"; 1757 case PPCISD::STRICT_FCTIDUZ: 1758 return "PPCISD::STRICT_FCTIDUZ"; 1759 case PPCISD::STRICT_FCTIWUZ: 1760 return "PPCISD::STRICT_FCTIWUZ"; 1761 case PPCISD::STRICT_FCFID: 1762 return "PPCISD::STRICT_FCFID"; 1763 case PPCISD::STRICT_FCFIDU: 1764 return "PPCISD::STRICT_FCFIDU"; 1765 case PPCISD::STRICT_FCFIDS: 1766 return "PPCISD::STRICT_FCFIDS"; 1767 case PPCISD::STRICT_FCFIDUS: 1768 return "PPCISD::STRICT_FCFIDUS"; 1769 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1770 } 1771 return nullptr; 1772 } 1773 1774 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1775 EVT VT) const { 1776 if (!VT.isVector()) 1777 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1778 1779 return VT.changeVectorElementTypeToInteger(); 1780 } 1781 1782 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1783 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1784 return true; 1785 } 1786 1787 //===----------------------------------------------------------------------===// 1788 // Node matching predicates, for use by the tblgen matching code. 1789 //===----------------------------------------------------------------------===// 1790 1791 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1792 static bool isFloatingPointZero(SDValue Op) { 1793 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1794 return CFP->getValueAPF().isZero(); 1795 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1796 // Maybe this has already been legalized into the constant pool? 1797 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1798 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1799 return CFP->getValueAPF().isZero(); 1800 } 1801 return false; 1802 } 1803 1804 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1805 /// true if Op is undef or if it matches the specified value. 1806 static bool isConstantOrUndef(int Op, int Val) { 1807 return Op < 0 || Op == Val; 1808 } 1809 1810 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1811 /// VPKUHUM instruction. 1812 /// The ShuffleKind distinguishes between big-endian operations with 1813 /// two different inputs (0), either-endian operations with two identical 1814 /// inputs (1), and little-endian operations with two different inputs (2). 1815 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1816 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1817 SelectionDAG &DAG) { 1818 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1819 if (ShuffleKind == 0) { 1820 if (IsLE) 1821 return false; 1822 for (unsigned i = 0; i != 16; ++i) 1823 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1824 return false; 1825 } else if (ShuffleKind == 2) { 1826 if (!IsLE) 1827 return false; 1828 for (unsigned i = 0; i != 16; ++i) 1829 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1830 return false; 1831 } else if (ShuffleKind == 1) { 1832 unsigned j = IsLE ? 0 : 1; 1833 for (unsigned i = 0; i != 8; ++i) 1834 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1835 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1836 return false; 1837 } 1838 return true; 1839 } 1840 1841 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1842 /// VPKUWUM instruction. 1843 /// The ShuffleKind distinguishes between big-endian operations with 1844 /// two different inputs (0), either-endian operations with two identical 1845 /// inputs (1), and little-endian operations with two different inputs (2). 1846 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1847 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1848 SelectionDAG &DAG) { 1849 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1850 if (ShuffleKind == 0) { 1851 if (IsLE) 1852 return false; 1853 for (unsigned i = 0; i != 16; i += 2) 1854 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1855 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1856 return false; 1857 } else if (ShuffleKind == 2) { 1858 if (!IsLE) 1859 return false; 1860 for (unsigned i = 0; i != 16; i += 2) 1861 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1862 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1863 return false; 1864 } else if (ShuffleKind == 1) { 1865 unsigned j = IsLE ? 0 : 2; 1866 for (unsigned i = 0; i != 8; i += 2) 1867 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1868 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1869 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1870 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1871 return false; 1872 } 1873 return true; 1874 } 1875 1876 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1877 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1878 /// current subtarget. 1879 /// 1880 /// The ShuffleKind distinguishes between big-endian operations with 1881 /// two different inputs (0), either-endian operations with two identical 1882 /// inputs (1), and little-endian operations with two different inputs (2). 1883 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1884 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1885 SelectionDAG &DAG) { 1886 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 1887 if (!Subtarget.hasP8Vector()) 1888 return false; 1889 1890 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1891 if (ShuffleKind == 0) { 1892 if (IsLE) 1893 return false; 1894 for (unsigned i = 0; i != 16; i += 4) 1895 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1896 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1897 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1898 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1899 return false; 1900 } else if (ShuffleKind == 2) { 1901 if (!IsLE) 1902 return false; 1903 for (unsigned i = 0; i != 16; i += 4) 1904 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1905 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1906 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1907 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1908 return false; 1909 } else if (ShuffleKind == 1) { 1910 unsigned j = IsLE ? 0 : 4; 1911 for (unsigned i = 0; i != 8; i += 4) 1912 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1913 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1914 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1915 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1916 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1917 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1918 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1919 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1920 return false; 1921 } 1922 return true; 1923 } 1924 1925 /// isVMerge - Common function, used to match vmrg* shuffles. 1926 /// 1927 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1928 unsigned LHSStart, unsigned RHSStart) { 1929 if (N->getValueType(0) != MVT::v16i8) 1930 return false; 1931 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1932 "Unsupported merge size!"); 1933 1934 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1935 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1936 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1937 LHSStart+j+i*UnitSize) || 1938 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1939 RHSStart+j+i*UnitSize)) 1940 return false; 1941 } 1942 return true; 1943 } 1944 1945 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1946 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1947 /// The ShuffleKind distinguishes between big-endian merges with two 1948 /// different inputs (0), either-endian merges with two identical inputs (1), 1949 /// and little-endian merges with two different inputs (2). For the latter, 1950 /// the input operands are swapped (see PPCInstrAltivec.td). 1951 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1952 unsigned ShuffleKind, SelectionDAG &DAG) { 1953 if (DAG.getDataLayout().isLittleEndian()) { 1954 if (ShuffleKind == 1) // unary 1955 return isVMerge(N, UnitSize, 0, 0); 1956 else if (ShuffleKind == 2) // swapped 1957 return isVMerge(N, UnitSize, 0, 16); 1958 else 1959 return false; 1960 } else { 1961 if (ShuffleKind == 1) // unary 1962 return isVMerge(N, UnitSize, 8, 8); 1963 else if (ShuffleKind == 0) // normal 1964 return isVMerge(N, UnitSize, 8, 24); 1965 else 1966 return false; 1967 } 1968 } 1969 1970 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1971 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1972 /// The ShuffleKind distinguishes between big-endian merges with two 1973 /// different inputs (0), either-endian merges with two identical inputs (1), 1974 /// and little-endian merges with two different inputs (2). For the latter, 1975 /// the input operands are swapped (see PPCInstrAltivec.td). 1976 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1977 unsigned ShuffleKind, SelectionDAG &DAG) { 1978 if (DAG.getDataLayout().isLittleEndian()) { 1979 if (ShuffleKind == 1) // unary 1980 return isVMerge(N, UnitSize, 8, 8); 1981 else if (ShuffleKind == 2) // swapped 1982 return isVMerge(N, UnitSize, 8, 24); 1983 else 1984 return false; 1985 } else { 1986 if (ShuffleKind == 1) // unary 1987 return isVMerge(N, UnitSize, 0, 0); 1988 else if (ShuffleKind == 0) // normal 1989 return isVMerge(N, UnitSize, 0, 16); 1990 else 1991 return false; 1992 } 1993 } 1994 1995 /** 1996 * Common function used to match vmrgew and vmrgow shuffles 1997 * 1998 * The indexOffset determines whether to look for even or odd words in 1999 * the shuffle mask. This is based on the of the endianness of the target 2000 * machine. 2001 * - Little Endian: 2002 * - Use offset of 0 to check for odd elements 2003 * - Use offset of 4 to check for even elements 2004 * - Big Endian: 2005 * - Use offset of 0 to check for even elements 2006 * - Use offset of 4 to check for odd elements 2007 * A detailed description of the vector element ordering for little endian and 2008 * big endian can be found at 2009 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 2010 * Targeting your applications - what little endian and big endian IBM XL C/C++ 2011 * compiler differences mean to you 2012 * 2013 * The mask to the shuffle vector instruction specifies the indices of the 2014 * elements from the two input vectors to place in the result. The elements are 2015 * numbered in array-access order, starting with the first vector. These vectors 2016 * are always of type v16i8, thus each vector will contain 16 elements of size 2017 * 8. More info on the shuffle vector can be found in the 2018 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 2019 * Language Reference. 2020 * 2021 * The RHSStartValue indicates whether the same input vectors are used (unary) 2022 * or two different input vectors are used, based on the following: 2023 * - If the instruction uses the same vector for both inputs, the range of the 2024 * indices will be 0 to 15. In this case, the RHSStart value passed should 2025 * be 0. 2026 * - If the instruction has two different vectors then the range of the 2027 * indices will be 0 to 31. In this case, the RHSStart value passed should 2028 * be 16 (indices 0-15 specify elements in the first vector while indices 16 2029 * to 31 specify elements in the second vector). 2030 * 2031 * \param[in] N The shuffle vector SD Node to analyze 2032 * \param[in] IndexOffset Specifies whether to look for even or odd elements 2033 * \param[in] RHSStartValue Specifies the starting index for the righthand input 2034 * vector to the shuffle_vector instruction 2035 * \return true iff this shuffle vector represents an even or odd word merge 2036 */ 2037 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 2038 unsigned RHSStartValue) { 2039 if (N->getValueType(0) != MVT::v16i8) 2040 return false; 2041 2042 for (unsigned i = 0; i < 2; ++i) 2043 for (unsigned j = 0; j < 4; ++j) 2044 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 2045 i*RHSStartValue+j+IndexOffset) || 2046 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 2047 i*RHSStartValue+j+IndexOffset+8)) 2048 return false; 2049 return true; 2050 } 2051 2052 /** 2053 * Determine if the specified shuffle mask is suitable for the vmrgew or 2054 * vmrgow instructions. 2055 * 2056 * \param[in] N The shuffle vector SD Node to analyze 2057 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 2058 * \param[in] ShuffleKind Identify the type of merge: 2059 * - 0 = big-endian merge with two different inputs; 2060 * - 1 = either-endian merge with two identical inputs; 2061 * - 2 = little-endian merge with two different inputs (inputs are swapped for 2062 * little-endian merges). 2063 * \param[in] DAG The current SelectionDAG 2064 * \return true iff this shuffle mask 2065 */ 2066 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 2067 unsigned ShuffleKind, SelectionDAG &DAG) { 2068 if (DAG.getDataLayout().isLittleEndian()) { 2069 unsigned indexOffset = CheckEven ? 4 : 0; 2070 if (ShuffleKind == 1) // Unary 2071 return isVMerge(N, indexOffset, 0); 2072 else if (ShuffleKind == 2) // swapped 2073 return isVMerge(N, indexOffset, 16); 2074 else 2075 return false; 2076 } 2077 else { 2078 unsigned indexOffset = CheckEven ? 0 : 4; 2079 if (ShuffleKind == 1) // Unary 2080 return isVMerge(N, indexOffset, 0); 2081 else if (ShuffleKind == 0) // Normal 2082 return isVMerge(N, indexOffset, 16); 2083 else 2084 return false; 2085 } 2086 return false; 2087 } 2088 2089 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 2090 /// amount, otherwise return -1. 2091 /// The ShuffleKind distinguishes between big-endian operations with two 2092 /// different inputs (0), either-endian operations with two identical inputs 2093 /// (1), and little-endian operations with two different inputs (2). For the 2094 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 2095 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 2096 SelectionDAG &DAG) { 2097 if (N->getValueType(0) != MVT::v16i8) 2098 return -1; 2099 2100 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2101 2102 // Find the first non-undef value in the shuffle mask. 2103 unsigned i; 2104 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 2105 /*search*/; 2106 2107 if (i == 16) return -1; // all undef. 2108 2109 // Otherwise, check to see if the rest of the elements are consecutively 2110 // numbered from this value. 2111 unsigned ShiftAmt = SVOp->getMaskElt(i); 2112 if (ShiftAmt < i) return -1; 2113 2114 ShiftAmt -= i; 2115 bool isLE = DAG.getDataLayout().isLittleEndian(); 2116 2117 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 2118 // Check the rest of the elements to see if they are consecutive. 2119 for (++i; i != 16; ++i) 2120 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2121 return -1; 2122 } else if (ShuffleKind == 1) { 2123 // Check the rest of the elements to see if they are consecutive. 2124 for (++i; i != 16; ++i) 2125 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 2126 return -1; 2127 } else 2128 return -1; 2129 2130 if (isLE) 2131 ShiftAmt = 16 - ShiftAmt; 2132 2133 return ShiftAmt; 2134 } 2135 2136 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 2137 /// specifies a splat of a single element that is suitable for input to 2138 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 2139 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 2140 EVT VT = N->getValueType(0); 2141 if (VT == MVT::v2i64 || VT == MVT::v2f64) 2142 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1); 2143 2144 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) && 2145 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2146 2147 // The consecutive indices need to specify an element, not part of two 2148 // different elements. So abandon ship early if this isn't the case. 2149 if (N->getMaskElt(0) % EltSize != 0) 2150 return false; 2151 2152 // This is a splat operation if each element of the permute is the same, and 2153 // if the value doesn't reference the second vector. 2154 unsigned ElementBase = N->getMaskElt(0); 2155 2156 // FIXME: Handle UNDEF elements too! 2157 if (ElementBase >= 16) 2158 return false; 2159 2160 // Check that the indices are consecutive, in the case of a multi-byte element 2161 // splatted with a v16i8 mask. 2162 for (unsigned i = 1; i != EltSize; ++i) 2163 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2164 return false; 2165 2166 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2167 if (N->getMaskElt(i) < 0) continue; 2168 for (unsigned j = 0; j != EltSize; ++j) 2169 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2170 return false; 2171 } 2172 return true; 2173 } 2174 2175 /// Check that the mask is shuffling N byte elements. Within each N byte 2176 /// element of the mask, the indices could be either in increasing or 2177 /// decreasing order as long as they are consecutive. 2178 /// \param[in] N the shuffle vector SD Node to analyze 2179 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2180 /// Word/DoubleWord/QuadWord). 2181 /// \param[in] StepLen the delta indices number among the N byte element, if 2182 /// the mask is in increasing/decreasing order then it is 1/-1. 2183 /// \return true iff the mask is shuffling N byte elements. 2184 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2185 int StepLen) { 2186 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2187 "Unexpected element width."); 2188 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2189 2190 unsigned NumOfElem = 16 / Width; 2191 unsigned MaskVal[16]; // Width is never greater than 16 2192 for (unsigned i = 0; i < NumOfElem; ++i) { 2193 MaskVal[0] = N->getMaskElt(i * Width); 2194 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2195 return false; 2196 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2197 return false; 2198 } 2199 2200 for (unsigned int j = 1; j < Width; ++j) { 2201 MaskVal[j] = N->getMaskElt(i * Width + j); 2202 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2203 return false; 2204 } 2205 } 2206 } 2207 2208 return true; 2209 } 2210 2211 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2212 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2213 if (!isNByteElemShuffleMask(N, 4, 1)) 2214 return false; 2215 2216 // Now we look at mask elements 0,4,8,12 2217 unsigned M0 = N->getMaskElt(0) / 4; 2218 unsigned M1 = N->getMaskElt(4) / 4; 2219 unsigned M2 = N->getMaskElt(8) / 4; 2220 unsigned M3 = N->getMaskElt(12) / 4; 2221 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2222 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2223 2224 // Below, let H and L be arbitrary elements of the shuffle mask 2225 // where H is in the range [4,7] and L is in the range [0,3]. 2226 // H, 1, 2, 3 or L, 5, 6, 7 2227 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2228 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2229 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2230 InsertAtByte = IsLE ? 12 : 0; 2231 Swap = M0 < 4; 2232 return true; 2233 } 2234 // 0, H, 2, 3 or 4, L, 6, 7 2235 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2236 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2237 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2238 InsertAtByte = IsLE ? 8 : 4; 2239 Swap = M1 < 4; 2240 return true; 2241 } 2242 // 0, 1, H, 3 or 4, 5, L, 7 2243 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2244 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2245 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2246 InsertAtByte = IsLE ? 4 : 8; 2247 Swap = M2 < 4; 2248 return true; 2249 } 2250 // 0, 1, 2, H or 4, 5, 6, L 2251 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2252 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2253 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2254 InsertAtByte = IsLE ? 0 : 12; 2255 Swap = M3 < 4; 2256 return true; 2257 } 2258 2259 // If both vector operands for the shuffle are the same vector, the mask will 2260 // contain only elements from the first one and the second one will be undef. 2261 if (N->getOperand(1).isUndef()) { 2262 ShiftElts = 0; 2263 Swap = true; 2264 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2265 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2266 InsertAtByte = IsLE ? 12 : 0; 2267 return true; 2268 } 2269 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2270 InsertAtByte = IsLE ? 8 : 4; 2271 return true; 2272 } 2273 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2274 InsertAtByte = IsLE ? 4 : 8; 2275 return true; 2276 } 2277 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2278 InsertAtByte = IsLE ? 0 : 12; 2279 return true; 2280 } 2281 } 2282 2283 return false; 2284 } 2285 2286 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2287 bool &Swap, bool IsLE) { 2288 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2289 // Ensure each byte index of the word is consecutive. 2290 if (!isNByteElemShuffleMask(N, 4, 1)) 2291 return false; 2292 2293 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2294 unsigned M0 = N->getMaskElt(0) / 4; 2295 unsigned M1 = N->getMaskElt(4) / 4; 2296 unsigned M2 = N->getMaskElt(8) / 4; 2297 unsigned M3 = N->getMaskElt(12) / 4; 2298 2299 // If both vector operands for the shuffle are the same vector, the mask will 2300 // contain only elements from the first one and the second one will be undef. 2301 if (N->getOperand(1).isUndef()) { 2302 assert(M0 < 4 && "Indexing into an undef vector?"); 2303 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2304 return false; 2305 2306 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2307 Swap = false; 2308 return true; 2309 } 2310 2311 // Ensure each word index of the ShuffleVector Mask is consecutive. 2312 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2313 return false; 2314 2315 if (IsLE) { 2316 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2317 // Input vectors don't need to be swapped if the leading element 2318 // of the result is one of the 3 left elements of the second vector 2319 // (or if there is no shift to be done at all). 2320 Swap = false; 2321 ShiftElts = (8 - M0) % 8; 2322 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2323 // Input vectors need to be swapped if the leading element 2324 // of the result is one of the 3 left elements of the first vector 2325 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2326 Swap = true; 2327 ShiftElts = (4 - M0) % 4; 2328 } 2329 2330 return true; 2331 } else { // BE 2332 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2333 // Input vectors don't need to be swapped if the leading element 2334 // of the result is one of the 4 elements of the first vector. 2335 Swap = false; 2336 ShiftElts = M0; 2337 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2338 // Input vectors need to be swapped if the leading element 2339 // of the result is one of the 4 elements of the right vector. 2340 Swap = true; 2341 ShiftElts = M0 - 4; 2342 } 2343 2344 return true; 2345 } 2346 } 2347 2348 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2349 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2350 2351 if (!isNByteElemShuffleMask(N, Width, -1)) 2352 return false; 2353 2354 for (int i = 0; i < 16; i += Width) 2355 if (N->getMaskElt(i) != i + Width - 1) 2356 return false; 2357 2358 return true; 2359 } 2360 2361 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2362 return isXXBRShuffleMaskHelper(N, 2); 2363 } 2364 2365 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2366 return isXXBRShuffleMaskHelper(N, 4); 2367 } 2368 2369 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2370 return isXXBRShuffleMaskHelper(N, 8); 2371 } 2372 2373 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2374 return isXXBRShuffleMaskHelper(N, 16); 2375 } 2376 2377 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2378 /// if the inputs to the instruction should be swapped and set \p DM to the 2379 /// value for the immediate. 2380 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2381 /// AND element 0 of the result comes from the first input (LE) or second input 2382 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2383 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2384 /// mask. 2385 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2386 bool &Swap, bool IsLE) { 2387 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2388 2389 // Ensure each byte index of the double word is consecutive. 2390 if (!isNByteElemShuffleMask(N, 8, 1)) 2391 return false; 2392 2393 unsigned M0 = N->getMaskElt(0) / 8; 2394 unsigned M1 = N->getMaskElt(8) / 8; 2395 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2396 2397 // If both vector operands for the shuffle are the same vector, the mask will 2398 // contain only elements from the first one and the second one will be undef. 2399 if (N->getOperand(1).isUndef()) { 2400 if ((M0 | M1) < 2) { 2401 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2402 Swap = false; 2403 return true; 2404 } else 2405 return false; 2406 } 2407 2408 if (IsLE) { 2409 if (M0 > 1 && M1 < 2) { 2410 Swap = false; 2411 } else if (M0 < 2 && M1 > 1) { 2412 M0 = (M0 + 2) % 4; 2413 M1 = (M1 + 2) % 4; 2414 Swap = true; 2415 } else 2416 return false; 2417 2418 // Note: if control flow comes here that means Swap is already set above 2419 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2420 return true; 2421 } else { // BE 2422 if (M0 < 2 && M1 > 1) { 2423 Swap = false; 2424 } else if (M0 > 1 && M1 < 2) { 2425 M0 = (M0 + 2) % 4; 2426 M1 = (M1 + 2) % 4; 2427 Swap = true; 2428 } else 2429 return false; 2430 2431 // Note: if control flow comes here that means Swap is already set above 2432 DM = (M0 << 1) + (M1 & 1); 2433 return true; 2434 } 2435 } 2436 2437 2438 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2439 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2440 /// elements are counted from the left of the vector register). 2441 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2442 SelectionDAG &DAG) { 2443 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2444 assert(isSplatShuffleMask(SVOp, EltSize)); 2445 EVT VT = SVOp->getValueType(0); 2446 2447 if (VT == MVT::v2i64 || VT == MVT::v2f64) 2448 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0) 2449 : SVOp->getMaskElt(0); 2450 2451 if (DAG.getDataLayout().isLittleEndian()) 2452 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2453 else 2454 return SVOp->getMaskElt(0) / EltSize; 2455 } 2456 2457 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2458 /// by using a vspltis[bhw] instruction of the specified element size, return 2459 /// the constant being splatted. The ByteSize field indicates the number of 2460 /// bytes of each element [124] -> [bhw]. 2461 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2462 SDValue OpVal; 2463 2464 // If ByteSize of the splat is bigger than the element size of the 2465 // build_vector, then we have a case where we are checking for a splat where 2466 // multiple elements of the buildvector are folded together into a single 2467 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2468 unsigned EltSize = 16/N->getNumOperands(); 2469 if (EltSize < ByteSize) { 2470 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2471 SDValue UniquedVals[4]; 2472 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2473 2474 // See if all of the elements in the buildvector agree across. 2475 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2476 if (N->getOperand(i).isUndef()) continue; 2477 // If the element isn't a constant, bail fully out. 2478 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2479 2480 if (!UniquedVals[i&(Multiple-1)].getNode()) 2481 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2482 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2483 return SDValue(); // no match. 2484 } 2485 2486 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2487 // either constant or undef values that are identical for each chunk. See 2488 // if these chunks can form into a larger vspltis*. 2489 2490 // Check to see if all of the leading entries are either 0 or -1. If 2491 // neither, then this won't fit into the immediate field. 2492 bool LeadingZero = true; 2493 bool LeadingOnes = true; 2494 for (unsigned i = 0; i != Multiple-1; ++i) { 2495 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2496 2497 LeadingZero &= isNullConstant(UniquedVals[i]); 2498 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2499 } 2500 // Finally, check the least significant entry. 2501 if (LeadingZero) { 2502 if (!UniquedVals[Multiple-1].getNode()) 2503 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2504 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2505 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2506 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2507 } 2508 if (LeadingOnes) { 2509 if (!UniquedVals[Multiple-1].getNode()) 2510 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2511 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2512 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2513 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2514 } 2515 2516 return SDValue(); 2517 } 2518 2519 // Check to see if this buildvec has a single non-undef value in its elements. 2520 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2521 if (N->getOperand(i).isUndef()) continue; 2522 if (!OpVal.getNode()) 2523 OpVal = N->getOperand(i); 2524 else if (OpVal != N->getOperand(i)) 2525 return SDValue(); 2526 } 2527 2528 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2529 2530 unsigned ValSizeInBytes = EltSize; 2531 uint64_t Value = 0; 2532 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2533 Value = CN->getZExtValue(); 2534 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2535 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2536 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2537 } 2538 2539 // If the splat value is larger than the element value, then we can never do 2540 // this splat. The only case that we could fit the replicated bits into our 2541 // immediate field for would be zero, and we prefer to use vxor for it. 2542 if (ValSizeInBytes < ByteSize) return SDValue(); 2543 2544 // If the element value is larger than the splat value, check if it consists 2545 // of a repeated bit pattern of size ByteSize. 2546 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2547 return SDValue(); 2548 2549 // Properly sign extend the value. 2550 int MaskVal = SignExtend32(Value, ByteSize * 8); 2551 2552 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2553 if (MaskVal == 0) return SDValue(); 2554 2555 // Finally, if this value fits in a 5 bit sext field, return it 2556 if (SignExtend32<5>(MaskVal) == MaskVal) 2557 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2558 return SDValue(); 2559 } 2560 2561 //===----------------------------------------------------------------------===// 2562 // Addressing Mode Selection 2563 //===----------------------------------------------------------------------===// 2564 2565 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2566 /// or 64-bit immediate, and if the value can be accurately represented as a 2567 /// sign extension from a 16-bit value. If so, this returns true and the 2568 /// immediate. 2569 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2570 if (!isa<ConstantSDNode>(N)) 2571 return false; 2572 2573 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2574 if (N->getValueType(0) == MVT::i32) 2575 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2576 else 2577 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2578 } 2579 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2580 return isIntS16Immediate(Op.getNode(), Imm); 2581 } 2582 2583 /// Used when computing address flags for selecting loads and stores. 2584 /// If we have an OR, check if the LHS and RHS are provably disjoint. 2585 /// An OR of two provably disjoint values is equivalent to an ADD. 2586 /// Most PPC load/store instructions compute the effective address as a sum, 2587 /// so doing this conversion is useful. 2588 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) { 2589 if (N.getOpcode() != ISD::OR) 2590 return false; 2591 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2592 if (!LHSKnown.Zero.getBoolValue()) 2593 return false; 2594 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2595 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0); 2596 } 2597 2598 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2599 /// be represented as an indexed [r+r] operation. 2600 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2601 SDValue &Index, 2602 SelectionDAG &DAG) const { 2603 for (SDNode *U : N->uses()) { 2604 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) { 2605 if (Memop->getMemoryVT() == MVT::f64) { 2606 Base = N.getOperand(0); 2607 Index = N.getOperand(1); 2608 return true; 2609 } 2610 } 2611 } 2612 return false; 2613 } 2614 2615 /// isIntS34Immediate - This method tests if value of node given can be 2616 /// accurately represented as a sign extension from a 34-bit value. If so, 2617 /// this returns true and the immediate. 2618 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2619 if (!isa<ConstantSDNode>(N)) 2620 return false; 2621 2622 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2623 return isInt<34>(Imm); 2624 } 2625 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2626 return isIntS34Immediate(Op.getNode(), Imm); 2627 } 2628 2629 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2630 /// can be represented as an indexed [r+r] operation. Returns false if it 2631 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2632 /// non-zero and N can be represented by a base register plus a signed 16-bit 2633 /// displacement, make a more precise judgement by checking (displacement % \p 2634 /// EncodingAlignment). 2635 bool PPCTargetLowering::SelectAddressRegReg( 2636 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2637 MaybeAlign EncodingAlignment) const { 2638 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2639 // a [pc+imm]. 2640 if (SelectAddressPCRel(N, Base)) 2641 return false; 2642 2643 int16_t Imm = 0; 2644 if (N.getOpcode() == ISD::ADD) { 2645 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2646 // SPE load/store can only handle 8-bit offsets. 2647 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2648 return true; 2649 if (isIntS16Immediate(N.getOperand(1), Imm) && 2650 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2651 return false; // r+i 2652 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2653 return false; // r+i 2654 2655 Base = N.getOperand(0); 2656 Index = N.getOperand(1); 2657 return true; 2658 } else if (N.getOpcode() == ISD::OR) { 2659 if (isIntS16Immediate(N.getOperand(1), Imm) && 2660 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2661 return false; // r+i can fold it if we can. 2662 2663 // If this is an or of disjoint bitfields, we can codegen this as an add 2664 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2665 // disjoint. 2666 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2667 2668 if (LHSKnown.Zero.getBoolValue()) { 2669 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2670 // If all of the bits are known zero on the LHS or RHS, the add won't 2671 // carry. 2672 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2673 Base = N.getOperand(0); 2674 Index = N.getOperand(1); 2675 return true; 2676 } 2677 } 2678 } 2679 2680 return false; 2681 } 2682 2683 // If we happen to be doing an i64 load or store into a stack slot that has 2684 // less than a 4-byte alignment, then the frame-index elimination may need to 2685 // use an indexed load or store instruction (because the offset may not be a 2686 // multiple of 4). The extra register needed to hold the offset comes from the 2687 // register scavenger, and it is possible that the scavenger will need to use 2688 // an emergency spill slot. As a result, we need to make sure that a spill slot 2689 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2690 // stack slot. 2691 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2692 // FIXME: This does not handle the LWA case. 2693 if (VT != MVT::i64) 2694 return; 2695 2696 // NOTE: We'll exclude negative FIs here, which come from argument 2697 // lowering, because there are no known test cases triggering this problem 2698 // using packed structures (or similar). We can remove this exclusion if 2699 // we find such a test case. The reason why this is so test-case driven is 2700 // because this entire 'fixup' is only to prevent crashes (from the 2701 // register scavenger) on not-really-valid inputs. For example, if we have: 2702 // %a = alloca i1 2703 // %b = bitcast i1* %a to i64* 2704 // store i64* a, i64 b 2705 // then the store should really be marked as 'align 1', but is not. If it 2706 // were marked as 'align 1' then the indexed form would have been 2707 // instruction-selected initially, and the problem this 'fixup' is preventing 2708 // won't happen regardless. 2709 if (FrameIdx < 0) 2710 return; 2711 2712 MachineFunction &MF = DAG.getMachineFunction(); 2713 MachineFrameInfo &MFI = MF.getFrameInfo(); 2714 2715 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2716 return; 2717 2718 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2719 FuncInfo->setHasNonRISpills(); 2720 } 2721 2722 /// Returns true if the address N can be represented by a base register plus 2723 /// a signed 16-bit displacement [r+imm], and if it is not better 2724 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2725 /// displacements that are multiples of that value. 2726 bool PPCTargetLowering::SelectAddressRegImm( 2727 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2728 MaybeAlign EncodingAlignment) const { 2729 // FIXME dl should come from parent load or store, not from address 2730 SDLoc dl(N); 2731 2732 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2733 // a [pc+imm]. 2734 if (SelectAddressPCRel(N, Base)) 2735 return false; 2736 2737 // If this can be more profitably realized as r+r, fail. 2738 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2739 return false; 2740 2741 if (N.getOpcode() == ISD::ADD) { 2742 int16_t imm = 0; 2743 if (isIntS16Immediate(N.getOperand(1), imm) && 2744 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2745 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2746 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2747 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2748 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2749 } else { 2750 Base = N.getOperand(0); 2751 } 2752 return true; // [r+i] 2753 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2754 // Match LOAD (ADD (X, Lo(G))). 2755 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2756 && "Cannot handle constant offsets yet!"); 2757 Disp = N.getOperand(1).getOperand(0); // The global address. 2758 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2759 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2760 Disp.getOpcode() == ISD::TargetConstantPool || 2761 Disp.getOpcode() == ISD::TargetJumpTable); 2762 Base = N.getOperand(0); 2763 return true; // [&g+r] 2764 } 2765 } else if (N.getOpcode() == ISD::OR) { 2766 int16_t imm = 0; 2767 if (isIntS16Immediate(N.getOperand(1), imm) && 2768 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2769 // If this is an or of disjoint bitfields, we can codegen this as an add 2770 // (for better address arithmetic) if the LHS and RHS of the OR are 2771 // provably disjoint. 2772 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2773 2774 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2775 // If all of the bits are known zero on the LHS or RHS, the add won't 2776 // carry. 2777 if (FrameIndexSDNode *FI = 2778 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2779 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2780 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2781 } else { 2782 Base = N.getOperand(0); 2783 } 2784 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2785 return true; 2786 } 2787 } 2788 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2789 // Loading from a constant address. 2790 2791 // If this address fits entirely in a 16-bit sext immediate field, codegen 2792 // this as "d, 0" 2793 int16_t Imm; 2794 if (isIntS16Immediate(CN, Imm) && 2795 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2796 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2797 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2798 CN->getValueType(0)); 2799 return true; 2800 } 2801 2802 // Handle 32-bit sext immediates with LIS + addr mode. 2803 if ((CN->getValueType(0) == MVT::i32 || 2804 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2805 (!EncodingAlignment || 2806 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2807 int Addr = (int)CN->getZExtValue(); 2808 2809 // Otherwise, break this down into an LIS + disp. 2810 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2811 2812 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2813 MVT::i32); 2814 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2815 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2816 return true; 2817 } 2818 } 2819 2820 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2821 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2822 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2823 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2824 } else 2825 Base = N; 2826 return true; // [r+0] 2827 } 2828 2829 /// Similar to the 16-bit case but for instructions that take a 34-bit 2830 /// displacement field (prefixed loads/stores). 2831 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2832 SDValue &Base, 2833 SelectionDAG &DAG) const { 2834 // Only on 64-bit targets. 2835 if (N.getValueType() != MVT::i64) 2836 return false; 2837 2838 SDLoc dl(N); 2839 int64_t Imm = 0; 2840 2841 if (N.getOpcode() == ISD::ADD) { 2842 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2843 return false; 2844 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2845 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2846 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2847 else 2848 Base = N.getOperand(0); 2849 return true; 2850 } 2851 2852 if (N.getOpcode() == ISD::OR) { 2853 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2854 return false; 2855 // If this is an or of disjoint bitfields, we can codegen this as an add 2856 // (for better address arithmetic) if the LHS and RHS of the OR are 2857 // provably disjoint. 2858 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2859 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2860 return false; 2861 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2862 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2863 else 2864 Base = N.getOperand(0); 2865 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2866 return true; 2867 } 2868 2869 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2870 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2871 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2872 return true; 2873 } 2874 2875 return false; 2876 } 2877 2878 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2879 /// represented as an indexed [r+r] operation. 2880 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2881 SDValue &Index, 2882 SelectionDAG &DAG) const { 2883 // Check to see if we can easily represent this as an [r+r] address. This 2884 // will fail if it thinks that the address is more profitably represented as 2885 // reg+imm, e.g. where imm = 0. 2886 if (SelectAddressRegReg(N, Base, Index, DAG)) 2887 return true; 2888 2889 // If the address is the result of an add, we will utilize the fact that the 2890 // address calculation includes an implicit add. However, we can reduce 2891 // register pressure if we do not materialize a constant just for use as the 2892 // index register. We only get rid of the add if it is not an add of a 2893 // value and a 16-bit signed constant and both have a single use. 2894 int16_t imm = 0; 2895 if (N.getOpcode() == ISD::ADD && 2896 (!isIntS16Immediate(N.getOperand(1), imm) || 2897 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2898 Base = N.getOperand(0); 2899 Index = N.getOperand(1); 2900 return true; 2901 } 2902 2903 // Otherwise, do it the hard way, using R0 as the base register. 2904 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2905 N.getValueType()); 2906 Index = N; 2907 return true; 2908 } 2909 2910 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2911 Ty *PCRelCand = dyn_cast<Ty>(N); 2912 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2913 } 2914 2915 /// Returns true if this address is a PC Relative address. 2916 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2917 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2918 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2919 // This is a materialize PC Relative node. Always select this as PC Relative. 2920 Base = N; 2921 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2922 return true; 2923 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2924 isValidPCRelNode<GlobalAddressSDNode>(N) || 2925 isValidPCRelNode<JumpTableSDNode>(N) || 2926 isValidPCRelNode<BlockAddressSDNode>(N)) 2927 return true; 2928 return false; 2929 } 2930 2931 /// Returns true if we should use a direct load into vector instruction 2932 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2933 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2934 2935 // If there are any other uses other than scalar to vector, then we should 2936 // keep it as a scalar load -> direct move pattern to prevent multiple 2937 // loads. 2938 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2939 if (!LD) 2940 return false; 2941 2942 EVT MemVT = LD->getMemoryVT(); 2943 if (!MemVT.isSimple()) 2944 return false; 2945 switch(MemVT.getSimpleVT().SimpleTy) { 2946 case MVT::i64: 2947 break; 2948 case MVT::i32: 2949 if (!ST.hasP8Vector()) 2950 return false; 2951 break; 2952 case MVT::i16: 2953 case MVT::i8: 2954 if (!ST.hasP9Vector()) 2955 return false; 2956 break; 2957 default: 2958 return false; 2959 } 2960 2961 SDValue LoadedVal(N, 0); 2962 if (!LoadedVal.hasOneUse()) 2963 return false; 2964 2965 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2966 UI != UE; ++UI) 2967 if (UI.getUse().get().getResNo() == 0 && 2968 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2969 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2970 return false; 2971 2972 return true; 2973 } 2974 2975 /// getPreIndexedAddressParts - returns true by value, base pointer and 2976 /// offset pointer and addressing mode by reference if the node's address 2977 /// can be legally represented as pre-indexed load / store address. 2978 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2979 SDValue &Offset, 2980 ISD::MemIndexedMode &AM, 2981 SelectionDAG &DAG) const { 2982 if (DisablePPCPreinc) return false; 2983 2984 bool isLoad = true; 2985 SDValue Ptr; 2986 EVT VT; 2987 unsigned Alignment; 2988 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2989 Ptr = LD->getBasePtr(); 2990 VT = LD->getMemoryVT(); 2991 Alignment = LD->getAlignment(); 2992 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2993 Ptr = ST->getBasePtr(); 2994 VT = ST->getMemoryVT(); 2995 Alignment = ST->getAlignment(); 2996 isLoad = false; 2997 } else 2998 return false; 2999 3000 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 3001 // instructions because we can fold these into a more efficient instruction 3002 // instead, (such as LXSD). 3003 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 3004 return false; 3005 } 3006 3007 // PowerPC doesn't have preinc load/store instructions for vectors 3008 if (VT.isVector()) 3009 return false; 3010 3011 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 3012 // Common code will reject creating a pre-inc form if the base pointer 3013 // is a frame index, or if N is a store and the base pointer is either 3014 // the same as or a predecessor of the value being stored. Check for 3015 // those situations here, and try with swapped Base/Offset instead. 3016 bool Swap = false; 3017 3018 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 3019 Swap = true; 3020 else if (!isLoad) { 3021 SDValue Val = cast<StoreSDNode>(N)->getValue(); 3022 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 3023 Swap = true; 3024 } 3025 3026 if (Swap) 3027 std::swap(Base, Offset); 3028 3029 AM = ISD::PRE_INC; 3030 return true; 3031 } 3032 3033 // LDU/STU can only handle immediates that are a multiple of 4. 3034 if (VT != MVT::i64) { 3035 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 3036 return false; 3037 } else { 3038 // LDU/STU need an address with at least 4-byte alignment. 3039 if (Alignment < 4) 3040 return false; 3041 3042 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 3043 return false; 3044 } 3045 3046 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 3047 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 3048 // sext i32 to i64 when addr mode is r+i. 3049 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 3050 LD->getExtensionType() == ISD::SEXTLOAD && 3051 isa<ConstantSDNode>(Offset)) 3052 return false; 3053 } 3054 3055 AM = ISD::PRE_INC; 3056 return true; 3057 } 3058 3059 //===----------------------------------------------------------------------===// 3060 // LowerOperation implementation 3061 //===----------------------------------------------------------------------===// 3062 3063 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 3064 /// and LoOpFlags to the target MO flags. 3065 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 3066 unsigned &HiOpFlags, unsigned &LoOpFlags, 3067 const GlobalValue *GV = nullptr) { 3068 HiOpFlags = PPCII::MO_HA; 3069 LoOpFlags = PPCII::MO_LO; 3070 3071 // Don't use the pic base if not in PIC relocation model. 3072 if (IsPIC) { 3073 HiOpFlags |= PPCII::MO_PIC_FLAG; 3074 LoOpFlags |= PPCII::MO_PIC_FLAG; 3075 } 3076 } 3077 3078 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 3079 SelectionDAG &DAG) { 3080 SDLoc DL(HiPart); 3081 EVT PtrVT = HiPart.getValueType(); 3082 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 3083 3084 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 3085 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 3086 3087 // With PIC, the first instruction is actually "GR+hi(&G)". 3088 if (isPIC) 3089 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 3090 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 3091 3092 // Generate non-pic code that has direct accesses to the constant pool. 3093 // The address of the global is just (hi(&g)+lo(&g)). 3094 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 3095 } 3096 3097 static void setUsesTOCBasePtr(MachineFunction &MF) { 3098 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3099 FuncInfo->setUsesTOCBasePtr(); 3100 } 3101 3102 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 3103 setUsesTOCBasePtr(DAG.getMachineFunction()); 3104 } 3105 3106 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 3107 SDValue GA) const { 3108 const bool Is64Bit = Subtarget.isPPC64(); 3109 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 3110 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 3111 : Subtarget.isAIXABI() 3112 ? DAG.getRegister(PPC::R2, VT) 3113 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 3114 SDValue Ops[] = { GA, Reg }; 3115 return DAG.getMemIntrinsicNode( 3116 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 3117 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 3118 MachineMemOperand::MOLoad); 3119 } 3120 3121 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 3122 SelectionDAG &DAG) const { 3123 EVT PtrVT = Op.getValueType(); 3124 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3125 const Constant *C = CP->getConstVal(); 3126 3127 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3128 // The actual address of the GlobalValue is stored in the TOC. 3129 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3130 if (Subtarget.isUsingPCRelativeCalls()) { 3131 SDLoc DL(CP); 3132 EVT Ty = getPointerTy(DAG.getDataLayout()); 3133 SDValue ConstPool = DAG.getTargetConstantPool( 3134 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 3135 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 3136 } 3137 setUsesTOCBasePtr(DAG); 3138 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 3139 return getTOCEntry(DAG, SDLoc(CP), GA); 3140 } 3141 3142 unsigned MOHiFlag, MOLoFlag; 3143 bool IsPIC = isPositionIndependent(); 3144 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3145 3146 if (IsPIC && Subtarget.isSVR4ABI()) { 3147 SDValue GA = 3148 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 3149 return getTOCEntry(DAG, SDLoc(CP), GA); 3150 } 3151 3152 SDValue CPIHi = 3153 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 3154 SDValue CPILo = 3155 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 3156 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 3157 } 3158 3159 // For 64-bit PowerPC, prefer the more compact relative encodings. 3160 // This trades 32 bits per jump table entry for one or two instructions 3161 // on the jump site. 3162 unsigned PPCTargetLowering::getJumpTableEncoding() const { 3163 if (isJumpTableRelative()) 3164 return MachineJumpTableInfo::EK_LabelDifference32; 3165 3166 return TargetLowering::getJumpTableEncoding(); 3167 } 3168 3169 bool PPCTargetLowering::isJumpTableRelative() const { 3170 if (UseAbsoluteJumpTables) 3171 return false; 3172 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3173 return true; 3174 return TargetLowering::isJumpTableRelative(); 3175 } 3176 3177 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3178 SelectionDAG &DAG) const { 3179 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3180 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3181 3182 switch (getTargetMachine().getCodeModel()) { 3183 case CodeModel::Small: 3184 case CodeModel::Medium: 3185 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3186 default: 3187 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3188 getPointerTy(DAG.getDataLayout())); 3189 } 3190 } 3191 3192 const MCExpr * 3193 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3194 unsigned JTI, 3195 MCContext &Ctx) const { 3196 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3197 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3198 3199 switch (getTargetMachine().getCodeModel()) { 3200 case CodeModel::Small: 3201 case CodeModel::Medium: 3202 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3203 default: 3204 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3205 } 3206 } 3207 3208 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3209 EVT PtrVT = Op.getValueType(); 3210 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3211 3212 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3213 if (Subtarget.isUsingPCRelativeCalls()) { 3214 SDLoc DL(JT); 3215 EVT Ty = getPointerTy(DAG.getDataLayout()); 3216 SDValue GA = 3217 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3218 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3219 return MatAddr; 3220 } 3221 3222 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3223 // The actual address of the GlobalValue is stored in the TOC. 3224 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3225 setUsesTOCBasePtr(DAG); 3226 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3227 return getTOCEntry(DAG, SDLoc(JT), GA); 3228 } 3229 3230 unsigned MOHiFlag, MOLoFlag; 3231 bool IsPIC = isPositionIndependent(); 3232 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3233 3234 if (IsPIC && Subtarget.isSVR4ABI()) { 3235 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3236 PPCII::MO_PIC_FLAG); 3237 return getTOCEntry(DAG, SDLoc(GA), GA); 3238 } 3239 3240 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3241 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3242 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3243 } 3244 3245 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3246 SelectionDAG &DAG) const { 3247 EVT PtrVT = Op.getValueType(); 3248 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3249 const BlockAddress *BA = BASDN->getBlockAddress(); 3250 3251 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3252 if (Subtarget.isUsingPCRelativeCalls()) { 3253 SDLoc DL(BASDN); 3254 EVT Ty = getPointerTy(DAG.getDataLayout()); 3255 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3256 PPCII::MO_PCREL_FLAG); 3257 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3258 return MatAddr; 3259 } 3260 3261 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3262 // The actual BlockAddress is stored in the TOC. 3263 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3264 setUsesTOCBasePtr(DAG); 3265 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3266 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3267 } 3268 3269 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3270 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3271 return getTOCEntry( 3272 DAG, SDLoc(BASDN), 3273 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3274 3275 unsigned MOHiFlag, MOLoFlag; 3276 bool IsPIC = isPositionIndependent(); 3277 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3278 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3279 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3280 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3281 } 3282 3283 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3284 SelectionDAG &DAG) const { 3285 if (Subtarget.isAIXABI()) 3286 return LowerGlobalTLSAddressAIX(Op, DAG); 3287 3288 return LowerGlobalTLSAddressLinux(Op, DAG); 3289 } 3290 3291 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3292 SelectionDAG &DAG) const { 3293 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3294 3295 if (DAG.getTarget().useEmulatedTLS()) 3296 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3297 3298 SDLoc dl(GA); 3299 const GlobalValue *GV = GA->getGlobal(); 3300 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3301 3302 // The general-dynamic model is the only access model supported for now, so 3303 // all the GlobalTLSAddress nodes are lowered with this model. 3304 // We need to generate two TOC entries, one for the variable offset, one for 3305 // the region handle. The global address for the TOC entry of the region 3306 // handle is created with the MO_TLSGDM_FLAG flag and the global address 3307 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG. 3308 SDValue VariableOffsetTGA = 3309 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3310 SDValue RegionHandleTGA = 3311 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG); 3312 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3313 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3314 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3315 RegionHandle); 3316 } 3317 3318 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3319 SelectionDAG &DAG) const { 3320 // FIXME: TLS addresses currently use medium model code sequences, 3321 // which is the most useful form. Eventually support for small and 3322 // large models could be added if users need it, at the cost of 3323 // additional complexity. 3324 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3325 if (DAG.getTarget().useEmulatedTLS()) 3326 return LowerToTLSEmulatedModel(GA, DAG); 3327 3328 SDLoc dl(GA); 3329 const GlobalValue *GV = GA->getGlobal(); 3330 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3331 bool is64bit = Subtarget.isPPC64(); 3332 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3333 PICLevel::Level picLevel = M->getPICLevel(); 3334 3335 const TargetMachine &TM = getTargetMachine(); 3336 TLSModel::Model Model = TM.getTLSModel(GV); 3337 3338 if (Model == TLSModel::LocalExec) { 3339 if (Subtarget.isUsingPCRelativeCalls()) { 3340 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3341 SDValue TGA = DAG.getTargetGlobalAddress( 3342 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3343 SDValue MatAddr = 3344 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3345 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3346 } 3347 3348 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3349 PPCII::MO_TPREL_HA); 3350 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3351 PPCII::MO_TPREL_LO); 3352 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3353 : DAG.getRegister(PPC::R2, MVT::i32); 3354 3355 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3356 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3357 } 3358 3359 if (Model == TLSModel::InitialExec) { 3360 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3361 SDValue TGA = DAG.getTargetGlobalAddress( 3362 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3363 SDValue TGATLS = DAG.getTargetGlobalAddress( 3364 GV, dl, PtrVT, 0, 3365 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3366 SDValue TPOffset; 3367 if (IsPCRel) { 3368 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3369 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3370 MachinePointerInfo()); 3371 } else { 3372 SDValue GOTPtr; 3373 if (is64bit) { 3374 setUsesTOCBasePtr(DAG); 3375 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3376 GOTPtr = 3377 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3378 } else { 3379 if (!TM.isPositionIndependent()) 3380 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3381 else if (picLevel == PICLevel::SmallPIC) 3382 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3383 else 3384 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3385 } 3386 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3387 } 3388 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3389 } 3390 3391 if (Model == TLSModel::GeneralDynamic) { 3392 if (Subtarget.isUsingPCRelativeCalls()) { 3393 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3394 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3395 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3396 } 3397 3398 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3399 SDValue GOTPtr; 3400 if (is64bit) { 3401 setUsesTOCBasePtr(DAG); 3402 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3403 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3404 GOTReg, TGA); 3405 } else { 3406 if (picLevel == PICLevel::SmallPIC) 3407 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3408 else 3409 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3410 } 3411 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3412 GOTPtr, TGA, TGA); 3413 } 3414 3415 if (Model == TLSModel::LocalDynamic) { 3416 if (Subtarget.isUsingPCRelativeCalls()) { 3417 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3418 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3419 SDValue MatPCRel = 3420 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3421 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3422 } 3423 3424 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3425 SDValue GOTPtr; 3426 if (is64bit) { 3427 setUsesTOCBasePtr(DAG); 3428 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3429 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3430 GOTReg, TGA); 3431 } else { 3432 if (picLevel == PICLevel::SmallPIC) 3433 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3434 else 3435 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3436 } 3437 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3438 PtrVT, GOTPtr, TGA, TGA); 3439 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3440 PtrVT, TLSAddr, TGA); 3441 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3442 } 3443 3444 llvm_unreachable("Unknown TLS model!"); 3445 } 3446 3447 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3448 SelectionDAG &DAG) const { 3449 EVT PtrVT = Op.getValueType(); 3450 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3451 SDLoc DL(GSDN); 3452 const GlobalValue *GV = GSDN->getGlobal(); 3453 3454 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3455 // The actual address of the GlobalValue is stored in the TOC. 3456 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3457 if (Subtarget.isUsingPCRelativeCalls()) { 3458 EVT Ty = getPointerTy(DAG.getDataLayout()); 3459 if (isAccessedAsGotIndirect(Op)) { 3460 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3461 PPCII::MO_PCREL_FLAG | 3462 PPCII::MO_GOT_FLAG); 3463 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3464 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3465 MachinePointerInfo()); 3466 return Load; 3467 } else { 3468 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3469 PPCII::MO_PCREL_FLAG); 3470 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3471 } 3472 } 3473 setUsesTOCBasePtr(DAG); 3474 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3475 return getTOCEntry(DAG, DL, GA); 3476 } 3477 3478 unsigned MOHiFlag, MOLoFlag; 3479 bool IsPIC = isPositionIndependent(); 3480 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3481 3482 if (IsPIC && Subtarget.isSVR4ABI()) { 3483 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3484 GSDN->getOffset(), 3485 PPCII::MO_PIC_FLAG); 3486 return getTOCEntry(DAG, DL, GA); 3487 } 3488 3489 SDValue GAHi = 3490 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3491 SDValue GALo = 3492 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3493 3494 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3495 } 3496 3497 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3498 bool IsStrict = Op->isStrictFPOpcode(); 3499 ISD::CondCode CC = 3500 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get(); 3501 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0); 3502 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1); 3503 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 3504 EVT LHSVT = LHS.getValueType(); 3505 SDLoc dl(Op); 3506 3507 // Soften the setcc with libcall if it is fp128. 3508 if (LHSVT == MVT::f128) { 3509 assert(!Subtarget.hasP9Vector() && 3510 "SETCC for f128 is already legal under Power9!"); 3511 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain, 3512 Op->getOpcode() == ISD::STRICT_FSETCCS); 3513 if (RHS.getNode()) 3514 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS, 3515 DAG.getCondCode(CC)); 3516 if (IsStrict) 3517 return DAG.getMergeValues({LHS, Chain}, dl); 3518 return LHS; 3519 } 3520 3521 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!"); 3522 3523 if (Op.getValueType() == MVT::v2i64) { 3524 // When the operands themselves are v2i64 values, we need to do something 3525 // special because VSX has no underlying comparison operations for these. 3526 if (LHS.getValueType() == MVT::v2i64) { 3527 // Equality can be handled by casting to the legal type for Altivec 3528 // comparisons, everything else needs to be expanded. 3529 if (CC != ISD::SETEQ && CC != ISD::SETNE) 3530 return SDValue(); 3531 SDValue SetCC32 = DAG.getSetCC( 3532 dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS), 3533 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC); 3534 int ShuffV[] = {1, 0, 3, 2}; 3535 SDValue Shuff = 3536 DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV); 3537 return DAG.getBitcast(MVT::v2i64, 3538 DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR, 3539 dl, MVT::v4i32, Shuff, SetCC32)); 3540 } 3541 3542 // We handle most of these in the usual way. 3543 return Op; 3544 } 3545 3546 // If we're comparing for equality to zero, expose the fact that this is 3547 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3548 // fold the new nodes. 3549 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3550 return V; 3551 3552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 3553 // Leave comparisons against 0 and -1 alone for now, since they're usually 3554 // optimized. FIXME: revisit this when we can custom lower all setcc 3555 // optimizations. 3556 if (C->isAllOnes() || C->isZero()) 3557 return SDValue(); 3558 } 3559 3560 // If we have an integer seteq/setne, turn it into a compare against zero 3561 // by xor'ing the rhs with the lhs, which is faster than setting a 3562 // condition register, reading it back out, and masking the correct bit. The 3563 // normal approach here uses sub to do this instead of xor. Using xor exposes 3564 // the result to other bit-twiddling opportunities. 3565 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3566 EVT VT = Op.getValueType(); 3567 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS); 3568 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3569 } 3570 return SDValue(); 3571 } 3572 3573 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3574 SDNode *Node = Op.getNode(); 3575 EVT VT = Node->getValueType(0); 3576 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3577 SDValue InChain = Node->getOperand(0); 3578 SDValue VAListPtr = Node->getOperand(1); 3579 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3580 SDLoc dl(Node); 3581 3582 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3583 3584 // gpr_index 3585 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3586 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3587 InChain = GprIndex.getValue(1); 3588 3589 if (VT == MVT::i64) { 3590 // Check if GprIndex is even 3591 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3592 DAG.getConstant(1, dl, MVT::i32)); 3593 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3594 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3595 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3596 DAG.getConstant(1, dl, MVT::i32)); 3597 // Align GprIndex to be even if it isn't 3598 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3599 GprIndex); 3600 } 3601 3602 // fpr index is 1 byte after gpr 3603 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3604 DAG.getConstant(1, dl, MVT::i32)); 3605 3606 // fpr 3607 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3608 FprPtr, MachinePointerInfo(SV), MVT::i8); 3609 InChain = FprIndex.getValue(1); 3610 3611 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3612 DAG.getConstant(8, dl, MVT::i32)); 3613 3614 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3615 DAG.getConstant(4, dl, MVT::i32)); 3616 3617 // areas 3618 SDValue OverflowArea = 3619 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3620 InChain = OverflowArea.getValue(1); 3621 3622 SDValue RegSaveArea = 3623 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3624 InChain = RegSaveArea.getValue(1); 3625 3626 // select overflow_area if index > 8 3627 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3628 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3629 3630 // adjustment constant gpr_index * 4/8 3631 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3632 VT.isInteger() ? GprIndex : FprIndex, 3633 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3634 MVT::i32)); 3635 3636 // OurReg = RegSaveArea + RegConstant 3637 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3638 RegConstant); 3639 3640 // Floating types are 32 bytes into RegSaveArea 3641 if (VT.isFloatingPoint()) 3642 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3643 DAG.getConstant(32, dl, MVT::i32)); 3644 3645 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3646 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3647 VT.isInteger() ? GprIndex : FprIndex, 3648 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3649 MVT::i32)); 3650 3651 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3652 VT.isInteger() ? VAListPtr : FprPtr, 3653 MachinePointerInfo(SV), MVT::i8); 3654 3655 // determine if we should load from reg_save_area or overflow_area 3656 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3657 3658 // increase overflow_area by 4/8 if gpr/fpr > 8 3659 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3660 DAG.getConstant(VT.isInteger() ? 4 : 8, 3661 dl, MVT::i32)); 3662 3663 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3664 OverflowAreaPlusN); 3665 3666 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3667 MachinePointerInfo(), MVT::i32); 3668 3669 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3670 } 3671 3672 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3673 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3674 3675 // We have to copy the entire va_list struct: 3676 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3677 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3678 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3679 false, true, false, MachinePointerInfo(), 3680 MachinePointerInfo()); 3681 } 3682 3683 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3684 SelectionDAG &DAG) const { 3685 if (Subtarget.isAIXABI()) 3686 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3687 3688 return Op.getOperand(0); 3689 } 3690 3691 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const { 3692 MachineFunction &MF = DAG.getMachineFunction(); 3693 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>(); 3694 3695 assert((Op.getOpcode() == ISD::INLINEASM || 3696 Op.getOpcode() == ISD::INLINEASM_BR) && 3697 "Expecting Inline ASM node."); 3698 3699 // If an LR store is already known to be required then there is not point in 3700 // checking this ASM as well. 3701 if (MFI.isLRStoreRequired()) 3702 return Op; 3703 3704 // Inline ASM nodes have an optional last operand that is an incoming Flag of 3705 // type MVT::Glue. We want to ignore this last operand if that is the case. 3706 unsigned NumOps = Op.getNumOperands(); 3707 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue) 3708 --NumOps; 3709 3710 // Check all operands that may contain the LR. 3711 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 3712 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue(); 3713 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 3714 ++i; // Skip the ID value. 3715 3716 switch (InlineAsm::getKind(Flags)) { 3717 default: 3718 llvm_unreachable("Bad flags!"); 3719 case InlineAsm::Kind_RegUse: 3720 case InlineAsm::Kind_Imm: 3721 case InlineAsm::Kind_Mem: 3722 i += NumVals; 3723 break; 3724 case InlineAsm::Kind_Clobber: 3725 case InlineAsm::Kind_RegDef: 3726 case InlineAsm::Kind_RegDefEarlyClobber: { 3727 for (; NumVals; --NumVals, ++i) { 3728 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg(); 3729 if (Reg != PPC::LR && Reg != PPC::LR8) 3730 continue; 3731 MFI.setLRStoreRequired(); 3732 return Op; 3733 } 3734 break; 3735 } 3736 } 3737 } 3738 3739 return Op; 3740 } 3741 3742 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3743 SelectionDAG &DAG) const { 3744 if (Subtarget.isAIXABI()) 3745 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3746 3747 SDValue Chain = Op.getOperand(0); 3748 SDValue Trmp = Op.getOperand(1); // trampoline 3749 SDValue FPtr = Op.getOperand(2); // nested function 3750 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3751 SDLoc dl(Op); 3752 3753 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3754 bool isPPC64 = (PtrVT == MVT::i64); 3755 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3756 3757 TargetLowering::ArgListTy Args; 3758 TargetLowering::ArgListEntry Entry; 3759 3760 Entry.Ty = IntPtrTy; 3761 Entry.Node = Trmp; Args.push_back(Entry); 3762 3763 // TrampSize == (isPPC64 ? 48 : 40); 3764 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3765 isPPC64 ? MVT::i64 : MVT::i32); 3766 Args.push_back(Entry); 3767 3768 Entry.Node = FPtr; Args.push_back(Entry); 3769 Entry.Node = Nest; Args.push_back(Entry); 3770 3771 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3772 TargetLowering::CallLoweringInfo CLI(DAG); 3773 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3774 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3775 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3776 3777 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3778 return CallResult.second; 3779 } 3780 3781 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3782 MachineFunction &MF = DAG.getMachineFunction(); 3783 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3784 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3785 3786 SDLoc dl(Op); 3787 3788 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3789 // vastart just stores the address of the VarArgsFrameIndex slot into the 3790 // memory location argument. 3791 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3792 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3793 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3794 MachinePointerInfo(SV)); 3795 } 3796 3797 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3798 // We suppose the given va_list is already allocated. 3799 // 3800 // typedef struct { 3801 // char gpr; /* index into the array of 8 GPRs 3802 // * stored in the register save area 3803 // * gpr=0 corresponds to r3, 3804 // * gpr=1 to r4, etc. 3805 // */ 3806 // char fpr; /* index into the array of 8 FPRs 3807 // * stored in the register save area 3808 // * fpr=0 corresponds to f1, 3809 // * fpr=1 to f2, etc. 3810 // */ 3811 // char *overflow_arg_area; 3812 // /* location on stack that holds 3813 // * the next overflow argument 3814 // */ 3815 // char *reg_save_area; 3816 // /* where r3:r10 and f1:f8 (if saved) 3817 // * are stored 3818 // */ 3819 // } va_list[1]; 3820 3821 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3822 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3823 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3824 PtrVT); 3825 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3826 PtrVT); 3827 3828 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3829 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3830 3831 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3832 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3833 3834 uint64_t FPROffset = 1; 3835 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3836 3837 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3838 3839 // Store first byte : number of int regs 3840 SDValue firstStore = 3841 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3842 MachinePointerInfo(SV), MVT::i8); 3843 uint64_t nextOffset = FPROffset; 3844 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3845 ConstFPROffset); 3846 3847 // Store second byte : number of float regs 3848 SDValue secondStore = 3849 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3850 MachinePointerInfo(SV, nextOffset), MVT::i8); 3851 nextOffset += StackOffset; 3852 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3853 3854 // Store second word : arguments given on stack 3855 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3856 MachinePointerInfo(SV, nextOffset)); 3857 nextOffset += FrameOffset; 3858 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3859 3860 // Store third word : arguments given in registers 3861 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3862 MachinePointerInfo(SV, nextOffset)); 3863 } 3864 3865 /// FPR - The set of FP registers that should be allocated for arguments 3866 /// on Darwin and AIX. 3867 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3868 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3869 PPC::F11, PPC::F12, PPC::F13}; 3870 3871 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3872 /// the stack. 3873 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3874 unsigned PtrByteSize) { 3875 unsigned ArgSize = ArgVT.getStoreSize(); 3876 if (Flags.isByVal()) 3877 ArgSize = Flags.getByValSize(); 3878 3879 // Round up to multiples of the pointer size, except for array members, 3880 // which are always packed. 3881 if (!Flags.isInConsecutiveRegs()) 3882 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3883 3884 return ArgSize; 3885 } 3886 3887 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3888 /// on the stack. 3889 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3890 ISD::ArgFlagsTy Flags, 3891 unsigned PtrByteSize) { 3892 Align Alignment(PtrByteSize); 3893 3894 // Altivec parameters are padded to a 16 byte boundary. 3895 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3896 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3897 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3898 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3899 Alignment = Align(16); 3900 3901 // ByVal parameters are aligned as requested. 3902 if (Flags.isByVal()) { 3903 auto BVAlign = Flags.getNonZeroByValAlign(); 3904 if (BVAlign > PtrByteSize) { 3905 if (BVAlign.value() % PtrByteSize != 0) 3906 llvm_unreachable( 3907 "ByVal alignment is not a multiple of the pointer size"); 3908 3909 Alignment = BVAlign; 3910 } 3911 } 3912 3913 // Array members are always packed to their original alignment. 3914 if (Flags.isInConsecutiveRegs()) { 3915 // If the array member was split into multiple registers, the first 3916 // needs to be aligned to the size of the full type. (Except for 3917 // ppcf128, which is only aligned as its f64 components.) 3918 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3919 Alignment = Align(OrigVT.getStoreSize()); 3920 else 3921 Alignment = Align(ArgVT.getStoreSize()); 3922 } 3923 3924 return Alignment; 3925 } 3926 3927 /// CalculateStackSlotUsed - Return whether this argument will use its 3928 /// stack slot (instead of being passed in registers). ArgOffset, 3929 /// AvailableFPRs, and AvailableVRs must hold the current argument 3930 /// position, and will be updated to account for this argument. 3931 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3932 unsigned PtrByteSize, unsigned LinkageSize, 3933 unsigned ParamAreaSize, unsigned &ArgOffset, 3934 unsigned &AvailableFPRs, 3935 unsigned &AvailableVRs) { 3936 bool UseMemory = false; 3937 3938 // Respect alignment of argument on the stack. 3939 Align Alignment = 3940 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3941 ArgOffset = alignTo(ArgOffset, Alignment); 3942 // If there's no space left in the argument save area, we must 3943 // use memory (this check also catches zero-sized arguments). 3944 if (ArgOffset >= LinkageSize + ParamAreaSize) 3945 UseMemory = true; 3946 3947 // Allocate argument on the stack. 3948 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3949 if (Flags.isInConsecutiveRegsLast()) 3950 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3951 // If we overran the argument save area, we must use memory 3952 // (this check catches arguments passed partially in memory) 3953 if (ArgOffset > LinkageSize + ParamAreaSize) 3954 UseMemory = true; 3955 3956 // However, if the argument is actually passed in an FPR or a VR, 3957 // we don't use memory after all. 3958 if (!Flags.isByVal()) { 3959 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3960 if (AvailableFPRs > 0) { 3961 --AvailableFPRs; 3962 return false; 3963 } 3964 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3965 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3966 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3967 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3968 if (AvailableVRs > 0) { 3969 --AvailableVRs; 3970 return false; 3971 } 3972 } 3973 3974 return UseMemory; 3975 } 3976 3977 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3978 /// ensure minimum alignment required for target. 3979 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3980 unsigned NumBytes) { 3981 return alignTo(NumBytes, Lowering->getStackAlign()); 3982 } 3983 3984 SDValue PPCTargetLowering::LowerFormalArguments( 3985 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3986 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3987 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3988 if (Subtarget.isAIXABI()) 3989 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3990 InVals); 3991 if (Subtarget.is64BitELFABI()) 3992 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3993 InVals); 3994 assert(Subtarget.is32BitELFABI()); 3995 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3996 InVals); 3997 } 3998 3999 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 4000 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4001 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4002 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4003 4004 // 32-bit SVR4 ABI Stack Frame Layout: 4005 // +-----------------------------------+ 4006 // +--> | Back chain | 4007 // | +-----------------------------------+ 4008 // | | Floating-point register save area | 4009 // | +-----------------------------------+ 4010 // | | General register save area | 4011 // | +-----------------------------------+ 4012 // | | CR save word | 4013 // | +-----------------------------------+ 4014 // | | VRSAVE save word | 4015 // | +-----------------------------------+ 4016 // | | Alignment padding | 4017 // | +-----------------------------------+ 4018 // | | Vector register save area | 4019 // | +-----------------------------------+ 4020 // | | Local variable space | 4021 // | +-----------------------------------+ 4022 // | | Parameter list area | 4023 // | +-----------------------------------+ 4024 // | | LR save word | 4025 // | +-----------------------------------+ 4026 // SP--> +--- | Back chain | 4027 // +-----------------------------------+ 4028 // 4029 // Specifications: 4030 // System V Application Binary Interface PowerPC Processor Supplement 4031 // AltiVec Technology Programming Interface Manual 4032 4033 MachineFunction &MF = DAG.getMachineFunction(); 4034 MachineFrameInfo &MFI = MF.getFrameInfo(); 4035 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4036 4037 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4038 // Potential tail calls could cause overwriting of argument stack slots. 4039 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4040 (CallConv == CallingConv::Fast)); 4041 const Align PtrAlign(4); 4042 4043 // Assign locations to all of the incoming arguments. 4044 SmallVector<CCValAssign, 16> ArgLocs; 4045 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4046 *DAG.getContext()); 4047 4048 // Reserve space for the linkage area on the stack. 4049 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4050 CCInfo.AllocateStack(LinkageSize, PtrAlign); 4051 if (useSoftFloat()) 4052 CCInfo.PreAnalyzeFormalArguments(Ins); 4053 4054 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 4055 CCInfo.clearWasPPCF128(); 4056 4057 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4058 CCValAssign &VA = ArgLocs[i]; 4059 4060 // Arguments stored in registers. 4061 if (VA.isRegLoc()) { 4062 const TargetRegisterClass *RC; 4063 EVT ValVT = VA.getValVT(); 4064 4065 switch (ValVT.getSimpleVT().SimpleTy) { 4066 default: 4067 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 4068 case MVT::i1: 4069 case MVT::i32: 4070 RC = &PPC::GPRCRegClass; 4071 break; 4072 case MVT::f32: 4073 if (Subtarget.hasP8Vector()) 4074 RC = &PPC::VSSRCRegClass; 4075 else if (Subtarget.hasSPE()) 4076 RC = &PPC::GPRCRegClass; 4077 else 4078 RC = &PPC::F4RCRegClass; 4079 break; 4080 case MVT::f64: 4081 if (Subtarget.hasVSX()) 4082 RC = &PPC::VSFRCRegClass; 4083 else if (Subtarget.hasSPE()) 4084 // SPE passes doubles in GPR pairs. 4085 RC = &PPC::GPRCRegClass; 4086 else 4087 RC = &PPC::F8RCRegClass; 4088 break; 4089 case MVT::v16i8: 4090 case MVT::v8i16: 4091 case MVT::v4i32: 4092 RC = &PPC::VRRCRegClass; 4093 break; 4094 case MVT::v4f32: 4095 RC = &PPC::VRRCRegClass; 4096 break; 4097 case MVT::v2f64: 4098 case MVT::v2i64: 4099 RC = &PPC::VRRCRegClass; 4100 break; 4101 } 4102 4103 SDValue ArgValue; 4104 // Transform the arguments stored in physical registers into 4105 // virtual ones. 4106 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 4107 assert(i + 1 < e && "No second half of double precision argument"); 4108 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC); 4109 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 4110 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 4111 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 4112 if (!Subtarget.isLittleEndian()) 4113 std::swap (ArgValueLo, ArgValueHi); 4114 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 4115 ArgValueHi); 4116 } else { 4117 Register Reg = MF.addLiveIn(VA.getLocReg(), RC); 4118 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 4119 ValVT == MVT::i1 ? MVT::i32 : ValVT); 4120 if (ValVT == MVT::i1) 4121 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 4122 } 4123 4124 InVals.push_back(ArgValue); 4125 } else { 4126 // Argument stored in memory. 4127 assert(VA.isMemLoc()); 4128 4129 // Get the extended size of the argument type in stack 4130 unsigned ArgSize = VA.getLocVT().getStoreSize(); 4131 // Get the actual size of the argument type 4132 unsigned ObjSize = VA.getValVT().getStoreSize(); 4133 unsigned ArgOffset = VA.getLocMemOffset(); 4134 // Stack objects in PPC32 are right justified. 4135 ArgOffset += ArgSize - ObjSize; 4136 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 4137 4138 // Create load nodes to retrieve arguments from the stack. 4139 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4140 InVals.push_back( 4141 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 4142 } 4143 } 4144 4145 // Assign locations to all of the incoming aggregate by value arguments. 4146 // Aggregates passed by value are stored in the local variable space of the 4147 // caller's stack frame, right above the parameter list area. 4148 SmallVector<CCValAssign, 16> ByValArgLocs; 4149 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4150 ByValArgLocs, *DAG.getContext()); 4151 4152 // Reserve stack space for the allocations in CCInfo. 4153 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 4154 4155 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 4156 4157 // Area that is at least reserved in the caller of this function. 4158 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 4159 MinReservedArea = std::max(MinReservedArea, LinkageSize); 4160 4161 // Set the size that is at least reserved in caller of this function. Tail 4162 // call optimized function's reserved stack space needs to be aligned so that 4163 // taking the difference between two stack areas will result in an aligned 4164 // stack. 4165 MinReservedArea = 4166 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4167 FuncInfo->setMinReservedArea(MinReservedArea); 4168 4169 SmallVector<SDValue, 8> MemOps; 4170 4171 // If the function takes variable number of arguments, make a frame index for 4172 // the start of the first vararg value... for expansion of llvm.va_start. 4173 if (isVarArg) { 4174 static const MCPhysReg GPArgRegs[] = { 4175 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4176 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4177 }; 4178 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 4179 4180 static const MCPhysReg FPArgRegs[] = { 4181 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 4182 PPC::F8 4183 }; 4184 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 4185 4186 if (useSoftFloat() || hasSPE()) 4187 NumFPArgRegs = 0; 4188 4189 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 4190 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 4191 4192 // Make room for NumGPArgRegs and NumFPArgRegs. 4193 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 4194 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 4195 4196 FuncInfo->setVarArgsStackOffset( 4197 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4198 CCInfo.getNextStackOffset(), true)); 4199 4200 FuncInfo->setVarArgsFrameIndex( 4201 MFI.CreateStackObject(Depth, Align(8), false)); 4202 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4203 4204 // The fixed integer arguments of a variadic function are stored to the 4205 // VarArgsFrameIndex on the stack so that they may be loaded by 4206 // dereferencing the result of va_next. 4207 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 4208 // Get an existing live-in vreg, or add a new one. 4209 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 4210 if (!VReg) 4211 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 4212 4213 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4214 SDValue Store = 4215 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4216 MemOps.push_back(Store); 4217 // Increment the address by four for the next argument to store 4218 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4219 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4220 } 4221 4222 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 4223 // is set. 4224 // The double arguments are stored to the VarArgsFrameIndex 4225 // on the stack. 4226 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 4227 // Get an existing live-in vreg, or add a new one. 4228 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 4229 if (!VReg) 4230 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 4231 4232 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 4233 SDValue Store = 4234 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4235 MemOps.push_back(Store); 4236 // Increment the address by eight for the next argument to store 4237 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4238 PtrVT); 4239 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4240 } 4241 } 4242 4243 if (!MemOps.empty()) 4244 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4245 4246 return Chain; 4247 } 4248 4249 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4250 // value to MVT::i64 and then truncate to the correct register size. 4251 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4252 EVT ObjectVT, SelectionDAG &DAG, 4253 SDValue ArgVal, 4254 const SDLoc &dl) const { 4255 if (Flags.isSExt()) 4256 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4257 DAG.getValueType(ObjectVT)); 4258 else if (Flags.isZExt()) 4259 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4260 DAG.getValueType(ObjectVT)); 4261 4262 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4263 } 4264 4265 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4266 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4267 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4268 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4269 // TODO: add description of PPC stack frame format, or at least some docs. 4270 // 4271 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4272 bool isLittleEndian = Subtarget.isLittleEndian(); 4273 MachineFunction &MF = DAG.getMachineFunction(); 4274 MachineFrameInfo &MFI = MF.getFrameInfo(); 4275 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4276 4277 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4278 "fastcc not supported on varargs functions"); 4279 4280 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4281 // Potential tail calls could cause overwriting of argument stack slots. 4282 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4283 (CallConv == CallingConv::Fast)); 4284 unsigned PtrByteSize = 8; 4285 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4286 4287 static const MCPhysReg GPR[] = { 4288 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4289 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4290 }; 4291 static const MCPhysReg VR[] = { 4292 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4293 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4294 }; 4295 4296 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4297 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4298 const unsigned Num_VR_Regs = array_lengthof(VR); 4299 4300 // Do a first pass over the arguments to determine whether the ABI 4301 // guarantees that our caller has allocated the parameter save area 4302 // on its stack frame. In the ELFv1 ABI, this is always the case; 4303 // in the ELFv2 ABI, it is true if this is a vararg function or if 4304 // any parameter is located in a stack slot. 4305 4306 bool HasParameterArea = !isELFv2ABI || isVarArg; 4307 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4308 unsigned NumBytes = LinkageSize; 4309 unsigned AvailableFPRs = Num_FPR_Regs; 4310 unsigned AvailableVRs = Num_VR_Regs; 4311 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4312 if (Ins[i].Flags.isNest()) 4313 continue; 4314 4315 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4316 PtrByteSize, LinkageSize, ParamAreaSize, 4317 NumBytes, AvailableFPRs, AvailableVRs)) 4318 HasParameterArea = true; 4319 } 4320 4321 // Add DAG nodes to load the arguments or copy them out of registers. On 4322 // entry to a function on PPC, the arguments start after the linkage area, 4323 // although the first ones are often in registers. 4324 4325 unsigned ArgOffset = LinkageSize; 4326 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4327 SmallVector<SDValue, 8> MemOps; 4328 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4329 unsigned CurArgIdx = 0; 4330 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4331 SDValue ArgVal; 4332 bool needsLoad = false; 4333 EVT ObjectVT = Ins[ArgNo].VT; 4334 EVT OrigVT = Ins[ArgNo].ArgVT; 4335 unsigned ObjSize = ObjectVT.getStoreSize(); 4336 unsigned ArgSize = ObjSize; 4337 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4338 if (Ins[ArgNo].isOrigArg()) { 4339 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4340 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4341 } 4342 // We re-align the argument offset for each argument, except when using the 4343 // fast calling convention, when we need to make sure we do that only when 4344 // we'll actually use a stack slot. 4345 unsigned CurArgOffset; 4346 Align Alignment; 4347 auto ComputeArgOffset = [&]() { 4348 /* Respect alignment of argument on the stack. */ 4349 Alignment = 4350 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4351 ArgOffset = alignTo(ArgOffset, Alignment); 4352 CurArgOffset = ArgOffset; 4353 }; 4354 4355 if (CallConv != CallingConv::Fast) { 4356 ComputeArgOffset(); 4357 4358 /* Compute GPR index associated with argument offset. */ 4359 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4360 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4361 } 4362 4363 // FIXME the codegen can be much improved in some cases. 4364 // We do not have to keep everything in memory. 4365 if (Flags.isByVal()) { 4366 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4367 4368 if (CallConv == CallingConv::Fast) 4369 ComputeArgOffset(); 4370 4371 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4372 ObjSize = Flags.getByValSize(); 4373 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4374 // Empty aggregate parameters do not take up registers. Examples: 4375 // struct { } a; 4376 // union { } b; 4377 // int c[0]; 4378 // etc. However, we have to provide a place-holder in InVals, so 4379 // pretend we have an 8-byte item at the current address for that 4380 // purpose. 4381 if (!ObjSize) { 4382 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4383 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4384 InVals.push_back(FIN); 4385 continue; 4386 } 4387 4388 // Create a stack object covering all stack doublewords occupied 4389 // by the argument. If the argument is (fully or partially) on 4390 // the stack, or if the argument is fully in registers but the 4391 // caller has allocated the parameter save anyway, we can refer 4392 // directly to the caller's stack frame. Otherwise, create a 4393 // local copy in our own frame. 4394 int FI; 4395 if (HasParameterArea || 4396 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4397 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4398 else 4399 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4400 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4401 4402 // Handle aggregates smaller than 8 bytes. 4403 if (ObjSize < PtrByteSize) { 4404 // The value of the object is its address, which differs from the 4405 // address of the enclosing doubleword on big-endian systems. 4406 SDValue Arg = FIN; 4407 if (!isLittleEndian) { 4408 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4409 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4410 } 4411 InVals.push_back(Arg); 4412 4413 if (GPR_idx != Num_GPR_Regs) { 4414 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4415 FuncInfo->addLiveInAttr(VReg, Flags); 4416 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4417 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8); 4418 SDValue Store = 4419 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4420 MachinePointerInfo(&*FuncArg), ObjType); 4421 MemOps.push_back(Store); 4422 } 4423 // Whether we copied from a register or not, advance the offset 4424 // into the parameter save area by a full doubleword. 4425 ArgOffset += PtrByteSize; 4426 continue; 4427 } 4428 4429 // The value of the object is its address, which is the address of 4430 // its first stack doubleword. 4431 InVals.push_back(FIN); 4432 4433 // Store whatever pieces of the object are in registers to memory. 4434 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4435 if (GPR_idx == Num_GPR_Regs) 4436 break; 4437 4438 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4439 FuncInfo->addLiveInAttr(VReg, Flags); 4440 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4441 SDValue Addr = FIN; 4442 if (j) { 4443 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4444 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4445 } 4446 unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8; 4447 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits); 4448 SDValue Store = 4449 DAG.getTruncStore(Val.getValue(1), dl, Val, Addr, 4450 MachinePointerInfo(&*FuncArg, j), ObjType); 4451 MemOps.push_back(Store); 4452 ++GPR_idx; 4453 } 4454 ArgOffset += ArgSize; 4455 continue; 4456 } 4457 4458 switch (ObjectVT.getSimpleVT().SimpleTy) { 4459 default: llvm_unreachable("Unhandled argument type!"); 4460 case MVT::i1: 4461 case MVT::i32: 4462 case MVT::i64: 4463 if (Flags.isNest()) { 4464 // The 'nest' parameter, if any, is passed in R11. 4465 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4466 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4467 4468 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4469 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4470 4471 break; 4472 } 4473 4474 // These can be scalar arguments or elements of an integer array type 4475 // passed directly. Clang may use those instead of "byval" aggregate 4476 // types to avoid forcing arguments to memory unnecessarily. 4477 if (GPR_idx != Num_GPR_Regs) { 4478 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4479 FuncInfo->addLiveInAttr(VReg, Flags); 4480 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4481 4482 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4483 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4484 // value to MVT::i64 and then truncate to the correct register size. 4485 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4486 } else { 4487 if (CallConv == CallingConv::Fast) 4488 ComputeArgOffset(); 4489 4490 needsLoad = true; 4491 ArgSize = PtrByteSize; 4492 } 4493 if (CallConv != CallingConv::Fast || needsLoad) 4494 ArgOffset += 8; 4495 break; 4496 4497 case MVT::f32: 4498 case MVT::f64: 4499 // These can be scalar arguments or elements of a float array type 4500 // passed directly. The latter are used to implement ELFv2 homogenous 4501 // float aggregates. 4502 if (FPR_idx != Num_FPR_Regs) { 4503 unsigned VReg; 4504 4505 if (ObjectVT == MVT::f32) 4506 VReg = MF.addLiveIn(FPR[FPR_idx], 4507 Subtarget.hasP8Vector() 4508 ? &PPC::VSSRCRegClass 4509 : &PPC::F4RCRegClass); 4510 else 4511 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4512 ? &PPC::VSFRCRegClass 4513 : &PPC::F8RCRegClass); 4514 4515 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4516 ++FPR_idx; 4517 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4518 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4519 // once we support fp <-> gpr moves. 4520 4521 // This can only ever happen in the presence of f32 array types, 4522 // since otherwise we never run out of FPRs before running out 4523 // of GPRs. 4524 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4525 FuncInfo->addLiveInAttr(VReg, Flags); 4526 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4527 4528 if (ObjectVT == MVT::f32) { 4529 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4530 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4531 DAG.getConstant(32, dl, MVT::i32)); 4532 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4533 } 4534 4535 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4536 } else { 4537 if (CallConv == CallingConv::Fast) 4538 ComputeArgOffset(); 4539 4540 needsLoad = true; 4541 } 4542 4543 // When passing an array of floats, the array occupies consecutive 4544 // space in the argument area; only round up to the next doubleword 4545 // at the end of the array. Otherwise, each float takes 8 bytes. 4546 if (CallConv != CallingConv::Fast || needsLoad) { 4547 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4548 ArgOffset += ArgSize; 4549 if (Flags.isInConsecutiveRegsLast()) 4550 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4551 } 4552 break; 4553 case MVT::v4f32: 4554 case MVT::v4i32: 4555 case MVT::v8i16: 4556 case MVT::v16i8: 4557 case MVT::v2f64: 4558 case MVT::v2i64: 4559 case MVT::v1i128: 4560 case MVT::f128: 4561 // These can be scalar arguments or elements of a vector array type 4562 // passed directly. The latter are used to implement ELFv2 homogenous 4563 // vector aggregates. 4564 if (VR_idx != Num_VR_Regs) { 4565 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4566 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4567 ++VR_idx; 4568 } else { 4569 if (CallConv == CallingConv::Fast) 4570 ComputeArgOffset(); 4571 needsLoad = true; 4572 } 4573 if (CallConv != CallingConv::Fast || needsLoad) 4574 ArgOffset += 16; 4575 break; 4576 } 4577 4578 // We need to load the argument to a virtual register if we determined 4579 // above that we ran out of physical registers of the appropriate type. 4580 if (needsLoad) { 4581 if (ObjSize < ArgSize && !isLittleEndian) 4582 CurArgOffset += ArgSize - ObjSize; 4583 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4584 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4585 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4586 } 4587 4588 InVals.push_back(ArgVal); 4589 } 4590 4591 // Area that is at least reserved in the caller of this function. 4592 unsigned MinReservedArea; 4593 if (HasParameterArea) 4594 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4595 else 4596 MinReservedArea = LinkageSize; 4597 4598 // Set the size that is at least reserved in caller of this function. Tail 4599 // call optimized functions' reserved stack space needs to be aligned so that 4600 // taking the difference between two stack areas will result in an aligned 4601 // stack. 4602 MinReservedArea = 4603 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4604 FuncInfo->setMinReservedArea(MinReservedArea); 4605 4606 // If the function takes variable number of arguments, make a frame index for 4607 // the start of the first vararg value... for expansion of llvm.va_start. 4608 // On ELFv2ABI spec, it writes: 4609 // C programs that are intended to be *portable* across different compilers 4610 // and architectures must use the header file <stdarg.h> to deal with variable 4611 // argument lists. 4612 if (isVarArg && MFI.hasVAStart()) { 4613 int Depth = ArgOffset; 4614 4615 FuncInfo->setVarArgsFrameIndex( 4616 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4617 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4618 4619 // If this function is vararg, store any remaining integer argument regs 4620 // to their spots on the stack so that they may be loaded by dereferencing 4621 // the result of va_next. 4622 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4623 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4624 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4625 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4626 SDValue Store = 4627 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4628 MemOps.push_back(Store); 4629 // Increment the address by four for the next argument to store 4630 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4631 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4632 } 4633 } 4634 4635 if (!MemOps.empty()) 4636 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4637 4638 return Chain; 4639 } 4640 4641 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4642 /// adjusted to accommodate the arguments for the tailcall. 4643 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4644 unsigned ParamSize) { 4645 4646 if (!isTailCall) return 0; 4647 4648 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4649 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4650 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4651 // Remember only if the new adjustment is bigger. 4652 if (SPDiff < FI->getTailCallSPDelta()) 4653 FI->setTailCallSPDelta(SPDiff); 4654 4655 return SPDiff; 4656 } 4657 4658 static bool isFunctionGlobalAddress(SDValue Callee); 4659 4660 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4661 const TargetMachine &TM) { 4662 // It does not make sense to call callsShareTOCBase() with a caller that 4663 // is PC Relative since PC Relative callers do not have a TOC. 4664 #ifndef NDEBUG 4665 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4666 assert(!STICaller->isUsingPCRelativeCalls() && 4667 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4668 #endif 4669 4670 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4671 // don't have enough information to determine if the caller and callee share 4672 // the same TOC base, so we have to pessimistically assume they don't for 4673 // correctness. 4674 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4675 if (!G) 4676 return false; 4677 4678 const GlobalValue *GV = G->getGlobal(); 4679 4680 // If the callee is preemptable, then the static linker will use a plt-stub 4681 // which saves the toc to the stack, and needs a nop after the call 4682 // instruction to convert to a toc-restore. 4683 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4684 return false; 4685 4686 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4687 // We may need a TOC restore in the situation where the caller requires a 4688 // valid TOC but the callee is PC Relative and does not. 4689 const Function *F = dyn_cast<Function>(GV); 4690 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4691 4692 // If we have an Alias we can try to get the function from there. 4693 if (Alias) { 4694 const GlobalObject *GlobalObj = Alias->getAliaseeObject(); 4695 F = dyn_cast<Function>(GlobalObj); 4696 } 4697 4698 // If we still have no valid function pointer we do not have enough 4699 // information to determine if the callee uses PC Relative calls so we must 4700 // assume that it does. 4701 if (!F) 4702 return false; 4703 4704 // If the callee uses PC Relative we cannot guarantee that the callee won't 4705 // clobber the TOC of the caller and so we must assume that the two 4706 // functions do not share a TOC base. 4707 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4708 if (STICallee->isUsingPCRelativeCalls()) 4709 return false; 4710 4711 // If the GV is not a strong definition then we need to assume it can be 4712 // replaced by another function at link time. The function that replaces 4713 // it may not share the same TOC as the caller since the callee may be 4714 // replaced by a PC Relative version of the same function. 4715 if (!GV->isStrongDefinitionForLinker()) 4716 return false; 4717 4718 // The medium and large code models are expected to provide a sufficiently 4719 // large TOC to provide all data addressing needs of a module with a 4720 // single TOC. 4721 if (CodeModel::Medium == TM.getCodeModel() || 4722 CodeModel::Large == TM.getCodeModel()) 4723 return true; 4724 4725 // Any explicitly-specified sections and section prefixes must also match. 4726 // Also, if we're using -ffunction-sections, then each function is always in 4727 // a different section (the same is true for COMDAT functions). 4728 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4729 GV->getSection() != Caller->getSection()) 4730 return false; 4731 if (const auto *F = dyn_cast<Function>(GV)) { 4732 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4733 return false; 4734 } 4735 4736 return true; 4737 } 4738 4739 static bool 4740 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4741 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4742 assert(Subtarget.is64BitELFABI()); 4743 4744 const unsigned PtrByteSize = 8; 4745 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4746 4747 static const MCPhysReg GPR[] = { 4748 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4749 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4750 }; 4751 static const MCPhysReg VR[] = { 4752 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4753 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4754 }; 4755 4756 const unsigned NumGPRs = array_lengthof(GPR); 4757 const unsigned NumFPRs = 13; 4758 const unsigned NumVRs = array_lengthof(VR); 4759 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4760 4761 unsigned NumBytes = LinkageSize; 4762 unsigned AvailableFPRs = NumFPRs; 4763 unsigned AvailableVRs = NumVRs; 4764 4765 for (const ISD::OutputArg& Param : Outs) { 4766 if (Param.Flags.isNest()) continue; 4767 4768 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4769 LinkageSize, ParamAreaSize, NumBytes, 4770 AvailableFPRs, AvailableVRs)) 4771 return true; 4772 } 4773 return false; 4774 } 4775 4776 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4777 if (CB.arg_size() != CallerFn->arg_size()) 4778 return false; 4779 4780 auto CalleeArgIter = CB.arg_begin(); 4781 auto CalleeArgEnd = CB.arg_end(); 4782 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4783 4784 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4785 const Value* CalleeArg = *CalleeArgIter; 4786 const Value* CallerArg = &(*CallerArgIter); 4787 if (CalleeArg == CallerArg) 4788 continue; 4789 4790 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4791 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4792 // } 4793 // 1st argument of callee is undef and has the same type as caller. 4794 if (CalleeArg->getType() == CallerArg->getType() && 4795 isa<UndefValue>(CalleeArg)) 4796 continue; 4797 4798 return false; 4799 } 4800 4801 return true; 4802 } 4803 4804 // Returns true if TCO is possible between the callers and callees 4805 // calling conventions. 4806 static bool 4807 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4808 CallingConv::ID CalleeCC) { 4809 // Tail calls are possible with fastcc and ccc. 4810 auto isTailCallableCC = [] (CallingConv::ID CC){ 4811 return CC == CallingConv::C || CC == CallingConv::Fast; 4812 }; 4813 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4814 return false; 4815 4816 // We can safely tail call both fastcc and ccc callees from a c calling 4817 // convention caller. If the caller is fastcc, we may have less stack space 4818 // than a non-fastcc caller with the same signature so disable tail-calls in 4819 // that case. 4820 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4821 } 4822 4823 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4824 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4825 const SmallVectorImpl<ISD::OutputArg> &Outs, 4826 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4827 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4828 4829 if (DisableSCO && !TailCallOpt) return false; 4830 4831 // Variadic argument functions are not supported. 4832 if (isVarArg) return false; 4833 4834 auto &Caller = DAG.getMachineFunction().getFunction(); 4835 // Check that the calling conventions are compatible for tco. 4836 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4837 return false; 4838 4839 // Caller contains any byval parameter is not supported. 4840 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4841 return false; 4842 4843 // Callee contains any byval parameter is not supported, too. 4844 // Note: This is a quick work around, because in some cases, e.g. 4845 // caller's stack size > callee's stack size, we are still able to apply 4846 // sibling call optimization. For example, gcc is able to do SCO for caller1 4847 // in the following example, but not for caller2. 4848 // struct test { 4849 // long int a; 4850 // char ary[56]; 4851 // } gTest; 4852 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4853 // b->a = v.a; 4854 // return 0; 4855 // } 4856 // void caller1(struct test a, struct test c, struct test *b) { 4857 // callee(gTest, b); } 4858 // void caller2(struct test *b) { callee(gTest, b); } 4859 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4860 return false; 4861 4862 // If callee and caller use different calling conventions, we cannot pass 4863 // parameters on stack since offsets for the parameter area may be different. 4864 if (Caller.getCallingConv() != CalleeCC && 4865 needStackSlotPassParameters(Subtarget, Outs)) 4866 return false; 4867 4868 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4869 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4870 // callee potentially have different TOC bases then we cannot tail call since 4871 // we need to restore the TOC pointer after the call. 4872 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4873 // We cannot guarantee this for indirect calls or calls to external functions. 4874 // When PC-Relative addressing is used, the concept of the TOC is no longer 4875 // applicable so this check is not required. 4876 // Check first for indirect calls. 4877 if (!Subtarget.isUsingPCRelativeCalls() && 4878 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4879 return false; 4880 4881 // Check if we share the TOC base. 4882 if (!Subtarget.isUsingPCRelativeCalls() && 4883 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4884 return false; 4885 4886 // TCO allows altering callee ABI, so we don't have to check further. 4887 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4888 return true; 4889 4890 if (DisableSCO) return false; 4891 4892 // If callee use the same argument list that caller is using, then we can 4893 // apply SCO on this case. If it is not, then we need to check if callee needs 4894 // stack for passing arguments. 4895 // PC Relative tail calls may not have a CallBase. 4896 // If there is no CallBase we cannot verify if we have the same argument 4897 // list so assume that we don't have the same argument list. 4898 if (CB && !hasSameArgumentList(&Caller, *CB) && 4899 needStackSlotPassParameters(Subtarget, Outs)) 4900 return false; 4901 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4902 return false; 4903 4904 return true; 4905 } 4906 4907 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4908 /// for tail call optimization. Targets which want to do tail call 4909 /// optimization should implement this function. 4910 bool 4911 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4912 CallingConv::ID CalleeCC, 4913 bool isVarArg, 4914 const SmallVectorImpl<ISD::InputArg> &Ins, 4915 SelectionDAG& DAG) const { 4916 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4917 return false; 4918 4919 // Variable argument functions are not supported. 4920 if (isVarArg) 4921 return false; 4922 4923 MachineFunction &MF = DAG.getMachineFunction(); 4924 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4925 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4926 // Functions containing by val parameters are not supported. 4927 for (unsigned i = 0; i != Ins.size(); i++) { 4928 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4929 if (Flags.isByVal()) return false; 4930 } 4931 4932 // Non-PIC/GOT tail calls are supported. 4933 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4934 return true; 4935 4936 // At the moment we can only do local tail calls (in same module, hidden 4937 // or protected) if we are generating PIC. 4938 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4939 return G->getGlobal()->hasHiddenVisibility() 4940 || G->getGlobal()->hasProtectedVisibility(); 4941 } 4942 4943 return false; 4944 } 4945 4946 /// isCallCompatibleAddress - Return the immediate to use if the specified 4947 /// 32-bit value is representable in the immediate field of a BxA instruction. 4948 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4949 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4950 if (!C) return nullptr; 4951 4952 int Addr = C->getZExtValue(); 4953 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4954 SignExtend32<26>(Addr) != Addr) 4955 return nullptr; // Top 6 bits have to be sext of immediate. 4956 4957 return DAG 4958 .getConstant( 4959 (int)C->getZExtValue() >> 2, SDLoc(Op), 4960 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4961 .getNode(); 4962 } 4963 4964 namespace { 4965 4966 struct TailCallArgumentInfo { 4967 SDValue Arg; 4968 SDValue FrameIdxOp; 4969 int FrameIdx = 0; 4970 4971 TailCallArgumentInfo() = default; 4972 }; 4973 4974 } // end anonymous namespace 4975 4976 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4977 static void StoreTailCallArgumentsToStackSlot( 4978 SelectionDAG &DAG, SDValue Chain, 4979 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4980 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4981 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4982 SDValue Arg = TailCallArgs[i].Arg; 4983 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4984 int FI = TailCallArgs[i].FrameIdx; 4985 // Store relative to framepointer. 4986 MemOpChains.push_back(DAG.getStore( 4987 Chain, dl, Arg, FIN, 4988 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4989 } 4990 } 4991 4992 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4993 /// the appropriate stack slot for the tail call optimized function call. 4994 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4995 SDValue OldRetAddr, SDValue OldFP, 4996 int SPDiff, const SDLoc &dl) { 4997 if (SPDiff) { 4998 // Calculate the new stack slot for the return address. 4999 MachineFunction &MF = DAG.getMachineFunction(); 5000 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 5001 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 5002 bool isPPC64 = Subtarget.isPPC64(); 5003 int SlotSize = isPPC64 ? 8 : 4; 5004 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 5005 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 5006 NewRetAddrLoc, true); 5007 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5008 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5009 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5010 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5011 } 5012 return Chain; 5013 } 5014 5015 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5016 /// the position of the argument. 5017 static void 5018 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5019 SDValue Arg, int SPDiff, unsigned ArgOffset, 5020 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5021 int Offset = ArgOffset + SPDiff; 5022 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5023 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5024 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5025 SDValue FIN = DAG.getFrameIndex(FI, VT); 5026 TailCallArgumentInfo Info; 5027 Info.Arg = Arg; 5028 Info.FrameIdxOp = FIN; 5029 Info.FrameIdx = FI; 5030 TailCallArguments.push_back(Info); 5031 } 5032 5033 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5034 /// stack slot. Returns the chain as result and the loaded frame pointers in 5035 /// LROpOut/FPOpout. Used when tail calling. 5036 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5037 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5038 SDValue &FPOpOut, const SDLoc &dl) const { 5039 if (SPDiff) { 5040 // Load the LR and FP stack slot for later adjusting. 5041 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5042 LROpOut = getReturnAddrFrameIndex(DAG); 5043 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5044 Chain = SDValue(LROpOut.getNode(), 1); 5045 } 5046 return Chain; 5047 } 5048 5049 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5050 /// by "Src" to address "Dst" of size "Size". Alignment information is 5051 /// specified by the specific parameter attribute. The copy will be passed as 5052 /// a byval function parameter. 5053 /// Sometimes what we are copying is the end of a larger object, the part that 5054 /// does not fit in registers. 5055 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5056 SDValue Chain, ISD::ArgFlagsTy Flags, 5057 SelectionDAG &DAG, const SDLoc &dl) { 5058 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5059 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5060 Flags.getNonZeroByValAlign(), false, false, false, 5061 MachinePointerInfo(), MachinePointerInfo()); 5062 } 5063 5064 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5065 /// tail calls. 5066 static void LowerMemOpCallTo( 5067 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5068 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5069 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5070 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5071 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5072 if (!isTailCall) { 5073 if (isVector) { 5074 SDValue StackPtr; 5075 if (isPPC64) 5076 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5077 else 5078 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5079 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5080 DAG.getConstant(ArgOffset, dl, PtrVT)); 5081 } 5082 MemOpChains.push_back( 5083 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5084 // Calculate and remember argument location. 5085 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5086 TailCallArguments); 5087 } 5088 5089 static void 5090 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5091 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5092 SDValue FPOp, 5093 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5094 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5095 // might overwrite each other in case of tail call optimization. 5096 SmallVector<SDValue, 8> MemOpChains2; 5097 // Do not flag preceding copytoreg stuff together with the following stuff. 5098 InFlag = SDValue(); 5099 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5100 MemOpChains2, dl); 5101 if (!MemOpChains2.empty()) 5102 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5103 5104 // Store the return address to the appropriate stack slot. 5105 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5106 5107 // Emit callseq_end just before tailcall node. 5108 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5109 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5110 InFlag = Chain.getValue(1); 5111 } 5112 5113 // Is this global address that of a function that can be called by name? (as 5114 // opposed to something that must hold a descriptor for an indirect call). 5115 static bool isFunctionGlobalAddress(SDValue Callee) { 5116 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5117 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5118 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5119 return false; 5120 5121 return G->getGlobal()->getValueType()->isFunctionTy(); 5122 } 5123 5124 return false; 5125 } 5126 5127 SDValue PPCTargetLowering::LowerCallResult( 5128 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5129 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5130 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5131 SmallVector<CCValAssign, 16> RVLocs; 5132 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5133 *DAG.getContext()); 5134 5135 CCRetInfo.AnalyzeCallResult( 5136 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5137 ? RetCC_PPC_Cold 5138 : RetCC_PPC); 5139 5140 // Copy all of the result registers out of their specified physreg. 5141 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5142 CCValAssign &VA = RVLocs[i]; 5143 assert(VA.isRegLoc() && "Can only return in registers!"); 5144 5145 SDValue Val; 5146 5147 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5148 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5149 InFlag); 5150 Chain = Lo.getValue(1); 5151 InFlag = Lo.getValue(2); 5152 VA = RVLocs[++i]; // skip ahead to next loc 5153 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5154 InFlag); 5155 Chain = Hi.getValue(1); 5156 InFlag = Hi.getValue(2); 5157 if (!Subtarget.isLittleEndian()) 5158 std::swap (Lo, Hi); 5159 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5160 } else { 5161 Val = DAG.getCopyFromReg(Chain, dl, 5162 VA.getLocReg(), VA.getLocVT(), InFlag); 5163 Chain = Val.getValue(1); 5164 InFlag = Val.getValue(2); 5165 } 5166 5167 switch (VA.getLocInfo()) { 5168 default: llvm_unreachable("Unknown loc info!"); 5169 case CCValAssign::Full: break; 5170 case CCValAssign::AExt: 5171 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5172 break; 5173 case CCValAssign::ZExt: 5174 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5175 DAG.getValueType(VA.getValVT())); 5176 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5177 break; 5178 case CCValAssign::SExt: 5179 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5180 DAG.getValueType(VA.getValVT())); 5181 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5182 break; 5183 } 5184 5185 InVals.push_back(Val); 5186 } 5187 5188 return Chain; 5189 } 5190 5191 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5192 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5193 // PatchPoint calls are not indirect. 5194 if (isPatchPoint) 5195 return false; 5196 5197 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 5198 return false; 5199 5200 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5201 // becuase the immediate function pointer points to a descriptor instead of 5202 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5203 // pointer immediate points to the global entry point, while the BLA would 5204 // need to jump to the local entry point (see rL211174). 5205 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5206 isBLACompatibleAddress(Callee, DAG)) 5207 return false; 5208 5209 return true; 5210 } 5211 5212 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5213 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5214 return Subtarget.isAIXABI() || 5215 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5216 } 5217 5218 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5219 const Function &Caller, const SDValue &Callee, 5220 const PPCSubtarget &Subtarget, 5221 const TargetMachine &TM, 5222 bool IsStrictFPCall = false) { 5223 if (CFlags.IsTailCall) 5224 return PPCISD::TC_RETURN; 5225 5226 unsigned RetOpc = 0; 5227 // This is a call through a function pointer. 5228 if (CFlags.IsIndirect) { 5229 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5230 // indirect calls. The save of the caller's TOC pointer to the stack will be 5231 // inserted into the DAG as part of call lowering. The restore of the TOC 5232 // pointer is modeled by using a pseudo instruction for the call opcode that 5233 // represents the 2 instruction sequence of an indirect branch and link, 5234 // immediately followed by a load of the TOC pointer from the the stack save 5235 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5236 // as it is not saved or used. 5237 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5238 : PPCISD::BCTRL; 5239 } else if (Subtarget.isUsingPCRelativeCalls()) { 5240 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5241 RetOpc = PPCISD::CALL_NOTOC; 5242 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5243 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5244 // immediately following the call instruction if the caller and callee may 5245 // have different TOC bases. At link time if the linker determines the calls 5246 // may not share a TOC base, the call is redirected to a trampoline inserted 5247 // by the linker. The trampoline will (among other things) save the callers 5248 // TOC pointer at an ABI designated offset in the linkage area and the 5249 // linker will rewrite the nop to be a load of the TOC pointer from the 5250 // linkage area into gpr2. 5251 RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5252 : PPCISD::CALL_NOP; 5253 else 5254 RetOpc = PPCISD::CALL; 5255 if (IsStrictFPCall) { 5256 switch (RetOpc) { 5257 default: 5258 llvm_unreachable("Unknown call opcode"); 5259 case PPCISD::BCTRL_LOAD_TOC: 5260 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM; 5261 break; 5262 case PPCISD::BCTRL: 5263 RetOpc = PPCISD::BCTRL_RM; 5264 break; 5265 case PPCISD::CALL_NOTOC: 5266 RetOpc = PPCISD::CALL_NOTOC_RM; 5267 break; 5268 case PPCISD::CALL: 5269 RetOpc = PPCISD::CALL_RM; 5270 break; 5271 case PPCISD::CALL_NOP: 5272 RetOpc = PPCISD::CALL_NOP_RM; 5273 break; 5274 } 5275 } 5276 return RetOpc; 5277 } 5278 5279 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5280 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5281 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5282 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5283 return SDValue(Dest, 0); 5284 5285 // Returns true if the callee is local, and false otherwise. 5286 auto isLocalCallee = [&]() { 5287 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5288 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5289 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5290 5291 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5292 !isa_and_nonnull<GlobalIFunc>(GV); 5293 }; 5294 5295 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5296 // a static relocation model causes some versions of GNU LD (2.17.50, at 5297 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5298 // built with secure-PLT. 5299 bool UsePlt = 5300 Subtarget.is32BitELFABI() && !isLocalCallee() && 5301 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5302 5303 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5304 const TargetMachine &TM = Subtarget.getTargetMachine(); 5305 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5306 MCSymbolXCOFF *S = 5307 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5308 5309 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5310 return DAG.getMCSymbol(S, PtrVT); 5311 }; 5312 5313 if (isFunctionGlobalAddress(Callee)) { 5314 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5315 5316 if (Subtarget.isAIXABI()) { 5317 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5318 return getAIXFuncEntryPointSymbolSDNode(GV); 5319 } 5320 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5321 UsePlt ? PPCII::MO_PLT : 0); 5322 } 5323 5324 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5325 const char *SymName = S->getSymbol(); 5326 if (Subtarget.isAIXABI()) { 5327 // If there exists a user-declared function whose name is the same as the 5328 // ExternalSymbol's, then we pick up the user-declared version. 5329 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5330 if (const Function *F = 5331 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5332 return getAIXFuncEntryPointSymbolSDNode(F); 5333 5334 // On AIX, direct function calls reference the symbol for the function's 5335 // entry point, which is named by prepending a "." before the function's 5336 // C-linkage name. A Qualname is returned here because an external 5337 // function entry point is a csect with XTY_ER property. 5338 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5339 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5340 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5341 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5342 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5343 return Sec->getQualNameSymbol(); 5344 }; 5345 5346 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5347 } 5348 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5349 UsePlt ? PPCII::MO_PLT : 0); 5350 } 5351 5352 // No transformation needed. 5353 assert(Callee.getNode() && "What no callee?"); 5354 return Callee; 5355 } 5356 5357 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5358 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5359 "Expected a CALLSEQ_STARTSDNode."); 5360 5361 // The last operand is the chain, except when the node has glue. If the node 5362 // has glue, then the last operand is the glue, and the chain is the second 5363 // last operand. 5364 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5365 if (LastValue.getValueType() != MVT::Glue) 5366 return LastValue; 5367 5368 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5369 } 5370 5371 // Creates the node that moves a functions address into the count register 5372 // to prepare for an indirect call instruction. 5373 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5374 SDValue &Glue, SDValue &Chain, 5375 const SDLoc &dl) { 5376 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5377 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5378 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5379 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5380 // The glue is the second value produced. 5381 Glue = Chain.getValue(1); 5382 } 5383 5384 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5385 SDValue &Glue, SDValue &Chain, 5386 SDValue CallSeqStart, 5387 const CallBase *CB, const SDLoc &dl, 5388 bool hasNest, 5389 const PPCSubtarget &Subtarget) { 5390 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5391 // entry point, but to the function descriptor (the function entry point 5392 // address is part of the function descriptor though). 5393 // The function descriptor is a three doubleword structure with the 5394 // following fields: function entry point, TOC base address and 5395 // environment pointer. 5396 // Thus for a call through a function pointer, the following actions need 5397 // to be performed: 5398 // 1. Save the TOC of the caller in the TOC save area of its stack 5399 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5400 // 2. Load the address of the function entry point from the function 5401 // descriptor. 5402 // 3. Load the TOC of the callee from the function descriptor into r2. 5403 // 4. Load the environment pointer from the function descriptor into 5404 // r11. 5405 // 5. Branch to the function entry point address. 5406 // 6. On return of the callee, the TOC of the caller needs to be 5407 // restored (this is done in FinishCall()). 5408 // 5409 // The loads are scheduled at the beginning of the call sequence, and the 5410 // register copies are flagged together to ensure that no other 5411 // operations can be scheduled in between. E.g. without flagging the 5412 // copies together, a TOC access in the caller could be scheduled between 5413 // the assignment of the callee TOC and the branch to the callee, which leads 5414 // to incorrect code. 5415 5416 // Start by loading the function address from the descriptor. 5417 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5418 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5419 ? (MachineMemOperand::MODereferenceable | 5420 MachineMemOperand::MOInvariant) 5421 : MachineMemOperand::MONone; 5422 5423 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5424 5425 // Registers used in building the DAG. 5426 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5427 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5428 5429 // Offsets of descriptor members. 5430 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5431 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5432 5433 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5434 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5435 5436 // One load for the functions entry point address. 5437 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5438 Alignment, MMOFlags); 5439 5440 // One for loading the TOC anchor for the module that contains the called 5441 // function. 5442 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5443 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5444 SDValue TOCPtr = 5445 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5446 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5447 5448 // One for loading the environment pointer. 5449 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5450 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5451 SDValue LoadEnvPtr = 5452 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5453 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5454 5455 5456 // Then copy the newly loaded TOC anchor to the TOC pointer. 5457 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5458 Chain = TOCVal.getValue(0); 5459 Glue = TOCVal.getValue(1); 5460 5461 // If the function call has an explicit 'nest' parameter, it takes the 5462 // place of the environment pointer. 5463 assert((!hasNest || !Subtarget.isAIXABI()) && 5464 "Nest parameter is not supported on AIX."); 5465 if (!hasNest) { 5466 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5467 Chain = EnvVal.getValue(0); 5468 Glue = EnvVal.getValue(1); 5469 } 5470 5471 // The rest of the indirect call sequence is the same as the non-descriptor 5472 // DAG. 5473 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5474 } 5475 5476 static void 5477 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5478 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5479 SelectionDAG &DAG, 5480 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5481 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5482 const PPCSubtarget &Subtarget) { 5483 const bool IsPPC64 = Subtarget.isPPC64(); 5484 // MVT for a general purpose register. 5485 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5486 5487 // First operand is always the chain. 5488 Ops.push_back(Chain); 5489 5490 // If it's a direct call pass the callee as the second operand. 5491 if (!CFlags.IsIndirect) 5492 Ops.push_back(Callee); 5493 else { 5494 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5495 5496 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5497 // on the stack (this would have been done in `LowerCall_64SVR4` or 5498 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5499 // represents both the indirect branch and a load that restores the TOC 5500 // pointer from the linkage area. The operand for the TOC restore is an add 5501 // of the TOC save offset to the stack pointer. This must be the second 5502 // operand: after the chain input but before any other variadic arguments. 5503 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5504 // saved or used. 5505 if (isTOCSaveRestoreRequired(Subtarget)) { 5506 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5507 5508 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5509 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5510 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5511 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5512 Ops.push_back(AddTOC); 5513 } 5514 5515 // Add the register used for the environment pointer. 5516 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5517 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5518 RegVT)); 5519 5520 5521 // Add CTR register as callee so a bctr can be emitted later. 5522 if (CFlags.IsTailCall) 5523 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5524 } 5525 5526 // If this is a tail call add stack pointer delta. 5527 if (CFlags.IsTailCall) 5528 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5529 5530 // Add argument registers to the end of the list so that they are known live 5531 // into the call. 5532 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5533 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5534 RegsToPass[i].second.getValueType())); 5535 5536 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5537 // no way to mark dependencies as implicit here. 5538 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5539 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5540 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5541 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5542 5543 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5544 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5545 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5546 5547 // Add a register mask operand representing the call-preserved registers. 5548 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5549 const uint32_t *Mask = 5550 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5551 assert(Mask && "Missing call preserved mask for calling convention"); 5552 Ops.push_back(DAG.getRegisterMask(Mask)); 5553 5554 // If the glue is valid, it is the last operand. 5555 if (Glue.getNode()) 5556 Ops.push_back(Glue); 5557 } 5558 5559 SDValue PPCTargetLowering::FinishCall( 5560 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5561 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5562 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5563 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5564 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5565 5566 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5567 Subtarget.isAIXABI()) 5568 setUsesTOCBasePtr(DAG); 5569 5570 unsigned CallOpc = 5571 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5572 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false); 5573 5574 if (!CFlags.IsIndirect) 5575 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5576 else if (Subtarget.usesFunctionDescriptors()) 5577 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5578 dl, CFlags.HasNest, Subtarget); 5579 else 5580 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5581 5582 // Build the operand list for the call instruction. 5583 SmallVector<SDValue, 8> Ops; 5584 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5585 SPDiff, Subtarget); 5586 5587 // Emit tail call. 5588 if (CFlags.IsTailCall) { 5589 // Indirect tail call when using PC Relative calls do not have the same 5590 // constraints. 5591 assert(((Callee.getOpcode() == ISD::Register && 5592 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5593 Callee.getOpcode() == ISD::TargetExternalSymbol || 5594 Callee.getOpcode() == ISD::TargetGlobalAddress || 5595 isa<ConstantSDNode>(Callee) || 5596 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5597 "Expecting a global address, external symbol, absolute value, " 5598 "register or an indirect tail call when PC Relative calls are " 5599 "used."); 5600 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5601 assert(CallOpc == PPCISD::TC_RETURN && 5602 "Unexpected call opcode for a tail call."); 5603 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5604 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5605 } 5606 5607 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5608 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5609 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5610 Glue = Chain.getValue(1); 5611 5612 // When performing tail call optimization the callee pops its arguments off 5613 // the stack. Account for this here so these bytes can be pushed back on in 5614 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5615 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5616 getTargetMachine().Options.GuaranteedTailCallOpt) 5617 ? NumBytes 5618 : 0; 5619 5620 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5621 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5622 Glue, dl); 5623 Glue = Chain.getValue(1); 5624 5625 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5626 DAG, InVals); 5627 } 5628 5629 SDValue 5630 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5631 SmallVectorImpl<SDValue> &InVals) const { 5632 SelectionDAG &DAG = CLI.DAG; 5633 SDLoc &dl = CLI.DL; 5634 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5635 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5636 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5637 SDValue Chain = CLI.Chain; 5638 SDValue Callee = CLI.Callee; 5639 bool &isTailCall = CLI.IsTailCall; 5640 CallingConv::ID CallConv = CLI.CallConv; 5641 bool isVarArg = CLI.IsVarArg; 5642 bool isPatchPoint = CLI.IsPatchPoint; 5643 const CallBase *CB = CLI.CB; 5644 5645 if (isTailCall) { 5646 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5647 isTailCall = false; 5648 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5649 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5650 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5651 else 5652 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5653 Ins, DAG); 5654 if (isTailCall) { 5655 ++NumTailCalls; 5656 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5657 ++NumSiblingCalls; 5658 5659 // PC Relative calls no longer guarantee that the callee is a Global 5660 // Address Node. The callee could be an indirect tail call in which 5661 // case the SDValue for the callee could be a load (to load the address 5662 // of a function pointer) or it may be a register copy (to move the 5663 // address of the callee from a function parameter into a virtual 5664 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5665 assert((Subtarget.isUsingPCRelativeCalls() || 5666 isa<GlobalAddressSDNode>(Callee)) && 5667 "Callee should be an llvm::Function object."); 5668 5669 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5670 << "\nTCO callee: "); 5671 LLVM_DEBUG(Callee.dump()); 5672 } 5673 } 5674 5675 if (!isTailCall && CB && CB->isMustTailCall()) 5676 report_fatal_error("failed to perform tail call elimination on a call " 5677 "site marked musttail"); 5678 5679 // When long calls (i.e. indirect calls) are always used, calls are always 5680 // made via function pointer. If we have a function name, first translate it 5681 // into a pointer. 5682 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5683 !isTailCall) 5684 Callee = LowerGlobalAddress(Callee, DAG); 5685 5686 CallFlags CFlags( 5687 CallConv, isTailCall, isVarArg, isPatchPoint, 5688 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5689 // hasNest 5690 Subtarget.is64BitELFABI() && 5691 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5692 CLI.NoMerge); 5693 5694 if (Subtarget.isAIXABI()) 5695 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5696 InVals, CB); 5697 5698 assert(Subtarget.isSVR4ABI()); 5699 if (Subtarget.isPPC64()) 5700 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5701 InVals, CB); 5702 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5703 InVals, CB); 5704 } 5705 5706 SDValue PPCTargetLowering::LowerCall_32SVR4( 5707 SDValue Chain, SDValue Callee, CallFlags CFlags, 5708 const SmallVectorImpl<ISD::OutputArg> &Outs, 5709 const SmallVectorImpl<SDValue> &OutVals, 5710 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5711 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5712 const CallBase *CB) const { 5713 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5714 // of the 32-bit SVR4 ABI stack frame layout. 5715 5716 const CallingConv::ID CallConv = CFlags.CallConv; 5717 const bool IsVarArg = CFlags.IsVarArg; 5718 const bool IsTailCall = CFlags.IsTailCall; 5719 5720 assert((CallConv == CallingConv::C || 5721 CallConv == CallingConv::Cold || 5722 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5723 5724 const Align PtrAlign(4); 5725 5726 MachineFunction &MF = DAG.getMachineFunction(); 5727 5728 // Mark this function as potentially containing a function that contains a 5729 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5730 // and restoring the callers stack pointer in this functions epilog. This is 5731 // done because by tail calling the called function might overwrite the value 5732 // in this function's (MF) stack pointer stack slot 0(SP). 5733 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5734 CallConv == CallingConv::Fast) 5735 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5736 5737 // Count how many bytes are to be pushed on the stack, including the linkage 5738 // area, parameter list area and the part of the local variable space which 5739 // contains copies of aggregates which are passed by value. 5740 5741 // Assign locations to all of the outgoing arguments. 5742 SmallVector<CCValAssign, 16> ArgLocs; 5743 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5744 5745 // Reserve space for the linkage area on the stack. 5746 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5747 PtrAlign); 5748 if (useSoftFloat()) 5749 CCInfo.PreAnalyzeCallOperands(Outs); 5750 5751 if (IsVarArg) { 5752 // Handle fixed and variable vector arguments differently. 5753 // Fixed vector arguments go into registers as long as registers are 5754 // available. Variable vector arguments always go into memory. 5755 unsigned NumArgs = Outs.size(); 5756 5757 for (unsigned i = 0; i != NumArgs; ++i) { 5758 MVT ArgVT = Outs[i].VT; 5759 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5760 bool Result; 5761 5762 if (Outs[i].IsFixed) { 5763 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5764 CCInfo); 5765 } else { 5766 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5767 ArgFlags, CCInfo); 5768 } 5769 5770 if (Result) { 5771 #ifndef NDEBUG 5772 errs() << "Call operand #" << i << " has unhandled type " 5773 << EVT(ArgVT).getEVTString() << "\n"; 5774 #endif 5775 llvm_unreachable(nullptr); 5776 } 5777 } 5778 } else { 5779 // All arguments are treated the same. 5780 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5781 } 5782 CCInfo.clearWasPPCF128(); 5783 5784 // Assign locations to all of the outgoing aggregate by value arguments. 5785 SmallVector<CCValAssign, 16> ByValArgLocs; 5786 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5787 5788 // Reserve stack space for the allocations in CCInfo. 5789 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5790 5791 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5792 5793 // Size of the linkage area, parameter list area and the part of the local 5794 // space variable where copies of aggregates which are passed by value are 5795 // stored. 5796 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5797 5798 // Calculate by how many bytes the stack has to be adjusted in case of tail 5799 // call optimization. 5800 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5801 5802 // Adjust the stack pointer for the new arguments... 5803 // These operations are automatically eliminated by the prolog/epilog pass 5804 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5805 SDValue CallSeqStart = Chain; 5806 5807 // Load the return address and frame pointer so it can be moved somewhere else 5808 // later. 5809 SDValue LROp, FPOp; 5810 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5811 5812 // Set up a copy of the stack pointer for use loading and storing any 5813 // arguments that may not fit in the registers available for argument 5814 // passing. 5815 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5816 5817 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5818 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5819 SmallVector<SDValue, 8> MemOpChains; 5820 5821 bool seenFloatArg = false; 5822 // Walk the register/memloc assignments, inserting copies/loads. 5823 // i - Tracks the index into the list of registers allocated for the call 5824 // RealArgIdx - Tracks the index into the list of actual function arguments 5825 // j - Tracks the index into the list of byval arguments 5826 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5827 i != e; 5828 ++i, ++RealArgIdx) { 5829 CCValAssign &VA = ArgLocs[i]; 5830 SDValue Arg = OutVals[RealArgIdx]; 5831 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5832 5833 if (Flags.isByVal()) { 5834 // Argument is an aggregate which is passed by value, thus we need to 5835 // create a copy of it in the local variable space of the current stack 5836 // frame (which is the stack frame of the caller) and pass the address of 5837 // this copy to the callee. 5838 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5839 CCValAssign &ByValVA = ByValArgLocs[j++]; 5840 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5841 5842 // Memory reserved in the local variable space of the callers stack frame. 5843 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5844 5845 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5846 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5847 StackPtr, PtrOff); 5848 5849 // Create a copy of the argument in the local area of the current 5850 // stack frame. 5851 SDValue MemcpyCall = 5852 CreateCopyOfByValArgument(Arg, PtrOff, 5853 CallSeqStart.getNode()->getOperand(0), 5854 Flags, DAG, dl); 5855 5856 // This must go outside the CALLSEQ_START..END. 5857 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5858 SDLoc(MemcpyCall)); 5859 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5860 NewCallSeqStart.getNode()); 5861 Chain = CallSeqStart = NewCallSeqStart; 5862 5863 // Pass the address of the aggregate copy on the stack either in a 5864 // physical register or in the parameter list area of the current stack 5865 // frame to the callee. 5866 Arg = PtrOff; 5867 } 5868 5869 // When useCRBits() is true, there can be i1 arguments. 5870 // It is because getRegisterType(MVT::i1) => MVT::i1, 5871 // and for other integer types getRegisterType() => MVT::i32. 5872 // Extend i1 and ensure callee will get i32. 5873 if (Arg.getValueType() == MVT::i1) 5874 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5875 dl, MVT::i32, Arg); 5876 5877 if (VA.isRegLoc()) { 5878 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5879 // Put argument in a physical register. 5880 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5881 bool IsLE = Subtarget.isLittleEndian(); 5882 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5883 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5884 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5885 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5886 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5887 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5888 SVal.getValue(0))); 5889 } else 5890 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5891 } else { 5892 // Put argument in the parameter list area of the current stack frame. 5893 assert(VA.isMemLoc()); 5894 unsigned LocMemOffset = VA.getLocMemOffset(); 5895 5896 if (!IsTailCall) { 5897 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5898 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5899 StackPtr, PtrOff); 5900 5901 MemOpChains.push_back( 5902 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5903 } else { 5904 // Calculate and remember argument location. 5905 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5906 TailCallArguments); 5907 } 5908 } 5909 } 5910 5911 if (!MemOpChains.empty()) 5912 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5913 5914 // Build a sequence of copy-to-reg nodes chained together with token chain 5915 // and flag operands which copy the outgoing args into the appropriate regs. 5916 SDValue InFlag; 5917 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5918 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5919 RegsToPass[i].second, InFlag); 5920 InFlag = Chain.getValue(1); 5921 } 5922 5923 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5924 // registers. 5925 if (IsVarArg) { 5926 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5927 SDValue Ops[] = { Chain, InFlag }; 5928 5929 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5930 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5931 5932 InFlag = Chain.getValue(1); 5933 } 5934 5935 if (IsTailCall) 5936 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5937 TailCallArguments); 5938 5939 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5940 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5941 } 5942 5943 // Copy an argument into memory, being careful to do this outside the 5944 // call sequence for the call to which the argument belongs. 5945 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5946 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5947 SelectionDAG &DAG, const SDLoc &dl) const { 5948 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5949 CallSeqStart.getNode()->getOperand(0), 5950 Flags, DAG, dl); 5951 // The MEMCPY must go outside the CALLSEQ_START..END. 5952 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5953 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5954 SDLoc(MemcpyCall)); 5955 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5956 NewCallSeqStart.getNode()); 5957 return NewCallSeqStart; 5958 } 5959 5960 SDValue PPCTargetLowering::LowerCall_64SVR4( 5961 SDValue Chain, SDValue Callee, CallFlags CFlags, 5962 const SmallVectorImpl<ISD::OutputArg> &Outs, 5963 const SmallVectorImpl<SDValue> &OutVals, 5964 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5965 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5966 const CallBase *CB) const { 5967 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5968 bool isLittleEndian = Subtarget.isLittleEndian(); 5969 unsigned NumOps = Outs.size(); 5970 bool IsSibCall = false; 5971 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5972 5973 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5974 unsigned PtrByteSize = 8; 5975 5976 MachineFunction &MF = DAG.getMachineFunction(); 5977 5978 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5979 IsSibCall = true; 5980 5981 // Mark this function as potentially containing a function that contains a 5982 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5983 // and restoring the callers stack pointer in this functions epilog. This is 5984 // done because by tail calling the called function might overwrite the value 5985 // in this function's (MF) stack pointer stack slot 0(SP). 5986 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5987 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5988 5989 assert(!(IsFastCall && CFlags.IsVarArg) && 5990 "fastcc not supported on varargs functions"); 5991 5992 // Count how many bytes are to be pushed on the stack, including the linkage 5993 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5994 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5995 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5996 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5997 unsigned NumBytes = LinkageSize; 5998 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5999 6000 static const MCPhysReg GPR[] = { 6001 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6002 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6003 }; 6004 static const MCPhysReg VR[] = { 6005 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6006 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6007 }; 6008 6009 const unsigned NumGPRs = array_lengthof(GPR); 6010 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 6011 const unsigned NumVRs = array_lengthof(VR); 6012 6013 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6014 // can be passed to the callee in registers. 6015 // For the fast calling convention, there is another check below. 6016 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6017 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6018 if (!HasParameterArea) { 6019 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6020 unsigned AvailableFPRs = NumFPRs; 6021 unsigned AvailableVRs = NumVRs; 6022 unsigned NumBytesTmp = NumBytes; 6023 for (unsigned i = 0; i != NumOps; ++i) { 6024 if (Outs[i].Flags.isNest()) continue; 6025 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6026 PtrByteSize, LinkageSize, ParamAreaSize, 6027 NumBytesTmp, AvailableFPRs, AvailableVRs)) 6028 HasParameterArea = true; 6029 } 6030 } 6031 6032 // When using the fast calling convention, we don't provide backing for 6033 // arguments that will be in registers. 6034 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6035 6036 // Avoid allocating parameter area for fastcc functions if all the arguments 6037 // can be passed in the registers. 6038 if (IsFastCall) 6039 HasParameterArea = false; 6040 6041 // Add up all the space actually used. 6042 for (unsigned i = 0; i != NumOps; ++i) { 6043 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6044 EVT ArgVT = Outs[i].VT; 6045 EVT OrigVT = Outs[i].ArgVT; 6046 6047 if (Flags.isNest()) 6048 continue; 6049 6050 if (IsFastCall) { 6051 if (Flags.isByVal()) { 6052 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6053 if (NumGPRsUsed > NumGPRs) 6054 HasParameterArea = true; 6055 } else { 6056 switch (ArgVT.getSimpleVT().SimpleTy) { 6057 default: llvm_unreachable("Unexpected ValueType for argument!"); 6058 case MVT::i1: 6059 case MVT::i32: 6060 case MVT::i64: 6061 if (++NumGPRsUsed <= NumGPRs) 6062 continue; 6063 break; 6064 case MVT::v4i32: 6065 case MVT::v8i16: 6066 case MVT::v16i8: 6067 case MVT::v2f64: 6068 case MVT::v2i64: 6069 case MVT::v1i128: 6070 case MVT::f128: 6071 if (++NumVRsUsed <= NumVRs) 6072 continue; 6073 break; 6074 case MVT::v4f32: 6075 if (++NumVRsUsed <= NumVRs) 6076 continue; 6077 break; 6078 case MVT::f32: 6079 case MVT::f64: 6080 if (++NumFPRsUsed <= NumFPRs) 6081 continue; 6082 break; 6083 } 6084 HasParameterArea = true; 6085 } 6086 } 6087 6088 /* Respect alignment of argument on the stack. */ 6089 auto Alignement = 6090 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6091 NumBytes = alignTo(NumBytes, Alignement); 6092 6093 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6094 if (Flags.isInConsecutiveRegsLast()) 6095 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6096 } 6097 6098 unsigned NumBytesActuallyUsed = NumBytes; 6099 6100 // In the old ELFv1 ABI, 6101 // the prolog code of the callee may store up to 8 GPR argument registers to 6102 // the stack, allowing va_start to index over them in memory if its varargs. 6103 // Because we cannot tell if this is needed on the caller side, we have to 6104 // conservatively assume that it is needed. As such, make sure we have at 6105 // least enough stack space for the caller to store the 8 GPRs. 6106 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6107 // really requires memory operands, e.g. a vararg function. 6108 if (HasParameterArea) 6109 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6110 else 6111 NumBytes = LinkageSize; 6112 6113 // Tail call needs the stack to be aligned. 6114 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6115 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6116 6117 int SPDiff = 0; 6118 6119 // Calculate by how many bytes the stack has to be adjusted in case of tail 6120 // call optimization. 6121 if (!IsSibCall) 6122 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6123 6124 // To protect arguments on the stack from being clobbered in a tail call, 6125 // force all the loads to happen before doing any other lowering. 6126 if (CFlags.IsTailCall) 6127 Chain = DAG.getStackArgumentTokenFactor(Chain); 6128 6129 // Adjust the stack pointer for the new arguments... 6130 // These operations are automatically eliminated by the prolog/epilog pass 6131 if (!IsSibCall) 6132 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6133 SDValue CallSeqStart = Chain; 6134 6135 // Load the return address and frame pointer so it can be move somewhere else 6136 // later. 6137 SDValue LROp, FPOp; 6138 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6139 6140 // Set up a copy of the stack pointer for use loading and storing any 6141 // arguments that may not fit in the registers available for argument 6142 // passing. 6143 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6144 6145 // Figure out which arguments are going to go in registers, and which in 6146 // memory. Also, if this is a vararg function, floating point operations 6147 // must be stored to our stack, and loaded into integer regs as well, if 6148 // any integer regs are available for argument passing. 6149 unsigned ArgOffset = LinkageSize; 6150 6151 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6152 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6153 6154 SmallVector<SDValue, 8> MemOpChains; 6155 for (unsigned i = 0; i != NumOps; ++i) { 6156 SDValue Arg = OutVals[i]; 6157 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6158 EVT ArgVT = Outs[i].VT; 6159 EVT OrigVT = Outs[i].ArgVT; 6160 6161 // PtrOff will be used to store the current argument to the stack if a 6162 // register cannot be found for it. 6163 SDValue PtrOff; 6164 6165 // We re-align the argument offset for each argument, except when using the 6166 // fast calling convention, when we need to make sure we do that only when 6167 // we'll actually use a stack slot. 6168 auto ComputePtrOff = [&]() { 6169 /* Respect alignment of argument on the stack. */ 6170 auto Alignment = 6171 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6172 ArgOffset = alignTo(ArgOffset, Alignment); 6173 6174 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6175 6176 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6177 }; 6178 6179 if (!IsFastCall) { 6180 ComputePtrOff(); 6181 6182 /* Compute GPR index associated with argument offset. */ 6183 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6184 GPR_idx = std::min(GPR_idx, NumGPRs); 6185 } 6186 6187 // Promote integers to 64-bit values. 6188 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6189 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6190 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6191 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6192 } 6193 6194 // FIXME memcpy is used way more than necessary. Correctness first. 6195 // Note: "by value" is code for passing a structure by value, not 6196 // basic types. 6197 if (Flags.isByVal()) { 6198 // Note: Size includes alignment padding, so 6199 // struct x { short a; char b; } 6200 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6201 // These are the proper values we need for right-justifying the 6202 // aggregate in a parameter register. 6203 unsigned Size = Flags.getByValSize(); 6204 6205 // An empty aggregate parameter takes up no storage and no 6206 // registers. 6207 if (Size == 0) 6208 continue; 6209 6210 if (IsFastCall) 6211 ComputePtrOff(); 6212 6213 // All aggregates smaller than 8 bytes must be passed right-justified. 6214 if (Size==1 || Size==2 || Size==4) { 6215 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6216 if (GPR_idx != NumGPRs) { 6217 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6218 MachinePointerInfo(), VT); 6219 MemOpChains.push_back(Load.getValue(1)); 6220 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6221 6222 ArgOffset += PtrByteSize; 6223 continue; 6224 } 6225 } 6226 6227 if (GPR_idx == NumGPRs && Size < 8) { 6228 SDValue AddPtr = PtrOff; 6229 if (!isLittleEndian) { 6230 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6231 PtrOff.getValueType()); 6232 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6233 } 6234 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6235 CallSeqStart, 6236 Flags, DAG, dl); 6237 ArgOffset += PtrByteSize; 6238 continue; 6239 } 6240 // Copy the object to parameter save area if it can not be entirely passed 6241 // by registers. 6242 // FIXME: we only need to copy the parts which need to be passed in 6243 // parameter save area. For the parts passed by registers, we don't need 6244 // to copy them to the stack although we need to allocate space for them 6245 // in parameter save area. 6246 if ((NumGPRs - GPR_idx) * PtrByteSize < Size) 6247 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6248 CallSeqStart, 6249 Flags, DAG, dl); 6250 6251 // When a register is available, pass a small aggregate right-justified. 6252 if (Size < 8 && GPR_idx != NumGPRs) { 6253 // The easiest way to get this right-justified in a register 6254 // is to copy the structure into the rightmost portion of a 6255 // local variable slot, then load the whole slot into the 6256 // register. 6257 // FIXME: The memcpy seems to produce pretty awful code for 6258 // small aggregates, particularly for packed ones. 6259 // FIXME: It would be preferable to use the slot in the 6260 // parameter save area instead of a new local variable. 6261 SDValue AddPtr = PtrOff; 6262 if (!isLittleEndian) { 6263 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6264 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6265 } 6266 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6267 CallSeqStart, 6268 Flags, DAG, dl); 6269 6270 // Load the slot into the register. 6271 SDValue Load = 6272 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6273 MemOpChains.push_back(Load.getValue(1)); 6274 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6275 6276 // Done with this argument. 6277 ArgOffset += PtrByteSize; 6278 continue; 6279 } 6280 6281 // For aggregates larger than PtrByteSize, copy the pieces of the 6282 // object that fit into registers from the parameter save area. 6283 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6284 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6285 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6286 if (GPR_idx != NumGPRs) { 6287 unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8; 6288 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits); 6289 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg, 6290 MachinePointerInfo(), ObjType); 6291 6292 MemOpChains.push_back(Load.getValue(1)); 6293 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6294 ArgOffset += PtrByteSize; 6295 } else { 6296 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6297 break; 6298 } 6299 } 6300 continue; 6301 } 6302 6303 switch (Arg.getSimpleValueType().SimpleTy) { 6304 default: llvm_unreachable("Unexpected ValueType for argument!"); 6305 case MVT::i1: 6306 case MVT::i32: 6307 case MVT::i64: 6308 if (Flags.isNest()) { 6309 // The 'nest' parameter, if any, is passed in R11. 6310 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6311 break; 6312 } 6313 6314 // These can be scalar arguments or elements of an integer array type 6315 // passed directly. Clang may use those instead of "byval" aggregate 6316 // types to avoid forcing arguments to memory unnecessarily. 6317 if (GPR_idx != NumGPRs) { 6318 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6319 } else { 6320 if (IsFastCall) 6321 ComputePtrOff(); 6322 6323 assert(HasParameterArea && 6324 "Parameter area must exist to pass an argument in memory."); 6325 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6326 true, CFlags.IsTailCall, false, MemOpChains, 6327 TailCallArguments, dl); 6328 if (IsFastCall) 6329 ArgOffset += PtrByteSize; 6330 } 6331 if (!IsFastCall) 6332 ArgOffset += PtrByteSize; 6333 break; 6334 case MVT::f32: 6335 case MVT::f64: { 6336 // These can be scalar arguments or elements of a float array type 6337 // passed directly. The latter are used to implement ELFv2 homogenous 6338 // float aggregates. 6339 6340 // Named arguments go into FPRs first, and once they overflow, the 6341 // remaining arguments go into GPRs and then the parameter save area. 6342 // Unnamed arguments for vararg functions always go to GPRs and 6343 // then the parameter save area. For now, put all arguments to vararg 6344 // routines always in both locations (FPR *and* GPR or stack slot). 6345 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6346 bool NeededLoad = false; 6347 6348 // First load the argument into the next available FPR. 6349 if (FPR_idx != NumFPRs) 6350 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6351 6352 // Next, load the argument into GPR or stack slot if needed. 6353 if (!NeedGPROrStack) 6354 ; 6355 else if (GPR_idx != NumGPRs && !IsFastCall) { 6356 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6357 // once we support fp <-> gpr moves. 6358 6359 // In the non-vararg case, this can only ever happen in the 6360 // presence of f32 array types, since otherwise we never run 6361 // out of FPRs before running out of GPRs. 6362 SDValue ArgVal; 6363 6364 // Double values are always passed in a single GPR. 6365 if (Arg.getValueType() != MVT::f32) { 6366 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6367 6368 // Non-array float values are extended and passed in a GPR. 6369 } else if (!Flags.isInConsecutiveRegs()) { 6370 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6371 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6372 6373 // If we have an array of floats, we collect every odd element 6374 // together with its predecessor into one GPR. 6375 } else if (ArgOffset % PtrByteSize != 0) { 6376 SDValue Lo, Hi; 6377 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6378 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6379 if (!isLittleEndian) 6380 std::swap(Lo, Hi); 6381 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6382 6383 // The final element, if even, goes into the first half of a GPR. 6384 } else if (Flags.isInConsecutiveRegsLast()) { 6385 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6386 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6387 if (!isLittleEndian) 6388 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6389 DAG.getConstant(32, dl, MVT::i32)); 6390 6391 // Non-final even elements are skipped; they will be handled 6392 // together the with subsequent argument on the next go-around. 6393 } else 6394 ArgVal = SDValue(); 6395 6396 if (ArgVal.getNode()) 6397 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6398 } else { 6399 if (IsFastCall) 6400 ComputePtrOff(); 6401 6402 // Single-precision floating-point values are mapped to the 6403 // second (rightmost) word of the stack doubleword. 6404 if (Arg.getValueType() == MVT::f32 && 6405 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6406 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6407 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6408 } 6409 6410 assert(HasParameterArea && 6411 "Parameter area must exist to pass an argument in memory."); 6412 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6413 true, CFlags.IsTailCall, false, MemOpChains, 6414 TailCallArguments, dl); 6415 6416 NeededLoad = true; 6417 } 6418 // When passing an array of floats, the array occupies consecutive 6419 // space in the argument area; only round up to the next doubleword 6420 // at the end of the array. Otherwise, each float takes 8 bytes. 6421 if (!IsFastCall || NeededLoad) { 6422 ArgOffset += (Arg.getValueType() == MVT::f32 && 6423 Flags.isInConsecutiveRegs()) ? 4 : 8; 6424 if (Flags.isInConsecutiveRegsLast()) 6425 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6426 } 6427 break; 6428 } 6429 case MVT::v4f32: 6430 case MVT::v4i32: 6431 case MVT::v8i16: 6432 case MVT::v16i8: 6433 case MVT::v2f64: 6434 case MVT::v2i64: 6435 case MVT::v1i128: 6436 case MVT::f128: 6437 // These can be scalar arguments or elements of a vector array type 6438 // passed directly. The latter are used to implement ELFv2 homogenous 6439 // vector aggregates. 6440 6441 // For a varargs call, named arguments go into VRs or on the stack as 6442 // usual; unnamed arguments always go to the stack or the corresponding 6443 // GPRs when within range. For now, we always put the value in both 6444 // locations (or even all three). 6445 if (CFlags.IsVarArg) { 6446 assert(HasParameterArea && 6447 "Parameter area must exist if we have a varargs call."); 6448 // We could elide this store in the case where the object fits 6449 // entirely in R registers. Maybe later. 6450 SDValue Store = 6451 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6452 MemOpChains.push_back(Store); 6453 if (VR_idx != NumVRs) { 6454 SDValue Load = 6455 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6456 MemOpChains.push_back(Load.getValue(1)); 6457 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6458 } 6459 ArgOffset += 16; 6460 for (unsigned i=0; i<16; i+=PtrByteSize) { 6461 if (GPR_idx == NumGPRs) 6462 break; 6463 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6464 DAG.getConstant(i, dl, PtrVT)); 6465 SDValue Load = 6466 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6467 MemOpChains.push_back(Load.getValue(1)); 6468 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6469 } 6470 break; 6471 } 6472 6473 // Non-varargs Altivec params go into VRs or on the stack. 6474 if (VR_idx != NumVRs) { 6475 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6476 } else { 6477 if (IsFastCall) 6478 ComputePtrOff(); 6479 6480 assert(HasParameterArea && 6481 "Parameter area must exist to pass an argument in memory."); 6482 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6483 true, CFlags.IsTailCall, true, MemOpChains, 6484 TailCallArguments, dl); 6485 if (IsFastCall) 6486 ArgOffset += 16; 6487 } 6488 6489 if (!IsFastCall) 6490 ArgOffset += 16; 6491 break; 6492 } 6493 } 6494 6495 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6496 "mismatch in size of parameter area"); 6497 (void)NumBytesActuallyUsed; 6498 6499 if (!MemOpChains.empty()) 6500 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6501 6502 // Check if this is an indirect call (MTCTR/BCTRL). 6503 // See prepareDescriptorIndirectCall and buildCallOperands for more 6504 // information about calls through function pointers in the 64-bit SVR4 ABI. 6505 if (CFlags.IsIndirect) { 6506 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6507 // caller in the TOC save area. 6508 if (isTOCSaveRestoreRequired(Subtarget)) { 6509 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6510 // Load r2 into a virtual register and store it to the TOC save area. 6511 setUsesTOCBasePtr(DAG); 6512 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6513 // TOC save area offset. 6514 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6515 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6516 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6517 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6518 MachinePointerInfo::getStack( 6519 DAG.getMachineFunction(), TOCSaveOffset)); 6520 } 6521 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6522 // This does not mean the MTCTR instruction must use R12; it's easier 6523 // to model this as an extra parameter, so do that. 6524 if (isELFv2ABI && !CFlags.IsPatchPoint) 6525 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6526 } 6527 6528 // Build a sequence of copy-to-reg nodes chained together with token chain 6529 // and flag operands which copy the outgoing args into the appropriate regs. 6530 SDValue InFlag; 6531 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6532 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6533 RegsToPass[i].second, InFlag); 6534 InFlag = Chain.getValue(1); 6535 } 6536 6537 if (CFlags.IsTailCall && !IsSibCall) 6538 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6539 TailCallArguments); 6540 6541 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6542 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6543 } 6544 6545 // Returns true when the shadow of a general purpose argument register 6546 // in the parameter save area is aligned to at least 'RequiredAlign'. 6547 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6548 assert(RequiredAlign.value() <= 16 && 6549 "Required alignment greater than stack alignment."); 6550 switch (Reg) { 6551 default: 6552 report_fatal_error("called on invalid register."); 6553 case PPC::R5: 6554 case PPC::R9: 6555 case PPC::X3: 6556 case PPC::X5: 6557 case PPC::X7: 6558 case PPC::X9: 6559 // These registers are 16 byte aligned which is the most strict aligment 6560 // we can support. 6561 return true; 6562 case PPC::R3: 6563 case PPC::R7: 6564 case PPC::X4: 6565 case PPC::X6: 6566 case PPC::X8: 6567 case PPC::X10: 6568 // The shadow of these registers in the PSA is 8 byte aligned. 6569 return RequiredAlign <= 8; 6570 case PPC::R4: 6571 case PPC::R6: 6572 case PPC::R8: 6573 case PPC::R10: 6574 return RequiredAlign <= 4; 6575 } 6576 } 6577 6578 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6579 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6580 CCState &S) { 6581 AIXCCState &State = static_cast<AIXCCState &>(S); 6582 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6583 State.getMachineFunction().getSubtarget()); 6584 const bool IsPPC64 = Subtarget.isPPC64(); 6585 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6586 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6587 6588 if (ValVT == MVT::f128) 6589 report_fatal_error("f128 is unimplemented on AIX."); 6590 6591 if (ArgFlags.isNest()) 6592 report_fatal_error("Nest arguments are unimplemented."); 6593 6594 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6595 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6596 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6597 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6598 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6599 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6600 6601 static const MCPhysReg VR[] = {// Vector registers. 6602 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6603 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6604 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6605 6606 if (ArgFlags.isByVal()) { 6607 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6608 report_fatal_error("Pass-by-value arguments with alignment greater than " 6609 "register width are not supported."); 6610 6611 const unsigned ByValSize = ArgFlags.getByValSize(); 6612 6613 // An empty aggregate parameter takes up no storage and no registers, 6614 // but needs a MemLoc for a stack slot for the formal arguments side. 6615 if (ByValSize == 0) { 6616 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6617 State.getNextStackOffset(), RegVT, 6618 LocInfo)); 6619 return false; 6620 } 6621 6622 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6623 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6624 for (const unsigned E = Offset + StackSize; Offset < E; 6625 Offset += PtrAlign.value()) { 6626 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6627 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6628 else { 6629 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6630 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6631 LocInfo)); 6632 break; 6633 } 6634 } 6635 return false; 6636 } 6637 6638 // Arguments always reserve parameter save area. 6639 switch (ValVT.SimpleTy) { 6640 default: 6641 report_fatal_error("Unhandled value type for argument."); 6642 case MVT::i64: 6643 // i64 arguments should have been split to i32 for PPC32. 6644 assert(IsPPC64 && "PPC32 should have split i64 values."); 6645 LLVM_FALLTHROUGH; 6646 case MVT::i1: 6647 case MVT::i32: { 6648 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6649 // AIX integer arguments are always passed in register width. 6650 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6651 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6652 : CCValAssign::LocInfo::ZExt; 6653 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6654 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6655 else 6656 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6657 6658 return false; 6659 } 6660 case MVT::f32: 6661 case MVT::f64: { 6662 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6663 const unsigned StoreSize = LocVT.getStoreSize(); 6664 // Floats are always 4-byte aligned in the PSA on AIX. 6665 // This includes f64 in 64-bit mode for ABI compatibility. 6666 const unsigned Offset = 6667 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6668 unsigned FReg = State.AllocateReg(FPR); 6669 if (FReg) 6670 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6671 6672 // Reserve and initialize GPRs or initialize the PSA as required. 6673 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6674 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6675 assert(FReg && "An FPR should be available when a GPR is reserved."); 6676 if (State.isVarArg()) { 6677 // Successfully reserved GPRs are only initialized for vararg calls. 6678 // Custom handling is required for: 6679 // f64 in PPC32 needs to be split into 2 GPRs. 6680 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6681 State.addLoc( 6682 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6683 } 6684 } else { 6685 // If there are insufficient GPRs, the PSA needs to be initialized. 6686 // Initialization occurs even if an FPR was initialized for 6687 // compatibility with the AIX XL compiler. The full memory for the 6688 // argument will be initialized even if a prior word is saved in GPR. 6689 // A custom memLoc is used when the argument also passes in FPR so 6690 // that the callee handling can skip over it easily. 6691 State.addLoc( 6692 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6693 LocInfo) 6694 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6695 break; 6696 } 6697 } 6698 6699 return false; 6700 } 6701 case MVT::v4f32: 6702 case MVT::v4i32: 6703 case MVT::v8i16: 6704 case MVT::v16i8: 6705 case MVT::v2i64: 6706 case MVT::v2f64: 6707 case MVT::v1i128: { 6708 const unsigned VecSize = 16; 6709 const Align VecAlign(VecSize); 6710 6711 if (!State.isVarArg()) { 6712 // If there are vector registers remaining we don't consume any stack 6713 // space. 6714 if (unsigned VReg = State.AllocateReg(VR)) { 6715 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6716 return false; 6717 } 6718 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6719 // might be allocated in the portion of the PSA that is shadowed by the 6720 // GPRs. 6721 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6722 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6723 return false; 6724 } 6725 6726 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6727 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6728 6729 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6730 // Burn any underaligned registers and their shadowed stack space until 6731 // we reach the required alignment. 6732 while (NextRegIndex != GPRs.size() && 6733 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6734 // Shadow allocate register and its stack shadow. 6735 unsigned Reg = State.AllocateReg(GPRs); 6736 State.AllocateStack(PtrSize, PtrAlign); 6737 assert(Reg && "Allocating register unexpectedly failed."); 6738 (void)Reg; 6739 NextRegIndex = State.getFirstUnallocated(GPRs); 6740 } 6741 6742 // Vectors that are passed as fixed arguments are handled differently. 6743 // They are passed in VRs if any are available (unlike arguments passed 6744 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6745 // functions) 6746 if (State.isFixed(ValNo)) { 6747 if (unsigned VReg = State.AllocateReg(VR)) { 6748 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6749 // Shadow allocate GPRs and stack space even though we pass in a VR. 6750 for (unsigned I = 0; I != VecSize; I += PtrSize) 6751 State.AllocateReg(GPRs); 6752 State.AllocateStack(VecSize, VecAlign); 6753 return false; 6754 } 6755 // No vector registers remain so pass on the stack. 6756 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6757 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6758 return false; 6759 } 6760 6761 // If all GPRS are consumed then we pass the argument fully on the stack. 6762 if (NextRegIndex == GPRs.size()) { 6763 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6764 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6765 return false; 6766 } 6767 6768 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6769 // half of the argument, and then need to pass the remaining half on the 6770 // stack. 6771 if (GPRs[NextRegIndex] == PPC::R9) { 6772 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6773 State.addLoc( 6774 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6775 6776 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6777 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6778 assert(FirstReg && SecondReg && 6779 "Allocating R9 or R10 unexpectedly failed."); 6780 State.addLoc( 6781 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6782 State.addLoc( 6783 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6784 return false; 6785 } 6786 6787 // We have enough GPRs to fully pass the vector argument, and we have 6788 // already consumed any underaligned registers. Start with the custom 6789 // MemLoc and then the custom RegLocs. 6790 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6791 State.addLoc( 6792 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6793 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6794 const unsigned Reg = State.AllocateReg(GPRs); 6795 assert(Reg && "Failed to allocated register for vararg vector argument"); 6796 State.addLoc( 6797 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6798 } 6799 return false; 6800 } 6801 } 6802 return true; 6803 } 6804 6805 // So far, this function is only used by LowerFormalArguments_AIX() 6806 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6807 bool IsPPC64, 6808 bool HasP8Vector, 6809 bool HasVSX) { 6810 assert((IsPPC64 || SVT != MVT::i64) && 6811 "i64 should have been split for 32-bit codegen."); 6812 6813 switch (SVT) { 6814 default: 6815 report_fatal_error("Unexpected value type for formal argument"); 6816 case MVT::i1: 6817 case MVT::i32: 6818 case MVT::i64: 6819 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6820 case MVT::f32: 6821 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass; 6822 case MVT::f64: 6823 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass; 6824 case MVT::v4f32: 6825 case MVT::v4i32: 6826 case MVT::v8i16: 6827 case MVT::v16i8: 6828 case MVT::v2i64: 6829 case MVT::v2f64: 6830 case MVT::v1i128: 6831 return &PPC::VRRCRegClass; 6832 } 6833 } 6834 6835 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6836 SelectionDAG &DAG, SDValue ArgValue, 6837 MVT LocVT, const SDLoc &dl) { 6838 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6839 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6840 6841 if (Flags.isSExt()) 6842 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6843 DAG.getValueType(ValVT)); 6844 else if (Flags.isZExt()) 6845 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6846 DAG.getValueType(ValVT)); 6847 6848 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6849 } 6850 6851 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6852 const unsigned LASize = FL->getLinkageSize(); 6853 6854 if (PPC::GPRCRegClass.contains(Reg)) { 6855 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6856 "Reg must be a valid argument register!"); 6857 return LASize + 4 * (Reg - PPC::R3); 6858 } 6859 6860 if (PPC::G8RCRegClass.contains(Reg)) { 6861 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6862 "Reg must be a valid argument register!"); 6863 return LASize + 8 * (Reg - PPC::X3); 6864 } 6865 6866 llvm_unreachable("Only general purpose registers expected."); 6867 } 6868 6869 // AIX ABI Stack Frame Layout: 6870 // 6871 // Low Memory +--------------------------------------------+ 6872 // SP +---> | Back chain | ---+ 6873 // | +--------------------------------------------+ | 6874 // | | Saved Condition Register | | 6875 // | +--------------------------------------------+ | 6876 // | | Saved Linkage Register | | 6877 // | +--------------------------------------------+ | Linkage Area 6878 // | | Reserved for compilers | | 6879 // | +--------------------------------------------+ | 6880 // | | Reserved for binders | | 6881 // | +--------------------------------------------+ | 6882 // | | Saved TOC pointer | ---+ 6883 // | +--------------------------------------------+ 6884 // | | Parameter save area | 6885 // | +--------------------------------------------+ 6886 // | | Alloca space | 6887 // | +--------------------------------------------+ 6888 // | | Local variable space | 6889 // | +--------------------------------------------+ 6890 // | | Float/int conversion temporary | 6891 // | +--------------------------------------------+ 6892 // | | Save area for AltiVec registers | 6893 // | +--------------------------------------------+ 6894 // | | AltiVec alignment padding | 6895 // | +--------------------------------------------+ 6896 // | | Save area for VRSAVE register | 6897 // | +--------------------------------------------+ 6898 // | | Save area for General Purpose registers | 6899 // | +--------------------------------------------+ 6900 // | | Save area for Floating Point registers | 6901 // | +--------------------------------------------+ 6902 // +---- | Back chain | 6903 // High Memory +--------------------------------------------+ 6904 // 6905 // Specifications: 6906 // AIX 7.2 Assembler Language Reference 6907 // Subroutine linkage convention 6908 6909 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6910 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6911 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6912 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6913 6914 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6915 CallConv == CallingConv::Fast) && 6916 "Unexpected calling convention!"); 6917 6918 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6919 report_fatal_error("Tail call support is unimplemented on AIX."); 6920 6921 if (useSoftFloat()) 6922 report_fatal_error("Soft float support is unimplemented on AIX."); 6923 6924 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 6925 6926 const bool IsPPC64 = Subtarget.isPPC64(); 6927 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6928 6929 // Assign locations to all of the incoming arguments. 6930 SmallVector<CCValAssign, 16> ArgLocs; 6931 MachineFunction &MF = DAG.getMachineFunction(); 6932 MachineFrameInfo &MFI = MF.getFrameInfo(); 6933 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6934 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6935 6936 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6937 // Reserve space for the linkage area on the stack. 6938 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6939 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6940 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6941 6942 SmallVector<SDValue, 8> MemOps; 6943 6944 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6945 CCValAssign &VA = ArgLocs[I++]; 6946 MVT LocVT = VA.getLocVT(); 6947 MVT ValVT = VA.getValVT(); 6948 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6949 // For compatibility with the AIX XL compiler, the float args in the 6950 // parameter save area are initialized even if the argument is available 6951 // in register. The caller is required to initialize both the register 6952 // and memory, however, the callee can choose to expect it in either. 6953 // The memloc is dismissed here because the argument is retrieved from 6954 // the register. 6955 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6956 continue; 6957 6958 auto HandleMemLoc = [&]() { 6959 const unsigned LocSize = LocVT.getStoreSize(); 6960 const unsigned ValSize = ValVT.getStoreSize(); 6961 assert((ValSize <= LocSize) && 6962 "Object size is larger than size of MemLoc"); 6963 int CurArgOffset = VA.getLocMemOffset(); 6964 // Objects are right-justified because AIX is big-endian. 6965 if (LocSize > ValSize) 6966 CurArgOffset += LocSize - ValSize; 6967 // Potential tail calls could cause overwriting of argument stack slots. 6968 const bool IsImmutable = 6969 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6970 (CallConv == CallingConv::Fast)); 6971 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6972 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6973 SDValue ArgValue = 6974 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6975 InVals.push_back(ArgValue); 6976 }; 6977 6978 // Vector arguments to VaArg functions are passed both on the stack, and 6979 // in any available GPRs. Load the value from the stack and add the GPRs 6980 // as live ins. 6981 if (VA.isMemLoc() && VA.needsCustom()) { 6982 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 6983 assert(isVarArg && "Only use custom memloc for vararg."); 6984 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 6985 // matching custom RegLocs. 6986 const unsigned OriginalValNo = VA.getValNo(); 6987 (void)OriginalValNo; 6988 6989 auto HandleCustomVecRegLoc = [&]() { 6990 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 6991 "Missing custom RegLoc."); 6992 VA = ArgLocs[I++]; 6993 assert(VA.getValVT().isVector() && 6994 "Unexpected Val type for custom RegLoc."); 6995 assert(VA.getValNo() == OriginalValNo && 6996 "ValNo mismatch between custom MemLoc and RegLoc."); 6997 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 6998 MF.addLiveIn(VA.getLocReg(), 6999 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7000 Subtarget.hasVSX())); 7001 }; 7002 7003 HandleMemLoc(); 7004 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7005 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7006 // R10. 7007 HandleCustomVecRegLoc(); 7008 HandleCustomVecRegLoc(); 7009 7010 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 7011 // we passed the vector in R5, R6, R7 and R8. 7012 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 7013 assert(!IsPPC64 && 7014 "Only 2 custom RegLocs expected for 64-bit codegen."); 7015 HandleCustomVecRegLoc(); 7016 HandleCustomVecRegLoc(); 7017 } 7018 7019 continue; 7020 } 7021 7022 if (VA.isRegLoc()) { 7023 if (VA.getValVT().isScalarInteger()) 7024 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7025 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) { 7026 switch (VA.getValVT().SimpleTy) { 7027 default: 7028 report_fatal_error("Unhandled value type for argument."); 7029 case MVT::f32: 7030 FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint); 7031 break; 7032 case MVT::f64: 7033 FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint); 7034 break; 7035 } 7036 } else if (VA.getValVT().isVector()) { 7037 switch (VA.getValVT().SimpleTy) { 7038 default: 7039 report_fatal_error("Unhandled value type for argument."); 7040 case MVT::v16i8: 7041 FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar); 7042 break; 7043 case MVT::v8i16: 7044 FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort); 7045 break; 7046 case MVT::v4i32: 7047 case MVT::v2i64: 7048 case MVT::v1i128: 7049 FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt); 7050 break; 7051 case MVT::v4f32: 7052 case MVT::v2f64: 7053 FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat); 7054 break; 7055 } 7056 } 7057 } 7058 7059 if (Flags.isByVal() && VA.isMemLoc()) { 7060 const unsigned Size = 7061 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7062 PtrByteSize); 7063 const int FI = MF.getFrameInfo().CreateFixedObject( 7064 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7065 /* IsAliased */ true); 7066 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7067 InVals.push_back(FIN); 7068 7069 continue; 7070 } 7071 7072 if (Flags.isByVal()) { 7073 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7074 7075 const MCPhysReg ArgReg = VA.getLocReg(); 7076 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7077 7078 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7079 report_fatal_error("Over aligned byvals not supported yet."); 7080 7081 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7082 const int FI = MF.getFrameInfo().CreateFixedObject( 7083 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7084 /* IsAliased */ true); 7085 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7086 InVals.push_back(FIN); 7087 7088 // Add live ins for all the RegLocs for the same ByVal. 7089 const TargetRegisterClass *RegClass = 7090 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7091 7092 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7093 unsigned Offset) { 7094 const Register VReg = MF.addLiveIn(PhysReg, RegClass); 7095 // Since the callers side has left justified the aggregate in the 7096 // register, we can simply store the entire register into the stack 7097 // slot. 7098 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7099 // The store to the fixedstack object is needed becuase accessing a 7100 // field of the ByVal will use a gep and load. Ideally we will optimize 7101 // to extracting the value from the register directly, and elide the 7102 // stores when the arguments address is not taken, but that will need to 7103 // be future work. 7104 SDValue Store = DAG.getStore( 7105 CopyFrom.getValue(1), dl, CopyFrom, 7106 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7107 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7108 7109 MemOps.push_back(Store); 7110 }; 7111 7112 unsigned Offset = 0; 7113 HandleRegLoc(VA.getLocReg(), Offset); 7114 Offset += PtrByteSize; 7115 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7116 Offset += PtrByteSize) { 7117 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7118 "RegLocs should be for ByVal argument."); 7119 7120 const CCValAssign RL = ArgLocs[I++]; 7121 HandleRegLoc(RL.getLocReg(), Offset); 7122 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7123 } 7124 7125 if (Offset != StackSize) { 7126 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7127 "Expected MemLoc for remaining bytes."); 7128 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7129 // Consume the MemLoc.The InVal has already been emitted, so nothing 7130 // more needs to be done. 7131 ++I; 7132 } 7133 7134 continue; 7135 } 7136 7137 if (VA.isRegLoc() && !VA.needsCustom()) { 7138 MVT::SimpleValueType SVT = ValVT.SimpleTy; 7139 Register VReg = 7140 MF.addLiveIn(VA.getLocReg(), 7141 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7142 Subtarget.hasVSX())); 7143 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7144 if (ValVT.isScalarInteger() && 7145 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7146 ArgValue = 7147 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7148 } 7149 InVals.push_back(ArgValue); 7150 continue; 7151 } 7152 if (VA.isMemLoc()) { 7153 HandleMemLoc(); 7154 continue; 7155 } 7156 } 7157 7158 // On AIX a minimum of 8 words is saved to the parameter save area. 7159 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7160 // Area that is at least reserved in the caller of this function. 7161 unsigned CallerReservedArea = 7162 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7163 7164 // Set the size that is at least reserved in caller of this function. Tail 7165 // call optimized function's reserved stack space needs to be aligned so 7166 // that taking the difference between two stack areas will result in an 7167 // aligned stack. 7168 CallerReservedArea = 7169 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7170 FuncInfo->setMinReservedArea(CallerReservedArea); 7171 7172 if (isVarArg) { 7173 FuncInfo->setVarArgsFrameIndex( 7174 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7175 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7176 7177 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7178 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7179 7180 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7181 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7182 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7183 7184 // The fixed integer arguments of a variadic function are stored to the 7185 // VarArgsFrameIndex on the stack so that they may be loaded by 7186 // dereferencing the result of va_next. 7187 for (unsigned GPRIndex = 7188 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7189 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7190 7191 const Register VReg = 7192 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7193 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7194 7195 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7196 SDValue Store = 7197 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7198 MemOps.push_back(Store); 7199 // Increment the address for the next argument to store. 7200 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7201 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7202 } 7203 } 7204 7205 if (!MemOps.empty()) 7206 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7207 7208 return Chain; 7209 } 7210 7211 SDValue PPCTargetLowering::LowerCall_AIX( 7212 SDValue Chain, SDValue Callee, CallFlags CFlags, 7213 const SmallVectorImpl<ISD::OutputArg> &Outs, 7214 const SmallVectorImpl<SDValue> &OutVals, 7215 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7216 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7217 const CallBase *CB) const { 7218 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7219 // AIX ABI stack frame layout. 7220 7221 assert((CFlags.CallConv == CallingConv::C || 7222 CFlags.CallConv == CallingConv::Cold || 7223 CFlags.CallConv == CallingConv::Fast) && 7224 "Unexpected calling convention!"); 7225 7226 if (CFlags.IsPatchPoint) 7227 report_fatal_error("This call type is unimplemented on AIX."); 7228 7229 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 7230 7231 MachineFunction &MF = DAG.getMachineFunction(); 7232 SmallVector<CCValAssign, 16> ArgLocs; 7233 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7234 *DAG.getContext()); 7235 7236 // Reserve space for the linkage save area (LSA) on the stack. 7237 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7238 // [SP][CR][LR][2 x reserved][TOC]. 7239 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7240 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7241 const bool IsPPC64 = Subtarget.isPPC64(); 7242 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7243 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7244 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7245 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7246 7247 // The prolog code of the callee may store up to 8 GPR argument registers to 7248 // the stack, allowing va_start to index over them in memory if the callee 7249 // is variadic. 7250 // Because we cannot tell if this is needed on the caller side, we have to 7251 // conservatively assume that it is needed. As such, make sure we have at 7252 // least enough stack space for the caller to store the 8 GPRs. 7253 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7254 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7255 CCInfo.getNextStackOffset()); 7256 7257 // Adjust the stack pointer for the new arguments... 7258 // These operations are automatically eliminated by the prolog/epilog pass. 7259 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7260 SDValue CallSeqStart = Chain; 7261 7262 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7263 SmallVector<SDValue, 8> MemOpChains; 7264 7265 // Set up a copy of the stack pointer for loading and storing any 7266 // arguments that may not fit in the registers available for argument 7267 // passing. 7268 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7269 : DAG.getRegister(PPC::R1, MVT::i32); 7270 7271 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7272 const unsigned ValNo = ArgLocs[I].getValNo(); 7273 SDValue Arg = OutVals[ValNo]; 7274 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7275 7276 if (Flags.isByVal()) { 7277 const unsigned ByValSize = Flags.getByValSize(); 7278 7279 // Nothing to do for zero-sized ByVals on the caller side. 7280 if (!ByValSize) { 7281 ++I; 7282 continue; 7283 } 7284 7285 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7286 return DAG.getExtLoad( 7287 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7288 (LoadOffset != 0) 7289 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7290 : Arg, 7291 MachinePointerInfo(), VT); 7292 }; 7293 7294 unsigned LoadOffset = 0; 7295 7296 // Initialize registers, which are fully occupied by the by-val argument. 7297 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7298 SDValue Load = GetLoad(PtrVT, LoadOffset); 7299 MemOpChains.push_back(Load.getValue(1)); 7300 LoadOffset += PtrByteSize; 7301 const CCValAssign &ByValVA = ArgLocs[I++]; 7302 assert(ByValVA.getValNo() == ValNo && 7303 "Unexpected location for pass-by-value argument."); 7304 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7305 } 7306 7307 if (LoadOffset == ByValSize) 7308 continue; 7309 7310 // There must be one more loc to handle the remainder. 7311 assert(ArgLocs[I].getValNo() == ValNo && 7312 "Expected additional location for by-value argument."); 7313 7314 if (ArgLocs[I].isMemLoc()) { 7315 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7316 const CCValAssign &ByValVA = ArgLocs[I++]; 7317 ISD::ArgFlagsTy MemcpyFlags = Flags; 7318 // Only memcpy the bytes that don't pass in register. 7319 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7320 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7321 (LoadOffset != 0) 7322 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7323 : Arg, 7324 DAG.getObjectPtrOffset(dl, StackPtr, 7325 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7326 CallSeqStart, MemcpyFlags, DAG, dl); 7327 continue; 7328 } 7329 7330 // Initialize the final register residue. 7331 // Any residue that occupies the final by-val arg register must be 7332 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7333 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7334 // 2 and 1 byte loads. 7335 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7336 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7337 "Unexpected register residue for by-value argument."); 7338 SDValue ResidueVal; 7339 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7340 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7341 const MVT VT = 7342 N == 1 ? MVT::i8 7343 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7344 SDValue Load = GetLoad(VT, LoadOffset); 7345 MemOpChains.push_back(Load.getValue(1)); 7346 LoadOffset += N; 7347 Bytes += N; 7348 7349 // By-val arguments are passed left-justfied in register. 7350 // Every load here needs to be shifted, otherwise a full register load 7351 // should have been used. 7352 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7353 "Unexpected load emitted during handling of pass-by-value " 7354 "argument."); 7355 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7356 EVT ShiftAmountTy = 7357 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7358 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7359 SDValue ShiftedLoad = 7360 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7361 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7362 ShiftedLoad) 7363 : ShiftedLoad; 7364 } 7365 7366 const CCValAssign &ByValVA = ArgLocs[I++]; 7367 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7368 continue; 7369 } 7370 7371 CCValAssign &VA = ArgLocs[I++]; 7372 const MVT LocVT = VA.getLocVT(); 7373 const MVT ValVT = VA.getValVT(); 7374 7375 switch (VA.getLocInfo()) { 7376 default: 7377 report_fatal_error("Unexpected argument extension type."); 7378 case CCValAssign::Full: 7379 break; 7380 case CCValAssign::ZExt: 7381 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7382 break; 7383 case CCValAssign::SExt: 7384 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7385 break; 7386 } 7387 7388 if (VA.isRegLoc() && !VA.needsCustom()) { 7389 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7390 continue; 7391 } 7392 7393 // Vector arguments passed to VarArg functions need custom handling when 7394 // they are passed (at least partially) in GPRs. 7395 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7396 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7397 // Store value to its stack slot. 7398 SDValue PtrOff = 7399 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7400 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7401 SDValue Store = 7402 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7403 MemOpChains.push_back(Store); 7404 const unsigned OriginalValNo = VA.getValNo(); 7405 // Then load the GPRs from the stack 7406 unsigned LoadOffset = 0; 7407 auto HandleCustomVecRegLoc = [&]() { 7408 assert(I != E && "Unexpected end of CCvalAssigns."); 7409 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7410 "Expected custom RegLoc."); 7411 CCValAssign RegVA = ArgLocs[I++]; 7412 assert(RegVA.getValNo() == OriginalValNo && 7413 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7414 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7415 DAG.getConstant(LoadOffset, dl, PtrVT)); 7416 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7417 MemOpChains.push_back(Load.getValue(1)); 7418 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7419 LoadOffset += PtrByteSize; 7420 }; 7421 7422 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7423 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7424 // R10. 7425 HandleCustomVecRegLoc(); 7426 HandleCustomVecRegLoc(); 7427 7428 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7429 ArgLocs[I].getValNo() == OriginalValNo) { 7430 assert(!IsPPC64 && 7431 "Only 2 custom RegLocs expected for 64-bit codegen."); 7432 HandleCustomVecRegLoc(); 7433 HandleCustomVecRegLoc(); 7434 } 7435 7436 continue; 7437 } 7438 7439 if (VA.isMemLoc()) { 7440 SDValue PtrOff = 7441 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7442 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7443 MemOpChains.push_back( 7444 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7445 7446 continue; 7447 } 7448 7449 if (!ValVT.isFloatingPoint()) 7450 report_fatal_error( 7451 "Unexpected register handling for calling convention."); 7452 7453 // Custom handling is used for GPR initializations for vararg float 7454 // arguments. 7455 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7456 LocVT.isInteger() && 7457 "Custom register handling only expected for VarArg."); 7458 7459 SDValue ArgAsInt = 7460 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7461 7462 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7463 // f32 in 32-bit GPR 7464 // f64 in 64-bit GPR 7465 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7466 else if (Arg.getValueType().getFixedSizeInBits() < 7467 LocVT.getFixedSizeInBits()) 7468 // f32 in 64-bit GPR. 7469 RegsToPass.push_back(std::make_pair( 7470 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7471 else { 7472 // f64 in two 32-bit GPRs 7473 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7474 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7475 "Unexpected custom register for argument!"); 7476 CCValAssign &GPR1 = VA; 7477 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7478 DAG.getConstant(32, dl, MVT::i8)); 7479 RegsToPass.push_back(std::make_pair( 7480 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7481 7482 if (I != E) { 7483 // If only 1 GPR was available, there will only be one custom GPR and 7484 // the argument will also pass in memory. 7485 CCValAssign &PeekArg = ArgLocs[I]; 7486 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7487 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7488 CCValAssign &GPR2 = ArgLocs[I++]; 7489 RegsToPass.push_back(std::make_pair( 7490 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7491 } 7492 } 7493 } 7494 } 7495 7496 if (!MemOpChains.empty()) 7497 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7498 7499 // For indirect calls, we need to save the TOC base to the stack for 7500 // restoration after the call. 7501 if (CFlags.IsIndirect) { 7502 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7503 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7504 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7505 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7506 const unsigned TOCSaveOffset = 7507 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7508 7509 setUsesTOCBasePtr(DAG); 7510 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7511 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7512 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7513 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7514 Chain = DAG.getStore( 7515 Val.getValue(1), dl, Val, AddPtr, 7516 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7517 } 7518 7519 // Build a sequence of copy-to-reg nodes chained together with token chain 7520 // and flag operands which copy the outgoing args into the appropriate regs. 7521 SDValue InFlag; 7522 for (auto Reg : RegsToPass) { 7523 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7524 InFlag = Chain.getValue(1); 7525 } 7526 7527 const int SPDiff = 0; 7528 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7529 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7530 } 7531 7532 bool 7533 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7534 MachineFunction &MF, bool isVarArg, 7535 const SmallVectorImpl<ISD::OutputArg> &Outs, 7536 LLVMContext &Context) const { 7537 SmallVector<CCValAssign, 16> RVLocs; 7538 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7539 return CCInfo.CheckReturn( 7540 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7541 ? RetCC_PPC_Cold 7542 : RetCC_PPC); 7543 } 7544 7545 SDValue 7546 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7547 bool isVarArg, 7548 const SmallVectorImpl<ISD::OutputArg> &Outs, 7549 const SmallVectorImpl<SDValue> &OutVals, 7550 const SDLoc &dl, SelectionDAG &DAG) const { 7551 SmallVector<CCValAssign, 16> RVLocs; 7552 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7553 *DAG.getContext()); 7554 CCInfo.AnalyzeReturn(Outs, 7555 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7556 ? RetCC_PPC_Cold 7557 : RetCC_PPC); 7558 7559 SDValue Flag; 7560 SmallVector<SDValue, 4> RetOps(1, Chain); 7561 7562 // Copy the result values into the output registers. 7563 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7564 CCValAssign &VA = RVLocs[i]; 7565 assert(VA.isRegLoc() && "Can only return in registers!"); 7566 7567 SDValue Arg = OutVals[RealResIdx]; 7568 7569 switch (VA.getLocInfo()) { 7570 default: llvm_unreachable("Unknown loc info!"); 7571 case CCValAssign::Full: break; 7572 case CCValAssign::AExt: 7573 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7574 break; 7575 case CCValAssign::ZExt: 7576 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7577 break; 7578 case CCValAssign::SExt: 7579 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7580 break; 7581 } 7582 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7583 bool isLittleEndian = Subtarget.isLittleEndian(); 7584 // Legalize ret f64 -> ret 2 x i32. 7585 SDValue SVal = 7586 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7587 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7588 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7589 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7590 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7591 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7592 Flag = Chain.getValue(1); 7593 VA = RVLocs[++i]; // skip ahead to next loc 7594 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7595 } else 7596 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7597 Flag = Chain.getValue(1); 7598 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7599 } 7600 7601 RetOps[0] = Chain; // Update chain. 7602 7603 // Add the flag if we have it. 7604 if (Flag.getNode()) 7605 RetOps.push_back(Flag); 7606 7607 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7608 } 7609 7610 SDValue 7611 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7612 SelectionDAG &DAG) const { 7613 SDLoc dl(Op); 7614 7615 // Get the correct type for integers. 7616 EVT IntVT = Op.getValueType(); 7617 7618 // Get the inputs. 7619 SDValue Chain = Op.getOperand(0); 7620 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7621 // Build a DYNAREAOFFSET node. 7622 SDValue Ops[2] = {Chain, FPSIdx}; 7623 SDVTList VTs = DAG.getVTList(IntVT); 7624 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7625 } 7626 7627 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7628 SelectionDAG &DAG) const { 7629 // When we pop the dynamic allocation we need to restore the SP link. 7630 SDLoc dl(Op); 7631 7632 // Get the correct type for pointers. 7633 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7634 7635 // Construct the stack pointer operand. 7636 bool isPPC64 = Subtarget.isPPC64(); 7637 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7638 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7639 7640 // Get the operands for the STACKRESTORE. 7641 SDValue Chain = Op.getOperand(0); 7642 SDValue SaveSP = Op.getOperand(1); 7643 7644 // Load the old link SP. 7645 SDValue LoadLinkSP = 7646 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7647 7648 // Restore the stack pointer. 7649 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7650 7651 // Store the old link SP. 7652 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7653 } 7654 7655 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7656 MachineFunction &MF = DAG.getMachineFunction(); 7657 bool isPPC64 = Subtarget.isPPC64(); 7658 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7659 7660 // Get current frame pointer save index. The users of this index will be 7661 // primarily DYNALLOC instructions. 7662 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7663 int RASI = FI->getReturnAddrSaveIndex(); 7664 7665 // If the frame pointer save index hasn't been defined yet. 7666 if (!RASI) { 7667 // Find out what the fix offset of the frame pointer save area. 7668 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7669 // Allocate the frame index for frame pointer save area. 7670 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7671 // Save the result. 7672 FI->setReturnAddrSaveIndex(RASI); 7673 } 7674 return DAG.getFrameIndex(RASI, PtrVT); 7675 } 7676 7677 SDValue 7678 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7679 MachineFunction &MF = DAG.getMachineFunction(); 7680 bool isPPC64 = Subtarget.isPPC64(); 7681 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7682 7683 // Get current frame pointer save index. The users of this index will be 7684 // primarily DYNALLOC instructions. 7685 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7686 int FPSI = FI->getFramePointerSaveIndex(); 7687 7688 // If the frame pointer save index hasn't been defined yet. 7689 if (!FPSI) { 7690 // Find out what the fix offset of the frame pointer save area. 7691 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7692 // Allocate the frame index for frame pointer save area. 7693 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7694 // Save the result. 7695 FI->setFramePointerSaveIndex(FPSI); 7696 } 7697 return DAG.getFrameIndex(FPSI, PtrVT); 7698 } 7699 7700 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7701 SelectionDAG &DAG) const { 7702 MachineFunction &MF = DAG.getMachineFunction(); 7703 // Get the inputs. 7704 SDValue Chain = Op.getOperand(0); 7705 SDValue Size = Op.getOperand(1); 7706 SDLoc dl(Op); 7707 7708 // Get the correct type for pointers. 7709 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7710 // Negate the size. 7711 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7712 DAG.getConstant(0, dl, PtrVT), Size); 7713 // Construct a node for the frame pointer save index. 7714 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7715 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7716 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7717 if (hasInlineStackProbe(MF)) 7718 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7719 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7720 } 7721 7722 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7723 SelectionDAG &DAG) const { 7724 MachineFunction &MF = DAG.getMachineFunction(); 7725 7726 bool isPPC64 = Subtarget.isPPC64(); 7727 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7728 7729 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7730 return DAG.getFrameIndex(FI, PtrVT); 7731 } 7732 7733 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7734 SelectionDAG &DAG) const { 7735 SDLoc DL(Op); 7736 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7737 DAG.getVTList(MVT::i32, MVT::Other), 7738 Op.getOperand(0), Op.getOperand(1)); 7739 } 7740 7741 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7742 SelectionDAG &DAG) const { 7743 SDLoc DL(Op); 7744 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7745 Op.getOperand(0), Op.getOperand(1)); 7746 } 7747 7748 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7749 if (Op.getValueType().isVector()) 7750 return LowerVectorLoad(Op, DAG); 7751 7752 assert(Op.getValueType() == MVT::i1 && 7753 "Custom lowering only for i1 loads"); 7754 7755 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7756 7757 SDLoc dl(Op); 7758 LoadSDNode *LD = cast<LoadSDNode>(Op); 7759 7760 SDValue Chain = LD->getChain(); 7761 SDValue BasePtr = LD->getBasePtr(); 7762 MachineMemOperand *MMO = LD->getMemOperand(); 7763 7764 SDValue NewLD = 7765 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7766 BasePtr, MVT::i8, MMO); 7767 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7768 7769 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7770 return DAG.getMergeValues(Ops, dl); 7771 } 7772 7773 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7774 if (Op.getOperand(1).getValueType().isVector()) 7775 return LowerVectorStore(Op, DAG); 7776 7777 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7778 "Custom lowering only for i1 stores"); 7779 7780 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7781 7782 SDLoc dl(Op); 7783 StoreSDNode *ST = cast<StoreSDNode>(Op); 7784 7785 SDValue Chain = ST->getChain(); 7786 SDValue BasePtr = ST->getBasePtr(); 7787 SDValue Value = ST->getValue(); 7788 MachineMemOperand *MMO = ST->getMemOperand(); 7789 7790 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7791 Value); 7792 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7793 } 7794 7795 // FIXME: Remove this once the ANDI glue bug is fixed: 7796 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7797 assert(Op.getValueType() == MVT::i1 && 7798 "Custom lowering only for i1 results"); 7799 7800 SDLoc DL(Op); 7801 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7802 } 7803 7804 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7805 SelectionDAG &DAG) const { 7806 7807 // Implements a vector truncate that fits in a vector register as a shuffle. 7808 // We want to legalize vector truncates down to where the source fits in 7809 // a vector register (and target is therefore smaller than vector register 7810 // size). At that point legalization will try to custom lower the sub-legal 7811 // result and get here - where we can contain the truncate as a single target 7812 // operation. 7813 7814 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7815 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7816 // 7817 // We will implement it for big-endian ordering as this (where x denotes 7818 // undefined): 7819 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7820 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7821 // 7822 // The same operation in little-endian ordering will be: 7823 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7824 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7825 7826 EVT TrgVT = Op.getValueType(); 7827 assert(TrgVT.isVector() && "Vector type expected."); 7828 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7829 EVT EltVT = TrgVT.getVectorElementType(); 7830 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7831 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7832 !isPowerOf2_32(EltVT.getSizeInBits())) 7833 return SDValue(); 7834 7835 SDValue N1 = Op.getOperand(0); 7836 EVT SrcVT = N1.getValueType(); 7837 unsigned SrcSize = SrcVT.getSizeInBits(); 7838 if (SrcSize > 256 || 7839 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7840 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7841 return SDValue(); 7842 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7843 return SDValue(); 7844 7845 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7846 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7847 7848 SDLoc DL(Op); 7849 SDValue Op1, Op2; 7850 if (SrcSize == 256) { 7851 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7852 EVT SplitVT = 7853 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7854 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7855 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7856 DAG.getConstant(0, DL, VecIdxTy)); 7857 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7858 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7859 } 7860 else { 7861 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7862 Op2 = DAG.getUNDEF(WideVT); 7863 } 7864 7865 // First list the elements we want to keep. 7866 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7867 SmallVector<int, 16> ShuffV; 7868 if (Subtarget.isLittleEndian()) 7869 for (unsigned i = 0; i < TrgNumElts; ++i) 7870 ShuffV.push_back(i * SizeMult); 7871 else 7872 for (unsigned i = 1; i <= TrgNumElts; ++i) 7873 ShuffV.push_back(i * SizeMult - 1); 7874 7875 // Populate the remaining elements with undefs. 7876 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7877 // ShuffV.push_back(i + WideNumElts); 7878 ShuffV.push_back(WideNumElts + 1); 7879 7880 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7881 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7882 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7883 } 7884 7885 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7886 /// possible. 7887 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7888 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7889 EVT ResVT = Op.getValueType(); 7890 EVT CmpVT = Op.getOperand(0).getValueType(); 7891 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7892 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7893 SDLoc dl(Op); 7894 7895 // Without power9-vector, we don't have native instruction for f128 comparison. 7896 // Following transformation to libcall is needed for setcc: 7897 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7898 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7899 SDValue Z = DAG.getSetCC( 7900 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7901 LHS, RHS, CC); 7902 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7903 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7904 } 7905 7906 // Not FP, or using SPE? Not a fsel. 7907 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7908 Subtarget.hasSPE()) 7909 return Op; 7910 7911 SDNodeFlags Flags = Op.getNode()->getFlags(); 7912 7913 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the 7914 // presence of infinities. 7915 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7916 switch (CC) { 7917 default: 7918 break; 7919 case ISD::SETOGT: 7920 case ISD::SETGT: 7921 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS); 7922 case ISD::SETOLT: 7923 case ISD::SETLT: 7924 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS); 7925 } 7926 } 7927 7928 // We might be able to do better than this under some circumstances, but in 7929 // general, fsel-based lowering of select is a finite-math-only optimization. 7930 // For more information, see section F.3 of the 2.06 ISA specification. 7931 // With ISA 3.0 7932 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7933 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7934 return Op; 7935 7936 // If the RHS of the comparison is a 0.0, we don't need to do the 7937 // subtraction at all. 7938 SDValue Sel1; 7939 if (isFloatingPointZero(RHS)) 7940 switch (CC) { 7941 default: break; // SETUO etc aren't handled by fsel. 7942 case ISD::SETNE: 7943 std::swap(TV, FV); 7944 LLVM_FALLTHROUGH; 7945 case ISD::SETEQ: 7946 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7947 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7948 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7949 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7950 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7951 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7952 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7953 case ISD::SETULT: 7954 case ISD::SETLT: 7955 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7956 LLVM_FALLTHROUGH; 7957 case ISD::SETOGE: 7958 case ISD::SETGE: 7959 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7960 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7961 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7962 case ISD::SETUGT: 7963 case ISD::SETGT: 7964 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7965 LLVM_FALLTHROUGH; 7966 case ISD::SETOLE: 7967 case ISD::SETLE: 7968 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7969 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7970 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7971 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7972 } 7973 7974 SDValue Cmp; 7975 switch (CC) { 7976 default: break; // SETUO etc aren't handled by fsel. 7977 case ISD::SETNE: 7978 std::swap(TV, FV); 7979 LLVM_FALLTHROUGH; 7980 case ISD::SETEQ: 7981 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7982 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7983 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7984 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7985 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7986 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7987 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7988 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7989 case ISD::SETULT: 7990 case ISD::SETLT: 7991 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7992 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7993 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7994 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7995 case ISD::SETOGE: 7996 case ISD::SETGE: 7997 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7998 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7999 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8000 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8001 case ISD::SETUGT: 8002 case ISD::SETGT: 8003 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8004 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8005 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8006 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8007 case ISD::SETOLE: 8008 case ISD::SETLE: 8009 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, 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, TV, FV); 8013 } 8014 return Op; 8015 } 8016 8017 static unsigned getPPCStrictOpcode(unsigned Opc) { 8018 switch (Opc) { 8019 default: 8020 llvm_unreachable("No strict version of this opcode!"); 8021 case PPCISD::FCTIDZ: 8022 return PPCISD::STRICT_FCTIDZ; 8023 case PPCISD::FCTIWZ: 8024 return PPCISD::STRICT_FCTIWZ; 8025 case PPCISD::FCTIDUZ: 8026 return PPCISD::STRICT_FCTIDUZ; 8027 case PPCISD::FCTIWUZ: 8028 return PPCISD::STRICT_FCTIWUZ; 8029 case PPCISD::FCFID: 8030 return PPCISD::STRICT_FCFID; 8031 case PPCISD::FCFIDU: 8032 return PPCISD::STRICT_FCFIDU; 8033 case PPCISD::FCFIDS: 8034 return PPCISD::STRICT_FCFIDS; 8035 case PPCISD::FCFIDUS: 8036 return PPCISD::STRICT_FCFIDUS; 8037 } 8038 } 8039 8040 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8041 const PPCSubtarget &Subtarget) { 8042 SDLoc dl(Op); 8043 bool IsStrict = Op->isStrictFPOpcode(); 8044 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8045 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8046 8047 // TODO: Any other flags to propagate? 8048 SDNodeFlags Flags; 8049 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8050 8051 // For strict nodes, source is the second operand. 8052 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8053 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8054 assert(Src.getValueType().isFloatingPoint()); 8055 if (Src.getValueType() == MVT::f32) { 8056 if (IsStrict) { 8057 Src = 8058 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8059 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8060 Chain = Src.getValue(1); 8061 } else 8062 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8063 } 8064 SDValue Conv; 8065 unsigned Opc = ISD::DELETED_NODE; 8066 switch (Op.getSimpleValueType().SimpleTy) { 8067 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8068 case MVT::i32: 8069 Opc = IsSigned ? PPCISD::FCTIWZ 8070 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8071 break; 8072 case MVT::i64: 8073 assert((IsSigned || Subtarget.hasFPCVT()) && 8074 "i64 FP_TO_UINT is supported only with FPCVT"); 8075 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8076 } 8077 if (IsStrict) { 8078 Opc = getPPCStrictOpcode(Opc); 8079 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8080 {Chain, Src}, Flags); 8081 } else { 8082 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8083 } 8084 return Conv; 8085 } 8086 8087 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8088 SelectionDAG &DAG, 8089 const SDLoc &dl) const { 8090 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8091 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8092 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8093 bool IsStrict = Op->isStrictFPOpcode(); 8094 8095 // Convert the FP value to an int value through memory. 8096 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8097 (IsSigned || Subtarget.hasFPCVT()); 8098 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8099 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8100 MachinePointerInfo MPI = 8101 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8102 8103 // Emit a store to the stack slot. 8104 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8105 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8106 if (i32Stack) { 8107 MachineFunction &MF = DAG.getMachineFunction(); 8108 Alignment = Align(4); 8109 MachineMemOperand *MMO = 8110 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8111 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8112 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8113 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8114 } else 8115 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8116 8117 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8118 // add in a bias on big endian. 8119 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8120 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8121 DAG.getConstant(4, dl, FIPtr.getValueType())); 8122 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8123 } 8124 8125 RLI.Chain = Chain; 8126 RLI.Ptr = FIPtr; 8127 RLI.MPI = MPI; 8128 RLI.Alignment = Alignment; 8129 } 8130 8131 /// Custom lowers floating point to integer conversions to use 8132 /// the direct move instructions available in ISA 2.07 to avoid the 8133 /// need for load/store combinations. 8134 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8135 SelectionDAG &DAG, 8136 const SDLoc &dl) const { 8137 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8138 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8139 if (Op->isStrictFPOpcode()) 8140 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8141 else 8142 return Mov; 8143 } 8144 8145 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8146 const SDLoc &dl) const { 8147 bool IsStrict = Op->isStrictFPOpcode(); 8148 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8149 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8150 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8151 EVT SrcVT = Src.getValueType(); 8152 EVT DstVT = Op.getValueType(); 8153 8154 // FP to INT conversions are legal for f128. 8155 if (SrcVT == MVT::f128) 8156 return Subtarget.hasP9Vector() ? Op : SDValue(); 8157 8158 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8159 // PPC (the libcall is not available). 8160 if (SrcVT == MVT::ppcf128) { 8161 if (DstVT == MVT::i32) { 8162 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8163 // set other fast-math flags to FP operations in both strict and 8164 // non-strict cases. (FP_TO_SINT, FSUB) 8165 SDNodeFlags Flags; 8166 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8167 8168 if (IsSigned) { 8169 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8170 DAG.getIntPtrConstant(0, dl)); 8171 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8172 DAG.getIntPtrConstant(1, dl)); 8173 8174 // Add the two halves of the long double in round-to-zero mode, and use 8175 // a smaller FP_TO_SINT. 8176 if (IsStrict) { 8177 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8178 DAG.getVTList(MVT::f64, MVT::Other), 8179 {Op.getOperand(0), Lo, Hi}, Flags); 8180 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8181 DAG.getVTList(MVT::i32, MVT::Other), 8182 {Res.getValue(1), Res}, Flags); 8183 } else { 8184 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8185 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8186 } 8187 } else { 8188 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8189 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8190 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8191 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8192 if (IsStrict) { 8193 // Sel = Src < 0x80000000 8194 // FltOfs = select Sel, 0.0, 0x80000000 8195 // IntOfs = select Sel, 0, 0x80000000 8196 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8197 SDValue Chain = Op.getOperand(0); 8198 EVT SetCCVT = 8199 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8200 EVT DstSetCCVT = 8201 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8202 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8203 Chain, true); 8204 Chain = Sel.getValue(1); 8205 8206 SDValue FltOfs = DAG.getSelect( 8207 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8208 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8209 8210 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8211 DAG.getVTList(SrcVT, MVT::Other), 8212 {Chain, Src, FltOfs}, Flags); 8213 Chain = Val.getValue(1); 8214 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8215 DAG.getVTList(DstVT, MVT::Other), 8216 {Chain, Val}, Flags); 8217 Chain = SInt.getValue(1); 8218 SDValue IntOfs = DAG.getSelect( 8219 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8220 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8221 return DAG.getMergeValues({Result, Chain}, dl); 8222 } else { 8223 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8224 // FIXME: generated code sucks. 8225 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8226 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8227 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8228 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8229 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8230 } 8231 } 8232 } 8233 8234 return SDValue(); 8235 } 8236 8237 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8238 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8239 8240 ReuseLoadInfo RLI; 8241 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8242 8243 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8244 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8245 } 8246 8247 // We're trying to insert a regular store, S, and then a load, L. If the 8248 // incoming value, O, is a load, we might just be able to have our load use the 8249 // address used by O. However, we don't know if anything else will store to 8250 // that address before we can load from it. To prevent this situation, we need 8251 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8252 // the same chain operand as O, we create a token factor from the chain results 8253 // of O and L, and we replace all uses of O's chain result with that token 8254 // factor (see spliceIntoChain below for this last part). 8255 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8256 ReuseLoadInfo &RLI, 8257 SelectionDAG &DAG, 8258 ISD::LoadExtType ET) const { 8259 // Conservatively skip reusing for constrained FP nodes. 8260 if (Op->isStrictFPOpcode()) 8261 return false; 8262 8263 SDLoc dl(Op); 8264 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8265 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8266 if (ET == ISD::NON_EXTLOAD && 8267 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8268 isOperationLegalOrCustom(Op.getOpcode(), 8269 Op.getOperand(0).getValueType())) { 8270 8271 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8272 return true; 8273 } 8274 8275 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8276 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8277 LD->isNonTemporal()) 8278 return false; 8279 if (LD->getMemoryVT() != MemVT) 8280 return false; 8281 8282 // If the result of the load is an illegal type, then we can't build a 8283 // valid chain for reuse since the legalised loads and token factor node that 8284 // ties the legalised loads together uses a different output chain then the 8285 // illegal load. 8286 if (!isTypeLegal(LD->getValueType(0))) 8287 return false; 8288 8289 RLI.Ptr = LD->getBasePtr(); 8290 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8291 assert(LD->getAddressingMode() == ISD::PRE_INC && 8292 "Non-pre-inc AM on PPC?"); 8293 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8294 LD->getOffset()); 8295 } 8296 8297 RLI.Chain = LD->getChain(); 8298 RLI.MPI = LD->getPointerInfo(); 8299 RLI.IsDereferenceable = LD->isDereferenceable(); 8300 RLI.IsInvariant = LD->isInvariant(); 8301 RLI.Alignment = LD->getAlign(); 8302 RLI.AAInfo = LD->getAAInfo(); 8303 RLI.Ranges = LD->getRanges(); 8304 8305 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8306 return true; 8307 } 8308 8309 // Given the head of the old chain, ResChain, insert a token factor containing 8310 // it and NewResChain, and make users of ResChain now be users of that token 8311 // factor. 8312 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8313 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8314 SDValue NewResChain, 8315 SelectionDAG &DAG) const { 8316 if (!ResChain) 8317 return; 8318 8319 SDLoc dl(NewResChain); 8320 8321 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8322 NewResChain, DAG.getUNDEF(MVT::Other)); 8323 assert(TF.getNode() != NewResChain.getNode() && 8324 "A new TF really is required here"); 8325 8326 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8327 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8328 } 8329 8330 /// Analyze profitability of direct move 8331 /// prefer float load to int load plus direct move 8332 /// when there is no integer use of int load 8333 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8334 SDNode *Origin = Op.getOperand(0).getNode(); 8335 if (Origin->getOpcode() != ISD::LOAD) 8336 return true; 8337 8338 // If there is no LXSIBZX/LXSIHZX, like Power8, 8339 // prefer direct move if the memory size is 1 or 2 bytes. 8340 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8341 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8342 return true; 8343 8344 for (SDNode::use_iterator UI = Origin->use_begin(), 8345 UE = Origin->use_end(); 8346 UI != UE; ++UI) { 8347 8348 // Only look at the users of the loaded value. 8349 if (UI.getUse().get().getResNo() != 0) 8350 continue; 8351 8352 if (UI->getOpcode() != ISD::SINT_TO_FP && 8353 UI->getOpcode() != ISD::UINT_TO_FP && 8354 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8355 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8356 return true; 8357 } 8358 8359 return false; 8360 } 8361 8362 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8363 const PPCSubtarget &Subtarget, 8364 SDValue Chain = SDValue()) { 8365 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8366 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8367 SDLoc dl(Op); 8368 8369 // TODO: Any other flags to propagate? 8370 SDNodeFlags Flags; 8371 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8372 8373 // If we have FCFIDS, then use it when converting to single-precision. 8374 // Otherwise, convert to double-precision and then round. 8375 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8376 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8377 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8378 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8379 if (Op->isStrictFPOpcode()) { 8380 if (!Chain) 8381 Chain = Op.getOperand(0); 8382 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8383 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8384 } else 8385 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8386 } 8387 8388 /// Custom lowers integer to floating point conversions to use 8389 /// the direct move instructions available in ISA 2.07 to avoid the 8390 /// need for load/store combinations. 8391 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8392 SelectionDAG &DAG, 8393 const SDLoc &dl) const { 8394 assert((Op.getValueType() == MVT::f32 || 8395 Op.getValueType() == MVT::f64) && 8396 "Invalid floating point type as target of conversion"); 8397 assert(Subtarget.hasFPCVT() && 8398 "Int to FP conversions with direct moves require FPCVT"); 8399 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8400 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8401 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8402 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8403 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8404 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8405 return convertIntToFP(Op, Mov, DAG, Subtarget); 8406 } 8407 8408 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8409 8410 EVT VecVT = Vec.getValueType(); 8411 assert(VecVT.isVector() && "Expected a vector type."); 8412 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8413 8414 EVT EltVT = VecVT.getVectorElementType(); 8415 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8416 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8417 8418 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8419 SmallVector<SDValue, 16> Ops(NumConcat); 8420 Ops[0] = Vec; 8421 SDValue UndefVec = DAG.getUNDEF(VecVT); 8422 for (unsigned i = 1; i < NumConcat; ++i) 8423 Ops[i] = UndefVec; 8424 8425 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8426 } 8427 8428 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8429 const SDLoc &dl) const { 8430 bool IsStrict = Op->isStrictFPOpcode(); 8431 unsigned Opc = Op.getOpcode(); 8432 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8433 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8434 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8435 "Unexpected conversion type"); 8436 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8437 "Supports conversions to v2f64/v4f32 only."); 8438 8439 // TODO: Any other flags to propagate? 8440 SDNodeFlags Flags; 8441 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8442 8443 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8444 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8445 8446 SDValue Wide = widenVec(DAG, Src, dl); 8447 EVT WideVT = Wide.getValueType(); 8448 unsigned WideNumElts = WideVT.getVectorNumElements(); 8449 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8450 8451 SmallVector<int, 16> ShuffV; 8452 for (unsigned i = 0; i < WideNumElts; ++i) 8453 ShuffV.push_back(i + WideNumElts); 8454 8455 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8456 int SaveElts = FourEltRes ? 4 : 2; 8457 if (Subtarget.isLittleEndian()) 8458 for (int i = 0; i < SaveElts; i++) 8459 ShuffV[i * Stride] = i; 8460 else 8461 for (int i = 1; i <= SaveElts; i++) 8462 ShuffV[i * Stride - 1] = i - 1; 8463 8464 SDValue ShuffleSrc2 = 8465 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8466 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8467 8468 SDValue Extend; 8469 if (SignedConv) { 8470 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8471 EVT ExtVT = Src.getValueType(); 8472 if (Subtarget.hasP9Altivec()) 8473 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8474 IntermediateVT.getVectorNumElements()); 8475 8476 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8477 DAG.getValueType(ExtVT)); 8478 } else 8479 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8480 8481 if (IsStrict) 8482 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8483 {Op.getOperand(0), Extend}, Flags); 8484 8485 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8486 } 8487 8488 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8489 SelectionDAG &DAG) const { 8490 SDLoc dl(Op); 8491 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8492 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8493 bool IsStrict = Op->isStrictFPOpcode(); 8494 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8495 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8496 8497 // TODO: Any other flags to propagate? 8498 SDNodeFlags Flags; 8499 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8500 8501 EVT InVT = Src.getValueType(); 8502 EVT OutVT = Op.getValueType(); 8503 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8504 isOperationCustom(Op.getOpcode(), InVT)) 8505 return LowerINT_TO_FPVector(Op, DAG, dl); 8506 8507 // Conversions to f128 are legal. 8508 if (Op.getValueType() == MVT::f128) 8509 return Subtarget.hasP9Vector() ? Op : SDValue(); 8510 8511 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8512 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8513 return SDValue(); 8514 8515 if (Src.getValueType() == MVT::i1) { 8516 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8517 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8518 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8519 if (IsStrict) 8520 return DAG.getMergeValues({Sel, Chain}, dl); 8521 else 8522 return Sel; 8523 } 8524 8525 // If we have direct moves, we can do all the conversion, skip the store/load 8526 // however, without FPCVT we can't do most conversions. 8527 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8528 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8529 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8530 8531 assert((IsSigned || Subtarget.hasFPCVT()) && 8532 "UINT_TO_FP is supported only with FPCVT"); 8533 8534 if (Src.getValueType() == MVT::i64) { 8535 SDValue SINT = Src; 8536 // When converting to single-precision, we actually need to convert 8537 // to double-precision first and then round to single-precision. 8538 // To avoid double-rounding effects during that operation, we have 8539 // to prepare the input operand. Bits that might be truncated when 8540 // converting to double-precision are replaced by a bit that won't 8541 // be lost at this stage, but is below the single-precision rounding 8542 // position. 8543 // 8544 // However, if -enable-unsafe-fp-math is in effect, accept double 8545 // rounding to avoid the extra overhead. 8546 if (Op.getValueType() == MVT::f32 && 8547 !Subtarget.hasFPCVT() && 8548 !DAG.getTarget().Options.UnsafeFPMath) { 8549 8550 // Twiddle input to make sure the low 11 bits are zero. (If this 8551 // is the case, we are guaranteed the value will fit into the 53 bit 8552 // mantissa of an IEEE double-precision value without rounding.) 8553 // If any of those low 11 bits were not zero originally, make sure 8554 // bit 12 (value 2048) is set instead, so that the final rounding 8555 // to single-precision gets the correct result. 8556 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8557 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8558 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8559 Round, DAG.getConstant(2047, dl, MVT::i64)); 8560 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8561 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8562 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8563 8564 // However, we cannot use that value unconditionally: if the magnitude 8565 // of the input value is small, the bit-twiddling we did above might 8566 // end up visibly changing the output. Fortunately, in that case, we 8567 // don't need to twiddle bits since the original input will convert 8568 // exactly to double-precision floating-point already. Therefore, 8569 // construct a conditional to use the original value if the top 11 8570 // bits are all sign-bit copies, and use the rounded value computed 8571 // above otherwise. 8572 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8573 SINT, DAG.getConstant(53, dl, MVT::i32)); 8574 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8575 Cond, DAG.getConstant(1, dl, MVT::i64)); 8576 Cond = DAG.getSetCC( 8577 dl, 8578 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8579 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8580 8581 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8582 } 8583 8584 ReuseLoadInfo RLI; 8585 SDValue Bits; 8586 8587 MachineFunction &MF = DAG.getMachineFunction(); 8588 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8589 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8590 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8591 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8592 } else if (Subtarget.hasLFIWAX() && 8593 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8594 MachineMemOperand *MMO = 8595 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8596 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8597 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8598 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8599 DAG.getVTList(MVT::f64, MVT::Other), 8600 Ops, MVT::i32, MMO); 8601 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8602 } else if (Subtarget.hasFPCVT() && 8603 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8604 MachineMemOperand *MMO = 8605 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8606 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8607 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8608 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8609 DAG.getVTList(MVT::f64, MVT::Other), 8610 Ops, MVT::i32, MMO); 8611 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8612 } else if (((Subtarget.hasLFIWAX() && 8613 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8614 (Subtarget.hasFPCVT() && 8615 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8616 SINT.getOperand(0).getValueType() == MVT::i32) { 8617 MachineFrameInfo &MFI = MF.getFrameInfo(); 8618 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8619 8620 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8621 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8622 8623 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8624 MachinePointerInfo::getFixedStack( 8625 DAG.getMachineFunction(), FrameIdx)); 8626 Chain = Store; 8627 8628 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8629 "Expected an i32 store"); 8630 8631 RLI.Ptr = FIdx; 8632 RLI.Chain = Chain; 8633 RLI.MPI = 8634 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8635 RLI.Alignment = Align(4); 8636 8637 MachineMemOperand *MMO = 8638 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8639 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8640 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8641 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8642 PPCISD::LFIWZX : PPCISD::LFIWAX, 8643 dl, DAG.getVTList(MVT::f64, MVT::Other), 8644 Ops, MVT::i32, MMO); 8645 Chain = Bits.getValue(1); 8646 } else 8647 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8648 8649 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8650 if (IsStrict) 8651 Chain = FP.getValue(1); 8652 8653 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8654 if (IsStrict) 8655 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8656 DAG.getVTList(MVT::f32, MVT::Other), 8657 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8658 else 8659 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8660 DAG.getIntPtrConstant(0, dl)); 8661 } 8662 return FP; 8663 } 8664 8665 assert(Src.getValueType() == MVT::i32 && 8666 "Unhandled INT_TO_FP type in custom expander!"); 8667 // Since we only generate this in 64-bit mode, we can take advantage of 8668 // 64-bit registers. In particular, sign extend the input value into the 8669 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8670 // then lfd it and fcfid it. 8671 MachineFunction &MF = DAG.getMachineFunction(); 8672 MachineFrameInfo &MFI = MF.getFrameInfo(); 8673 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8674 8675 SDValue Ld; 8676 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8677 ReuseLoadInfo RLI; 8678 bool ReusingLoad; 8679 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8680 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8681 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8682 8683 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8684 MachinePointerInfo::getFixedStack( 8685 DAG.getMachineFunction(), FrameIdx)); 8686 Chain = Store; 8687 8688 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8689 "Expected an i32 store"); 8690 8691 RLI.Ptr = FIdx; 8692 RLI.Chain = Chain; 8693 RLI.MPI = 8694 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8695 RLI.Alignment = Align(4); 8696 } 8697 8698 MachineMemOperand *MMO = 8699 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8700 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8701 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8702 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8703 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8704 MVT::i32, MMO); 8705 Chain = Ld.getValue(1); 8706 if (ReusingLoad) 8707 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8708 } else { 8709 assert(Subtarget.isPPC64() && 8710 "i32->FP without LFIWAX supported only on PPC64"); 8711 8712 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8713 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8714 8715 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8716 8717 // STD the extended value into the stack slot. 8718 SDValue Store = DAG.getStore( 8719 Chain, dl, Ext64, FIdx, 8720 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8721 Chain = Store; 8722 8723 // Load the value as a double. 8724 Ld = DAG.getLoad( 8725 MVT::f64, dl, Chain, FIdx, 8726 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8727 Chain = Ld.getValue(1); 8728 } 8729 8730 // FCFID it and return it. 8731 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8732 if (IsStrict) 8733 Chain = FP.getValue(1); 8734 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8735 if (IsStrict) 8736 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8737 DAG.getVTList(MVT::f32, MVT::Other), 8738 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8739 else 8740 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8741 DAG.getIntPtrConstant(0, dl)); 8742 } 8743 return FP; 8744 } 8745 8746 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8747 SelectionDAG &DAG) const { 8748 SDLoc dl(Op); 8749 /* 8750 The rounding mode is in bits 30:31 of FPSR, and has the following 8751 settings: 8752 00 Round to nearest 8753 01 Round to 0 8754 10 Round to +inf 8755 11 Round to -inf 8756 8757 FLT_ROUNDS, on the other hand, expects the following: 8758 -1 Undefined 8759 0 Round to 0 8760 1 Round to nearest 8761 2 Round to +inf 8762 3 Round to -inf 8763 8764 To perform the conversion, we do: 8765 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8766 */ 8767 8768 MachineFunction &MF = DAG.getMachineFunction(); 8769 EVT VT = Op.getValueType(); 8770 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8771 8772 // Save FP Control Word to register 8773 SDValue Chain = Op.getOperand(0); 8774 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8775 Chain = MFFS.getValue(1); 8776 8777 SDValue CWD; 8778 if (isTypeLegal(MVT::i64)) { 8779 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8780 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8781 } else { 8782 // Save FP register to stack slot 8783 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8784 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8785 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8786 8787 // Load FP Control Word from low 32 bits of stack slot. 8788 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8789 "Stack slot adjustment is valid only on big endian subtargets!"); 8790 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8791 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8792 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8793 Chain = CWD.getValue(1); 8794 } 8795 8796 // Transform as necessary 8797 SDValue CWD1 = 8798 DAG.getNode(ISD::AND, dl, MVT::i32, 8799 CWD, DAG.getConstant(3, dl, MVT::i32)); 8800 SDValue CWD2 = 8801 DAG.getNode(ISD::SRL, dl, MVT::i32, 8802 DAG.getNode(ISD::AND, dl, MVT::i32, 8803 DAG.getNode(ISD::XOR, dl, MVT::i32, 8804 CWD, DAG.getConstant(3, dl, MVT::i32)), 8805 DAG.getConstant(3, dl, MVT::i32)), 8806 DAG.getConstant(1, dl, MVT::i32)); 8807 8808 SDValue RetVal = 8809 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8810 8811 RetVal = 8812 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8813 dl, VT, RetVal); 8814 8815 return DAG.getMergeValues({RetVal, Chain}, dl); 8816 } 8817 8818 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8819 EVT VT = Op.getValueType(); 8820 unsigned BitWidth = VT.getSizeInBits(); 8821 SDLoc dl(Op); 8822 assert(Op.getNumOperands() == 3 && 8823 VT == Op.getOperand(1).getValueType() && 8824 "Unexpected SHL!"); 8825 8826 // Expand into a bunch of logical ops. Note that these ops 8827 // depend on the PPC behavior for oversized shift amounts. 8828 SDValue Lo = Op.getOperand(0); 8829 SDValue Hi = Op.getOperand(1); 8830 SDValue Amt = Op.getOperand(2); 8831 EVT AmtVT = Amt.getValueType(); 8832 8833 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8834 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8835 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8836 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8837 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8838 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8839 DAG.getConstant(-BitWidth, dl, AmtVT)); 8840 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8841 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8842 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8843 SDValue OutOps[] = { OutLo, OutHi }; 8844 return DAG.getMergeValues(OutOps, dl); 8845 } 8846 8847 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8848 EVT VT = Op.getValueType(); 8849 SDLoc dl(Op); 8850 unsigned BitWidth = VT.getSizeInBits(); 8851 assert(Op.getNumOperands() == 3 && 8852 VT == Op.getOperand(1).getValueType() && 8853 "Unexpected SRL!"); 8854 8855 // Expand into a bunch of logical ops. Note that these ops 8856 // depend on the PPC behavior for oversized shift amounts. 8857 SDValue Lo = Op.getOperand(0); 8858 SDValue Hi = Op.getOperand(1); 8859 SDValue Amt = Op.getOperand(2); 8860 EVT AmtVT = Amt.getValueType(); 8861 8862 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8863 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8864 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8865 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8866 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8867 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8868 DAG.getConstant(-BitWidth, dl, AmtVT)); 8869 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8870 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8871 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8872 SDValue OutOps[] = { OutLo, OutHi }; 8873 return DAG.getMergeValues(OutOps, dl); 8874 } 8875 8876 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8877 SDLoc dl(Op); 8878 EVT VT = Op.getValueType(); 8879 unsigned BitWidth = VT.getSizeInBits(); 8880 assert(Op.getNumOperands() == 3 && 8881 VT == Op.getOperand(1).getValueType() && 8882 "Unexpected SRA!"); 8883 8884 // Expand into a bunch of logical ops, followed by a select_cc. 8885 SDValue Lo = Op.getOperand(0); 8886 SDValue Hi = Op.getOperand(1); 8887 SDValue Amt = Op.getOperand(2); 8888 EVT AmtVT = Amt.getValueType(); 8889 8890 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8891 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8892 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8893 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8894 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8895 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8896 DAG.getConstant(-BitWidth, dl, AmtVT)); 8897 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8898 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8899 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8900 Tmp4, Tmp6, ISD::SETLE); 8901 SDValue OutOps[] = { OutLo, OutHi }; 8902 return DAG.getMergeValues(OutOps, dl); 8903 } 8904 8905 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8906 SelectionDAG &DAG) const { 8907 SDLoc dl(Op); 8908 EVT VT = Op.getValueType(); 8909 unsigned BitWidth = VT.getSizeInBits(); 8910 8911 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8912 SDValue X = Op.getOperand(0); 8913 SDValue Y = Op.getOperand(1); 8914 SDValue Z = Op.getOperand(2); 8915 EVT AmtVT = Z.getValueType(); 8916 8917 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8918 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8919 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8920 // on PowerPC shift by BW being well defined. 8921 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8922 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8923 SDValue SubZ = 8924 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8925 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8926 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8927 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8928 } 8929 8930 //===----------------------------------------------------------------------===// 8931 // Vector related lowering. 8932 // 8933 8934 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8935 /// element size of SplatSize. Cast the result to VT. 8936 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8937 SelectionDAG &DAG, const SDLoc &dl) { 8938 static const MVT VTys[] = { // canonical VT to use for each size. 8939 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8940 }; 8941 8942 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8943 8944 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8945 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8946 SplatSize = 1; 8947 Val = 0xFF; 8948 } 8949 8950 EVT CanonicalVT = VTys[SplatSize-1]; 8951 8952 // Build a canonical splat for this value. 8953 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8954 } 8955 8956 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8957 /// specified intrinsic ID. 8958 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8959 const SDLoc &dl, EVT DestVT = MVT::Other) { 8960 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8961 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8962 DAG.getConstant(IID, dl, MVT::i32), Op); 8963 } 8964 8965 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8966 /// specified intrinsic ID. 8967 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8968 SelectionDAG &DAG, const SDLoc &dl, 8969 EVT DestVT = MVT::Other) { 8970 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8971 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8972 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8973 } 8974 8975 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8976 /// specified intrinsic ID. 8977 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8978 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8979 EVT DestVT = MVT::Other) { 8980 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8981 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8982 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8983 } 8984 8985 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8986 /// amount. The result has the specified value type. 8987 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8988 SelectionDAG &DAG, const SDLoc &dl) { 8989 // Force LHS/RHS to be the right type. 8990 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8991 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8992 8993 int Ops[16]; 8994 for (unsigned i = 0; i != 16; ++i) 8995 Ops[i] = i + Amt; 8996 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8997 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8998 } 8999 9000 /// Do we have an efficient pattern in a .td file for this node? 9001 /// 9002 /// \param V - pointer to the BuildVectorSDNode being matched 9003 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9004 /// 9005 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9006 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9007 /// the opposite is true (expansion is beneficial) are: 9008 /// - The node builds a vector out of integers that are not 32 or 64-bits 9009 /// - The node builds a vector out of constants 9010 /// - The node is a "load-and-splat" 9011 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9012 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9013 bool HasDirectMove, 9014 bool HasP8Vector) { 9015 EVT VecVT = V->getValueType(0); 9016 bool RightType = VecVT == MVT::v2f64 || 9017 (HasP8Vector && VecVT == MVT::v4f32) || 9018 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9019 if (!RightType) 9020 return false; 9021 9022 bool IsSplat = true; 9023 bool IsLoad = false; 9024 SDValue Op0 = V->getOperand(0); 9025 9026 // This function is called in a block that confirms the node is not a constant 9027 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9028 // different constants. 9029 if (V->isConstant()) 9030 return false; 9031 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9032 if (V->getOperand(i).isUndef()) 9033 return false; 9034 // We want to expand nodes that represent load-and-splat even if the 9035 // loaded value is a floating point truncation or conversion to int. 9036 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9037 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9038 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9039 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9040 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9041 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9042 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9043 IsLoad = true; 9044 // If the operands are different or the input is not a load and has more 9045 // uses than just this BV node, then it isn't a splat. 9046 if (V->getOperand(i) != Op0 || 9047 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9048 IsSplat = false; 9049 } 9050 return !(IsSplat && IsLoad); 9051 } 9052 9053 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9054 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9055 9056 SDLoc dl(Op); 9057 SDValue Op0 = Op->getOperand(0); 9058 9059 if ((Op.getValueType() != MVT::f128) || 9060 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9061 (Op0.getOperand(0).getValueType() != MVT::i64) || 9062 (Op0.getOperand(1).getValueType() != MVT::i64)) 9063 return SDValue(); 9064 9065 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9066 Op0.getOperand(1)); 9067 } 9068 9069 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9070 const SDValue *InputLoad = &Op; 9071 if (InputLoad->getOpcode() == ISD::BITCAST) 9072 InputLoad = &InputLoad->getOperand(0); 9073 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9074 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9075 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9076 InputLoad = &InputLoad->getOperand(0); 9077 } 9078 if (InputLoad->getOpcode() != ISD::LOAD) 9079 return nullptr; 9080 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9081 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9082 } 9083 9084 // Convert the argument APFloat to a single precision APFloat if there is no 9085 // loss in information during the conversion to single precision APFloat and the 9086 // resulting number is not a denormal number. Return true if successful. 9087 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9088 APFloat APFloatToConvert = ArgAPFloat; 9089 bool LosesInfo = true; 9090 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9091 &LosesInfo); 9092 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9093 if (Success) 9094 ArgAPFloat = APFloatToConvert; 9095 return Success; 9096 } 9097 9098 // Bitcast the argument APInt to a double and convert it to a single precision 9099 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9100 // argument if there is no loss in information during the conversion from 9101 // double to single precision APFloat and the resulting number is not a denormal 9102 // number. Return true if successful. 9103 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9104 double DpValue = ArgAPInt.bitsToDouble(); 9105 APFloat APFloatDp(DpValue); 9106 bool Success = convertToNonDenormSingle(APFloatDp); 9107 if (Success) 9108 ArgAPInt = APFloatDp.bitcastToAPInt(); 9109 return Success; 9110 } 9111 9112 // Nondestructive check for convertTonNonDenormSingle. 9113 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 9114 // Only convert if it loses info, since XXSPLTIDP should 9115 // handle the other case. 9116 APFloat APFloatToConvert = ArgAPFloat; 9117 bool LosesInfo = true; 9118 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9119 &LosesInfo); 9120 9121 return (!LosesInfo && !APFloatToConvert.isDenormal()); 9122 } 9123 9124 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op, 9125 unsigned &Opcode) { 9126 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0)); 9127 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode)) 9128 return false; 9129 9130 EVT Ty = Op->getValueType(0); 9131 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending 9132 // as we cannot handle extending loads for these types. 9133 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) && 9134 ISD::isNON_EXTLoad(InputNode)) 9135 return true; 9136 9137 EVT MemVT = InputNode->getMemoryVT(); 9138 // For v8i16 and v16i8 types, extending loads can be handled as long as the 9139 // memory VT is the same vector element VT type. 9140 // The loads feeding into the v8i16 and v16i8 types will be extending because 9141 // scalar i8/i16 are not legal types. 9142 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) && 9143 (MemVT == Ty.getVectorElementType())) 9144 return true; 9145 9146 if (Ty == MVT::v2i64) { 9147 // Check the extend type, when the input type is i32, and the output vector 9148 // type is v2i64. 9149 if (MemVT == MVT::i32) { 9150 if (ISD::isZEXTLoad(InputNode)) 9151 Opcode = PPCISD::ZEXT_LD_SPLAT; 9152 if (ISD::isSEXTLoad(InputNode)) 9153 Opcode = PPCISD::SEXT_LD_SPLAT; 9154 } 9155 return true; 9156 } 9157 return false; 9158 } 9159 9160 // If this is a case we can't handle, return null and let the default 9161 // expansion code take care of it. If we CAN select this case, and if it 9162 // selects to a single instruction, return Op. Otherwise, if we can codegen 9163 // this case more efficiently than a constant pool load, lower it to the 9164 // sequence of ops that should be used. 9165 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9166 SelectionDAG &DAG) const { 9167 SDLoc dl(Op); 9168 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9169 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9170 9171 // Check if this is a splat of a constant value. 9172 APInt APSplatBits, APSplatUndef; 9173 unsigned SplatBitSize; 9174 bool HasAnyUndefs; 9175 bool BVNIsConstantSplat = 9176 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9177 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9178 9179 // If it is a splat of a double, check if we can shrink it to a 32 bit 9180 // non-denormal float which when converted back to double gives us the same 9181 // double. This is to exploit the XXSPLTIDP instruction. 9182 // If we lose precision, we use XXSPLTI32DX. 9183 if (BVNIsConstantSplat && (SplatBitSize == 64) && 9184 Subtarget.hasPrefixInstrs()) { 9185 // Check the type first to short-circuit so we don't modify APSplatBits if 9186 // this block isn't executed. 9187 if ((Op->getValueType(0) == MVT::v2f64) && 9188 convertToNonDenormSingle(APSplatBits)) { 9189 SDValue SplatNode = DAG.getNode( 9190 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9191 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9192 return DAG.getBitcast(Op.getValueType(), SplatNode); 9193 } else { 9194 // We may lose precision, so we have to use XXSPLTI32DX. 9195 9196 uint32_t Hi = 9197 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 9198 uint32_t Lo = 9199 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 9200 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 9201 9202 if (!Hi || !Lo) 9203 // If either load is 0, then we should generate XXLXOR to set to 0. 9204 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 9205 9206 if (Hi) 9207 SplatNode = DAG.getNode( 9208 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9209 DAG.getTargetConstant(0, dl, MVT::i32), 9210 DAG.getTargetConstant(Hi, dl, MVT::i32)); 9211 9212 if (Lo) 9213 SplatNode = 9214 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9215 DAG.getTargetConstant(1, dl, MVT::i32), 9216 DAG.getTargetConstant(Lo, dl, MVT::i32)); 9217 9218 return DAG.getBitcast(Op.getValueType(), SplatNode); 9219 } 9220 } 9221 9222 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9223 unsigned NewOpcode = PPCISD::LD_SPLAT; 9224 9225 // Handle load-and-splat patterns as we have instructions that will do this 9226 // in one go. 9227 if (DAG.isSplatValue(Op, true) && 9228 isValidSplatLoad(Subtarget, Op, NewOpcode)) { 9229 const SDValue *InputLoad = &Op.getOperand(0); 9230 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9231 9232 // If the input load is an extending load, it will be an i32 -> i64 9233 // extending load and isValidSplatLoad() will update NewOpcode. 9234 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits(); 9235 unsigned ElementSize = 9236 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2); 9237 9238 assert(((ElementSize == 2 * MemorySize) 9239 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || 9240 NewOpcode == PPCISD::SEXT_LD_SPLAT) 9241 : (NewOpcode == PPCISD::LD_SPLAT)) && 9242 "Unmatched element size and opcode!\n"); 9243 9244 // Checking for a single use of this load, we have to check for vector 9245 // width (128 bits) / ElementSize uses (since each operand of the 9246 // BUILD_VECTOR is a separate use of the value. 9247 unsigned NumUsesOfInputLD = 128 / ElementSize; 9248 for (SDValue BVInOp : Op->ops()) 9249 if (BVInOp.isUndef()) 9250 NumUsesOfInputLD--; 9251 9252 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector: 9253 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index 9254 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index 9255 // 15", but funciton IsValidSplatLoad() now will only return true when 9256 // the data at index 0 is not nullptr. So we will not get into trouble for 9257 // these cases. 9258 // 9259 // case 1 - lfiwzx/lfiwax 9260 // 1.1: load result is i32 and is sign/zero extend to i64; 9261 // 1.2: build a v2i64 vector type with above loaded value; 9262 // 1.3: the vector has only one value at index 0, others are all undef; 9263 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute. 9264 if (NumUsesOfInputLD == 1 && 9265 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT && 9266 !Subtarget.isLittleEndian() && Subtarget.hasVSX() && 9267 Subtarget.hasLFIWAX())) 9268 return SDValue(); 9269 9270 // case 2 - lxvr[hb]x 9271 // 2.1: load result is at most i16; 9272 // 2.2: build a vector with above loaded value; 9273 // 2.3: the vector has only one value at index 0, others are all undef; 9274 // 2.4: on LE target, so that lxvr[hb]x does not need any permute. 9275 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() && 9276 Subtarget.isISA3_1() && ElementSize <= 16) 9277 return SDValue(); 9278 9279 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9280 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9281 Subtarget.hasVSX()) { 9282 SDValue Ops[] = { 9283 LD->getChain(), // Chain 9284 LD->getBasePtr(), // Ptr 9285 DAG.getValueType(Op.getValueType()) // VT 9286 }; 9287 SDValue LdSplt = DAG.getMemIntrinsicNode( 9288 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops, 9289 LD->getMemoryVT(), LD->getMemOperand()); 9290 // Replace all uses of the output chain of the original load with the 9291 // output chain of the new load. 9292 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9293 LdSplt.getValue(1)); 9294 return LdSplt; 9295 } 9296 } 9297 9298 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9299 // 32-bits can be lowered to VSX instructions under certain conditions. 9300 // Without VSX, there is no pattern more efficient than expanding the node. 9301 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9302 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9303 Subtarget.hasP8Vector())) 9304 return Op; 9305 return SDValue(); 9306 } 9307 9308 uint64_t SplatBits = APSplatBits.getZExtValue(); 9309 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9310 unsigned SplatSize = SplatBitSize / 8; 9311 9312 // First, handle single instruction cases. 9313 9314 // All zeros? 9315 if (SplatBits == 0) { 9316 // Canonicalize all zero vectors to be v4i32. 9317 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9318 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9319 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9320 } 9321 return Op; 9322 } 9323 9324 // We have XXSPLTIW for constant splats four bytes wide. 9325 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9326 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9327 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9328 // turned into a 4-byte splat of 0xABABABAB. 9329 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9330 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9331 Op.getValueType(), DAG, dl); 9332 9333 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9334 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9335 dl); 9336 9337 // We have XXSPLTIB for constant splats one byte wide. 9338 if (Subtarget.hasP9Vector() && SplatSize == 1) 9339 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9340 dl); 9341 9342 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9343 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9344 (32-SplatBitSize)); 9345 if (SextVal >= -16 && SextVal <= 15) 9346 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9347 dl); 9348 9349 // Two instruction sequences. 9350 9351 // If this value is in the range [-32,30] and is even, use: 9352 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9353 // If this value is in the range [17,31] and is odd, use: 9354 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9355 // If this value is in the range [-31,-17] and is odd, use: 9356 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9357 // Note the last two are three-instruction sequences. 9358 if (SextVal >= -32 && SextVal <= 31) { 9359 // To avoid having these optimizations undone by constant folding, 9360 // we convert to a pseudo that will be expanded later into one of 9361 // the above forms. 9362 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9363 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9364 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9365 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9366 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9367 if (VT == Op.getValueType()) 9368 return RetVal; 9369 else 9370 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9371 } 9372 9373 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9374 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9375 // for fneg/fabs. 9376 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9377 // Make -1 and vspltisw -1: 9378 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9379 9380 // Make the VSLW intrinsic, computing 0x8000_0000. 9381 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9382 OnesV, DAG, dl); 9383 9384 // xor by OnesV to invert it. 9385 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9386 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9387 } 9388 9389 // Check to see if this is a wide variety of vsplti*, binop self cases. 9390 static const signed char SplatCsts[] = { 9391 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9392 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9393 }; 9394 9395 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9396 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9397 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9398 int i = SplatCsts[idx]; 9399 9400 // Figure out what shift amount will be used by altivec if shifted by i in 9401 // this splat size. 9402 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9403 9404 // vsplti + shl self. 9405 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9406 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9407 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9408 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9409 Intrinsic::ppc_altivec_vslw 9410 }; 9411 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9412 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9413 } 9414 9415 // vsplti + srl self. 9416 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9417 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9418 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9419 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9420 Intrinsic::ppc_altivec_vsrw 9421 }; 9422 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9423 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9424 } 9425 9426 // vsplti + rol self. 9427 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9428 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9429 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9430 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9431 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9432 Intrinsic::ppc_altivec_vrlw 9433 }; 9434 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9435 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9436 } 9437 9438 // t = vsplti c, result = vsldoi t, t, 1 9439 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9440 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9441 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9442 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9443 } 9444 // t = vsplti c, result = vsldoi t, t, 2 9445 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9446 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9447 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9448 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9449 } 9450 // t = vsplti c, result = vsldoi t, t, 3 9451 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9452 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9453 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9454 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9455 } 9456 } 9457 9458 return SDValue(); 9459 } 9460 9461 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9462 /// the specified operations to build the shuffle. 9463 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9464 SDValue RHS, SelectionDAG &DAG, 9465 const SDLoc &dl) { 9466 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9467 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9468 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9469 9470 enum { 9471 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9472 OP_VMRGHW, 9473 OP_VMRGLW, 9474 OP_VSPLTISW0, 9475 OP_VSPLTISW1, 9476 OP_VSPLTISW2, 9477 OP_VSPLTISW3, 9478 OP_VSLDOI4, 9479 OP_VSLDOI8, 9480 OP_VSLDOI12 9481 }; 9482 9483 if (OpNum == OP_COPY) { 9484 if (LHSID == (1*9+2)*9+3) return LHS; 9485 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9486 return RHS; 9487 } 9488 9489 SDValue OpLHS, OpRHS; 9490 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9491 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9492 9493 int ShufIdxs[16]; 9494 switch (OpNum) { 9495 default: llvm_unreachable("Unknown i32 permute!"); 9496 case OP_VMRGHW: 9497 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9498 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9499 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9500 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9501 break; 9502 case OP_VMRGLW: 9503 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9504 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9505 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9506 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9507 break; 9508 case OP_VSPLTISW0: 9509 for (unsigned i = 0; i != 16; ++i) 9510 ShufIdxs[i] = (i&3)+0; 9511 break; 9512 case OP_VSPLTISW1: 9513 for (unsigned i = 0; i != 16; ++i) 9514 ShufIdxs[i] = (i&3)+4; 9515 break; 9516 case OP_VSPLTISW2: 9517 for (unsigned i = 0; i != 16; ++i) 9518 ShufIdxs[i] = (i&3)+8; 9519 break; 9520 case OP_VSPLTISW3: 9521 for (unsigned i = 0; i != 16; ++i) 9522 ShufIdxs[i] = (i&3)+12; 9523 break; 9524 case OP_VSLDOI4: 9525 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9526 case OP_VSLDOI8: 9527 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9528 case OP_VSLDOI12: 9529 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9530 } 9531 EVT VT = OpLHS.getValueType(); 9532 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9533 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9534 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9535 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9536 } 9537 9538 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9539 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9540 /// SDValue. 9541 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9542 SelectionDAG &DAG) const { 9543 const unsigned BytesInVector = 16; 9544 bool IsLE = Subtarget.isLittleEndian(); 9545 SDLoc dl(N); 9546 SDValue V1 = N->getOperand(0); 9547 SDValue V2 = N->getOperand(1); 9548 unsigned ShiftElts = 0, InsertAtByte = 0; 9549 bool Swap = false; 9550 9551 // Shifts required to get the byte we want at element 7. 9552 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9553 0, 15, 14, 13, 12, 11, 10, 9}; 9554 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9555 1, 2, 3, 4, 5, 6, 7, 8}; 9556 9557 ArrayRef<int> Mask = N->getMask(); 9558 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9559 9560 // For each mask element, find out if we're just inserting something 9561 // from V2 into V1 or vice versa. 9562 // Possible permutations inserting an element from V2 into V1: 9563 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9564 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9565 // ... 9566 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9567 // Inserting from V1 into V2 will be similar, except mask range will be 9568 // [16,31]. 9569 9570 bool FoundCandidate = false; 9571 // If both vector operands for the shuffle are the same vector, the mask 9572 // will contain only elements from the first one and the second one will be 9573 // undef. 9574 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9575 // Go through the mask of half-words to find an element that's being moved 9576 // from one vector to the other. 9577 for (unsigned i = 0; i < BytesInVector; ++i) { 9578 unsigned CurrentElement = Mask[i]; 9579 // If 2nd operand is undefined, we should only look for element 7 in the 9580 // Mask. 9581 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9582 continue; 9583 9584 bool OtherElementsInOrder = true; 9585 // Examine the other elements in the Mask to see if they're in original 9586 // order. 9587 for (unsigned j = 0; j < BytesInVector; ++j) { 9588 if (j == i) 9589 continue; 9590 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9591 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9592 // in which we always assume we're always picking from the 1st operand. 9593 int MaskOffset = 9594 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9595 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9596 OtherElementsInOrder = false; 9597 break; 9598 } 9599 } 9600 // If other elements are in original order, we record the number of shifts 9601 // we need to get the element we want into element 7. Also record which byte 9602 // in the vector we should insert into. 9603 if (OtherElementsInOrder) { 9604 // If 2nd operand is undefined, we assume no shifts and no swapping. 9605 if (V2.isUndef()) { 9606 ShiftElts = 0; 9607 Swap = false; 9608 } else { 9609 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9610 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9611 : BigEndianShifts[CurrentElement & 0xF]; 9612 Swap = CurrentElement < BytesInVector; 9613 } 9614 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9615 FoundCandidate = true; 9616 break; 9617 } 9618 } 9619 9620 if (!FoundCandidate) 9621 return SDValue(); 9622 9623 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9624 // optionally with VECSHL if shift is required. 9625 if (Swap) 9626 std::swap(V1, V2); 9627 if (V2.isUndef()) 9628 V2 = V1; 9629 if (ShiftElts) { 9630 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9631 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9632 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9633 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9634 } 9635 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9636 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9637 } 9638 9639 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9640 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9641 /// SDValue. 9642 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9643 SelectionDAG &DAG) const { 9644 const unsigned NumHalfWords = 8; 9645 const unsigned BytesInVector = NumHalfWords * 2; 9646 // Check that the shuffle is on half-words. 9647 if (!isNByteElemShuffleMask(N, 2, 1)) 9648 return SDValue(); 9649 9650 bool IsLE = Subtarget.isLittleEndian(); 9651 SDLoc dl(N); 9652 SDValue V1 = N->getOperand(0); 9653 SDValue V2 = N->getOperand(1); 9654 unsigned ShiftElts = 0, InsertAtByte = 0; 9655 bool Swap = false; 9656 9657 // Shifts required to get the half-word we want at element 3. 9658 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9659 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9660 9661 uint32_t Mask = 0; 9662 uint32_t OriginalOrderLow = 0x1234567; 9663 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9664 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9665 // 32-bit space, only need 4-bit nibbles per element. 9666 for (unsigned i = 0; i < NumHalfWords; ++i) { 9667 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9668 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9669 } 9670 9671 // For each mask element, find out if we're just inserting something 9672 // from V2 into V1 or vice versa. Possible permutations inserting an element 9673 // from V2 into V1: 9674 // X, 1, 2, 3, 4, 5, 6, 7 9675 // 0, X, 2, 3, 4, 5, 6, 7 9676 // 0, 1, X, 3, 4, 5, 6, 7 9677 // 0, 1, 2, X, 4, 5, 6, 7 9678 // 0, 1, 2, 3, X, 5, 6, 7 9679 // 0, 1, 2, 3, 4, X, 6, 7 9680 // 0, 1, 2, 3, 4, 5, X, 7 9681 // 0, 1, 2, 3, 4, 5, 6, X 9682 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9683 9684 bool FoundCandidate = false; 9685 // Go through the mask of half-words to find an element that's being moved 9686 // from one vector to the other. 9687 for (unsigned i = 0; i < NumHalfWords; ++i) { 9688 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9689 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9690 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9691 uint32_t TargetOrder = 0x0; 9692 9693 // If both vector operands for the shuffle are the same vector, the mask 9694 // will contain only elements from the first one and the second one will be 9695 // undef. 9696 if (V2.isUndef()) { 9697 ShiftElts = 0; 9698 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9699 TargetOrder = OriginalOrderLow; 9700 Swap = false; 9701 // Skip if not the correct element or mask of other elements don't equal 9702 // to our expected order. 9703 if (MaskOneElt == VINSERTHSrcElem && 9704 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9705 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9706 FoundCandidate = true; 9707 break; 9708 } 9709 } else { // If both operands are defined. 9710 // Target order is [8,15] if the current mask is between [0,7]. 9711 TargetOrder = 9712 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9713 // Skip if mask of other elements don't equal our expected order. 9714 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9715 // We only need the last 3 bits for the number of shifts. 9716 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9717 : BigEndianShifts[MaskOneElt & 0x7]; 9718 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9719 Swap = MaskOneElt < NumHalfWords; 9720 FoundCandidate = true; 9721 break; 9722 } 9723 } 9724 } 9725 9726 if (!FoundCandidate) 9727 return SDValue(); 9728 9729 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9730 // optionally with VECSHL if shift is required. 9731 if (Swap) 9732 std::swap(V1, V2); 9733 if (V2.isUndef()) 9734 V2 = V1; 9735 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9736 if (ShiftElts) { 9737 // Double ShiftElts because we're left shifting on v16i8 type. 9738 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9739 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9740 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9741 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9742 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9743 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9744 } 9745 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9746 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9747 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9748 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9749 } 9750 9751 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9752 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9753 /// return the default SDValue. 9754 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9755 SelectionDAG &DAG) const { 9756 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9757 // to v16i8. Peek through the bitcasts to get the actual operands. 9758 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9759 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9760 9761 auto ShuffleMask = SVN->getMask(); 9762 SDValue VecShuffle(SVN, 0); 9763 SDLoc DL(SVN); 9764 9765 // Check that we have a four byte shuffle. 9766 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9767 return SDValue(); 9768 9769 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9770 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9771 std::swap(LHS, RHS); 9772 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9773 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9774 } 9775 9776 // Ensure that the RHS is a vector of constants. 9777 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9778 if (!BVN) 9779 return SDValue(); 9780 9781 // Check if RHS is a splat of 4-bytes (or smaller). 9782 APInt APSplatValue, APSplatUndef; 9783 unsigned SplatBitSize; 9784 bool HasAnyUndefs; 9785 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9786 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9787 SplatBitSize > 32) 9788 return SDValue(); 9789 9790 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9791 // The instruction splats a constant C into two words of the source vector 9792 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9793 // Thus we check that the shuffle mask is the equivalent of 9794 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9795 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9796 // within each word are consecutive, so we only need to check the first byte. 9797 SDValue Index; 9798 bool IsLE = Subtarget.isLittleEndian(); 9799 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9800 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9801 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9802 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9803 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9804 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9805 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9806 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9807 else 9808 return SDValue(); 9809 9810 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9811 // for XXSPLTI32DX. 9812 unsigned SplatVal = APSplatValue.getZExtValue(); 9813 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9814 SplatVal |= (SplatVal << SplatBitSize); 9815 9816 SDValue SplatNode = DAG.getNode( 9817 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9818 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9819 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9820 } 9821 9822 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9823 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9824 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9825 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9826 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9827 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9828 assert(Op.getValueType() == MVT::v1i128 && 9829 "Only set v1i128 as custom, other type shouldn't reach here!"); 9830 SDLoc dl(Op); 9831 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9832 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9833 unsigned SHLAmt = N1.getConstantOperandVal(0); 9834 if (SHLAmt % 8 == 0) { 9835 std::array<int, 16> Mask; 9836 std::iota(Mask.begin(), Mask.end(), 0); 9837 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9838 if (SDValue Shuffle = 9839 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9840 DAG.getUNDEF(MVT::v16i8), Mask)) 9841 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9842 } 9843 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9844 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9845 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9846 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9847 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9848 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9849 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9850 } 9851 9852 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9853 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9854 /// return the code it can be lowered into. Worst case, it can always be 9855 /// lowered into a vperm. 9856 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9857 SelectionDAG &DAG) const { 9858 SDLoc dl(Op); 9859 SDValue V1 = Op.getOperand(0); 9860 SDValue V2 = Op.getOperand(1); 9861 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9862 9863 // Any nodes that were combined in the target-independent combiner prior 9864 // to vector legalization will not be sent to the target combine. Try to 9865 // combine it here. 9866 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9867 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9868 return NewShuffle; 9869 Op = NewShuffle; 9870 SVOp = cast<ShuffleVectorSDNode>(Op); 9871 V1 = Op.getOperand(0); 9872 V2 = Op.getOperand(1); 9873 } 9874 EVT VT = Op.getValueType(); 9875 bool isLittleEndian = Subtarget.isLittleEndian(); 9876 9877 unsigned ShiftElts, InsertAtByte; 9878 bool Swap = false; 9879 9880 // If this is a load-and-splat, we can do that with a single instruction 9881 // in some cases. However if the load has multiple uses, we don't want to 9882 // combine it because that will just produce multiple loads. 9883 bool IsPermutedLoad = false; 9884 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9885 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9886 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9887 InputLoad->hasOneUse()) { 9888 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9889 int SplatIdx = 9890 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9891 9892 // The splat index for permuted loads will be in the left half of the vector 9893 // which is strictly wider than the loaded value by 8 bytes. So we need to 9894 // adjust the splat index to point to the correct address in memory. 9895 if (IsPermutedLoad) { 9896 assert((isLittleEndian || IsFourByte) && 9897 "Unexpected size for permuted load on big endian target"); 9898 SplatIdx += IsFourByte ? 2 : 1; 9899 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9900 "Splat of a value outside of the loaded memory"); 9901 } 9902 9903 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9904 // For 4-byte load-and-splat, we need Power9. 9905 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9906 uint64_t Offset = 0; 9907 if (IsFourByte) 9908 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9909 else 9910 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9911 9912 // If the width of the load is the same as the width of the splat, 9913 // loading with an offset would load the wrong memory. 9914 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9915 Offset = 0; 9916 9917 SDValue BasePtr = LD->getBasePtr(); 9918 if (Offset != 0) 9919 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9920 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9921 SDValue Ops[] = { 9922 LD->getChain(), // Chain 9923 BasePtr, // BasePtr 9924 DAG.getValueType(Op.getValueType()) // VT 9925 }; 9926 SDVTList VTL = 9927 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9928 SDValue LdSplt = 9929 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9930 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9931 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9932 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9933 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9934 return LdSplt; 9935 } 9936 } 9937 9938 // All v2i64 and v2f64 shuffles are legal 9939 if (VT == MVT::v2i64 || VT == MVT::v2f64) 9940 return Op; 9941 9942 if (Subtarget.hasP9Vector() && 9943 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9944 isLittleEndian)) { 9945 if (Swap) 9946 std::swap(V1, V2); 9947 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9948 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9949 if (ShiftElts) { 9950 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9951 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9952 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9953 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9954 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9955 } 9956 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9957 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9958 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9959 } 9960 9961 if (Subtarget.hasPrefixInstrs()) { 9962 SDValue SplatInsertNode; 9963 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9964 return SplatInsertNode; 9965 } 9966 9967 if (Subtarget.hasP9Altivec()) { 9968 SDValue NewISDNode; 9969 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9970 return NewISDNode; 9971 9972 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9973 return NewISDNode; 9974 } 9975 9976 if (Subtarget.hasVSX() && 9977 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9978 if (Swap) 9979 std::swap(V1, V2); 9980 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9981 SDValue Conv2 = 9982 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9983 9984 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9985 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9986 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9987 } 9988 9989 if (Subtarget.hasVSX() && 9990 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9991 if (Swap) 9992 std::swap(V1, V2); 9993 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9994 SDValue Conv2 = 9995 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9996 9997 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9998 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9999 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 10000 } 10001 10002 if (Subtarget.hasP9Vector()) { 10003 if (PPC::isXXBRHShuffleMask(SVOp)) { 10004 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 10005 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 10006 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 10007 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 10008 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10009 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 10010 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 10011 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 10012 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 10013 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 10014 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 10015 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 10016 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 10017 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 10018 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 10019 } 10020 } 10021 10022 if (Subtarget.hasVSX()) { 10023 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 10024 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 10025 10026 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10027 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 10028 DAG.getConstant(SplatIdx, dl, MVT::i32)); 10029 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 10030 } 10031 10032 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 10033 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 10034 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 10035 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 10036 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 10037 } 10038 } 10039 10040 // Cases that are handled by instructions that take permute immediates 10041 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 10042 // selected by the instruction selector. 10043 if (V2.isUndef()) { 10044 if (PPC::isSplatShuffleMask(SVOp, 1) || 10045 PPC::isSplatShuffleMask(SVOp, 2) || 10046 PPC::isSplatShuffleMask(SVOp, 4) || 10047 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 10048 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 10049 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 10050 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 10051 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 10052 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 10053 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 10054 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 10055 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 10056 (Subtarget.hasP8Altivec() && ( 10057 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 10058 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 10059 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 10060 return Op; 10061 } 10062 } 10063 10064 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10065 // and produce a fixed permutation. If any of these match, do not lower to 10066 // VPERM. 10067 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10068 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10069 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10070 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10071 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10072 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10073 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10074 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10075 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10076 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10077 (Subtarget.hasP8Altivec() && ( 10078 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10079 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10080 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10081 return Op; 10082 10083 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10084 // perfect shuffle table to emit an optimal matching sequence. 10085 ArrayRef<int> PermMask = SVOp->getMask(); 10086 10087 if (!DisablePerfectShuffle && !isLittleEndian) { 10088 unsigned PFIndexes[4]; 10089 bool isFourElementShuffle = true; 10090 for (unsigned i = 0; i != 4 && isFourElementShuffle; 10091 ++i) { // Element number 10092 unsigned EltNo = 8; // Start out undef. 10093 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10094 if (PermMask[i * 4 + j] < 0) 10095 continue; // Undef, ignore it. 10096 10097 unsigned ByteSource = PermMask[i * 4 + j]; 10098 if ((ByteSource & 3) != j) { 10099 isFourElementShuffle = false; 10100 break; 10101 } 10102 10103 if (EltNo == 8) { 10104 EltNo = ByteSource / 4; 10105 } else if (EltNo != ByteSource / 4) { 10106 isFourElementShuffle = false; 10107 break; 10108 } 10109 } 10110 PFIndexes[i] = EltNo; 10111 } 10112 10113 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10114 // perfect shuffle vector to determine if it is cost effective to do this as 10115 // discrete instructions, or whether we should use a vperm. 10116 // For now, we skip this for little endian until such time as we have a 10117 // little-endian perfect shuffle table. 10118 if (isFourElementShuffle) { 10119 // Compute the index in the perfect shuffle table. 10120 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 10121 PFIndexes[2] * 9 + PFIndexes[3]; 10122 10123 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10124 unsigned Cost = (PFEntry >> 30); 10125 10126 // Determining when to avoid vperm is tricky. Many things affect the cost 10127 // of vperm, particularly how many times the perm mask needs to be 10128 // computed. For example, if the perm mask can be hoisted out of a loop or 10129 // is already used (perhaps because there are multiple permutes with the 10130 // same shuffle mask?) the vperm has a cost of 1. OTOH, hoisting the 10131 // permute mask out of the loop requires an extra register. 10132 // 10133 // As a compromise, we only emit discrete instructions if the shuffle can 10134 // be generated in 3 or fewer operations. When we have loop information 10135 // available, if this block is within a loop, we should avoid using vperm 10136 // for 3-operation perms and use a constant pool load instead. 10137 if (Cost < 3) 10138 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10139 } 10140 } 10141 10142 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10143 // vector that will get spilled to the constant pool. 10144 if (V2.isUndef()) V2 = V1; 10145 10146 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10147 // that it is in input element units, not in bytes. Convert now. 10148 10149 // For little endian, the order of the input vectors is reversed, and 10150 // the permutation mask is complemented with respect to 31. This is 10151 // necessary to produce proper semantics with the big-endian-biased vperm 10152 // instruction. 10153 EVT EltVT = V1.getValueType().getVectorElementType(); 10154 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10155 10156 SmallVector<SDValue, 16> ResultMask; 10157 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10158 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10159 10160 for (unsigned j = 0; j != BytesPerElement; ++j) 10161 if (isLittleEndian) 10162 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10163 dl, MVT::i32)); 10164 else 10165 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10166 MVT::i32)); 10167 } 10168 10169 ShufflesHandledWithVPERM++; 10170 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10171 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10172 LLVM_DEBUG(SVOp->dump()); 10173 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10174 LLVM_DEBUG(VPermMask.dump()); 10175 10176 if (isLittleEndian) 10177 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10178 V2, V1, VPermMask); 10179 else 10180 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10181 V1, V2, VPermMask); 10182 } 10183 10184 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10185 /// vector comparison. If it is, return true and fill in Opc/isDot with 10186 /// information about the intrinsic. 10187 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10188 bool &isDot, const PPCSubtarget &Subtarget) { 10189 unsigned IntrinsicID = 10190 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10191 CompareOpc = -1; 10192 isDot = false; 10193 switch (IntrinsicID) { 10194 default: 10195 return false; 10196 // Comparison predicates. 10197 case Intrinsic::ppc_altivec_vcmpbfp_p: 10198 CompareOpc = 966; 10199 isDot = true; 10200 break; 10201 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10202 CompareOpc = 198; 10203 isDot = true; 10204 break; 10205 case Intrinsic::ppc_altivec_vcmpequb_p: 10206 CompareOpc = 6; 10207 isDot = true; 10208 break; 10209 case Intrinsic::ppc_altivec_vcmpequh_p: 10210 CompareOpc = 70; 10211 isDot = true; 10212 break; 10213 case Intrinsic::ppc_altivec_vcmpequw_p: 10214 CompareOpc = 134; 10215 isDot = true; 10216 break; 10217 case Intrinsic::ppc_altivec_vcmpequd_p: 10218 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10219 CompareOpc = 199; 10220 isDot = true; 10221 } else 10222 return false; 10223 break; 10224 case Intrinsic::ppc_altivec_vcmpneb_p: 10225 case Intrinsic::ppc_altivec_vcmpneh_p: 10226 case Intrinsic::ppc_altivec_vcmpnew_p: 10227 case Intrinsic::ppc_altivec_vcmpnezb_p: 10228 case Intrinsic::ppc_altivec_vcmpnezh_p: 10229 case Intrinsic::ppc_altivec_vcmpnezw_p: 10230 if (Subtarget.hasP9Altivec()) { 10231 switch (IntrinsicID) { 10232 default: 10233 llvm_unreachable("Unknown comparison intrinsic."); 10234 case Intrinsic::ppc_altivec_vcmpneb_p: 10235 CompareOpc = 7; 10236 break; 10237 case Intrinsic::ppc_altivec_vcmpneh_p: 10238 CompareOpc = 71; 10239 break; 10240 case Intrinsic::ppc_altivec_vcmpnew_p: 10241 CompareOpc = 135; 10242 break; 10243 case Intrinsic::ppc_altivec_vcmpnezb_p: 10244 CompareOpc = 263; 10245 break; 10246 case Intrinsic::ppc_altivec_vcmpnezh_p: 10247 CompareOpc = 327; 10248 break; 10249 case Intrinsic::ppc_altivec_vcmpnezw_p: 10250 CompareOpc = 391; 10251 break; 10252 } 10253 isDot = true; 10254 } else 10255 return false; 10256 break; 10257 case Intrinsic::ppc_altivec_vcmpgefp_p: 10258 CompareOpc = 454; 10259 isDot = true; 10260 break; 10261 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10262 CompareOpc = 710; 10263 isDot = true; 10264 break; 10265 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10266 CompareOpc = 774; 10267 isDot = true; 10268 break; 10269 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10270 CompareOpc = 838; 10271 isDot = true; 10272 break; 10273 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10274 CompareOpc = 902; 10275 isDot = true; 10276 break; 10277 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10278 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10279 CompareOpc = 967; 10280 isDot = true; 10281 } else 10282 return false; 10283 break; 10284 case Intrinsic::ppc_altivec_vcmpgtub_p: 10285 CompareOpc = 518; 10286 isDot = true; 10287 break; 10288 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10289 CompareOpc = 582; 10290 isDot = true; 10291 break; 10292 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10293 CompareOpc = 646; 10294 isDot = true; 10295 break; 10296 case Intrinsic::ppc_altivec_vcmpgtud_p: 10297 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10298 CompareOpc = 711; 10299 isDot = true; 10300 } else 10301 return false; 10302 break; 10303 10304 case Intrinsic::ppc_altivec_vcmpequq: 10305 case Intrinsic::ppc_altivec_vcmpgtsq: 10306 case Intrinsic::ppc_altivec_vcmpgtuq: 10307 if (!Subtarget.isISA3_1()) 10308 return false; 10309 switch (IntrinsicID) { 10310 default: 10311 llvm_unreachable("Unknown comparison intrinsic."); 10312 case Intrinsic::ppc_altivec_vcmpequq: 10313 CompareOpc = 455; 10314 break; 10315 case Intrinsic::ppc_altivec_vcmpgtsq: 10316 CompareOpc = 903; 10317 break; 10318 case Intrinsic::ppc_altivec_vcmpgtuq: 10319 CompareOpc = 647; 10320 break; 10321 } 10322 break; 10323 10324 // VSX predicate comparisons use the same infrastructure 10325 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10326 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10327 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10328 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10329 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10330 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10331 if (Subtarget.hasVSX()) { 10332 switch (IntrinsicID) { 10333 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10334 CompareOpc = 99; 10335 break; 10336 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10337 CompareOpc = 115; 10338 break; 10339 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10340 CompareOpc = 107; 10341 break; 10342 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10343 CompareOpc = 67; 10344 break; 10345 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10346 CompareOpc = 83; 10347 break; 10348 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10349 CompareOpc = 75; 10350 break; 10351 } 10352 isDot = true; 10353 } else 10354 return false; 10355 break; 10356 10357 // Normal Comparisons. 10358 case Intrinsic::ppc_altivec_vcmpbfp: 10359 CompareOpc = 966; 10360 break; 10361 case Intrinsic::ppc_altivec_vcmpeqfp: 10362 CompareOpc = 198; 10363 break; 10364 case Intrinsic::ppc_altivec_vcmpequb: 10365 CompareOpc = 6; 10366 break; 10367 case Intrinsic::ppc_altivec_vcmpequh: 10368 CompareOpc = 70; 10369 break; 10370 case Intrinsic::ppc_altivec_vcmpequw: 10371 CompareOpc = 134; 10372 break; 10373 case Intrinsic::ppc_altivec_vcmpequd: 10374 if (Subtarget.hasP8Altivec()) 10375 CompareOpc = 199; 10376 else 10377 return false; 10378 break; 10379 case Intrinsic::ppc_altivec_vcmpneb: 10380 case Intrinsic::ppc_altivec_vcmpneh: 10381 case Intrinsic::ppc_altivec_vcmpnew: 10382 case Intrinsic::ppc_altivec_vcmpnezb: 10383 case Intrinsic::ppc_altivec_vcmpnezh: 10384 case Intrinsic::ppc_altivec_vcmpnezw: 10385 if (Subtarget.hasP9Altivec()) 10386 switch (IntrinsicID) { 10387 default: 10388 llvm_unreachable("Unknown comparison intrinsic."); 10389 case Intrinsic::ppc_altivec_vcmpneb: 10390 CompareOpc = 7; 10391 break; 10392 case Intrinsic::ppc_altivec_vcmpneh: 10393 CompareOpc = 71; 10394 break; 10395 case Intrinsic::ppc_altivec_vcmpnew: 10396 CompareOpc = 135; 10397 break; 10398 case Intrinsic::ppc_altivec_vcmpnezb: 10399 CompareOpc = 263; 10400 break; 10401 case Intrinsic::ppc_altivec_vcmpnezh: 10402 CompareOpc = 327; 10403 break; 10404 case Intrinsic::ppc_altivec_vcmpnezw: 10405 CompareOpc = 391; 10406 break; 10407 } 10408 else 10409 return false; 10410 break; 10411 case Intrinsic::ppc_altivec_vcmpgefp: 10412 CompareOpc = 454; 10413 break; 10414 case Intrinsic::ppc_altivec_vcmpgtfp: 10415 CompareOpc = 710; 10416 break; 10417 case Intrinsic::ppc_altivec_vcmpgtsb: 10418 CompareOpc = 774; 10419 break; 10420 case Intrinsic::ppc_altivec_vcmpgtsh: 10421 CompareOpc = 838; 10422 break; 10423 case Intrinsic::ppc_altivec_vcmpgtsw: 10424 CompareOpc = 902; 10425 break; 10426 case Intrinsic::ppc_altivec_vcmpgtsd: 10427 if (Subtarget.hasP8Altivec()) 10428 CompareOpc = 967; 10429 else 10430 return false; 10431 break; 10432 case Intrinsic::ppc_altivec_vcmpgtub: 10433 CompareOpc = 518; 10434 break; 10435 case Intrinsic::ppc_altivec_vcmpgtuh: 10436 CompareOpc = 582; 10437 break; 10438 case Intrinsic::ppc_altivec_vcmpgtuw: 10439 CompareOpc = 646; 10440 break; 10441 case Intrinsic::ppc_altivec_vcmpgtud: 10442 if (Subtarget.hasP8Altivec()) 10443 CompareOpc = 711; 10444 else 10445 return false; 10446 break; 10447 case Intrinsic::ppc_altivec_vcmpequq_p: 10448 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10449 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10450 if (!Subtarget.isISA3_1()) 10451 return false; 10452 switch (IntrinsicID) { 10453 default: 10454 llvm_unreachable("Unknown comparison intrinsic."); 10455 case Intrinsic::ppc_altivec_vcmpequq_p: 10456 CompareOpc = 455; 10457 break; 10458 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10459 CompareOpc = 903; 10460 break; 10461 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10462 CompareOpc = 647; 10463 break; 10464 } 10465 isDot = true; 10466 break; 10467 } 10468 return true; 10469 } 10470 10471 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10472 /// lower, do it, otherwise return null. 10473 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10474 SelectionDAG &DAG) const { 10475 unsigned IntrinsicID = 10476 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10477 10478 SDLoc dl(Op); 10479 10480 switch (IntrinsicID) { 10481 case Intrinsic::thread_pointer: 10482 // Reads the thread pointer register, used for __builtin_thread_pointer. 10483 if (Subtarget.isPPC64()) 10484 return DAG.getRegister(PPC::X13, MVT::i64); 10485 return DAG.getRegister(PPC::R2, MVT::i32); 10486 10487 case Intrinsic::ppc_mma_disassemble_acc: 10488 case Intrinsic::ppc_vsx_disassemble_pair: { 10489 int NumVecs = 2; 10490 SDValue WideVec = Op.getOperand(1); 10491 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10492 NumVecs = 4; 10493 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10494 } 10495 SmallVector<SDValue, 4> RetOps; 10496 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10497 SDValue Extract = DAG.getNode( 10498 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10499 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10500 : VecNo, 10501 dl, getPointerTy(DAG.getDataLayout()))); 10502 RetOps.push_back(Extract); 10503 } 10504 return DAG.getMergeValues(RetOps, dl); 10505 } 10506 10507 case Intrinsic::ppc_unpack_longdouble: { 10508 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10509 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) && 10510 "Argument of long double unpack must be 0 or 1!"); 10511 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1), 10512 DAG.getConstant(!!(Idx->getSExtValue()), dl, 10513 Idx->getValueType(0))); 10514 } 10515 10516 case Intrinsic::ppc_compare_exp_lt: 10517 case Intrinsic::ppc_compare_exp_gt: 10518 case Intrinsic::ppc_compare_exp_eq: 10519 case Intrinsic::ppc_compare_exp_uo: { 10520 unsigned Pred; 10521 switch (IntrinsicID) { 10522 case Intrinsic::ppc_compare_exp_lt: 10523 Pred = PPC::PRED_LT; 10524 break; 10525 case Intrinsic::ppc_compare_exp_gt: 10526 Pred = PPC::PRED_GT; 10527 break; 10528 case Intrinsic::ppc_compare_exp_eq: 10529 Pred = PPC::PRED_EQ; 10530 break; 10531 case Intrinsic::ppc_compare_exp_uo: 10532 Pred = PPC::PRED_UN; 10533 break; 10534 } 10535 return SDValue( 10536 DAG.getMachineNode( 10537 PPC::SELECT_CC_I4, dl, MVT::i32, 10538 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32, 10539 Op.getOperand(1), Op.getOperand(2)), 10540 0), 10541 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10542 DAG.getTargetConstant(Pred, dl, MVT::i32)}), 10543 0); 10544 } 10545 case Intrinsic::ppc_test_data_class_d: 10546 case Intrinsic::ppc_test_data_class_f: { 10547 unsigned CmprOpc = PPC::XSTSTDCDP; 10548 if (IntrinsicID == Intrinsic::ppc_test_data_class_f) 10549 CmprOpc = PPC::XSTSTDCSP; 10550 return SDValue( 10551 DAG.getMachineNode( 10552 PPC::SELECT_CC_I4, dl, MVT::i32, 10553 {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2), 10554 Op.getOperand(1)), 10555 0), 10556 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10557 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}), 10558 0); 10559 } 10560 case Intrinsic::ppc_fnmsub: { 10561 EVT VT = Op.getOperand(1).getValueType(); 10562 if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128)) 10563 return DAG.getNode( 10564 ISD::FNEG, dl, VT, 10565 DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2), 10566 DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3)))); 10567 return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1), 10568 Op.getOperand(2), Op.getOperand(3)); 10569 } 10570 case Intrinsic::ppc_convert_f128_to_ppcf128: 10571 case Intrinsic::ppc_convert_ppcf128_to_f128: { 10572 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128 10573 ? RTLIB::CONVERT_PPCF128_F128 10574 : RTLIB::CONVERT_F128_PPCF128; 10575 MakeLibCallOptions CallOptions; 10576 std::pair<SDValue, SDValue> Result = 10577 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions, 10578 dl, SDValue()); 10579 return Result.first; 10580 } 10581 case Intrinsic::ppc_maxfe: 10582 case Intrinsic::ppc_maxfl: 10583 case Intrinsic::ppc_maxfs: 10584 case Intrinsic::ppc_minfe: 10585 case Intrinsic::ppc_minfl: 10586 case Intrinsic::ppc_minfs: { 10587 EVT VT = Op.getValueType(); 10588 assert( 10589 all_of(Op->ops().drop_front(4), 10590 [VT](const SDUse &Use) { return Use.getValueType() == VT; }) && 10591 "ppc_[max|min]f[e|l|s] must have uniform type arguments"); 10592 (void)VT; 10593 ISD::CondCode CC = ISD::SETGT; 10594 if (IntrinsicID == Intrinsic::ppc_minfe || 10595 IntrinsicID == Intrinsic::ppc_minfl || 10596 IntrinsicID == Intrinsic::ppc_minfs) 10597 CC = ISD::SETLT; 10598 unsigned I = Op.getNumOperands() - 2, Cnt = I; 10599 SDValue Res = Op.getOperand(I); 10600 for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) { 10601 Res = 10602 DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC); 10603 } 10604 return Res; 10605 } 10606 } 10607 10608 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10609 // opcode number of the comparison. 10610 int CompareOpc; 10611 bool isDot; 10612 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10613 return SDValue(); // Don't custom lower most intrinsics. 10614 10615 // If this is a non-dot comparison, make the VCMP node and we are done. 10616 if (!isDot) { 10617 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10618 Op.getOperand(1), Op.getOperand(2), 10619 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10620 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10621 } 10622 10623 // Create the PPCISD altivec 'dot' comparison node. 10624 SDValue Ops[] = { 10625 Op.getOperand(2), // LHS 10626 Op.getOperand(3), // RHS 10627 DAG.getConstant(CompareOpc, dl, MVT::i32) 10628 }; 10629 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10630 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10631 10632 // Now that we have the comparison, emit a copy from the CR to a GPR. 10633 // This is flagged to the above dot comparison. 10634 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10635 DAG.getRegister(PPC::CR6, MVT::i32), 10636 CompNode.getValue(1)); 10637 10638 // Unpack the result based on how the target uses it. 10639 unsigned BitNo; // Bit # of CR6. 10640 bool InvertBit; // Invert result? 10641 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10642 default: // Can't happen, don't crash on invalid number though. 10643 case 0: // Return the value of the EQ bit of CR6. 10644 BitNo = 0; InvertBit = false; 10645 break; 10646 case 1: // Return the inverted value of the EQ bit of CR6. 10647 BitNo = 0; InvertBit = true; 10648 break; 10649 case 2: // Return the value of the LT bit of CR6. 10650 BitNo = 2; InvertBit = false; 10651 break; 10652 case 3: // Return the inverted value of the LT bit of CR6. 10653 BitNo = 2; InvertBit = true; 10654 break; 10655 } 10656 10657 // Shift the bit into the low position. 10658 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10659 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10660 // Isolate the bit. 10661 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10662 DAG.getConstant(1, dl, MVT::i32)); 10663 10664 // If we are supposed to, toggle the bit. 10665 if (InvertBit) 10666 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10667 DAG.getConstant(1, dl, MVT::i32)); 10668 return Flags; 10669 } 10670 10671 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10672 SelectionDAG &DAG) const { 10673 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10674 // the beginning of the argument list. 10675 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10676 SDLoc DL(Op); 10677 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10678 case Intrinsic::ppc_cfence: { 10679 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10680 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10681 SDValue Val = Op.getOperand(ArgStart + 1); 10682 EVT Ty = Val.getValueType(); 10683 if (Ty == MVT::i128) { 10684 // FIXME: Testing one of two paired registers is sufficient to guarantee 10685 // ordering? 10686 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val); 10687 } 10688 return SDValue( 10689 DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10690 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val), 10691 Op.getOperand(0)), 10692 0); 10693 } 10694 default: 10695 break; 10696 } 10697 return SDValue(); 10698 } 10699 10700 // Lower scalar BSWAP64 to xxbrd. 10701 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10702 SDLoc dl(Op); 10703 if (!Subtarget.isPPC64()) 10704 return Op; 10705 // MTVSRDD 10706 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10707 Op.getOperand(0)); 10708 // XXBRD 10709 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10710 // MFVSRD 10711 int VectorIndex = 0; 10712 if (Subtarget.isLittleEndian()) 10713 VectorIndex = 1; 10714 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10715 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10716 return Op; 10717 } 10718 10719 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10720 // compared to a value that is atomically loaded (atomic loads zero-extend). 10721 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10722 SelectionDAG &DAG) const { 10723 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10724 "Expecting an atomic compare-and-swap here."); 10725 SDLoc dl(Op); 10726 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10727 EVT MemVT = AtomicNode->getMemoryVT(); 10728 if (MemVT.getSizeInBits() >= 32) 10729 return Op; 10730 10731 SDValue CmpOp = Op.getOperand(2); 10732 // If this is already correctly zero-extended, leave it alone. 10733 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10734 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10735 return Op; 10736 10737 // Clear the high bits of the compare operand. 10738 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10739 SDValue NewCmpOp = 10740 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10741 DAG.getConstant(MaskVal, dl, MVT::i32)); 10742 10743 // Replace the existing compare operand with the properly zero-extended one. 10744 SmallVector<SDValue, 4> Ops; 10745 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10746 Ops.push_back(AtomicNode->getOperand(i)); 10747 Ops[2] = NewCmpOp; 10748 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10749 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10750 auto NodeTy = 10751 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10752 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10753 } 10754 10755 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op, 10756 SelectionDAG &DAG) const { 10757 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode()); 10758 EVT MemVT = N->getMemoryVT(); 10759 assert(MemVT.getSimpleVT() == MVT::i128 && 10760 "Expect quadword atomic operations"); 10761 SDLoc dl(N); 10762 unsigned Opc = N->getOpcode(); 10763 switch (Opc) { 10764 case ISD::ATOMIC_LOAD: { 10765 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be 10766 // lowered to ppc instructions by pattern matching instruction selector. 10767 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other); 10768 SmallVector<SDValue, 4> Ops{ 10769 N->getOperand(0), 10770 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)}; 10771 for (int I = 1, E = N->getNumOperands(); I < E; ++I) 10772 Ops.push_back(N->getOperand(I)); 10773 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys, 10774 Ops, MemVT, N->getMemOperand()); 10775 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal); 10776 SDValue ValHi = 10777 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1)); 10778 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi, 10779 DAG.getConstant(64, dl, MVT::i32)); 10780 SDValue Val = 10781 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi}); 10782 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other}, 10783 {Val, LoadedVal.getValue(2)}); 10784 } 10785 case ISD::ATOMIC_STORE: { 10786 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be 10787 // lowered to ppc instructions by pattern matching instruction selector. 10788 SDVTList Tys = DAG.getVTList(MVT::Other); 10789 SmallVector<SDValue, 4> Ops{ 10790 N->getOperand(0), 10791 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)}; 10792 SDValue Val = N->getOperand(2); 10793 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val); 10794 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val, 10795 DAG.getConstant(64, dl, MVT::i32)); 10796 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi); 10797 Ops.push_back(ValLo); 10798 Ops.push_back(ValHi); 10799 Ops.push_back(N->getOperand(1)); 10800 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT, 10801 N->getMemOperand()); 10802 } 10803 default: 10804 llvm_unreachable("Unexpected atomic opcode"); 10805 } 10806 } 10807 10808 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10809 SelectionDAG &DAG) const { 10810 SDLoc dl(Op); 10811 // Create a stack slot that is 16-byte aligned. 10812 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10813 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10814 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10815 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10816 10817 // Store the input value into Value#0 of the stack slot. 10818 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10819 MachinePointerInfo()); 10820 // Load it out. 10821 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10822 } 10823 10824 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10825 SelectionDAG &DAG) const { 10826 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10827 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10828 10829 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10830 10831 EVT VT = Op.getValueType(); 10832 SDLoc dl(Op); 10833 SDValue V1 = Op.getOperand(0); 10834 SDValue V2 = Op.getOperand(1); 10835 10836 if (VT == MVT::v2f64 && C) 10837 return Op; 10838 10839 if (Subtarget.hasP9Vector()) { 10840 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way 10841 // because on P10, it allows this specific insert_vector_elt load pattern to 10842 // utilize the refactored load and store infrastructure in order to exploit 10843 // prefixed loads. 10844 // On targets with inexpensive direct moves (Power9 and up), a 10845 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer 10846 // load since a single precision load will involve conversion to double 10847 // precision on the load followed by another conversion to single precision. 10848 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) && 10849 (isa<LoadSDNode>(V2))) { 10850 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1); 10851 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2); 10852 SDValue InsVecElt = 10853 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector, 10854 BitcastLoad, Op.getOperand(2)); 10855 return DAG.getBitcast(MVT::v4f32, InsVecElt); 10856 } 10857 } 10858 10859 if (Subtarget.isISA3_1()) { 10860 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64()) 10861 return SDValue(); 10862 // On P10, we have legal lowering for constant and variable indices for 10863 // all vectors. 10864 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10865 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64) 10866 return Op; 10867 } 10868 10869 // Before P10, we have legal lowering for constant indices but not for 10870 // variable ones. 10871 if (!C) 10872 return SDValue(); 10873 10874 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10875 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10876 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10877 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10878 unsigned InsertAtElement = C->getZExtValue(); 10879 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10880 if (Subtarget.isLittleEndian()) { 10881 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10882 } 10883 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10884 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10885 } 10886 return Op; 10887 } 10888 10889 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10890 SelectionDAG &DAG) const { 10891 SDLoc dl(Op); 10892 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10893 SDValue LoadChain = LN->getChain(); 10894 SDValue BasePtr = LN->getBasePtr(); 10895 EVT VT = Op.getValueType(); 10896 10897 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10898 return Op; 10899 10900 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10901 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10902 // 2 or 4 vsx registers. 10903 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10904 "Type unsupported without MMA"); 10905 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10906 "Type unsupported without paired vector support"); 10907 Align Alignment = LN->getAlign(); 10908 SmallVector<SDValue, 4> Loads; 10909 SmallVector<SDValue, 4> LoadChains; 10910 unsigned NumVecs = VT.getSizeInBits() / 128; 10911 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10912 SDValue Load = 10913 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10914 LN->getPointerInfo().getWithOffset(Idx * 16), 10915 commonAlignment(Alignment, Idx * 16), 10916 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10917 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10918 DAG.getConstant(16, dl, BasePtr.getValueType())); 10919 Loads.push_back(Load); 10920 LoadChains.push_back(Load.getValue(1)); 10921 } 10922 if (Subtarget.isLittleEndian()) { 10923 std::reverse(Loads.begin(), Loads.end()); 10924 std::reverse(LoadChains.begin(), LoadChains.end()); 10925 } 10926 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10927 SDValue Value = 10928 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10929 dl, VT, Loads); 10930 SDValue RetOps[] = {Value, TF}; 10931 return DAG.getMergeValues(RetOps, dl); 10932 } 10933 10934 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10935 SelectionDAG &DAG) const { 10936 SDLoc dl(Op); 10937 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10938 SDValue StoreChain = SN->getChain(); 10939 SDValue BasePtr = SN->getBasePtr(); 10940 SDValue Value = SN->getValue(); 10941 EVT StoreVT = Value.getValueType(); 10942 10943 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10944 return Op; 10945 10946 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10947 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10948 // underlying registers individually. 10949 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10950 "Type unsupported without MMA"); 10951 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10952 "Type unsupported without paired vector support"); 10953 Align Alignment = SN->getAlign(); 10954 SmallVector<SDValue, 4> Stores; 10955 unsigned NumVecs = 2; 10956 if (StoreVT == MVT::v512i1) { 10957 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10958 NumVecs = 4; 10959 } 10960 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10961 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10962 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10963 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 10964 SDValue Store = 10965 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10966 SN->getPointerInfo().getWithOffset(Idx * 16), 10967 commonAlignment(Alignment, Idx * 16), 10968 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10969 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10970 DAG.getConstant(16, dl, BasePtr.getValueType())); 10971 Stores.push_back(Store); 10972 } 10973 SDValue TF = DAG.getTokenFactor(dl, Stores); 10974 return TF; 10975 } 10976 10977 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10978 SDLoc dl(Op); 10979 if (Op.getValueType() == MVT::v4i32) { 10980 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10981 10982 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10983 // +16 as shift amt. 10984 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10985 SDValue RHSSwap = // = vrlw RHS, 16 10986 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10987 10988 // Shrinkify inputs to v8i16. 10989 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10990 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10991 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10992 10993 // Low parts multiplied together, generating 32-bit results (we ignore the 10994 // top parts). 10995 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10996 LHS, RHS, DAG, dl, MVT::v4i32); 10997 10998 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10999 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 11000 // Shift the high parts up 16 bits. 11001 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 11002 Neg16, DAG, dl); 11003 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 11004 } else if (Op.getValueType() == MVT::v16i8) { 11005 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 11006 bool isLittleEndian = Subtarget.isLittleEndian(); 11007 11008 // Multiply the even 8-bit parts, producing 16-bit sums. 11009 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 11010 LHS, RHS, DAG, dl, MVT::v8i16); 11011 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 11012 11013 // Multiply the odd 8-bit parts, producing 16-bit sums. 11014 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 11015 LHS, RHS, DAG, dl, MVT::v8i16); 11016 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 11017 11018 // Merge the results together. Because vmuleub and vmuloub are 11019 // instructions with a big-endian bias, we must reverse the 11020 // element numbering and reverse the meaning of "odd" and "even" 11021 // when generating little endian code. 11022 int Ops[16]; 11023 for (unsigned i = 0; i != 8; ++i) { 11024 if (isLittleEndian) { 11025 Ops[i*2 ] = 2*i; 11026 Ops[i*2+1] = 2*i+16; 11027 } else { 11028 Ops[i*2 ] = 2*i+1; 11029 Ops[i*2+1] = 2*i+1+16; 11030 } 11031 } 11032 if (isLittleEndian) 11033 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 11034 else 11035 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 11036 } else { 11037 llvm_unreachable("Unknown mul to lower!"); 11038 } 11039 } 11040 11041 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11042 bool IsStrict = Op->isStrictFPOpcode(); 11043 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 11044 !Subtarget.hasP9Vector()) 11045 return SDValue(); 11046 11047 return Op; 11048 } 11049 11050 // Custom lowering for fpext vf32 to v2f64 11051 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11052 11053 assert(Op.getOpcode() == ISD::FP_EXTEND && 11054 "Should only be called for ISD::FP_EXTEND"); 11055 11056 // FIXME: handle extends from half precision float vectors on P9. 11057 // We only want to custom lower an extend from v2f32 to v2f64. 11058 if (Op.getValueType() != MVT::v2f64 || 11059 Op.getOperand(0).getValueType() != MVT::v2f32) 11060 return SDValue(); 11061 11062 SDLoc dl(Op); 11063 SDValue Op0 = Op.getOperand(0); 11064 11065 switch (Op0.getOpcode()) { 11066 default: 11067 return SDValue(); 11068 case ISD::EXTRACT_SUBVECTOR: { 11069 assert(Op0.getNumOperands() == 2 && 11070 isa<ConstantSDNode>(Op0->getOperand(1)) && 11071 "Node should have 2 operands with second one being a constant!"); 11072 11073 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 11074 return SDValue(); 11075 11076 // Custom lower is only done for high or low doubleword. 11077 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 11078 if (Idx % 2 != 0) 11079 return SDValue(); 11080 11081 // Since input is v4f32, at this point Idx is either 0 or 2. 11082 // Shift to get the doubleword position we want. 11083 int DWord = Idx >> 1; 11084 11085 // High and low word positions are different on little endian. 11086 if (Subtarget.isLittleEndian()) 11087 DWord ^= 0x1; 11088 11089 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 11090 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 11091 } 11092 case ISD::FADD: 11093 case ISD::FMUL: 11094 case ISD::FSUB: { 11095 SDValue NewLoad[2]; 11096 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 11097 // Ensure both input are loads. 11098 SDValue LdOp = Op0.getOperand(i); 11099 if (LdOp.getOpcode() != ISD::LOAD) 11100 return SDValue(); 11101 // Generate new load node. 11102 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 11103 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11104 NewLoad[i] = DAG.getMemIntrinsicNode( 11105 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11106 LD->getMemoryVT(), LD->getMemOperand()); 11107 } 11108 SDValue NewOp = 11109 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 11110 NewLoad[1], Op0.getNode()->getFlags()); 11111 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 11112 DAG.getConstant(0, dl, MVT::i32)); 11113 } 11114 case ISD::LOAD: { 11115 LoadSDNode *LD = cast<LoadSDNode>(Op0); 11116 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11117 SDValue NewLd = DAG.getMemIntrinsicNode( 11118 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11119 LD->getMemoryVT(), LD->getMemOperand()); 11120 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 11121 DAG.getConstant(0, dl, MVT::i32)); 11122 } 11123 } 11124 llvm_unreachable("ERROR:Should return for all cases within swtich."); 11125 } 11126 11127 /// LowerOperation - Provide custom lowering hooks for some operations. 11128 /// 11129 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11130 switch (Op.getOpcode()) { 11131 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 11132 case ISD::FPOW: return lowerPow(Op, DAG); 11133 case ISD::FSIN: return lowerSin(Op, DAG); 11134 case ISD::FCOS: return lowerCos(Op, DAG); 11135 case ISD::FLOG: return lowerLog(Op, DAG); 11136 case ISD::FLOG10: return lowerLog10(Op, DAG); 11137 case ISD::FEXP: return lowerExp(Op, DAG); 11138 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 11139 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 11140 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 11141 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 11142 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 11143 case ISD::STRICT_FSETCC: 11144 case ISD::STRICT_FSETCCS: 11145 case ISD::SETCC: return LowerSETCC(Op, DAG); 11146 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 11147 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 11148 11149 case ISD::INLINEASM: 11150 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG); 11151 // Variable argument lowering. 11152 case ISD::VASTART: return LowerVASTART(Op, DAG); 11153 case ISD::VAARG: return LowerVAARG(Op, DAG); 11154 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 11155 11156 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 11157 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 11158 case ISD::GET_DYNAMIC_AREA_OFFSET: 11159 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 11160 11161 // Exception handling lowering. 11162 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11163 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11164 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11165 11166 case ISD::LOAD: return LowerLOAD(Op, DAG); 11167 case ISD::STORE: return LowerSTORE(Op, DAG); 11168 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11169 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11170 case ISD::STRICT_FP_TO_UINT: 11171 case ISD::STRICT_FP_TO_SINT: 11172 case ISD::FP_TO_UINT: 11173 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11174 case ISD::STRICT_UINT_TO_FP: 11175 case ISD::STRICT_SINT_TO_FP: 11176 case ISD::UINT_TO_FP: 11177 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11178 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 11179 11180 // Lower 64-bit shifts. 11181 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11182 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11183 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11184 11185 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 11186 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 11187 11188 // Vector-related lowering. 11189 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11190 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11191 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11192 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11193 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11194 case ISD::MUL: return LowerMUL(Op, DAG); 11195 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11196 case ISD::STRICT_FP_ROUND: 11197 case ISD::FP_ROUND: 11198 return LowerFP_ROUND(Op, DAG); 11199 case ISD::ROTL: return LowerROTL(Op, DAG); 11200 11201 // For counter-based loop handling. 11202 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11203 11204 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11205 11206 // Frame & Return address. 11207 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11208 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11209 11210 case ISD::INTRINSIC_VOID: 11211 return LowerINTRINSIC_VOID(Op, DAG); 11212 case ISD::BSWAP: 11213 return LowerBSWAP(Op, DAG); 11214 case ISD::ATOMIC_CMP_SWAP: 11215 return LowerATOMIC_CMP_SWAP(Op, DAG); 11216 case ISD::ATOMIC_STORE: 11217 return LowerATOMIC_LOAD_STORE(Op, DAG); 11218 } 11219 } 11220 11221 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11222 SmallVectorImpl<SDValue>&Results, 11223 SelectionDAG &DAG) const { 11224 SDLoc dl(N); 11225 switch (N->getOpcode()) { 11226 default: 11227 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11228 case ISD::ATOMIC_LOAD: { 11229 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG); 11230 Results.push_back(Res); 11231 Results.push_back(Res.getValue(1)); 11232 break; 11233 } 11234 case ISD::READCYCLECOUNTER: { 11235 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11236 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11237 11238 Results.push_back( 11239 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11240 Results.push_back(RTB.getValue(2)); 11241 break; 11242 } 11243 case ISD::INTRINSIC_W_CHAIN: { 11244 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11245 Intrinsic::loop_decrement) 11246 break; 11247 11248 assert(N->getValueType(0) == MVT::i1 && 11249 "Unexpected result type for CTR decrement intrinsic"); 11250 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11251 N->getValueType(0)); 11252 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11253 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11254 N->getOperand(1)); 11255 11256 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11257 Results.push_back(NewInt.getValue(1)); 11258 break; 11259 } 11260 case ISD::INTRINSIC_WO_CHAIN: { 11261 switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) { 11262 case Intrinsic::ppc_pack_longdouble: 11263 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 11264 N->getOperand(2), N->getOperand(1))); 11265 break; 11266 case Intrinsic::ppc_maxfe: 11267 case Intrinsic::ppc_minfe: 11268 case Intrinsic::ppc_fnmsub: 11269 case Intrinsic::ppc_convert_f128_to_ppcf128: 11270 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG)); 11271 break; 11272 } 11273 break; 11274 } 11275 case ISD::VAARG: { 11276 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11277 return; 11278 11279 EVT VT = N->getValueType(0); 11280 11281 if (VT == MVT::i64) { 11282 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11283 11284 Results.push_back(NewNode); 11285 Results.push_back(NewNode.getValue(1)); 11286 } 11287 return; 11288 } 11289 case ISD::STRICT_FP_TO_SINT: 11290 case ISD::STRICT_FP_TO_UINT: 11291 case ISD::FP_TO_SINT: 11292 case ISD::FP_TO_UINT: { 11293 // LowerFP_TO_INT() can only handle f32 and f64. 11294 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11295 MVT::ppcf128) 11296 return; 11297 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl); 11298 Results.push_back(LoweredValue); 11299 if (N->isStrictFPOpcode()) 11300 Results.push_back(LoweredValue.getValue(1)); 11301 return; 11302 } 11303 case ISD::TRUNCATE: { 11304 if (!N->getValueType(0).isVector()) 11305 return; 11306 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11307 if (Lowered) 11308 Results.push_back(Lowered); 11309 return; 11310 } 11311 case ISD::FSHL: 11312 case ISD::FSHR: 11313 // Don't handle funnel shifts here. 11314 return; 11315 case ISD::BITCAST: 11316 // Don't handle bitcast here. 11317 return; 11318 case ISD::FP_EXTEND: 11319 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11320 if (Lowered) 11321 Results.push_back(Lowered); 11322 return; 11323 } 11324 } 11325 11326 //===----------------------------------------------------------------------===// 11327 // Other Lowering Code 11328 //===----------------------------------------------------------------------===// 11329 11330 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) { 11331 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11332 Function *Func = Intrinsic::getDeclaration(M, Id); 11333 return Builder.CreateCall(Func, {}); 11334 } 11335 11336 // The mappings for emitLeading/TrailingFence is taken from 11337 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11338 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11339 Instruction *Inst, 11340 AtomicOrdering Ord) const { 11341 if (Ord == AtomicOrdering::SequentiallyConsistent) 11342 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11343 if (isReleaseOrStronger(Ord)) 11344 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11345 return nullptr; 11346 } 11347 11348 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11349 Instruction *Inst, 11350 AtomicOrdering Ord) const { 11351 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11352 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11353 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11354 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11355 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11356 return Builder.CreateCall( 11357 Intrinsic::getDeclaration( 11358 Builder.GetInsertBlock()->getParent()->getParent(), 11359 Intrinsic::ppc_cfence, {Inst->getType()}), 11360 {Inst}); 11361 // FIXME: Can use isync for rmw operation. 11362 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11363 } 11364 return nullptr; 11365 } 11366 11367 MachineBasicBlock * 11368 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11369 unsigned AtomicSize, 11370 unsigned BinOpcode, 11371 unsigned CmpOpcode, 11372 unsigned CmpPred) const { 11373 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11374 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11375 11376 auto LoadMnemonic = PPC::LDARX; 11377 auto StoreMnemonic = PPC::STDCX; 11378 switch (AtomicSize) { 11379 default: 11380 llvm_unreachable("Unexpected size of atomic entity"); 11381 case 1: 11382 LoadMnemonic = PPC::LBARX; 11383 StoreMnemonic = PPC::STBCX; 11384 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11385 break; 11386 case 2: 11387 LoadMnemonic = PPC::LHARX; 11388 StoreMnemonic = PPC::STHCX; 11389 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11390 break; 11391 case 4: 11392 LoadMnemonic = PPC::LWARX; 11393 StoreMnemonic = PPC::STWCX; 11394 break; 11395 case 8: 11396 LoadMnemonic = PPC::LDARX; 11397 StoreMnemonic = PPC::STDCX; 11398 break; 11399 } 11400 11401 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11402 MachineFunction *F = BB->getParent(); 11403 MachineFunction::iterator It = ++BB->getIterator(); 11404 11405 Register dest = MI.getOperand(0).getReg(); 11406 Register ptrA = MI.getOperand(1).getReg(); 11407 Register ptrB = MI.getOperand(2).getReg(); 11408 Register incr = MI.getOperand(3).getReg(); 11409 DebugLoc dl = MI.getDebugLoc(); 11410 11411 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11412 MachineBasicBlock *loop2MBB = 11413 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11414 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11415 F->insert(It, loopMBB); 11416 if (CmpOpcode) 11417 F->insert(It, loop2MBB); 11418 F->insert(It, exitMBB); 11419 exitMBB->splice(exitMBB->begin(), BB, 11420 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11421 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11422 11423 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11424 Register TmpReg = (!BinOpcode) ? incr : 11425 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11426 : &PPC::GPRCRegClass); 11427 11428 // thisMBB: 11429 // ... 11430 // fallthrough --> loopMBB 11431 BB->addSuccessor(loopMBB); 11432 11433 // loopMBB: 11434 // l[wd]arx dest, ptr 11435 // add r0, dest, incr 11436 // st[wd]cx. r0, ptr 11437 // bne- loopMBB 11438 // fallthrough --> exitMBB 11439 11440 // For max/min... 11441 // loopMBB: 11442 // l[wd]arx dest, ptr 11443 // cmpl?[wd] incr, dest 11444 // bgt exitMBB 11445 // loop2MBB: 11446 // st[wd]cx. dest, ptr 11447 // bne- loopMBB 11448 // fallthrough --> exitMBB 11449 11450 BB = loopMBB; 11451 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11452 .addReg(ptrA).addReg(ptrB); 11453 if (BinOpcode) 11454 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11455 if (CmpOpcode) { 11456 // Signed comparisons of byte or halfword values must be sign-extended. 11457 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11458 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11459 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11460 ExtReg).addReg(dest); 11461 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11462 .addReg(incr).addReg(ExtReg); 11463 } else 11464 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11465 .addReg(incr).addReg(dest); 11466 11467 BuildMI(BB, dl, TII->get(PPC::BCC)) 11468 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11469 BB->addSuccessor(loop2MBB); 11470 BB->addSuccessor(exitMBB); 11471 BB = loop2MBB; 11472 } 11473 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11474 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11475 BuildMI(BB, dl, TII->get(PPC::BCC)) 11476 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11477 BB->addSuccessor(loopMBB); 11478 BB->addSuccessor(exitMBB); 11479 11480 // exitMBB: 11481 // ... 11482 BB = exitMBB; 11483 return BB; 11484 } 11485 11486 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 11487 switch(MI.getOpcode()) { 11488 default: 11489 return false; 11490 case PPC::COPY: 11491 return TII->isSignExtended(MI); 11492 case PPC::LHA: 11493 case PPC::LHA8: 11494 case PPC::LHAU: 11495 case PPC::LHAU8: 11496 case PPC::LHAUX: 11497 case PPC::LHAUX8: 11498 case PPC::LHAX: 11499 case PPC::LHAX8: 11500 case PPC::LWA: 11501 case PPC::LWAUX: 11502 case PPC::LWAX: 11503 case PPC::LWAX_32: 11504 case PPC::LWA_32: 11505 case PPC::PLHA: 11506 case PPC::PLHA8: 11507 case PPC::PLHA8pc: 11508 case PPC::PLHApc: 11509 case PPC::PLWA: 11510 case PPC::PLWA8: 11511 case PPC::PLWA8pc: 11512 case PPC::PLWApc: 11513 case PPC::EXTSB: 11514 case PPC::EXTSB8: 11515 case PPC::EXTSB8_32_64: 11516 case PPC::EXTSB8_rec: 11517 case PPC::EXTSB_rec: 11518 case PPC::EXTSH: 11519 case PPC::EXTSH8: 11520 case PPC::EXTSH8_32_64: 11521 case PPC::EXTSH8_rec: 11522 case PPC::EXTSH_rec: 11523 case PPC::EXTSW: 11524 case PPC::EXTSWSLI: 11525 case PPC::EXTSWSLI_32_64: 11526 case PPC::EXTSWSLI_32_64_rec: 11527 case PPC::EXTSWSLI_rec: 11528 case PPC::EXTSW_32: 11529 case PPC::EXTSW_32_64: 11530 case PPC::EXTSW_32_64_rec: 11531 case PPC::EXTSW_rec: 11532 case PPC::SRAW: 11533 case PPC::SRAWI: 11534 case PPC::SRAWI_rec: 11535 case PPC::SRAW_rec: 11536 return true; 11537 } 11538 return false; 11539 } 11540 11541 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11542 MachineInstr &MI, MachineBasicBlock *BB, 11543 bool is8bit, // operation 11544 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11545 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11546 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 11547 11548 // If this is a signed comparison and the value being compared is not known 11549 // to be sign extended, sign extend it here. 11550 DebugLoc dl = MI.getDebugLoc(); 11551 MachineFunction *F = BB->getParent(); 11552 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11553 Register incr = MI.getOperand(3).getReg(); 11554 bool IsSignExtended = Register::isVirtualRegister(incr) && 11555 isSignExtended(*RegInfo.getVRegDef(incr), TII); 11556 11557 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11558 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11559 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11560 .addReg(MI.getOperand(3).getReg()); 11561 MI.getOperand(3).setReg(ValueReg); 11562 } 11563 // If we support part-word atomic mnemonics, just use them 11564 if (Subtarget.hasPartwordAtomics()) 11565 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11566 CmpPred); 11567 11568 // In 64 bit mode we have to use 64 bits for addresses, even though the 11569 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11570 // registers without caring whether they're 32 or 64, but here we're 11571 // doing actual arithmetic on the addresses. 11572 bool is64bit = Subtarget.isPPC64(); 11573 bool isLittleEndian = Subtarget.isLittleEndian(); 11574 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11575 11576 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11577 MachineFunction::iterator It = ++BB->getIterator(); 11578 11579 Register dest = MI.getOperand(0).getReg(); 11580 Register ptrA = MI.getOperand(1).getReg(); 11581 Register ptrB = MI.getOperand(2).getReg(); 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 const TargetRegisterClass *RC = 11596 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11597 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11598 11599 Register PtrReg = RegInfo.createVirtualRegister(RC); 11600 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11601 Register ShiftReg = 11602 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11603 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11604 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11605 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11606 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11607 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11608 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11609 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11610 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11611 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC); 11612 Register Ptr1Reg; 11613 Register TmpReg = 11614 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11615 11616 // thisMBB: 11617 // ... 11618 // fallthrough --> loopMBB 11619 BB->addSuccessor(loopMBB); 11620 11621 // The 4-byte load must be aligned, while a char or short may be 11622 // anywhere in the word. Hence all this nasty bookkeeping code. 11623 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11624 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11625 // xori shift, shift1, 24 [16] 11626 // rlwinm ptr, ptr1, 0, 0, 29 11627 // slw incr2, incr, shift 11628 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11629 // slw mask, mask2, shift 11630 // loopMBB: 11631 // lwarx tmpDest, ptr 11632 // add tmp, tmpDest, incr2 11633 // andc tmp2, tmpDest, mask 11634 // and tmp3, tmp, mask 11635 // or tmp4, tmp3, tmp2 11636 // stwcx. tmp4, ptr 11637 // bne- loopMBB 11638 // fallthrough --> exitMBB 11639 // srw SrwDest, tmpDest, shift 11640 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31 11641 if (ptrA != ZeroReg) { 11642 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11643 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11644 .addReg(ptrA) 11645 .addReg(ptrB); 11646 } else { 11647 Ptr1Reg = ptrB; 11648 } 11649 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11650 // mode. 11651 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11652 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11653 .addImm(3) 11654 .addImm(27) 11655 .addImm(is8bit ? 28 : 27); 11656 if (!isLittleEndian) 11657 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11658 .addReg(Shift1Reg) 11659 .addImm(is8bit ? 24 : 16); 11660 if (is64bit) 11661 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11662 .addReg(Ptr1Reg) 11663 .addImm(0) 11664 .addImm(61); 11665 else 11666 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11667 .addReg(Ptr1Reg) 11668 .addImm(0) 11669 .addImm(0) 11670 .addImm(29); 11671 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11672 if (is8bit) 11673 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11674 else { 11675 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11676 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11677 .addReg(Mask3Reg) 11678 .addImm(65535); 11679 } 11680 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11681 .addReg(Mask2Reg) 11682 .addReg(ShiftReg); 11683 11684 BB = loopMBB; 11685 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11686 .addReg(ZeroReg) 11687 .addReg(PtrReg); 11688 if (BinOpcode) 11689 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11690 .addReg(Incr2Reg) 11691 .addReg(TmpDestReg); 11692 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11693 .addReg(TmpDestReg) 11694 .addReg(MaskReg); 11695 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11696 if (CmpOpcode) { 11697 // For unsigned comparisons, we can directly compare the shifted values. 11698 // For signed comparisons we shift and sign extend. 11699 Register SReg = RegInfo.createVirtualRegister(GPRC); 11700 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11701 .addReg(TmpDestReg) 11702 .addReg(MaskReg); 11703 unsigned ValueReg = SReg; 11704 unsigned CmpReg = Incr2Reg; 11705 if (CmpOpcode == PPC::CMPW) { 11706 ValueReg = RegInfo.createVirtualRegister(GPRC); 11707 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11708 .addReg(SReg) 11709 .addReg(ShiftReg); 11710 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11711 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11712 .addReg(ValueReg); 11713 ValueReg = ValueSReg; 11714 CmpReg = incr; 11715 } 11716 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11717 .addReg(CmpReg) 11718 .addReg(ValueReg); 11719 BuildMI(BB, dl, TII->get(PPC::BCC)) 11720 .addImm(CmpPred) 11721 .addReg(PPC::CR0) 11722 .addMBB(exitMBB); 11723 BB->addSuccessor(loop2MBB); 11724 BB->addSuccessor(exitMBB); 11725 BB = loop2MBB; 11726 } 11727 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11728 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11729 .addReg(Tmp4Reg) 11730 .addReg(ZeroReg) 11731 .addReg(PtrReg); 11732 BuildMI(BB, dl, TII->get(PPC::BCC)) 11733 .addImm(PPC::PRED_NE) 11734 .addReg(PPC::CR0) 11735 .addMBB(loopMBB); 11736 BB->addSuccessor(loopMBB); 11737 BB->addSuccessor(exitMBB); 11738 11739 // exitMBB: 11740 // ... 11741 BB = exitMBB; 11742 // Since the shift amount is not a constant, we need to clear 11743 // the upper bits with a separate RLWINM. 11744 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest) 11745 .addReg(SrwDestReg) 11746 .addImm(0) 11747 .addImm(is8bit ? 24 : 16) 11748 .addImm(31); 11749 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg) 11750 .addReg(TmpDestReg) 11751 .addReg(ShiftReg); 11752 return BB; 11753 } 11754 11755 llvm::MachineBasicBlock * 11756 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11757 MachineBasicBlock *MBB) const { 11758 DebugLoc DL = MI.getDebugLoc(); 11759 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11760 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11761 11762 MachineFunction *MF = MBB->getParent(); 11763 MachineRegisterInfo &MRI = MF->getRegInfo(); 11764 11765 const BasicBlock *BB = MBB->getBasicBlock(); 11766 MachineFunction::iterator I = ++MBB->getIterator(); 11767 11768 Register DstReg = MI.getOperand(0).getReg(); 11769 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11770 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11771 Register mainDstReg = MRI.createVirtualRegister(RC); 11772 Register restoreDstReg = MRI.createVirtualRegister(RC); 11773 11774 MVT PVT = getPointerTy(MF->getDataLayout()); 11775 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11776 "Invalid Pointer Size!"); 11777 // For v = setjmp(buf), we generate 11778 // 11779 // thisMBB: 11780 // SjLjSetup mainMBB 11781 // bl mainMBB 11782 // v_restore = 1 11783 // b sinkMBB 11784 // 11785 // mainMBB: 11786 // buf[LabelOffset] = LR 11787 // v_main = 0 11788 // 11789 // sinkMBB: 11790 // v = phi(main, restore) 11791 // 11792 11793 MachineBasicBlock *thisMBB = MBB; 11794 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11795 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11796 MF->insert(I, mainMBB); 11797 MF->insert(I, sinkMBB); 11798 11799 MachineInstrBuilder MIB; 11800 11801 // Transfer the remainder of BB and its successor edges to sinkMBB. 11802 sinkMBB->splice(sinkMBB->begin(), MBB, 11803 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11804 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11805 11806 // Note that the structure of the jmp_buf used here is not compatible 11807 // with that used by libc, and is not designed to be. Specifically, it 11808 // stores only those 'reserved' registers that LLVM does not otherwise 11809 // understand how to spill. Also, by convention, by the time this 11810 // intrinsic is called, Clang has already stored the frame address in the 11811 // first slot of the buffer and stack address in the third. Following the 11812 // X86 target code, we'll store the jump address in the second slot. We also 11813 // need to save the TOC pointer (R2) to handle jumps between shared 11814 // libraries, and that will be stored in the fourth slot. The thread 11815 // identifier (R13) is not affected. 11816 11817 // thisMBB: 11818 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11819 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11820 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11821 11822 // Prepare IP either in reg. 11823 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11824 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11825 Register BufReg = MI.getOperand(1).getReg(); 11826 11827 if (Subtarget.is64BitELFABI()) { 11828 setUsesTOCBasePtr(*MBB->getParent()); 11829 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11830 .addReg(PPC::X2) 11831 .addImm(TOCOffset) 11832 .addReg(BufReg) 11833 .cloneMemRefs(MI); 11834 } 11835 11836 // Naked functions never have a base pointer, and so we use r1. For all 11837 // other functions, this decision must be delayed until during PEI. 11838 unsigned BaseReg; 11839 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11840 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11841 else 11842 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11843 11844 MIB = BuildMI(*thisMBB, MI, DL, 11845 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11846 .addReg(BaseReg) 11847 .addImm(BPOffset) 11848 .addReg(BufReg) 11849 .cloneMemRefs(MI); 11850 11851 // Setup 11852 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11853 MIB.addRegMask(TRI->getNoPreservedMask()); 11854 11855 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11856 11857 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11858 .addMBB(mainMBB); 11859 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11860 11861 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11862 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11863 11864 // mainMBB: 11865 // mainDstReg = 0 11866 MIB = 11867 BuildMI(mainMBB, DL, 11868 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11869 11870 // Store IP 11871 if (Subtarget.isPPC64()) { 11872 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11873 .addReg(LabelReg) 11874 .addImm(LabelOffset) 11875 .addReg(BufReg); 11876 } else { 11877 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11878 .addReg(LabelReg) 11879 .addImm(LabelOffset) 11880 .addReg(BufReg); 11881 } 11882 MIB.cloneMemRefs(MI); 11883 11884 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11885 mainMBB->addSuccessor(sinkMBB); 11886 11887 // sinkMBB: 11888 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11889 TII->get(PPC::PHI), DstReg) 11890 .addReg(mainDstReg).addMBB(mainMBB) 11891 .addReg(restoreDstReg).addMBB(thisMBB); 11892 11893 MI.eraseFromParent(); 11894 return sinkMBB; 11895 } 11896 11897 MachineBasicBlock * 11898 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11899 MachineBasicBlock *MBB) const { 11900 DebugLoc DL = MI.getDebugLoc(); 11901 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11902 11903 MachineFunction *MF = MBB->getParent(); 11904 MachineRegisterInfo &MRI = MF->getRegInfo(); 11905 11906 MVT PVT = getPointerTy(MF->getDataLayout()); 11907 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11908 "Invalid Pointer Size!"); 11909 11910 const TargetRegisterClass *RC = 11911 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11912 Register Tmp = MRI.createVirtualRegister(RC); 11913 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11914 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11915 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11916 unsigned BP = 11917 (PVT == MVT::i64) 11918 ? PPC::X30 11919 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11920 : PPC::R30); 11921 11922 MachineInstrBuilder MIB; 11923 11924 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11925 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11926 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11927 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11928 11929 Register BufReg = MI.getOperand(0).getReg(); 11930 11931 // Reload FP (the jumped-to function may not have had a 11932 // frame pointer, and if so, then its r31 will be restored 11933 // as necessary). 11934 if (PVT == MVT::i64) { 11935 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11936 .addImm(0) 11937 .addReg(BufReg); 11938 } else { 11939 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11940 .addImm(0) 11941 .addReg(BufReg); 11942 } 11943 MIB.cloneMemRefs(MI); 11944 11945 // Reload IP 11946 if (PVT == MVT::i64) { 11947 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11948 .addImm(LabelOffset) 11949 .addReg(BufReg); 11950 } else { 11951 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11952 .addImm(LabelOffset) 11953 .addReg(BufReg); 11954 } 11955 MIB.cloneMemRefs(MI); 11956 11957 // Reload SP 11958 if (PVT == MVT::i64) { 11959 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11960 .addImm(SPOffset) 11961 .addReg(BufReg); 11962 } else { 11963 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11964 .addImm(SPOffset) 11965 .addReg(BufReg); 11966 } 11967 MIB.cloneMemRefs(MI); 11968 11969 // Reload BP 11970 if (PVT == MVT::i64) { 11971 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11972 .addImm(BPOffset) 11973 .addReg(BufReg); 11974 } else { 11975 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11976 .addImm(BPOffset) 11977 .addReg(BufReg); 11978 } 11979 MIB.cloneMemRefs(MI); 11980 11981 // Reload TOC 11982 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11983 setUsesTOCBasePtr(*MBB->getParent()); 11984 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11985 .addImm(TOCOffset) 11986 .addReg(BufReg) 11987 .cloneMemRefs(MI); 11988 } 11989 11990 // Jump 11991 BuildMI(*MBB, MI, DL, 11992 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11993 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11994 11995 MI.eraseFromParent(); 11996 return MBB; 11997 } 11998 11999 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 12000 // If the function specifically requests inline stack probes, emit them. 12001 if (MF.getFunction().hasFnAttribute("probe-stack")) 12002 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 12003 "inline-asm"; 12004 return false; 12005 } 12006 12007 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 12008 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 12009 unsigned StackAlign = TFI->getStackAlignment(); 12010 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 12011 "Unexpected stack alignment"); 12012 // The default stack probe size is 4096 if the function has no 12013 // stack-probe-size attribute. 12014 unsigned StackProbeSize = 4096; 12015 const Function &Fn = MF.getFunction(); 12016 if (Fn.hasFnAttribute("stack-probe-size")) 12017 Fn.getFnAttribute("stack-probe-size") 12018 .getValueAsString() 12019 .getAsInteger(0, StackProbeSize); 12020 // Round down to the stack alignment. 12021 StackProbeSize &= ~(StackAlign - 1); 12022 return StackProbeSize ? StackProbeSize : StackAlign; 12023 } 12024 12025 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 12026 // into three phases. In the first phase, it uses pseudo instruction 12027 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 12028 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 12029 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 12030 // MaxCallFrameSize so that it can calculate correct data area pointer. 12031 MachineBasicBlock * 12032 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 12033 MachineBasicBlock *MBB) const { 12034 const bool isPPC64 = Subtarget.isPPC64(); 12035 MachineFunction *MF = MBB->getParent(); 12036 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12037 DebugLoc DL = MI.getDebugLoc(); 12038 const unsigned ProbeSize = getStackProbeSize(*MF); 12039 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 12040 MachineRegisterInfo &MRI = MF->getRegInfo(); 12041 // The CFG of probing stack looks as 12042 // +-----+ 12043 // | MBB | 12044 // +--+--+ 12045 // | 12046 // +----v----+ 12047 // +--->+ TestMBB +---+ 12048 // | +----+----+ | 12049 // | | | 12050 // | +-----v----+ | 12051 // +---+ BlockMBB | | 12052 // +----------+ | 12053 // | 12054 // +---------+ | 12055 // | TailMBB +<--+ 12056 // +---------+ 12057 // In MBB, calculate previous frame pointer and final stack pointer. 12058 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 12059 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 12060 // TailMBB is spliced via \p MI. 12061 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 12062 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 12063 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 12064 12065 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 12066 MF->insert(MBBIter, TestMBB); 12067 MF->insert(MBBIter, BlockMBB); 12068 MF->insert(MBBIter, TailMBB); 12069 12070 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 12071 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12072 12073 Register DstReg = MI.getOperand(0).getReg(); 12074 Register NegSizeReg = MI.getOperand(1).getReg(); 12075 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 12076 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12077 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12078 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12079 12080 // Since value of NegSizeReg might be realigned in prologepilog, insert a 12081 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 12082 // NegSize. 12083 unsigned ProbeOpc; 12084 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 12085 ProbeOpc = 12086 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 12087 else 12088 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 12089 // and NegSizeReg will be allocated in the same phyreg to avoid 12090 // redundant copy when NegSizeReg has only one use which is current MI and 12091 // will be replaced by PREPARE_PROBED_ALLOCA then. 12092 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 12093 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 12094 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 12095 .addDef(ActualNegSizeReg) 12096 .addReg(NegSizeReg) 12097 .add(MI.getOperand(2)) 12098 .add(MI.getOperand(3)); 12099 12100 // Calculate final stack pointer, which equals to SP + ActualNegSize. 12101 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 12102 FinalStackPtr) 12103 .addReg(SPReg) 12104 .addReg(ActualNegSizeReg); 12105 12106 // Materialize a scratch register for update. 12107 int64_t NegProbeSize = -(int64_t)ProbeSize; 12108 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 12109 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12110 if (!isInt<16>(NegProbeSize)) { 12111 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12112 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 12113 .addImm(NegProbeSize >> 16); 12114 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 12115 ScratchReg) 12116 .addReg(TempReg) 12117 .addImm(NegProbeSize & 0xFFFF); 12118 } else 12119 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 12120 .addImm(NegProbeSize); 12121 12122 { 12123 // Probing leading residual part. 12124 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12125 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 12126 .addReg(ActualNegSizeReg) 12127 .addReg(ScratchReg); 12128 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12129 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 12130 .addReg(Div) 12131 .addReg(ScratchReg); 12132 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12133 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 12134 .addReg(Mul) 12135 .addReg(ActualNegSizeReg); 12136 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12137 .addReg(FramePointer) 12138 .addReg(SPReg) 12139 .addReg(NegMod); 12140 } 12141 12142 { 12143 // Remaining part should be multiple of ProbeSize. 12144 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 12145 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 12146 .addReg(SPReg) 12147 .addReg(FinalStackPtr); 12148 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 12149 .addImm(PPC::PRED_EQ) 12150 .addReg(CmpResult) 12151 .addMBB(TailMBB); 12152 TestMBB->addSuccessor(BlockMBB); 12153 TestMBB->addSuccessor(TailMBB); 12154 } 12155 12156 { 12157 // Touch the block. 12158 // |P...|P...|P... 12159 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12160 .addReg(FramePointer) 12161 .addReg(SPReg) 12162 .addReg(ScratchReg); 12163 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 12164 BlockMBB->addSuccessor(TestMBB); 12165 } 12166 12167 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 12168 // DYNAREAOFFSET pseudo instruction to get the future result. 12169 Register MaxCallFrameSizeReg = 12170 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12171 BuildMI(TailMBB, DL, 12172 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 12173 MaxCallFrameSizeReg) 12174 .add(MI.getOperand(2)) 12175 .add(MI.getOperand(3)); 12176 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 12177 .addReg(SPReg) 12178 .addReg(MaxCallFrameSizeReg); 12179 12180 // Splice instructions after MI to TailMBB. 12181 TailMBB->splice(TailMBB->end(), MBB, 12182 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 12183 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 12184 MBB->addSuccessor(TestMBB); 12185 12186 // Delete the pseudo instruction. 12187 MI.eraseFromParent(); 12188 12189 ++NumDynamicAllocaProbed; 12190 return TailMBB; 12191 } 12192 12193 MachineBasicBlock * 12194 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 12195 MachineBasicBlock *BB) const { 12196 if (MI.getOpcode() == TargetOpcode::STACKMAP || 12197 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 12198 if (Subtarget.is64BitELFABI() && 12199 MI.getOpcode() == TargetOpcode::PATCHPOINT && 12200 !Subtarget.isUsingPCRelativeCalls()) { 12201 // Call lowering should have added an r2 operand to indicate a dependence 12202 // on the TOC base pointer value. It can't however, because there is no 12203 // way to mark the dependence as implicit there, and so the stackmap code 12204 // will confuse it with a regular operand. Instead, add the dependence 12205 // here. 12206 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 12207 } 12208 12209 return emitPatchPoint(MI, BB); 12210 } 12211 12212 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 12213 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 12214 return emitEHSjLjSetJmp(MI, BB); 12215 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 12216 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 12217 return emitEHSjLjLongJmp(MI, BB); 12218 } 12219 12220 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12221 12222 // To "insert" these instructions we actually have to insert their 12223 // control-flow patterns. 12224 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12225 MachineFunction::iterator It = ++BB->getIterator(); 12226 12227 MachineFunction *F = BB->getParent(); 12228 MachineRegisterInfo &MRI = F->getRegInfo(); 12229 12230 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12231 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 12232 MI.getOpcode() == PPC::SELECT_I8) { 12233 SmallVector<MachineOperand, 2> Cond; 12234 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12235 MI.getOpcode() == PPC::SELECT_CC_I8) 12236 Cond.push_back(MI.getOperand(4)); 12237 else 12238 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 12239 Cond.push_back(MI.getOperand(1)); 12240 12241 DebugLoc dl = MI.getDebugLoc(); 12242 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 12243 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 12244 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 12245 MI.getOpcode() == PPC::SELECT_CC_F8 || 12246 MI.getOpcode() == PPC::SELECT_CC_F16 || 12247 MI.getOpcode() == PPC::SELECT_CC_VRRC || 12248 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 12249 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 12250 MI.getOpcode() == PPC::SELECT_CC_VSRC || 12251 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 12252 MI.getOpcode() == PPC::SELECT_CC_SPE || 12253 MI.getOpcode() == PPC::SELECT_F4 || 12254 MI.getOpcode() == PPC::SELECT_F8 || 12255 MI.getOpcode() == PPC::SELECT_F16 || 12256 MI.getOpcode() == PPC::SELECT_SPE || 12257 MI.getOpcode() == PPC::SELECT_SPE4 || 12258 MI.getOpcode() == PPC::SELECT_VRRC || 12259 MI.getOpcode() == PPC::SELECT_VSFRC || 12260 MI.getOpcode() == PPC::SELECT_VSSRC || 12261 MI.getOpcode() == PPC::SELECT_VSRC) { 12262 // The incoming instruction knows the destination vreg to set, the 12263 // condition code register to branch on, the true/false values to 12264 // select between, and a branch opcode to use. 12265 12266 // thisMBB: 12267 // ... 12268 // TrueVal = ... 12269 // cmpTY ccX, r1, r2 12270 // bCC copy1MBB 12271 // fallthrough --> copy0MBB 12272 MachineBasicBlock *thisMBB = BB; 12273 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12274 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12275 DebugLoc dl = MI.getDebugLoc(); 12276 F->insert(It, copy0MBB); 12277 F->insert(It, sinkMBB); 12278 12279 // Transfer the remainder of BB and its successor edges to sinkMBB. 12280 sinkMBB->splice(sinkMBB->begin(), BB, 12281 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12282 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12283 12284 // Next, add the true and fallthrough blocks as its successors. 12285 BB->addSuccessor(copy0MBB); 12286 BB->addSuccessor(sinkMBB); 12287 12288 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 12289 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 12290 MI.getOpcode() == PPC::SELECT_F16 || 12291 MI.getOpcode() == PPC::SELECT_SPE4 || 12292 MI.getOpcode() == PPC::SELECT_SPE || 12293 MI.getOpcode() == PPC::SELECT_VRRC || 12294 MI.getOpcode() == PPC::SELECT_VSFRC || 12295 MI.getOpcode() == PPC::SELECT_VSSRC || 12296 MI.getOpcode() == PPC::SELECT_VSRC) { 12297 BuildMI(BB, dl, TII->get(PPC::BC)) 12298 .addReg(MI.getOperand(1).getReg()) 12299 .addMBB(sinkMBB); 12300 } else { 12301 unsigned SelectPred = MI.getOperand(4).getImm(); 12302 BuildMI(BB, dl, TII->get(PPC::BCC)) 12303 .addImm(SelectPred) 12304 .addReg(MI.getOperand(1).getReg()) 12305 .addMBB(sinkMBB); 12306 } 12307 12308 // copy0MBB: 12309 // %FalseValue = ... 12310 // # fallthrough to sinkMBB 12311 BB = copy0MBB; 12312 12313 // Update machine-CFG edges 12314 BB->addSuccessor(sinkMBB); 12315 12316 // sinkMBB: 12317 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12318 // ... 12319 BB = sinkMBB; 12320 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 12321 .addReg(MI.getOperand(3).getReg()) 12322 .addMBB(copy0MBB) 12323 .addReg(MI.getOperand(2).getReg()) 12324 .addMBB(thisMBB); 12325 } else if (MI.getOpcode() == PPC::ReadTB) { 12326 // To read the 64-bit time-base register on a 32-bit target, we read the 12327 // two halves. Should the counter have wrapped while it was being read, we 12328 // need to try again. 12329 // ... 12330 // readLoop: 12331 // mfspr Rx,TBU # load from TBU 12332 // mfspr Ry,TB # load from TB 12333 // mfspr Rz,TBU # load from TBU 12334 // cmpw crX,Rx,Rz # check if 'old'='new' 12335 // bne readLoop # branch if they're not equal 12336 // ... 12337 12338 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 12339 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12340 DebugLoc dl = MI.getDebugLoc(); 12341 F->insert(It, readMBB); 12342 F->insert(It, sinkMBB); 12343 12344 // Transfer the remainder of BB and its successor edges to sinkMBB. 12345 sinkMBB->splice(sinkMBB->begin(), BB, 12346 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12347 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12348 12349 BB->addSuccessor(readMBB); 12350 BB = readMBB; 12351 12352 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12353 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12354 Register LoReg = MI.getOperand(0).getReg(); 12355 Register HiReg = MI.getOperand(1).getReg(); 12356 12357 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12358 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12359 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12360 12361 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12362 12363 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12364 .addReg(HiReg) 12365 .addReg(ReadAgainReg); 12366 BuildMI(BB, dl, TII->get(PPC::BCC)) 12367 .addImm(PPC::PRED_NE) 12368 .addReg(CmpReg) 12369 .addMBB(readMBB); 12370 12371 BB->addSuccessor(readMBB); 12372 BB->addSuccessor(sinkMBB); 12373 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12374 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12375 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12376 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12377 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12378 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12379 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12380 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12381 12382 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12383 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12384 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12385 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12386 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12387 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12388 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12389 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12390 12391 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12392 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12393 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12394 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12395 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12396 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12397 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12398 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12399 12400 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12401 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12402 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12403 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12404 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12405 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12406 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12407 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12408 12409 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12410 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12411 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12412 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12413 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12414 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12415 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12416 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12417 12418 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12419 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12420 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12421 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12422 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12423 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12424 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12425 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12426 12427 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12428 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12429 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12430 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12431 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12432 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12433 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12434 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12435 12436 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12437 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12438 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12439 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12440 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12441 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12442 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12443 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12444 12445 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12446 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12447 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12448 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12449 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12450 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12451 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12452 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12453 12454 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12455 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12456 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12457 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12458 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12459 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12460 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12461 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12462 12463 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12464 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12465 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12466 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12467 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12468 BB = EmitAtomicBinary(MI, BB, 4, 0); 12469 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12470 BB = EmitAtomicBinary(MI, BB, 8, 0); 12471 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12472 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12473 (Subtarget.hasPartwordAtomics() && 12474 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12475 (Subtarget.hasPartwordAtomics() && 12476 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12477 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12478 12479 auto LoadMnemonic = PPC::LDARX; 12480 auto StoreMnemonic = PPC::STDCX; 12481 switch (MI.getOpcode()) { 12482 default: 12483 llvm_unreachable("Compare and swap of unknown size"); 12484 case PPC::ATOMIC_CMP_SWAP_I8: 12485 LoadMnemonic = PPC::LBARX; 12486 StoreMnemonic = PPC::STBCX; 12487 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12488 break; 12489 case PPC::ATOMIC_CMP_SWAP_I16: 12490 LoadMnemonic = PPC::LHARX; 12491 StoreMnemonic = PPC::STHCX; 12492 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12493 break; 12494 case PPC::ATOMIC_CMP_SWAP_I32: 12495 LoadMnemonic = PPC::LWARX; 12496 StoreMnemonic = PPC::STWCX; 12497 break; 12498 case PPC::ATOMIC_CMP_SWAP_I64: 12499 LoadMnemonic = PPC::LDARX; 12500 StoreMnemonic = PPC::STDCX; 12501 break; 12502 } 12503 Register dest = MI.getOperand(0).getReg(); 12504 Register ptrA = MI.getOperand(1).getReg(); 12505 Register ptrB = MI.getOperand(2).getReg(); 12506 Register oldval = MI.getOperand(3).getReg(); 12507 Register newval = MI.getOperand(4).getReg(); 12508 DebugLoc dl = MI.getDebugLoc(); 12509 12510 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12511 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12512 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12513 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12514 F->insert(It, loop1MBB); 12515 F->insert(It, loop2MBB); 12516 F->insert(It, midMBB); 12517 F->insert(It, exitMBB); 12518 exitMBB->splice(exitMBB->begin(), BB, 12519 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12520 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12521 12522 // thisMBB: 12523 // ... 12524 // fallthrough --> loopMBB 12525 BB->addSuccessor(loop1MBB); 12526 12527 // loop1MBB: 12528 // l[bhwd]arx dest, ptr 12529 // cmp[wd] dest, oldval 12530 // bne- midMBB 12531 // loop2MBB: 12532 // st[bhwd]cx. newval, ptr 12533 // bne- loopMBB 12534 // b exitBB 12535 // midMBB: 12536 // st[bhwd]cx. dest, ptr 12537 // exitBB: 12538 BB = loop1MBB; 12539 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12540 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12541 .addReg(oldval) 12542 .addReg(dest); 12543 BuildMI(BB, dl, TII->get(PPC::BCC)) 12544 .addImm(PPC::PRED_NE) 12545 .addReg(PPC::CR0) 12546 .addMBB(midMBB); 12547 BB->addSuccessor(loop2MBB); 12548 BB->addSuccessor(midMBB); 12549 12550 BB = loop2MBB; 12551 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12552 .addReg(newval) 12553 .addReg(ptrA) 12554 .addReg(ptrB); 12555 BuildMI(BB, dl, TII->get(PPC::BCC)) 12556 .addImm(PPC::PRED_NE) 12557 .addReg(PPC::CR0) 12558 .addMBB(loop1MBB); 12559 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12560 BB->addSuccessor(loop1MBB); 12561 BB->addSuccessor(exitMBB); 12562 12563 BB = midMBB; 12564 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12565 .addReg(dest) 12566 .addReg(ptrA) 12567 .addReg(ptrB); 12568 BB->addSuccessor(exitMBB); 12569 12570 // exitMBB: 12571 // ... 12572 BB = exitMBB; 12573 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12574 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12575 // We must use 64-bit registers for addresses when targeting 64-bit, 12576 // since we're actually doing arithmetic on them. Other registers 12577 // can be 32-bit. 12578 bool is64bit = Subtarget.isPPC64(); 12579 bool isLittleEndian = Subtarget.isLittleEndian(); 12580 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12581 12582 Register dest = MI.getOperand(0).getReg(); 12583 Register ptrA = MI.getOperand(1).getReg(); 12584 Register ptrB = MI.getOperand(2).getReg(); 12585 Register oldval = MI.getOperand(3).getReg(); 12586 Register newval = MI.getOperand(4).getReg(); 12587 DebugLoc dl = MI.getDebugLoc(); 12588 12589 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12590 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12591 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12592 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12593 F->insert(It, loop1MBB); 12594 F->insert(It, loop2MBB); 12595 F->insert(It, midMBB); 12596 F->insert(It, exitMBB); 12597 exitMBB->splice(exitMBB->begin(), BB, 12598 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12599 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12600 12601 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12602 const TargetRegisterClass *RC = 12603 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12604 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12605 12606 Register PtrReg = RegInfo.createVirtualRegister(RC); 12607 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12608 Register ShiftReg = 12609 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12610 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12611 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12612 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12613 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12614 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12615 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12616 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12617 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12618 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12619 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12620 Register Ptr1Reg; 12621 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12622 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12623 // thisMBB: 12624 // ... 12625 // fallthrough --> loopMBB 12626 BB->addSuccessor(loop1MBB); 12627 12628 // The 4-byte load must be aligned, while a char or short may be 12629 // anywhere in the word. Hence all this nasty bookkeeping code. 12630 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12631 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12632 // xori shift, shift1, 24 [16] 12633 // rlwinm ptr, ptr1, 0, 0, 29 12634 // slw newval2, newval, shift 12635 // slw oldval2, oldval,shift 12636 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12637 // slw mask, mask2, shift 12638 // and newval3, newval2, mask 12639 // and oldval3, oldval2, mask 12640 // loop1MBB: 12641 // lwarx tmpDest, ptr 12642 // and tmp, tmpDest, mask 12643 // cmpw tmp, oldval3 12644 // bne- midMBB 12645 // loop2MBB: 12646 // andc tmp2, tmpDest, mask 12647 // or tmp4, tmp2, newval3 12648 // stwcx. tmp4, ptr 12649 // bne- loop1MBB 12650 // b exitBB 12651 // midMBB: 12652 // stwcx. tmpDest, ptr 12653 // exitBB: 12654 // srw dest, tmpDest, shift 12655 if (ptrA != ZeroReg) { 12656 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12657 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12658 .addReg(ptrA) 12659 .addReg(ptrB); 12660 } else { 12661 Ptr1Reg = ptrB; 12662 } 12663 12664 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12665 // mode. 12666 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12667 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12668 .addImm(3) 12669 .addImm(27) 12670 .addImm(is8bit ? 28 : 27); 12671 if (!isLittleEndian) 12672 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12673 .addReg(Shift1Reg) 12674 .addImm(is8bit ? 24 : 16); 12675 if (is64bit) 12676 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12677 .addReg(Ptr1Reg) 12678 .addImm(0) 12679 .addImm(61); 12680 else 12681 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12682 .addReg(Ptr1Reg) 12683 .addImm(0) 12684 .addImm(0) 12685 .addImm(29); 12686 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12687 .addReg(newval) 12688 .addReg(ShiftReg); 12689 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12690 .addReg(oldval) 12691 .addReg(ShiftReg); 12692 if (is8bit) 12693 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12694 else { 12695 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12696 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12697 .addReg(Mask3Reg) 12698 .addImm(65535); 12699 } 12700 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12701 .addReg(Mask2Reg) 12702 .addReg(ShiftReg); 12703 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12704 .addReg(NewVal2Reg) 12705 .addReg(MaskReg); 12706 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12707 .addReg(OldVal2Reg) 12708 .addReg(MaskReg); 12709 12710 BB = loop1MBB; 12711 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12712 .addReg(ZeroReg) 12713 .addReg(PtrReg); 12714 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12715 .addReg(TmpDestReg) 12716 .addReg(MaskReg); 12717 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12718 .addReg(TmpReg) 12719 .addReg(OldVal3Reg); 12720 BuildMI(BB, dl, TII->get(PPC::BCC)) 12721 .addImm(PPC::PRED_NE) 12722 .addReg(PPC::CR0) 12723 .addMBB(midMBB); 12724 BB->addSuccessor(loop2MBB); 12725 BB->addSuccessor(midMBB); 12726 12727 BB = loop2MBB; 12728 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12729 .addReg(TmpDestReg) 12730 .addReg(MaskReg); 12731 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12732 .addReg(Tmp2Reg) 12733 .addReg(NewVal3Reg); 12734 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12735 .addReg(Tmp4Reg) 12736 .addReg(ZeroReg) 12737 .addReg(PtrReg); 12738 BuildMI(BB, dl, TII->get(PPC::BCC)) 12739 .addImm(PPC::PRED_NE) 12740 .addReg(PPC::CR0) 12741 .addMBB(loop1MBB); 12742 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12743 BB->addSuccessor(loop1MBB); 12744 BB->addSuccessor(exitMBB); 12745 12746 BB = midMBB; 12747 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12748 .addReg(TmpDestReg) 12749 .addReg(ZeroReg) 12750 .addReg(PtrReg); 12751 BB->addSuccessor(exitMBB); 12752 12753 // exitMBB: 12754 // ... 12755 BB = exitMBB; 12756 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12757 .addReg(TmpReg) 12758 .addReg(ShiftReg); 12759 } else if (MI.getOpcode() == PPC::FADDrtz) { 12760 // This pseudo performs an FADD with rounding mode temporarily forced 12761 // to round-to-zero. We emit this via custom inserter since the FPSCR 12762 // is not modeled at the SelectionDAG level. 12763 Register Dest = MI.getOperand(0).getReg(); 12764 Register Src1 = MI.getOperand(1).getReg(); 12765 Register Src2 = MI.getOperand(2).getReg(); 12766 DebugLoc dl = MI.getDebugLoc(); 12767 12768 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12769 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12770 12771 // Save FPSCR value. 12772 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12773 12774 // Set rounding mode to round-to-zero. 12775 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12776 .addImm(31) 12777 .addReg(PPC::RM, RegState::ImplicitDefine); 12778 12779 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12780 .addImm(30) 12781 .addReg(PPC::RM, RegState::ImplicitDefine); 12782 12783 // Perform addition. 12784 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12785 .addReg(Src1) 12786 .addReg(Src2); 12787 if (MI.getFlag(MachineInstr::NoFPExcept)) 12788 MIB.setMIFlag(MachineInstr::NoFPExcept); 12789 12790 // Restore FPSCR value. 12791 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12792 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12793 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12794 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12795 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12796 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12797 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12798 ? PPC::ANDI8_rec 12799 : PPC::ANDI_rec; 12800 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12801 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12802 12803 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12804 Register Dest = RegInfo.createVirtualRegister( 12805 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12806 12807 DebugLoc Dl = MI.getDebugLoc(); 12808 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12809 .addReg(MI.getOperand(1).getReg()) 12810 .addImm(1); 12811 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12812 MI.getOperand(0).getReg()) 12813 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12814 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12815 DebugLoc Dl = MI.getDebugLoc(); 12816 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12817 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12818 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12819 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12820 MI.getOperand(0).getReg()) 12821 .addReg(CRReg); 12822 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12823 DebugLoc Dl = MI.getDebugLoc(); 12824 unsigned Imm = MI.getOperand(1).getImm(); 12825 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12826 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12827 MI.getOperand(0).getReg()) 12828 .addReg(PPC::CR0EQ); 12829 } else if (MI.getOpcode() == PPC::SETRNDi) { 12830 DebugLoc dl = MI.getDebugLoc(); 12831 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12832 12833 // Save FPSCR value. 12834 if (MRI.use_empty(OldFPSCRReg)) 12835 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 12836 else 12837 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12838 12839 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12840 // the following settings: 12841 // 00 Round to nearest 12842 // 01 Round to 0 12843 // 10 Round to +inf 12844 // 11 Round to -inf 12845 12846 // When the operand is immediate, using the two least significant bits of 12847 // the immediate to set the bits 62:63 of FPSCR. 12848 unsigned Mode = MI.getOperand(1).getImm(); 12849 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12850 .addImm(31) 12851 .addReg(PPC::RM, RegState::ImplicitDefine); 12852 12853 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12854 .addImm(30) 12855 .addReg(PPC::RM, RegState::ImplicitDefine); 12856 } else if (MI.getOpcode() == PPC::SETRND) { 12857 DebugLoc dl = MI.getDebugLoc(); 12858 12859 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12860 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12861 // If the target doesn't have DirectMove, we should use stack to do the 12862 // conversion, because the target doesn't have the instructions like mtvsrd 12863 // or mfvsrd to do this conversion directly. 12864 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12865 if (Subtarget.hasDirectMove()) { 12866 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12867 .addReg(SrcReg); 12868 } else { 12869 // Use stack to do the register copy. 12870 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12871 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12872 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12873 if (RC == &PPC::F8RCRegClass) { 12874 // Copy register from F8RCRegClass to G8RCRegclass. 12875 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12876 "Unsupported RegClass."); 12877 12878 StoreOp = PPC::STFD; 12879 LoadOp = PPC::LD; 12880 } else { 12881 // Copy register from G8RCRegClass to F8RCRegclass. 12882 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12883 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12884 "Unsupported RegClass."); 12885 } 12886 12887 MachineFrameInfo &MFI = F->getFrameInfo(); 12888 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12889 12890 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12891 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12892 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12893 MFI.getObjectAlign(FrameIdx)); 12894 12895 // Store the SrcReg into the stack. 12896 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12897 .addReg(SrcReg) 12898 .addImm(0) 12899 .addFrameIndex(FrameIdx) 12900 .addMemOperand(MMOStore); 12901 12902 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12903 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12904 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12905 MFI.getObjectAlign(FrameIdx)); 12906 12907 // Load from the stack where SrcReg is stored, and save to DestReg, 12908 // so we have done the RegClass conversion from RegClass::SrcReg to 12909 // RegClass::DestReg. 12910 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12911 .addImm(0) 12912 .addFrameIndex(FrameIdx) 12913 .addMemOperand(MMOLoad); 12914 } 12915 }; 12916 12917 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12918 12919 // Save FPSCR value. 12920 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12921 12922 // When the operand is gprc register, use two least significant bits of the 12923 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12924 // 12925 // copy OldFPSCRTmpReg, OldFPSCRReg 12926 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12927 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12928 // copy NewFPSCRReg, NewFPSCRTmpReg 12929 // mtfsf 255, NewFPSCRReg 12930 MachineOperand SrcOp = MI.getOperand(1); 12931 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12932 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12933 12934 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12935 12936 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12937 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12938 12939 // The first operand of INSERT_SUBREG should be a register which has 12940 // subregisters, we only care about its RegClass, so we should use an 12941 // IMPLICIT_DEF register. 12942 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12943 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12944 .addReg(ImDefReg) 12945 .add(SrcOp) 12946 .addImm(1); 12947 12948 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12949 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12950 .addReg(OldFPSCRTmpReg) 12951 .addReg(ExtSrcReg) 12952 .addImm(0) 12953 .addImm(62); 12954 12955 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12956 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12957 12958 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12959 // bits of FPSCR. 12960 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12961 .addImm(255) 12962 .addReg(NewFPSCRReg) 12963 .addImm(0) 12964 .addImm(0); 12965 } else if (MI.getOpcode() == PPC::SETFLM) { 12966 DebugLoc Dl = MI.getDebugLoc(); 12967 12968 // Result of setflm is previous FPSCR content, so we need to save it first. 12969 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12970 if (MRI.use_empty(OldFPSCRReg)) 12971 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 12972 else 12973 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12974 12975 // Put bits in 32:63 to FPSCR. 12976 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12977 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12978 .addImm(255) 12979 .addReg(NewFPSCRReg) 12980 .addImm(0) 12981 .addImm(0); 12982 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12983 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12984 return emitProbedAlloca(MI, BB); 12985 } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) { 12986 DebugLoc DL = MI.getDebugLoc(); 12987 Register Src = MI.getOperand(2).getReg(); 12988 Register Lo = MI.getOperand(0).getReg(); 12989 Register Hi = MI.getOperand(1).getReg(); 12990 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 12991 .addDef(Lo) 12992 .addUse(Src, 0, PPC::sub_gp8_x1); 12993 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 12994 .addDef(Hi) 12995 .addUse(Src, 0, PPC::sub_gp8_x0); 12996 } else if (MI.getOpcode() == PPC::LQX_PSEUDO || 12997 MI.getOpcode() == PPC::STQX_PSEUDO) { 12998 DebugLoc DL = MI.getDebugLoc(); 12999 // Ptr is used as the ptr_rc_no_r0 part 13000 // of LQ/STQ's memory operand and adding result of RA and RB, 13001 // so it has to be g8rc_and_g8rc_nox0. 13002 Register Ptr = 13003 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass); 13004 Register Val = MI.getOperand(0).getReg(); 13005 Register RA = MI.getOperand(1).getReg(); 13006 Register RB = MI.getOperand(2).getReg(); 13007 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB); 13008 BuildMI(*BB, MI, DL, 13009 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ) 13010 : TII->get(PPC::STQ)) 13011 .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0) 13012 .addImm(0) 13013 .addReg(Ptr); 13014 } else { 13015 llvm_unreachable("Unexpected instr type to insert"); 13016 } 13017 13018 MI.eraseFromParent(); // The pseudo instruction is gone now. 13019 return BB; 13020 } 13021 13022 //===----------------------------------------------------------------------===// 13023 // Target Optimization Hooks 13024 //===----------------------------------------------------------------------===// 13025 13026 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 13027 // For the estimates, convergence is quadratic, so we essentially double the 13028 // number of digits correct after every iteration. For both FRE and FRSQRTE, 13029 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 13030 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 13031 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 13032 if (VT.getScalarType() == MVT::f64) 13033 RefinementSteps++; 13034 return RefinementSteps; 13035 } 13036 13037 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 13038 const DenormalMode &Mode) const { 13039 // We only have VSX Vector Test for software Square Root. 13040 EVT VT = Op.getValueType(); 13041 if (!isTypeLegal(MVT::i1) || 13042 (VT != MVT::f64 && 13043 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 13044 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 13045 13046 SDLoc DL(Op); 13047 // The output register of FTSQRT is CR field. 13048 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 13049 // ftsqrt BF,FRB 13050 // Let e_b be the unbiased exponent of the double-precision 13051 // floating-point operand in register FRB. 13052 // fe_flag is set to 1 if either of the following conditions occurs. 13053 // - The double-precision floating-point operand in register FRB is a zero, 13054 // a NaN, or an infinity, or a negative value. 13055 // - e_b is less than or equal to -970. 13056 // Otherwise fe_flag is set to 0. 13057 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 13058 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 13059 // exponent is less than -970) 13060 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 13061 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 13062 FTSQRT, SRIdxVal), 13063 0); 13064 } 13065 13066 SDValue 13067 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 13068 SelectionDAG &DAG) const { 13069 // We only have VSX Vector Square Root. 13070 EVT VT = Op.getValueType(); 13071 if (VT != MVT::f64 && 13072 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 13073 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 13074 13075 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 13076 } 13077 13078 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 13079 int Enabled, int &RefinementSteps, 13080 bool &UseOneConstNR, 13081 bool Reciprocal) const { 13082 EVT VT = Operand.getValueType(); 13083 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 13084 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 13085 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13086 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13087 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13088 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13089 13090 // The Newton-Raphson computation with a single constant does not provide 13091 // enough accuracy on some CPUs. 13092 UseOneConstNR = !Subtarget.needsTwoConstNR(); 13093 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 13094 } 13095 return SDValue(); 13096 } 13097 13098 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 13099 int Enabled, 13100 int &RefinementSteps) const { 13101 EVT VT = Operand.getValueType(); 13102 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 13103 (VT == MVT::f64 && Subtarget.hasFRE()) || 13104 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13105 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13106 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13107 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13108 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 13109 } 13110 return SDValue(); 13111 } 13112 13113 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 13114 // Note: This functionality is used only when unsafe-fp-math is enabled, and 13115 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 13116 // enabled for division), this functionality is redundant with the default 13117 // combiner logic (once the division -> reciprocal/multiply transformation 13118 // has taken place). As a result, this matters more for older cores than for 13119 // newer ones. 13120 13121 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13122 // reciprocal if there are two or more FDIVs (for embedded cores with only 13123 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 13124 switch (Subtarget.getCPUDirective()) { 13125 default: 13126 return 3; 13127 case PPC::DIR_440: 13128 case PPC::DIR_A2: 13129 case PPC::DIR_E500: 13130 case PPC::DIR_E500mc: 13131 case PPC::DIR_E5500: 13132 return 2; 13133 } 13134 } 13135 13136 // isConsecutiveLSLoc needs to work even if all adds have not yet been 13137 // collapsed, and so we need to look through chains of them. 13138 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 13139 int64_t& Offset, SelectionDAG &DAG) { 13140 if (DAG.isBaseWithConstantOffset(Loc)) { 13141 Base = Loc.getOperand(0); 13142 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 13143 13144 // The base might itself be a base plus an offset, and if so, accumulate 13145 // that as well. 13146 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 13147 } 13148 } 13149 13150 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 13151 unsigned Bytes, int Dist, 13152 SelectionDAG &DAG) { 13153 if (VT.getSizeInBits() / 8 != Bytes) 13154 return false; 13155 13156 SDValue BaseLoc = Base->getBasePtr(); 13157 if (Loc.getOpcode() == ISD::FrameIndex) { 13158 if (BaseLoc.getOpcode() != ISD::FrameIndex) 13159 return false; 13160 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 13161 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 13162 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 13163 int FS = MFI.getObjectSize(FI); 13164 int BFS = MFI.getObjectSize(BFI); 13165 if (FS != BFS || FS != (int)Bytes) return false; 13166 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 13167 } 13168 13169 SDValue Base1 = Loc, Base2 = BaseLoc; 13170 int64_t Offset1 = 0, Offset2 = 0; 13171 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 13172 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 13173 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 13174 return true; 13175 13176 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13177 const GlobalValue *GV1 = nullptr; 13178 const GlobalValue *GV2 = nullptr; 13179 Offset1 = 0; 13180 Offset2 = 0; 13181 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 13182 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 13183 if (isGA1 && isGA2 && GV1 == GV2) 13184 return Offset1 == (Offset2 + Dist*Bytes); 13185 return false; 13186 } 13187 13188 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 13189 // not enforce equality of the chain operands. 13190 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 13191 unsigned Bytes, int Dist, 13192 SelectionDAG &DAG) { 13193 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 13194 EVT VT = LS->getMemoryVT(); 13195 SDValue Loc = LS->getBasePtr(); 13196 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 13197 } 13198 13199 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 13200 EVT VT; 13201 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13202 default: return false; 13203 case Intrinsic::ppc_altivec_lvx: 13204 case Intrinsic::ppc_altivec_lvxl: 13205 case Intrinsic::ppc_vsx_lxvw4x: 13206 case Intrinsic::ppc_vsx_lxvw4x_be: 13207 VT = MVT::v4i32; 13208 break; 13209 case Intrinsic::ppc_vsx_lxvd2x: 13210 case Intrinsic::ppc_vsx_lxvd2x_be: 13211 VT = MVT::v2f64; 13212 break; 13213 case Intrinsic::ppc_altivec_lvebx: 13214 VT = MVT::i8; 13215 break; 13216 case Intrinsic::ppc_altivec_lvehx: 13217 VT = MVT::i16; 13218 break; 13219 case Intrinsic::ppc_altivec_lvewx: 13220 VT = MVT::i32; 13221 break; 13222 } 13223 13224 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 13225 } 13226 13227 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 13228 EVT VT; 13229 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13230 default: return false; 13231 case Intrinsic::ppc_altivec_stvx: 13232 case Intrinsic::ppc_altivec_stvxl: 13233 case Intrinsic::ppc_vsx_stxvw4x: 13234 VT = MVT::v4i32; 13235 break; 13236 case Intrinsic::ppc_vsx_stxvd2x: 13237 VT = MVT::v2f64; 13238 break; 13239 case Intrinsic::ppc_vsx_stxvw4x_be: 13240 VT = MVT::v4i32; 13241 break; 13242 case Intrinsic::ppc_vsx_stxvd2x_be: 13243 VT = MVT::v2f64; 13244 break; 13245 case Intrinsic::ppc_altivec_stvebx: 13246 VT = MVT::i8; 13247 break; 13248 case Intrinsic::ppc_altivec_stvehx: 13249 VT = MVT::i16; 13250 break; 13251 case Intrinsic::ppc_altivec_stvewx: 13252 VT = MVT::i32; 13253 break; 13254 } 13255 13256 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 13257 } 13258 13259 return false; 13260 } 13261 13262 // Return true is there is a nearyby consecutive load to the one provided 13263 // (regardless of alignment). We search up and down the chain, looking though 13264 // token factors and other loads (but nothing else). As a result, a true result 13265 // indicates that it is safe to create a new consecutive load adjacent to the 13266 // load provided. 13267 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 13268 SDValue Chain = LD->getChain(); 13269 EVT VT = LD->getMemoryVT(); 13270 13271 SmallSet<SDNode *, 16> LoadRoots; 13272 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 13273 SmallSet<SDNode *, 16> Visited; 13274 13275 // First, search up the chain, branching to follow all token-factor operands. 13276 // If we find a consecutive load, then we're done, otherwise, record all 13277 // nodes just above the top-level loads and token factors. 13278 while (!Queue.empty()) { 13279 SDNode *ChainNext = Queue.pop_back_val(); 13280 if (!Visited.insert(ChainNext).second) 13281 continue; 13282 13283 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 13284 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13285 return true; 13286 13287 if (!Visited.count(ChainLD->getChain().getNode())) 13288 Queue.push_back(ChainLD->getChain().getNode()); 13289 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 13290 for (const SDUse &O : ChainNext->ops()) 13291 if (!Visited.count(O.getNode())) 13292 Queue.push_back(O.getNode()); 13293 } else 13294 LoadRoots.insert(ChainNext); 13295 } 13296 13297 // Second, search down the chain, starting from the top-level nodes recorded 13298 // in the first phase. These top-level nodes are the nodes just above all 13299 // loads and token factors. Starting with their uses, recursively look though 13300 // all loads (just the chain uses) and token factors to find a consecutive 13301 // load. 13302 Visited.clear(); 13303 Queue.clear(); 13304 13305 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 13306 IE = LoadRoots.end(); I != IE; ++I) { 13307 Queue.push_back(*I); 13308 13309 while (!Queue.empty()) { 13310 SDNode *LoadRoot = Queue.pop_back_val(); 13311 if (!Visited.insert(LoadRoot).second) 13312 continue; 13313 13314 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 13315 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13316 return true; 13317 13318 for (SDNode *U : LoadRoot->uses()) 13319 if (((isa<MemSDNode>(U) && 13320 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) || 13321 U->getOpcode() == ISD::TokenFactor) && 13322 !Visited.count(U)) 13323 Queue.push_back(U); 13324 } 13325 } 13326 13327 return false; 13328 } 13329 13330 /// This function is called when we have proved that a SETCC node can be replaced 13331 /// by subtraction (and other supporting instructions) so that the result of 13332 /// comparison is kept in a GPR instead of CR. This function is purely for 13333 /// codegen purposes and has some flags to guide the codegen process. 13334 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 13335 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 13336 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13337 13338 // Zero extend the operands to the largest legal integer. Originally, they 13339 // must be of a strictly smaller size. 13340 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 13341 DAG.getConstant(Size, DL, MVT::i32)); 13342 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 13343 DAG.getConstant(Size, DL, MVT::i32)); 13344 13345 // Swap if needed. Depends on the condition code. 13346 if (Swap) 13347 std::swap(Op0, Op1); 13348 13349 // Subtract extended integers. 13350 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 13351 13352 // Move the sign bit to the least significant position and zero out the rest. 13353 // Now the least significant bit carries the result of original comparison. 13354 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 13355 DAG.getConstant(Size - 1, DL, MVT::i32)); 13356 auto Final = Shifted; 13357 13358 // Complement the result if needed. Based on the condition code. 13359 if (Complement) 13360 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 13361 DAG.getConstant(1, DL, MVT::i64)); 13362 13363 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 13364 } 13365 13366 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 13367 DAGCombinerInfo &DCI) const { 13368 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13369 13370 SelectionDAG &DAG = DCI.DAG; 13371 SDLoc DL(N); 13372 13373 // Size of integers being compared has a critical role in the following 13374 // analysis, so we prefer to do this when all types are legal. 13375 if (!DCI.isAfterLegalizeDAG()) 13376 return SDValue(); 13377 13378 // If all users of SETCC extend its value to a legal integer type 13379 // then we replace SETCC with a subtraction 13380 for (const SDNode *U : N->uses()) 13381 if (U->getOpcode() != ISD::ZERO_EXTEND) 13382 return SDValue(); 13383 13384 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13385 auto OpSize = N->getOperand(0).getValueSizeInBits(); 13386 13387 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 13388 13389 if (OpSize < Size) { 13390 switch (CC) { 13391 default: break; 13392 case ISD::SETULT: 13393 return generateEquivalentSub(N, Size, false, false, DL, DAG); 13394 case ISD::SETULE: 13395 return generateEquivalentSub(N, Size, true, true, DL, DAG); 13396 case ISD::SETUGT: 13397 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13398 case ISD::SETUGE: 13399 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13400 } 13401 } 13402 13403 return SDValue(); 13404 } 13405 13406 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13407 DAGCombinerInfo &DCI) const { 13408 SelectionDAG &DAG = DCI.DAG; 13409 SDLoc dl(N); 13410 13411 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13412 // If we're tracking CR bits, we need to be careful that we don't have: 13413 // trunc(binary-ops(zext(x), zext(y))) 13414 // or 13415 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13416 // such that we're unnecessarily moving things into GPRs when it would be 13417 // better to keep them in CR bits. 13418 13419 // Note that trunc here can be an actual i1 trunc, or can be the effective 13420 // truncation that comes from a setcc or select_cc. 13421 if (N->getOpcode() == ISD::TRUNCATE && 13422 N->getValueType(0) != MVT::i1) 13423 return SDValue(); 13424 13425 if (N->getOperand(0).getValueType() != MVT::i32 && 13426 N->getOperand(0).getValueType() != MVT::i64) 13427 return SDValue(); 13428 13429 if (N->getOpcode() == ISD::SETCC || 13430 N->getOpcode() == ISD::SELECT_CC) { 13431 // If we're looking at a comparison, then we need to make sure that the 13432 // high bits (all except for the first) don't matter the result. 13433 ISD::CondCode CC = 13434 cast<CondCodeSDNode>(N->getOperand( 13435 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13436 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13437 13438 if (ISD::isSignedIntSetCC(CC)) { 13439 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13440 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13441 return SDValue(); 13442 } else if (ISD::isUnsignedIntSetCC(CC)) { 13443 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13444 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13445 !DAG.MaskedValueIsZero(N->getOperand(1), 13446 APInt::getHighBitsSet(OpBits, OpBits-1))) 13447 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13448 : SDValue()); 13449 } else { 13450 // This is neither a signed nor an unsigned comparison, just make sure 13451 // that the high bits are equal. 13452 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13453 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13454 13455 // We don't really care about what is known about the first bit (if 13456 // anything), so pretend that it is known zero for both to ensure they can 13457 // be compared as constants. 13458 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13459 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13460 13461 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13462 Op1Known.getConstant() != Op2Known.getConstant()) 13463 return SDValue(); 13464 } 13465 } 13466 13467 // We now know that the higher-order bits are irrelevant, we just need to 13468 // make sure that all of the intermediate operations are bit operations, and 13469 // all inputs are extensions. 13470 if (N->getOperand(0).getOpcode() != ISD::AND && 13471 N->getOperand(0).getOpcode() != ISD::OR && 13472 N->getOperand(0).getOpcode() != ISD::XOR && 13473 N->getOperand(0).getOpcode() != ISD::SELECT && 13474 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13475 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13476 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13477 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13478 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13479 return SDValue(); 13480 13481 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13482 N->getOperand(1).getOpcode() != ISD::AND && 13483 N->getOperand(1).getOpcode() != ISD::OR && 13484 N->getOperand(1).getOpcode() != ISD::XOR && 13485 N->getOperand(1).getOpcode() != ISD::SELECT && 13486 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13487 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13488 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13489 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13490 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13491 return SDValue(); 13492 13493 SmallVector<SDValue, 4> Inputs; 13494 SmallVector<SDValue, 8> BinOps, PromOps; 13495 SmallPtrSet<SDNode *, 16> Visited; 13496 13497 for (unsigned i = 0; i < 2; ++i) { 13498 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13499 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13500 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13501 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13502 isa<ConstantSDNode>(N->getOperand(i))) 13503 Inputs.push_back(N->getOperand(i)); 13504 else 13505 BinOps.push_back(N->getOperand(i)); 13506 13507 if (N->getOpcode() == ISD::TRUNCATE) 13508 break; 13509 } 13510 13511 // Visit all inputs, collect all binary operations (and, or, xor and 13512 // select) that are all fed by extensions. 13513 while (!BinOps.empty()) { 13514 SDValue BinOp = BinOps.pop_back_val(); 13515 13516 if (!Visited.insert(BinOp.getNode()).second) 13517 continue; 13518 13519 PromOps.push_back(BinOp); 13520 13521 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13522 // The condition of the select is not promoted. 13523 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13524 continue; 13525 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13526 continue; 13527 13528 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13529 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13530 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13531 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13532 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13533 Inputs.push_back(BinOp.getOperand(i)); 13534 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13535 BinOp.getOperand(i).getOpcode() == ISD::OR || 13536 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13537 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13538 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13539 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13540 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13541 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13542 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13543 BinOps.push_back(BinOp.getOperand(i)); 13544 } else { 13545 // We have an input that is not an extension or another binary 13546 // operation; we'll abort this transformation. 13547 return SDValue(); 13548 } 13549 } 13550 } 13551 13552 // Make sure that this is a self-contained cluster of operations (which 13553 // is not quite the same thing as saying that everything has only one 13554 // use). 13555 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13556 if (isa<ConstantSDNode>(Inputs[i])) 13557 continue; 13558 13559 for (const SDNode *User : Inputs[i].getNode()->uses()) { 13560 if (User != N && !Visited.count(User)) 13561 return SDValue(); 13562 13563 // Make sure that we're not going to promote the non-output-value 13564 // operand(s) or SELECT or SELECT_CC. 13565 // FIXME: Although we could sometimes handle this, and it does occur in 13566 // practice that one of the condition inputs to the select is also one of 13567 // the outputs, we currently can't deal with this. 13568 if (User->getOpcode() == ISD::SELECT) { 13569 if (User->getOperand(0) == Inputs[i]) 13570 return SDValue(); 13571 } else if (User->getOpcode() == ISD::SELECT_CC) { 13572 if (User->getOperand(0) == Inputs[i] || 13573 User->getOperand(1) == Inputs[i]) 13574 return SDValue(); 13575 } 13576 } 13577 } 13578 13579 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13580 for (const SDNode *User : PromOps[i].getNode()->uses()) { 13581 if (User != N && !Visited.count(User)) 13582 return SDValue(); 13583 13584 // Make sure that we're not going to promote the non-output-value 13585 // operand(s) or SELECT or SELECT_CC. 13586 // FIXME: Although we could sometimes handle this, and it does occur in 13587 // practice that one of the condition inputs to the select is also one of 13588 // the outputs, we currently can't deal with this. 13589 if (User->getOpcode() == ISD::SELECT) { 13590 if (User->getOperand(0) == PromOps[i]) 13591 return SDValue(); 13592 } else if (User->getOpcode() == ISD::SELECT_CC) { 13593 if (User->getOperand(0) == PromOps[i] || 13594 User->getOperand(1) == PromOps[i]) 13595 return SDValue(); 13596 } 13597 } 13598 } 13599 13600 // Replace all inputs with the extension operand. 13601 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13602 // Constants may have users outside the cluster of to-be-promoted nodes, 13603 // and so we need to replace those as we do the promotions. 13604 if (isa<ConstantSDNode>(Inputs[i])) 13605 continue; 13606 else 13607 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13608 } 13609 13610 std::list<HandleSDNode> PromOpHandles; 13611 for (auto &PromOp : PromOps) 13612 PromOpHandles.emplace_back(PromOp); 13613 13614 // Replace all operations (these are all the same, but have a different 13615 // (i1) return type). DAG.getNode will validate that the types of 13616 // a binary operator match, so go through the list in reverse so that 13617 // we've likely promoted both operands first. Any intermediate truncations or 13618 // extensions disappear. 13619 while (!PromOpHandles.empty()) { 13620 SDValue PromOp = PromOpHandles.back().getValue(); 13621 PromOpHandles.pop_back(); 13622 13623 if (PromOp.getOpcode() == ISD::TRUNCATE || 13624 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13625 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13626 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13627 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13628 PromOp.getOperand(0).getValueType() != MVT::i1) { 13629 // The operand is not yet ready (see comment below). 13630 PromOpHandles.emplace_front(PromOp); 13631 continue; 13632 } 13633 13634 SDValue RepValue = PromOp.getOperand(0); 13635 if (isa<ConstantSDNode>(RepValue)) 13636 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13637 13638 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13639 continue; 13640 } 13641 13642 unsigned C; 13643 switch (PromOp.getOpcode()) { 13644 default: C = 0; break; 13645 case ISD::SELECT: C = 1; break; 13646 case ISD::SELECT_CC: C = 2; break; 13647 } 13648 13649 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13650 PromOp.getOperand(C).getValueType() != MVT::i1) || 13651 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13652 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13653 // The to-be-promoted operands of this node have not yet been 13654 // promoted (this should be rare because we're going through the 13655 // list backward, but if one of the operands has several users in 13656 // this cluster of to-be-promoted nodes, it is possible). 13657 PromOpHandles.emplace_front(PromOp); 13658 continue; 13659 } 13660 13661 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13662 PromOp.getNode()->op_end()); 13663 13664 // If there are any constant inputs, make sure they're replaced now. 13665 for (unsigned i = 0; i < 2; ++i) 13666 if (isa<ConstantSDNode>(Ops[C+i])) 13667 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13668 13669 DAG.ReplaceAllUsesOfValueWith(PromOp, 13670 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13671 } 13672 13673 // Now we're left with the initial truncation itself. 13674 if (N->getOpcode() == ISD::TRUNCATE) 13675 return N->getOperand(0); 13676 13677 // Otherwise, this is a comparison. The operands to be compared have just 13678 // changed type (to i1), but everything else is the same. 13679 return SDValue(N, 0); 13680 } 13681 13682 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13683 DAGCombinerInfo &DCI) const { 13684 SelectionDAG &DAG = DCI.DAG; 13685 SDLoc dl(N); 13686 13687 // If we're tracking CR bits, we need to be careful that we don't have: 13688 // zext(binary-ops(trunc(x), trunc(y))) 13689 // or 13690 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13691 // such that we're unnecessarily moving things into CR bits that can more 13692 // efficiently stay in GPRs. Note that if we're not certain that the high 13693 // bits are set as required by the final extension, we still may need to do 13694 // some masking to get the proper behavior. 13695 13696 // This same functionality is important on PPC64 when dealing with 13697 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13698 // the return values of functions. Because it is so similar, it is handled 13699 // here as well. 13700 13701 if (N->getValueType(0) != MVT::i32 && 13702 N->getValueType(0) != MVT::i64) 13703 return SDValue(); 13704 13705 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13706 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13707 return SDValue(); 13708 13709 if (N->getOperand(0).getOpcode() != ISD::AND && 13710 N->getOperand(0).getOpcode() != ISD::OR && 13711 N->getOperand(0).getOpcode() != ISD::XOR && 13712 N->getOperand(0).getOpcode() != ISD::SELECT && 13713 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13714 return SDValue(); 13715 13716 SmallVector<SDValue, 4> Inputs; 13717 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13718 SmallPtrSet<SDNode *, 16> Visited; 13719 13720 // Visit all inputs, collect all binary operations (and, or, xor and 13721 // select) that are all fed by truncations. 13722 while (!BinOps.empty()) { 13723 SDValue BinOp = BinOps.pop_back_val(); 13724 13725 if (!Visited.insert(BinOp.getNode()).second) 13726 continue; 13727 13728 PromOps.push_back(BinOp); 13729 13730 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13731 // The condition of the select is not promoted. 13732 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13733 continue; 13734 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13735 continue; 13736 13737 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13738 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13739 Inputs.push_back(BinOp.getOperand(i)); 13740 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13741 BinOp.getOperand(i).getOpcode() == ISD::OR || 13742 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13743 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13744 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13745 BinOps.push_back(BinOp.getOperand(i)); 13746 } else { 13747 // We have an input that is not a truncation or another binary 13748 // operation; we'll abort this transformation. 13749 return SDValue(); 13750 } 13751 } 13752 } 13753 13754 // The operands of a select that must be truncated when the select is 13755 // promoted because the operand is actually part of the to-be-promoted set. 13756 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13757 13758 // Make sure that this is a self-contained cluster of operations (which 13759 // is not quite the same thing as saying that everything has only one 13760 // use). 13761 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13762 if (isa<ConstantSDNode>(Inputs[i])) 13763 continue; 13764 13765 for (SDNode *User : Inputs[i].getNode()->uses()) { 13766 if (User != N && !Visited.count(User)) 13767 return SDValue(); 13768 13769 // If we're going to promote the non-output-value operand(s) or SELECT or 13770 // SELECT_CC, record them for truncation. 13771 if (User->getOpcode() == ISD::SELECT) { 13772 if (User->getOperand(0) == Inputs[i]) 13773 SelectTruncOp[0].insert(std::make_pair(User, 13774 User->getOperand(0).getValueType())); 13775 } else if (User->getOpcode() == ISD::SELECT_CC) { 13776 if (User->getOperand(0) == Inputs[i]) 13777 SelectTruncOp[0].insert(std::make_pair(User, 13778 User->getOperand(0).getValueType())); 13779 if (User->getOperand(1) == Inputs[i]) 13780 SelectTruncOp[1].insert(std::make_pair(User, 13781 User->getOperand(1).getValueType())); 13782 } 13783 } 13784 } 13785 13786 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13787 for (SDNode *User : PromOps[i].getNode()->uses()) { 13788 if (User != N && !Visited.count(User)) 13789 return SDValue(); 13790 13791 // If we're going to promote the non-output-value operand(s) or SELECT or 13792 // SELECT_CC, record them for truncation. 13793 if (User->getOpcode() == ISD::SELECT) { 13794 if (User->getOperand(0) == PromOps[i]) 13795 SelectTruncOp[0].insert(std::make_pair(User, 13796 User->getOperand(0).getValueType())); 13797 } else if (User->getOpcode() == ISD::SELECT_CC) { 13798 if (User->getOperand(0) == PromOps[i]) 13799 SelectTruncOp[0].insert(std::make_pair(User, 13800 User->getOperand(0).getValueType())); 13801 if (User->getOperand(1) == PromOps[i]) 13802 SelectTruncOp[1].insert(std::make_pair(User, 13803 User->getOperand(1).getValueType())); 13804 } 13805 } 13806 } 13807 13808 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13809 bool ReallyNeedsExt = false; 13810 if (N->getOpcode() != ISD::ANY_EXTEND) { 13811 // If all of the inputs are not already sign/zero extended, then 13812 // we'll still need to do that at the end. 13813 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13814 if (isa<ConstantSDNode>(Inputs[i])) 13815 continue; 13816 13817 unsigned OpBits = 13818 Inputs[i].getOperand(0).getValueSizeInBits(); 13819 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13820 13821 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13822 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13823 APInt::getHighBitsSet(OpBits, 13824 OpBits-PromBits))) || 13825 (N->getOpcode() == ISD::SIGN_EXTEND && 13826 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13827 (OpBits-(PromBits-1)))) { 13828 ReallyNeedsExt = true; 13829 break; 13830 } 13831 } 13832 } 13833 13834 // Replace all inputs, either with the truncation operand, or a 13835 // truncation or extension to the final output type. 13836 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13837 // Constant inputs need to be replaced with the to-be-promoted nodes that 13838 // use them because they might have users outside of the cluster of 13839 // promoted nodes. 13840 if (isa<ConstantSDNode>(Inputs[i])) 13841 continue; 13842 13843 SDValue InSrc = Inputs[i].getOperand(0); 13844 if (Inputs[i].getValueType() == N->getValueType(0)) 13845 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13846 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13847 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13848 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13849 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13850 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13851 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13852 else 13853 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13854 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13855 } 13856 13857 std::list<HandleSDNode> PromOpHandles; 13858 for (auto &PromOp : PromOps) 13859 PromOpHandles.emplace_back(PromOp); 13860 13861 // Replace all operations (these are all the same, but have a different 13862 // (promoted) return type). DAG.getNode will validate that the types of 13863 // a binary operator match, so go through the list in reverse so that 13864 // we've likely promoted both operands first. 13865 while (!PromOpHandles.empty()) { 13866 SDValue PromOp = PromOpHandles.back().getValue(); 13867 PromOpHandles.pop_back(); 13868 13869 unsigned C; 13870 switch (PromOp.getOpcode()) { 13871 default: C = 0; break; 13872 case ISD::SELECT: C = 1; break; 13873 case ISD::SELECT_CC: C = 2; break; 13874 } 13875 13876 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13877 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13878 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13879 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13880 // The to-be-promoted operands of this node have not yet been 13881 // promoted (this should be rare because we're going through the 13882 // list backward, but if one of the operands has several users in 13883 // this cluster of to-be-promoted nodes, it is possible). 13884 PromOpHandles.emplace_front(PromOp); 13885 continue; 13886 } 13887 13888 // For SELECT and SELECT_CC nodes, we do a similar check for any 13889 // to-be-promoted comparison inputs. 13890 if (PromOp.getOpcode() == ISD::SELECT || 13891 PromOp.getOpcode() == ISD::SELECT_CC) { 13892 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13893 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13894 (SelectTruncOp[1].count(PromOp.getNode()) && 13895 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13896 PromOpHandles.emplace_front(PromOp); 13897 continue; 13898 } 13899 } 13900 13901 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13902 PromOp.getNode()->op_end()); 13903 13904 // If this node has constant inputs, then they'll need to be promoted here. 13905 for (unsigned i = 0; i < 2; ++i) { 13906 if (!isa<ConstantSDNode>(Ops[C+i])) 13907 continue; 13908 if (Ops[C+i].getValueType() == N->getValueType(0)) 13909 continue; 13910 13911 if (N->getOpcode() == ISD::SIGN_EXTEND) 13912 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13913 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13914 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13915 else 13916 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13917 } 13918 13919 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13920 // truncate them again to the original value type. 13921 if (PromOp.getOpcode() == ISD::SELECT || 13922 PromOp.getOpcode() == ISD::SELECT_CC) { 13923 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13924 if (SI0 != SelectTruncOp[0].end()) 13925 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13926 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13927 if (SI1 != SelectTruncOp[1].end()) 13928 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13929 } 13930 13931 DAG.ReplaceAllUsesOfValueWith(PromOp, 13932 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13933 } 13934 13935 // Now we're left with the initial extension itself. 13936 if (!ReallyNeedsExt) 13937 return N->getOperand(0); 13938 13939 // To zero extend, just mask off everything except for the first bit (in the 13940 // i1 case). 13941 if (N->getOpcode() == ISD::ZERO_EXTEND) 13942 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13943 DAG.getConstant(APInt::getLowBitsSet( 13944 N->getValueSizeInBits(0), PromBits), 13945 dl, N->getValueType(0))); 13946 13947 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13948 "Invalid extension type"); 13949 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13950 SDValue ShiftCst = 13951 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13952 return DAG.getNode( 13953 ISD::SRA, dl, N->getValueType(0), 13954 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13955 ShiftCst); 13956 } 13957 13958 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13959 DAGCombinerInfo &DCI) const { 13960 assert(N->getOpcode() == ISD::SETCC && 13961 "Should be called with a SETCC node"); 13962 13963 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13964 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13965 SDValue LHS = N->getOperand(0); 13966 SDValue RHS = N->getOperand(1); 13967 13968 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13969 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13970 LHS.hasOneUse()) 13971 std::swap(LHS, RHS); 13972 13973 // x == 0-y --> x+y == 0 13974 // x != 0-y --> x+y != 0 13975 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13976 RHS.hasOneUse()) { 13977 SDLoc DL(N); 13978 SelectionDAG &DAG = DCI.DAG; 13979 EVT VT = N->getValueType(0); 13980 EVT OpVT = LHS.getValueType(); 13981 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13982 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13983 } 13984 } 13985 13986 return DAGCombineTruncBoolExt(N, DCI); 13987 } 13988 13989 // Is this an extending load from an f32 to an f64? 13990 static bool isFPExtLoad(SDValue Op) { 13991 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13992 return LD->getExtensionType() == ISD::EXTLOAD && 13993 Op.getValueType() == MVT::f64; 13994 return false; 13995 } 13996 13997 /// Reduces the number of fp-to-int conversion when building a vector. 13998 /// 13999 /// If this vector is built out of floating to integer conversions, 14000 /// transform it to a vector built out of floating point values followed by a 14001 /// single floating to integer conversion of the vector. 14002 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 14003 /// becomes (fptosi (build_vector ($A, $B, ...))) 14004 SDValue PPCTargetLowering:: 14005 combineElementTruncationToVectorTruncation(SDNode *N, 14006 DAGCombinerInfo &DCI) const { 14007 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14008 "Should be called with a BUILD_VECTOR node"); 14009 14010 SelectionDAG &DAG = DCI.DAG; 14011 SDLoc dl(N); 14012 14013 SDValue FirstInput = N->getOperand(0); 14014 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 14015 "The input operand must be an fp-to-int conversion."); 14016 14017 // This combine happens after legalization so the fp_to_[su]i nodes are 14018 // already converted to PPCSISD nodes. 14019 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 14020 if (FirstConversion == PPCISD::FCTIDZ || 14021 FirstConversion == PPCISD::FCTIDUZ || 14022 FirstConversion == PPCISD::FCTIWZ || 14023 FirstConversion == PPCISD::FCTIWUZ) { 14024 bool IsSplat = true; 14025 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 14026 FirstConversion == PPCISD::FCTIWUZ; 14027 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 14028 SmallVector<SDValue, 4> Ops; 14029 EVT TargetVT = N->getValueType(0); 14030 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 14031 SDValue NextOp = N->getOperand(i); 14032 if (NextOp.getOpcode() != PPCISD::MFVSR) 14033 return SDValue(); 14034 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 14035 if (NextConversion != FirstConversion) 14036 return SDValue(); 14037 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 14038 // This is not valid if the input was originally double precision. It is 14039 // also not profitable to do unless this is an extending load in which 14040 // case doing this combine will allow us to combine consecutive loads. 14041 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 14042 return SDValue(); 14043 if (N->getOperand(i) != FirstInput) 14044 IsSplat = false; 14045 } 14046 14047 // If this is a splat, we leave it as-is since there will be only a single 14048 // fp-to-int conversion followed by a splat of the integer. This is better 14049 // for 32-bit and smaller ints and neutral for 64-bit ints. 14050 if (IsSplat) 14051 return SDValue(); 14052 14053 // Now that we know we have the right type of node, get its operands 14054 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 14055 SDValue In = N->getOperand(i).getOperand(0); 14056 if (Is32Bit) { 14057 // For 32-bit values, we need to add an FP_ROUND node (if we made it 14058 // here, we know that all inputs are extending loads so this is safe). 14059 if (In.isUndef()) 14060 Ops.push_back(DAG.getUNDEF(SrcVT)); 14061 else { 14062 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 14063 MVT::f32, In.getOperand(0), 14064 DAG.getIntPtrConstant(1, dl)); 14065 Ops.push_back(Trunc); 14066 } 14067 } else 14068 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 14069 } 14070 14071 unsigned Opcode; 14072 if (FirstConversion == PPCISD::FCTIDZ || 14073 FirstConversion == PPCISD::FCTIWZ) 14074 Opcode = ISD::FP_TO_SINT; 14075 else 14076 Opcode = ISD::FP_TO_UINT; 14077 14078 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 14079 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 14080 return DAG.getNode(Opcode, dl, TargetVT, BV); 14081 } 14082 return SDValue(); 14083 } 14084 14085 /// Reduce the number of loads when building a vector. 14086 /// 14087 /// Building a vector out of multiple loads can be converted to a load 14088 /// of the vector type if the loads are consecutive. If the loads are 14089 /// consecutive but in descending order, a shuffle is added at the end 14090 /// to reorder the vector. 14091 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 14092 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14093 "Should be called with a BUILD_VECTOR node"); 14094 14095 SDLoc dl(N); 14096 14097 // Return early for non byte-sized type, as they can't be consecutive. 14098 if (!N->getValueType(0).getVectorElementType().isByteSized()) 14099 return SDValue(); 14100 14101 bool InputsAreConsecutiveLoads = true; 14102 bool InputsAreReverseConsecutive = true; 14103 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 14104 SDValue FirstInput = N->getOperand(0); 14105 bool IsRoundOfExtLoad = false; 14106 14107 if (FirstInput.getOpcode() == ISD::FP_ROUND && 14108 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 14109 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 14110 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 14111 } 14112 // Not a build vector of (possibly fp_rounded) loads. 14113 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 14114 N->getNumOperands() == 1) 14115 return SDValue(); 14116 14117 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 14118 // If any inputs are fp_round(extload), they all must be. 14119 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 14120 return SDValue(); 14121 14122 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 14123 N->getOperand(i); 14124 if (NextInput.getOpcode() != ISD::LOAD) 14125 return SDValue(); 14126 14127 SDValue PreviousInput = 14128 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 14129 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 14130 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 14131 14132 // If any inputs are fp_round(extload), they all must be. 14133 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 14134 return SDValue(); 14135 14136 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 14137 InputsAreConsecutiveLoads = false; 14138 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 14139 InputsAreReverseConsecutive = false; 14140 14141 // Exit early if the loads are neither consecutive nor reverse consecutive. 14142 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 14143 return SDValue(); 14144 } 14145 14146 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 14147 "The loads cannot be both consecutive and reverse consecutive."); 14148 14149 SDValue FirstLoadOp = 14150 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 14151 SDValue LastLoadOp = 14152 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 14153 N->getOperand(N->getNumOperands()-1); 14154 14155 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 14156 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 14157 if (InputsAreConsecutiveLoads) { 14158 assert(LD1 && "Input needs to be a LoadSDNode."); 14159 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 14160 LD1->getBasePtr(), LD1->getPointerInfo(), 14161 LD1->getAlignment()); 14162 } 14163 if (InputsAreReverseConsecutive) { 14164 assert(LDL && "Input needs to be a LoadSDNode."); 14165 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 14166 LDL->getBasePtr(), LDL->getPointerInfo(), 14167 LDL->getAlignment()); 14168 SmallVector<int, 16> Ops; 14169 for (int i = N->getNumOperands() - 1; i >= 0; i--) 14170 Ops.push_back(i); 14171 14172 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 14173 DAG.getUNDEF(N->getValueType(0)), Ops); 14174 } 14175 return SDValue(); 14176 } 14177 14178 // This function adds the required vector_shuffle needed to get 14179 // the elements of the vector extract in the correct position 14180 // as specified by the CorrectElems encoding. 14181 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 14182 SDValue Input, uint64_t Elems, 14183 uint64_t CorrectElems) { 14184 SDLoc dl(N); 14185 14186 unsigned NumElems = Input.getValueType().getVectorNumElements(); 14187 SmallVector<int, 16> ShuffleMask(NumElems, -1); 14188 14189 // Knowing the element indices being extracted from the original 14190 // vector and the order in which they're being inserted, just put 14191 // them at element indices required for the instruction. 14192 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14193 if (DAG.getDataLayout().isLittleEndian()) 14194 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 14195 else 14196 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 14197 CorrectElems = CorrectElems >> 8; 14198 Elems = Elems >> 8; 14199 } 14200 14201 SDValue Shuffle = 14202 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 14203 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 14204 14205 EVT VT = N->getValueType(0); 14206 SDValue Conv = DAG.getBitcast(VT, Shuffle); 14207 14208 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 14209 Input.getValueType().getVectorElementType(), 14210 VT.getVectorNumElements()); 14211 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 14212 DAG.getValueType(ExtVT)); 14213 } 14214 14215 // Look for build vector patterns where input operands come from sign 14216 // extended vector_extract elements of specific indices. If the correct indices 14217 // aren't used, add a vector shuffle to fix up the indices and create 14218 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 14219 // during instruction selection. 14220 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 14221 // This array encodes the indices that the vector sign extend instructions 14222 // extract from when extending from one type to another for both BE and LE. 14223 // The right nibble of each byte corresponds to the LE incides. 14224 // and the left nibble of each byte corresponds to the BE incides. 14225 // For example: 0x3074B8FC byte->word 14226 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 14227 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 14228 // For example: 0x000070F8 byte->double word 14229 // For LE: the allowed indices are: 0x0,0x8 14230 // For BE: the allowed indices are: 0x7,0xF 14231 uint64_t TargetElems[] = { 14232 0x3074B8FC, // b->w 14233 0x000070F8, // b->d 14234 0x10325476, // h->w 14235 0x00003074, // h->d 14236 0x00001032, // w->d 14237 }; 14238 14239 uint64_t Elems = 0; 14240 int Index; 14241 SDValue Input; 14242 14243 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 14244 if (!Op) 14245 return false; 14246 if (Op.getOpcode() != ISD::SIGN_EXTEND && 14247 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 14248 return false; 14249 14250 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 14251 // of the right width. 14252 SDValue Extract = Op.getOperand(0); 14253 if (Extract.getOpcode() == ISD::ANY_EXTEND) 14254 Extract = Extract.getOperand(0); 14255 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14256 return false; 14257 14258 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 14259 if (!ExtOp) 14260 return false; 14261 14262 Index = ExtOp->getZExtValue(); 14263 if (Input && Input != Extract.getOperand(0)) 14264 return false; 14265 14266 if (!Input) 14267 Input = Extract.getOperand(0); 14268 14269 Elems = Elems << 8; 14270 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 14271 Elems |= Index; 14272 14273 return true; 14274 }; 14275 14276 // If the build vector operands aren't sign extended vector extracts, 14277 // of the same input vector, then return. 14278 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14279 if (!isSExtOfVecExtract(N->getOperand(i))) { 14280 return SDValue(); 14281 } 14282 } 14283 14284 // If the vector extract indicies are not correct, add the appropriate 14285 // vector_shuffle. 14286 int TgtElemArrayIdx; 14287 int InputSize = Input.getValueType().getScalarSizeInBits(); 14288 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 14289 if (InputSize + OutputSize == 40) 14290 TgtElemArrayIdx = 0; 14291 else if (InputSize + OutputSize == 72) 14292 TgtElemArrayIdx = 1; 14293 else if (InputSize + OutputSize == 48) 14294 TgtElemArrayIdx = 2; 14295 else if (InputSize + OutputSize == 80) 14296 TgtElemArrayIdx = 3; 14297 else if (InputSize + OutputSize == 96) 14298 TgtElemArrayIdx = 4; 14299 else 14300 return SDValue(); 14301 14302 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 14303 CorrectElems = DAG.getDataLayout().isLittleEndian() 14304 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 14305 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 14306 if (Elems != CorrectElems) { 14307 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 14308 } 14309 14310 // Regular lowering will catch cases where a shuffle is not needed. 14311 return SDValue(); 14312 } 14313 14314 // Look for the pattern of a load from a narrow width to i128, feeding 14315 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 14316 // (LXVRZX). This node represents a zero extending load that will be matched 14317 // to the Load VSX Vector Rightmost instructions. 14318 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 14319 SDLoc DL(N); 14320 14321 // This combine is only eligible for a BUILD_VECTOR of v1i128. 14322 if (N->getValueType(0) != MVT::v1i128) 14323 return SDValue(); 14324 14325 SDValue Operand = N->getOperand(0); 14326 // Proceed with the transformation if the operand to the BUILD_VECTOR 14327 // is a load instruction. 14328 if (Operand.getOpcode() != ISD::LOAD) 14329 return SDValue(); 14330 14331 auto *LD = cast<LoadSDNode>(Operand); 14332 EVT MemoryType = LD->getMemoryVT(); 14333 14334 // This transformation is only valid if the we are loading either a byte, 14335 // halfword, word, or doubleword. 14336 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 14337 MemoryType == MVT::i32 || MemoryType == MVT::i64; 14338 14339 // Ensure that the load from the narrow width is being zero extended to i128. 14340 if (!ValidLDType || 14341 (LD->getExtensionType() != ISD::ZEXTLOAD && 14342 LD->getExtensionType() != ISD::EXTLOAD)) 14343 return SDValue(); 14344 14345 SDValue LoadOps[] = { 14346 LD->getChain(), LD->getBasePtr(), 14347 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 14348 14349 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 14350 DAG.getVTList(MVT::v1i128, MVT::Other), 14351 LoadOps, MemoryType, LD->getMemOperand()); 14352 } 14353 14354 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 14355 DAGCombinerInfo &DCI) const { 14356 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14357 "Should be called with a BUILD_VECTOR node"); 14358 14359 SelectionDAG &DAG = DCI.DAG; 14360 SDLoc dl(N); 14361 14362 if (!Subtarget.hasVSX()) 14363 return SDValue(); 14364 14365 // The target independent DAG combiner will leave a build_vector of 14366 // float-to-int conversions intact. We can generate MUCH better code for 14367 // a float-to-int conversion of a vector of floats. 14368 SDValue FirstInput = N->getOperand(0); 14369 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 14370 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 14371 if (Reduced) 14372 return Reduced; 14373 } 14374 14375 // If we're building a vector out of consecutive loads, just load that 14376 // vector type. 14377 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 14378 if (Reduced) 14379 return Reduced; 14380 14381 // If we're building a vector out of extended elements from another vector 14382 // we have P9 vector integer extend instructions. The code assumes legal 14383 // input types (i.e. it can't handle things like v4i16) so do not run before 14384 // legalization. 14385 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14386 Reduced = combineBVOfVecSExt(N, DAG); 14387 if (Reduced) 14388 return Reduced; 14389 } 14390 14391 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14392 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14393 // is a load from <valid narrow width> to i128. 14394 if (Subtarget.isISA3_1()) { 14395 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14396 if (BVOfZLoad) 14397 return BVOfZLoad; 14398 } 14399 14400 if (N->getValueType(0) != MVT::v2f64) 14401 return SDValue(); 14402 14403 // Looking for: 14404 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14405 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14406 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14407 return SDValue(); 14408 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14409 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14410 return SDValue(); 14411 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14412 return SDValue(); 14413 14414 SDValue Ext1 = FirstInput.getOperand(0); 14415 SDValue Ext2 = N->getOperand(1).getOperand(0); 14416 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14417 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14418 return SDValue(); 14419 14420 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14421 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14422 if (!Ext1Op || !Ext2Op) 14423 return SDValue(); 14424 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14425 Ext1.getOperand(0) != Ext2.getOperand(0)) 14426 return SDValue(); 14427 14428 int FirstElem = Ext1Op->getZExtValue(); 14429 int SecondElem = Ext2Op->getZExtValue(); 14430 int SubvecIdx; 14431 if (FirstElem == 0 && SecondElem == 1) 14432 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14433 else if (FirstElem == 2 && SecondElem == 3) 14434 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14435 else 14436 return SDValue(); 14437 14438 SDValue SrcVec = Ext1.getOperand(0); 14439 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14440 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14441 return DAG.getNode(NodeType, dl, MVT::v2f64, 14442 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14443 } 14444 14445 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14446 DAGCombinerInfo &DCI) const { 14447 assert((N->getOpcode() == ISD::SINT_TO_FP || 14448 N->getOpcode() == ISD::UINT_TO_FP) && 14449 "Need an int -> FP conversion node here"); 14450 14451 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14452 return SDValue(); 14453 14454 SelectionDAG &DAG = DCI.DAG; 14455 SDLoc dl(N); 14456 SDValue Op(N, 0); 14457 14458 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14459 // from the hardware. 14460 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14461 return SDValue(); 14462 if (!Op.getOperand(0).getValueType().isSimple()) 14463 return SDValue(); 14464 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14465 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14466 return SDValue(); 14467 14468 SDValue FirstOperand(Op.getOperand(0)); 14469 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14470 (FirstOperand.getValueType() == MVT::i8 || 14471 FirstOperand.getValueType() == MVT::i16); 14472 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14473 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14474 bool DstDouble = Op.getValueType() == MVT::f64; 14475 unsigned ConvOp = Signed ? 14476 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14477 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14478 SDValue WidthConst = 14479 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14480 dl, false); 14481 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14482 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14483 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14484 DAG.getVTList(MVT::f64, MVT::Other), 14485 Ops, MVT::i8, LDN->getMemOperand()); 14486 14487 // For signed conversion, we need to sign-extend the value in the VSR 14488 if (Signed) { 14489 SDValue ExtOps[] = { Ld, WidthConst }; 14490 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14491 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14492 } else 14493 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14494 } 14495 14496 14497 // For i32 intermediate values, unfortunately, the conversion functions 14498 // leave the upper 32 bits of the value are undefined. Within the set of 14499 // scalar instructions, we have no method for zero- or sign-extending the 14500 // value. Thus, we cannot handle i32 intermediate values here. 14501 if (Op.getOperand(0).getValueType() == MVT::i32) 14502 return SDValue(); 14503 14504 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14505 "UINT_TO_FP is supported only with FPCVT"); 14506 14507 // If we have FCFIDS, then use it when converting to single-precision. 14508 // Otherwise, convert to double-precision and then round. 14509 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14510 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14511 : PPCISD::FCFIDS) 14512 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14513 : PPCISD::FCFID); 14514 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14515 ? MVT::f32 14516 : MVT::f64; 14517 14518 // If we're converting from a float, to an int, and back to a float again, 14519 // then we don't need the store/load pair at all. 14520 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14521 Subtarget.hasFPCVT()) || 14522 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14523 SDValue Src = Op.getOperand(0).getOperand(0); 14524 if (Src.getValueType() == MVT::f32) { 14525 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14526 DCI.AddToWorklist(Src.getNode()); 14527 } else if (Src.getValueType() != MVT::f64) { 14528 // Make sure that we don't pick up a ppc_fp128 source value. 14529 return SDValue(); 14530 } 14531 14532 unsigned FCTOp = 14533 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14534 PPCISD::FCTIDUZ; 14535 14536 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14537 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14538 14539 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14540 FP = DAG.getNode(ISD::FP_ROUND, dl, 14541 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14542 DCI.AddToWorklist(FP.getNode()); 14543 } 14544 14545 return FP; 14546 } 14547 14548 return SDValue(); 14549 } 14550 14551 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14552 // builtins) into loads with swaps. 14553 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14554 DAGCombinerInfo &DCI) const { 14555 SelectionDAG &DAG = DCI.DAG; 14556 SDLoc dl(N); 14557 SDValue Chain; 14558 SDValue Base; 14559 MachineMemOperand *MMO; 14560 14561 switch (N->getOpcode()) { 14562 default: 14563 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14564 case ISD::LOAD: { 14565 LoadSDNode *LD = cast<LoadSDNode>(N); 14566 Chain = LD->getChain(); 14567 Base = LD->getBasePtr(); 14568 MMO = LD->getMemOperand(); 14569 // If the MMO suggests this isn't a load of a full vector, leave 14570 // things alone. For a built-in, we have to make the change for 14571 // correctness, so if there is a size problem that will be a bug. 14572 if (MMO->getSize() < 16) 14573 return SDValue(); 14574 break; 14575 } 14576 case ISD::INTRINSIC_W_CHAIN: { 14577 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14578 Chain = Intrin->getChain(); 14579 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14580 // us what we want. Get operand 2 instead. 14581 Base = Intrin->getOperand(2); 14582 MMO = Intrin->getMemOperand(); 14583 break; 14584 } 14585 } 14586 14587 MVT VecTy = N->getValueType(0).getSimpleVT(); 14588 14589 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14590 // aligned and the type is a vector with elements up to 4 bytes 14591 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14592 VecTy.getScalarSizeInBits() <= 32) { 14593 return SDValue(); 14594 } 14595 14596 SDValue LoadOps[] = { Chain, Base }; 14597 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14598 DAG.getVTList(MVT::v2f64, MVT::Other), 14599 LoadOps, MVT::v2f64, MMO); 14600 14601 DCI.AddToWorklist(Load.getNode()); 14602 Chain = Load.getValue(1); 14603 SDValue Swap = DAG.getNode( 14604 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14605 DCI.AddToWorklist(Swap.getNode()); 14606 14607 // Add a bitcast if the resulting load type doesn't match v2f64. 14608 if (VecTy != MVT::v2f64) { 14609 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14610 DCI.AddToWorklist(N.getNode()); 14611 // Package {bitcast value, swap's chain} to match Load's shape. 14612 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14613 N, Swap.getValue(1)); 14614 } 14615 14616 return Swap; 14617 } 14618 14619 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14620 // builtins) into stores with swaps. 14621 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14622 DAGCombinerInfo &DCI) const { 14623 SelectionDAG &DAG = DCI.DAG; 14624 SDLoc dl(N); 14625 SDValue Chain; 14626 SDValue Base; 14627 unsigned SrcOpnd; 14628 MachineMemOperand *MMO; 14629 14630 switch (N->getOpcode()) { 14631 default: 14632 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14633 case ISD::STORE: { 14634 StoreSDNode *ST = cast<StoreSDNode>(N); 14635 Chain = ST->getChain(); 14636 Base = ST->getBasePtr(); 14637 MMO = ST->getMemOperand(); 14638 SrcOpnd = 1; 14639 // If the MMO suggests this isn't a store of a full vector, leave 14640 // things alone. For a built-in, we have to make the change for 14641 // correctness, so if there is a size problem that will be a bug. 14642 if (MMO->getSize() < 16) 14643 return SDValue(); 14644 break; 14645 } 14646 case ISD::INTRINSIC_VOID: { 14647 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14648 Chain = Intrin->getChain(); 14649 // Intrin->getBasePtr() oddly does not get what we want. 14650 Base = Intrin->getOperand(3); 14651 MMO = Intrin->getMemOperand(); 14652 SrcOpnd = 2; 14653 break; 14654 } 14655 } 14656 14657 SDValue Src = N->getOperand(SrcOpnd); 14658 MVT VecTy = Src.getValueType().getSimpleVT(); 14659 14660 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14661 // aligned and the type is a vector with elements up to 4 bytes 14662 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14663 VecTy.getScalarSizeInBits() <= 32) { 14664 return SDValue(); 14665 } 14666 14667 // All stores are done as v2f64 and possible bit cast. 14668 if (VecTy != MVT::v2f64) { 14669 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14670 DCI.AddToWorklist(Src.getNode()); 14671 } 14672 14673 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14674 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14675 DCI.AddToWorklist(Swap.getNode()); 14676 Chain = Swap.getValue(1); 14677 SDValue StoreOps[] = { Chain, Swap, Base }; 14678 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14679 DAG.getVTList(MVT::Other), 14680 StoreOps, VecTy, MMO); 14681 DCI.AddToWorklist(Store.getNode()); 14682 return Store; 14683 } 14684 14685 // Handle DAG combine for STORE (FP_TO_INT F). 14686 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14687 DAGCombinerInfo &DCI) const { 14688 14689 SelectionDAG &DAG = DCI.DAG; 14690 SDLoc dl(N); 14691 unsigned Opcode = N->getOperand(1).getOpcode(); 14692 14693 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14694 && "Not a FP_TO_INT Instruction!"); 14695 14696 SDValue Val = N->getOperand(1).getOperand(0); 14697 EVT Op1VT = N->getOperand(1).getValueType(); 14698 EVT ResVT = Val.getValueType(); 14699 14700 if (!isTypeLegal(ResVT)) 14701 return SDValue(); 14702 14703 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14704 bool ValidTypeForStoreFltAsInt = 14705 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14706 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14707 14708 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14709 return SDValue(); 14710 14711 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14712 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14713 return SDValue(); 14714 14715 // Extend f32 values to f64 14716 if (ResVT.getScalarSizeInBits() == 32) { 14717 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14718 DCI.AddToWorklist(Val.getNode()); 14719 } 14720 14721 // Set signed or unsigned conversion opcode. 14722 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14723 PPCISD::FP_TO_SINT_IN_VSR : 14724 PPCISD::FP_TO_UINT_IN_VSR; 14725 14726 Val = DAG.getNode(ConvOpcode, 14727 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14728 DCI.AddToWorklist(Val.getNode()); 14729 14730 // Set number of bytes being converted. 14731 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14732 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14733 DAG.getIntPtrConstant(ByteSize, dl, false), 14734 DAG.getValueType(Op1VT) }; 14735 14736 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14737 DAG.getVTList(MVT::Other), Ops, 14738 cast<StoreSDNode>(N)->getMemoryVT(), 14739 cast<StoreSDNode>(N)->getMemOperand()); 14740 14741 DCI.AddToWorklist(Val.getNode()); 14742 return Val; 14743 } 14744 14745 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14746 // Check that the source of the element keeps flipping 14747 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14748 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14749 for (int i = 1, e = Mask.size(); i < e; i++) { 14750 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14751 return false; 14752 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14753 return false; 14754 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14755 } 14756 return true; 14757 } 14758 14759 static bool isSplatBV(SDValue Op) { 14760 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14761 return false; 14762 SDValue FirstOp; 14763 14764 // Find first non-undef input. 14765 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14766 FirstOp = Op.getOperand(i); 14767 if (!FirstOp.isUndef()) 14768 break; 14769 } 14770 14771 // All inputs are undef or the same as the first non-undef input. 14772 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14773 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14774 return false; 14775 return true; 14776 } 14777 14778 static SDValue isScalarToVec(SDValue Op) { 14779 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14780 return Op; 14781 if (Op.getOpcode() != ISD::BITCAST) 14782 return SDValue(); 14783 Op = Op.getOperand(0); 14784 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14785 return Op; 14786 return SDValue(); 14787 } 14788 14789 // Fix up the shuffle mask to account for the fact that the result of 14790 // scalar_to_vector is not in lane zero. This just takes all values in 14791 // the ranges specified by the min/max indices and adds the number of 14792 // elements required to ensure each element comes from the respective 14793 // position in the valid lane. 14794 // On little endian, that's just the corresponding element in the other 14795 // half of the vector. On big endian, it is in the same half but right 14796 // justified rather than left justified in that half. 14797 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14798 int LHSMaxIdx, int RHSMinIdx, 14799 int RHSMaxIdx, int HalfVec, 14800 unsigned ValidLaneWidth, 14801 const PPCSubtarget &Subtarget) { 14802 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14803 int Idx = ShuffV[i]; 14804 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14805 ShuffV[i] += 14806 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14807 } 14808 } 14809 14810 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14811 // the original is: 14812 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14813 // In such a case, just change the shuffle mask to extract the element 14814 // from the permuted index. 14815 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14816 const PPCSubtarget &Subtarget) { 14817 SDLoc dl(OrigSToV); 14818 EVT VT = OrigSToV.getValueType(); 14819 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14820 "Expecting a SCALAR_TO_VECTOR here"); 14821 SDValue Input = OrigSToV.getOperand(0); 14822 14823 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14824 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14825 SDValue OrigVector = Input.getOperand(0); 14826 14827 // Can't handle non-const element indices or different vector types 14828 // for the input to the extract and the output of the scalar_to_vector. 14829 if (Idx && VT == OrigVector.getValueType()) { 14830 unsigned NumElts = VT.getVectorNumElements(); 14831 assert( 14832 NumElts > 1 && 14833 "Cannot produce a permuted scalar_to_vector for one element vector"); 14834 SmallVector<int, 16> NewMask(NumElts, -1); 14835 unsigned ResultInElt = NumElts / 2; 14836 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14837 NewMask[ResultInElt] = Idx->getZExtValue(); 14838 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14839 } 14840 } 14841 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14842 OrigSToV.getOperand(0)); 14843 } 14844 14845 // On little endian subtargets, combine shuffles such as: 14846 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14847 // into: 14848 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14849 // because the latter can be matched to a single instruction merge. 14850 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14851 // to put the value into element zero. Adjust the shuffle mask so that the 14852 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14853 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 14854 // nodes with elements smaller than doubleword because all the ways 14855 // of getting scalar data into a vector register put the value in the 14856 // rightmost element of the left half of the vector. 14857 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14858 SelectionDAG &DAG) const { 14859 SDValue LHS = SVN->getOperand(0); 14860 SDValue RHS = SVN->getOperand(1); 14861 auto Mask = SVN->getMask(); 14862 int NumElts = LHS.getValueType().getVectorNumElements(); 14863 SDValue Res(SVN, 0); 14864 SDLoc dl(SVN); 14865 bool IsLittleEndian = Subtarget.isLittleEndian(); 14866 14867 // On big endian targets this is only useful for subtargets with direct moves. 14868 // On little endian targets it would be useful for all subtargets with VSX. 14869 // However adding special handling for LE subtargets without direct moves 14870 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8) 14871 // which includes direct moves. 14872 if (!Subtarget.hasDirectMove()) 14873 return Res; 14874 14875 // If this is not a shuffle of a shuffle and the first element comes from 14876 // the second vector, canonicalize to the commuted form. This will make it 14877 // more likely to match one of the single instruction patterns. 14878 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14879 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14880 std::swap(LHS, RHS); 14881 Res = DAG.getCommutedVectorShuffle(*SVN); 14882 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14883 } 14884 14885 // Adjust the shuffle mask if either input vector comes from a 14886 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14887 // form (to prevent the need for a swap). 14888 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14889 SDValue SToVLHS = isScalarToVec(LHS); 14890 SDValue SToVRHS = isScalarToVec(RHS); 14891 if (SToVLHS || SToVRHS) { 14892 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14893 : SToVRHS.getValueType().getVectorNumElements(); 14894 int NumEltsOut = ShuffV.size(); 14895 // The width of the "valid lane" (i.e. the lane that contains the value that 14896 // is vectorized) needs to be expressed in terms of the number of elements 14897 // of the shuffle. It is thereby the ratio of the values before and after 14898 // any bitcast. 14899 unsigned ValidLaneWidth = 14900 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() / 14901 LHS.getValueType().getScalarSizeInBits() 14902 : SToVRHS.getValueType().getScalarSizeInBits() / 14903 RHS.getValueType().getScalarSizeInBits(); 14904 14905 // Initially assume that neither input is permuted. These will be adjusted 14906 // accordingly if either input is. 14907 int LHSMaxIdx = -1; 14908 int RHSMinIdx = -1; 14909 int RHSMaxIdx = -1; 14910 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14911 14912 // Get the permuted scalar to vector nodes for the source(s) that come from 14913 // ISD::SCALAR_TO_VECTOR. 14914 // On big endian systems, this only makes sense for element sizes smaller 14915 // than 64 bits since for 64-bit elements, all instructions already put 14916 // the value into element zero. Since scalar size of LHS and RHS may differ 14917 // after isScalarToVec, this should be checked using their own sizes. 14918 if (SToVLHS) { 14919 if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64) 14920 return Res; 14921 // Set up the values for the shuffle vector fixup. 14922 LHSMaxIdx = NumEltsOut / NumEltsIn; 14923 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 14924 if (SToVLHS.getValueType() != LHS.getValueType()) 14925 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14926 LHS = SToVLHS; 14927 } 14928 if (SToVRHS) { 14929 if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64) 14930 return Res; 14931 RHSMinIdx = NumEltsOut; 14932 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14933 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 14934 if (SToVRHS.getValueType() != RHS.getValueType()) 14935 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14936 RHS = SToVRHS; 14937 } 14938 14939 // Fix up the shuffle mask to reflect where the desired element actually is. 14940 // The minimum and maximum indices that correspond to element zero for both 14941 // the LHS and RHS are computed and will control which shuffle mask entries 14942 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14943 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 14944 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14945 HalfVec, ValidLaneWidth, Subtarget); 14946 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14947 14948 // We may have simplified away the shuffle. We won't be able to do anything 14949 // further with it here. 14950 if (!isa<ShuffleVectorSDNode>(Res)) 14951 return Res; 14952 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14953 } 14954 14955 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 14956 // The common case after we commuted the shuffle is that the RHS is a splat 14957 // and we have elements coming in from the splat at indices that are not 14958 // conducive to using a merge. 14959 // Example: 14960 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14961 if (!isSplatBV(TheSplat)) 14962 return Res; 14963 14964 // We are looking for a mask such that all even elements are from 14965 // one vector and all odd elements from the other. 14966 if (!isAlternatingShuffMask(Mask, NumElts)) 14967 return Res; 14968 14969 // Adjust the mask so we are pulling in the same index from the splat 14970 // as the index from the interesting vector in consecutive elements. 14971 if (IsLittleEndian) { 14972 // Example (even elements from first vector): 14973 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14974 if (Mask[0] < NumElts) 14975 for (int i = 1, e = Mask.size(); i < e; i += 2) 14976 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14977 // Example (odd elements from first vector): 14978 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14979 else 14980 for (int i = 0, e = Mask.size(); i < e; i += 2) 14981 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14982 } else { 14983 // Example (even elements from first vector): 14984 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 14985 if (Mask[0] < NumElts) 14986 for (int i = 0, e = Mask.size(); i < e; i += 2) 14987 ShuffV[i] = ShuffV[i + 1] - NumElts; 14988 // Example (odd elements from first vector): 14989 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 14990 else 14991 for (int i = 1, e = Mask.size(); i < e; i += 2) 14992 ShuffV[i] = ShuffV[i - 1] - NumElts; 14993 } 14994 14995 // If the RHS has undefs, we need to remove them since we may have created 14996 // a shuffle that adds those instead of the splat value. 14997 SDValue SplatVal = 14998 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 14999 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 15000 15001 if (IsLittleEndian) 15002 RHS = TheSplat; 15003 else 15004 LHS = TheSplat; 15005 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 15006 } 15007 15008 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 15009 LSBaseSDNode *LSBase, 15010 DAGCombinerInfo &DCI) const { 15011 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 15012 "Not a reverse memop pattern!"); 15013 15014 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 15015 auto Mask = SVN->getMask(); 15016 int i = 0; 15017 auto I = Mask.rbegin(); 15018 auto E = Mask.rend(); 15019 15020 for (; I != E; ++I) { 15021 if (*I != i) 15022 return false; 15023 i++; 15024 } 15025 return true; 15026 }; 15027 15028 SelectionDAG &DAG = DCI.DAG; 15029 EVT VT = SVN->getValueType(0); 15030 15031 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 15032 return SDValue(); 15033 15034 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 15035 // See comment in PPCVSXSwapRemoval.cpp. 15036 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 15037 if (!Subtarget.hasP9Vector()) 15038 return SDValue(); 15039 15040 if(!IsElementReverse(SVN)) 15041 return SDValue(); 15042 15043 if (LSBase->getOpcode() == ISD::LOAD) { 15044 // If the load return value 0 has more than one user except the 15045 // shufflevector instruction, it is not profitable to replace the 15046 // shufflevector with a reverse load. 15047 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end(); 15048 UI != UE; ++UI) 15049 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE) 15050 return SDValue(); 15051 15052 SDLoc dl(LSBase); 15053 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 15054 return DAG.getMemIntrinsicNode( 15055 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 15056 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15057 } 15058 15059 if (LSBase->getOpcode() == ISD::STORE) { 15060 // If there are other uses of the shuffle, the swap cannot be avoided. 15061 // Forcing the use of an X-Form (since swapped stores only have 15062 // X-Forms) without removing the swap is unprofitable. 15063 if (!SVN->hasOneUse()) 15064 return SDValue(); 15065 15066 SDLoc dl(LSBase); 15067 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 15068 LSBase->getBasePtr()}; 15069 return DAG.getMemIntrinsicNode( 15070 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 15071 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15072 } 15073 15074 llvm_unreachable("Expected a load or store node here"); 15075 } 15076 15077 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 15078 DAGCombinerInfo &DCI) const { 15079 SelectionDAG &DAG = DCI.DAG; 15080 SDLoc dl(N); 15081 switch (N->getOpcode()) { 15082 default: break; 15083 case ISD::ADD: 15084 return combineADD(N, DCI); 15085 case ISD::SHL: 15086 return combineSHL(N, DCI); 15087 case ISD::SRA: 15088 return combineSRA(N, DCI); 15089 case ISD::SRL: 15090 return combineSRL(N, DCI); 15091 case ISD::MUL: 15092 return combineMUL(N, DCI); 15093 case ISD::FMA: 15094 case PPCISD::FNMSUB: 15095 return combineFMALike(N, DCI); 15096 case PPCISD::SHL: 15097 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 15098 return N->getOperand(0); 15099 break; 15100 case PPCISD::SRL: 15101 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 15102 return N->getOperand(0); 15103 break; 15104 case PPCISD::SRA: 15105 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 15106 if (C->isZero() || // 0 >>s V -> 0. 15107 C->isAllOnes()) // -1 >>s V -> -1. 15108 return N->getOperand(0); 15109 } 15110 break; 15111 case ISD::SIGN_EXTEND: 15112 case ISD::ZERO_EXTEND: 15113 case ISD::ANY_EXTEND: 15114 return DAGCombineExtBoolTrunc(N, DCI); 15115 case ISD::TRUNCATE: 15116 return combineTRUNCATE(N, DCI); 15117 case ISD::SETCC: 15118 if (SDValue CSCC = combineSetCC(N, DCI)) 15119 return CSCC; 15120 LLVM_FALLTHROUGH; 15121 case ISD::SELECT_CC: 15122 return DAGCombineTruncBoolExt(N, DCI); 15123 case ISD::SINT_TO_FP: 15124 case ISD::UINT_TO_FP: 15125 return combineFPToIntToFP(N, DCI); 15126 case ISD::VECTOR_SHUFFLE: 15127 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 15128 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 15129 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 15130 } 15131 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 15132 case ISD::STORE: { 15133 15134 EVT Op1VT = N->getOperand(1).getValueType(); 15135 unsigned Opcode = N->getOperand(1).getOpcode(); 15136 15137 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 15138 SDValue Val= combineStoreFPToInt(N, DCI); 15139 if (Val) 15140 return Val; 15141 } 15142 15143 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 15144 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 15145 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 15146 if (Val) 15147 return Val; 15148 } 15149 15150 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 15151 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 15152 N->getOperand(1).getNode()->hasOneUse() && 15153 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 15154 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 15155 15156 // STBRX can only handle simple types and it makes no sense to store less 15157 // two bytes in byte-reversed order. 15158 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 15159 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 15160 break; 15161 15162 SDValue BSwapOp = N->getOperand(1).getOperand(0); 15163 // Do an any-extend to 32-bits if this is a half-word input. 15164 if (BSwapOp.getValueType() == MVT::i16) 15165 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 15166 15167 // If the type of BSWAP operand is wider than stored memory width 15168 // it need to be shifted to the right side before STBRX. 15169 if (Op1VT.bitsGT(mVT)) { 15170 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 15171 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 15172 DAG.getConstant(Shift, dl, MVT::i32)); 15173 // Need to truncate if this is a bswap of i64 stored as i32/i16. 15174 if (Op1VT == MVT::i64) 15175 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 15176 } 15177 15178 SDValue Ops[] = { 15179 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 15180 }; 15181 return 15182 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 15183 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 15184 cast<StoreSDNode>(N)->getMemOperand()); 15185 } 15186 15187 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 15188 // So it can increase the chance of CSE constant construction. 15189 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 15190 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 15191 // Need to sign-extended to 64-bits to handle negative values. 15192 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 15193 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 15194 MemVT.getSizeInBits()); 15195 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 15196 15197 // DAG.getTruncStore() can't be used here because it doesn't accept 15198 // the general (base + offset) addressing mode. 15199 // So we use UpdateNodeOperands and setTruncatingStore instead. 15200 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 15201 N->getOperand(3)); 15202 cast<StoreSDNode>(N)->setTruncatingStore(true); 15203 return SDValue(N, 0); 15204 } 15205 15206 // For little endian, VSX stores require generating xxswapd/lxvd2x. 15207 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15208 if (Op1VT.isSimple()) { 15209 MVT StoreVT = Op1VT.getSimpleVT(); 15210 if (Subtarget.needsSwapsForVSXMemOps() && 15211 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 15212 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 15213 return expandVSXStoreForLE(N, DCI); 15214 } 15215 break; 15216 } 15217 case ISD::LOAD: { 15218 LoadSDNode *LD = cast<LoadSDNode>(N); 15219 EVT VT = LD->getValueType(0); 15220 15221 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15222 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15223 if (VT.isSimple()) { 15224 MVT LoadVT = VT.getSimpleVT(); 15225 if (Subtarget.needsSwapsForVSXMemOps() && 15226 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 15227 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 15228 return expandVSXLoadForLE(N, DCI); 15229 } 15230 15231 // We sometimes end up with a 64-bit integer load, from which we extract 15232 // two single-precision floating-point numbers. This happens with 15233 // std::complex<float>, and other similar structures, because of the way we 15234 // canonicalize structure copies. However, if we lack direct moves, 15235 // then the final bitcasts from the extracted integer values to the 15236 // floating-point numbers turn into store/load pairs. Even with direct moves, 15237 // just loading the two floating-point numbers is likely better. 15238 auto ReplaceTwoFloatLoad = [&]() { 15239 if (VT != MVT::i64) 15240 return false; 15241 15242 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 15243 LD->isVolatile()) 15244 return false; 15245 15246 // We're looking for a sequence like this: 15247 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 15248 // t16: i64 = srl t13, Constant:i32<32> 15249 // t17: i32 = truncate t16 15250 // t18: f32 = bitcast t17 15251 // t19: i32 = truncate t13 15252 // t20: f32 = bitcast t19 15253 15254 if (!LD->hasNUsesOfValue(2, 0)) 15255 return false; 15256 15257 auto UI = LD->use_begin(); 15258 while (UI.getUse().getResNo() != 0) ++UI; 15259 SDNode *Trunc = *UI++; 15260 while (UI.getUse().getResNo() != 0) ++UI; 15261 SDNode *RightShift = *UI; 15262 if (Trunc->getOpcode() != ISD::TRUNCATE) 15263 std::swap(Trunc, RightShift); 15264 15265 if (Trunc->getOpcode() != ISD::TRUNCATE || 15266 Trunc->getValueType(0) != MVT::i32 || 15267 !Trunc->hasOneUse()) 15268 return false; 15269 if (RightShift->getOpcode() != ISD::SRL || 15270 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 15271 RightShift->getConstantOperandVal(1) != 32 || 15272 !RightShift->hasOneUse()) 15273 return false; 15274 15275 SDNode *Trunc2 = *RightShift->use_begin(); 15276 if (Trunc2->getOpcode() != ISD::TRUNCATE || 15277 Trunc2->getValueType(0) != MVT::i32 || 15278 !Trunc2->hasOneUse()) 15279 return false; 15280 15281 SDNode *Bitcast = *Trunc->use_begin(); 15282 SDNode *Bitcast2 = *Trunc2->use_begin(); 15283 15284 if (Bitcast->getOpcode() != ISD::BITCAST || 15285 Bitcast->getValueType(0) != MVT::f32) 15286 return false; 15287 if (Bitcast2->getOpcode() != ISD::BITCAST || 15288 Bitcast2->getValueType(0) != MVT::f32) 15289 return false; 15290 15291 if (Subtarget.isLittleEndian()) 15292 std::swap(Bitcast, Bitcast2); 15293 15294 // Bitcast has the second float (in memory-layout order) and Bitcast2 15295 // has the first one. 15296 15297 SDValue BasePtr = LD->getBasePtr(); 15298 if (LD->isIndexed()) { 15299 assert(LD->getAddressingMode() == ISD::PRE_INC && 15300 "Non-pre-inc AM on PPC?"); 15301 BasePtr = 15302 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15303 LD->getOffset()); 15304 } 15305 15306 auto MMOFlags = 15307 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 15308 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 15309 LD->getPointerInfo(), LD->getAlignment(), 15310 MMOFlags, LD->getAAInfo()); 15311 SDValue AddPtr = 15312 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 15313 BasePtr, DAG.getIntPtrConstant(4, dl)); 15314 SDValue FloatLoad2 = DAG.getLoad( 15315 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 15316 LD->getPointerInfo().getWithOffset(4), 15317 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 15318 15319 if (LD->isIndexed()) { 15320 // Note that DAGCombine should re-form any pre-increment load(s) from 15321 // what is produced here if that makes sense. 15322 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 15323 } 15324 15325 DCI.CombineTo(Bitcast2, FloatLoad); 15326 DCI.CombineTo(Bitcast, FloatLoad2); 15327 15328 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 15329 SDValue(FloatLoad2.getNode(), 1)); 15330 return true; 15331 }; 15332 15333 if (ReplaceTwoFloatLoad()) 15334 return SDValue(N, 0); 15335 15336 EVT MemVT = LD->getMemoryVT(); 15337 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 15338 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 15339 if (LD->isUnindexed() && VT.isVector() && 15340 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 15341 // P8 and later hardware should just use LOAD. 15342 !Subtarget.hasP8Vector() && 15343 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 15344 VT == MVT::v4f32))) && 15345 LD->getAlign() < ABIAlignment) { 15346 // This is a type-legal unaligned Altivec load. 15347 SDValue Chain = LD->getChain(); 15348 SDValue Ptr = LD->getBasePtr(); 15349 bool isLittleEndian = Subtarget.isLittleEndian(); 15350 15351 // This implements the loading of unaligned vectors as described in 15352 // the venerable Apple Velocity Engine overview. Specifically: 15353 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 15354 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 15355 // 15356 // The general idea is to expand a sequence of one or more unaligned 15357 // loads into an alignment-based permutation-control instruction (lvsl 15358 // or lvsr), a series of regular vector loads (which always truncate 15359 // their input address to an aligned address), and a series of 15360 // permutations. The results of these permutations are the requested 15361 // loaded values. The trick is that the last "extra" load is not taken 15362 // from the address you might suspect (sizeof(vector) bytes after the 15363 // last requested load), but rather sizeof(vector) - 1 bytes after the 15364 // last requested vector. The point of this is to avoid a page fault if 15365 // the base address happened to be aligned. This works because if the 15366 // base address is aligned, then adding less than a full vector length 15367 // will cause the last vector in the sequence to be (re)loaded. 15368 // Otherwise, the next vector will be fetched as you might suspect was 15369 // necessary. 15370 15371 // We might be able to reuse the permutation generation from 15372 // a different base address offset from this one by an aligned amount. 15373 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 15374 // optimization later. 15375 Intrinsic::ID Intr, IntrLD, IntrPerm; 15376 MVT PermCntlTy, PermTy, LDTy; 15377 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15378 : Intrinsic::ppc_altivec_lvsl; 15379 IntrLD = Intrinsic::ppc_altivec_lvx; 15380 IntrPerm = Intrinsic::ppc_altivec_vperm; 15381 PermCntlTy = MVT::v16i8; 15382 PermTy = MVT::v4i32; 15383 LDTy = MVT::v4i32; 15384 15385 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 15386 15387 // Create the new MMO for the new base load. It is like the original MMO, 15388 // but represents an area in memory almost twice the vector size centered 15389 // on the original address. If the address is unaligned, we might start 15390 // reading up to (sizeof(vector)-1) bytes below the address of the 15391 // original unaligned load. 15392 MachineFunction &MF = DAG.getMachineFunction(); 15393 MachineMemOperand *BaseMMO = 15394 MF.getMachineMemOperand(LD->getMemOperand(), 15395 -(long)MemVT.getStoreSize()+1, 15396 2*MemVT.getStoreSize()-1); 15397 15398 // Create the new base load. 15399 SDValue LDXIntID = 15400 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 15401 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 15402 SDValue BaseLoad = 15403 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15404 DAG.getVTList(PermTy, MVT::Other), 15405 BaseLoadOps, LDTy, BaseMMO); 15406 15407 // Note that the value of IncOffset (which is provided to the next 15408 // load's pointer info offset value, and thus used to calculate the 15409 // alignment), and the value of IncValue (which is actually used to 15410 // increment the pointer value) are different! This is because we 15411 // require the next load to appear to be aligned, even though it 15412 // is actually offset from the base pointer by a lesser amount. 15413 int IncOffset = VT.getSizeInBits() / 8; 15414 int IncValue = IncOffset; 15415 15416 // Walk (both up and down) the chain looking for another load at the real 15417 // (aligned) offset (the alignment of the other load does not matter in 15418 // this case). If found, then do not use the offset reduction trick, as 15419 // that will prevent the loads from being later combined (as they would 15420 // otherwise be duplicates). 15421 if (!findConsecutiveLoad(LD, DAG)) 15422 --IncValue; 15423 15424 SDValue Increment = 15425 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15426 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15427 15428 MachineMemOperand *ExtraMMO = 15429 MF.getMachineMemOperand(LD->getMemOperand(), 15430 1, 2*MemVT.getStoreSize()-1); 15431 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15432 SDValue ExtraLoad = 15433 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15434 DAG.getVTList(PermTy, MVT::Other), 15435 ExtraLoadOps, LDTy, ExtraMMO); 15436 15437 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15438 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15439 15440 // Because vperm has a big-endian bias, we must reverse the order 15441 // of the input vectors and complement the permute control vector 15442 // when generating little endian code. We have already handled the 15443 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15444 // and ExtraLoad here. 15445 SDValue Perm; 15446 if (isLittleEndian) 15447 Perm = BuildIntrinsicOp(IntrPerm, 15448 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15449 else 15450 Perm = BuildIntrinsicOp(IntrPerm, 15451 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15452 15453 if (VT != PermTy) 15454 Perm = Subtarget.hasAltivec() 15455 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15456 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15457 DAG.getTargetConstant(1, dl, MVT::i64)); 15458 // second argument is 1 because this rounding 15459 // is always exact. 15460 15461 // The output of the permutation is our loaded result, the TokenFactor is 15462 // our new chain. 15463 DCI.CombineTo(N, Perm, TF); 15464 return SDValue(N, 0); 15465 } 15466 } 15467 break; 15468 case ISD::INTRINSIC_WO_CHAIN: { 15469 bool isLittleEndian = Subtarget.isLittleEndian(); 15470 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15471 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15472 : Intrinsic::ppc_altivec_lvsl); 15473 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15474 SDValue Add = N->getOperand(1); 15475 15476 int Bits = 4 /* 16 byte alignment */; 15477 15478 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15479 APInt::getAllOnes(Bits /* alignment */) 15480 .zext(Add.getScalarValueSizeInBits()))) { 15481 SDNode *BasePtr = Add->getOperand(0).getNode(); 15482 for (SDNode *U : BasePtr->uses()) { 15483 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15484 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) { 15485 // We've found another LVSL/LVSR, and this address is an aligned 15486 // multiple of that one. The results will be the same, so use the 15487 // one we've just found instead. 15488 15489 return SDValue(U, 0); 15490 } 15491 } 15492 } 15493 15494 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15495 SDNode *BasePtr = Add->getOperand(0).getNode(); 15496 for (SDNode *U : BasePtr->uses()) { 15497 if (U->getOpcode() == ISD::ADD && 15498 isa<ConstantSDNode>(U->getOperand(1)) && 15499 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15500 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) % 15501 (1ULL << Bits) == 15502 0) { 15503 SDNode *OtherAdd = U; 15504 for (SDNode *V : OtherAdd->uses()) { 15505 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15506 cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() == 15507 IID) { 15508 return SDValue(V, 0); 15509 } 15510 } 15511 } 15512 } 15513 } 15514 } 15515 15516 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15517 // Expose the vabsduw/h/b opportunity for down stream 15518 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15519 (IID == Intrinsic::ppc_altivec_vmaxsw || 15520 IID == Intrinsic::ppc_altivec_vmaxsh || 15521 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15522 SDValue V1 = N->getOperand(1); 15523 SDValue V2 = N->getOperand(2); 15524 if ((V1.getSimpleValueType() == MVT::v4i32 || 15525 V1.getSimpleValueType() == MVT::v8i16 || 15526 V1.getSimpleValueType() == MVT::v16i8) && 15527 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15528 // (0-a, a) 15529 if (V1.getOpcode() == ISD::SUB && 15530 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15531 V1.getOperand(1) == V2) { 15532 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15533 } 15534 // (a, 0-a) 15535 if (V2.getOpcode() == ISD::SUB && 15536 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15537 V2.getOperand(1) == V1) { 15538 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15539 } 15540 // (x-y, y-x) 15541 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15542 V1.getOperand(0) == V2.getOperand(1) && 15543 V1.getOperand(1) == V2.getOperand(0)) { 15544 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15545 } 15546 } 15547 } 15548 } 15549 15550 break; 15551 case ISD::INTRINSIC_W_CHAIN: 15552 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15553 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15554 if (Subtarget.needsSwapsForVSXMemOps()) { 15555 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15556 default: 15557 break; 15558 case Intrinsic::ppc_vsx_lxvw4x: 15559 case Intrinsic::ppc_vsx_lxvd2x: 15560 return expandVSXLoadForLE(N, DCI); 15561 } 15562 } 15563 break; 15564 case ISD::INTRINSIC_VOID: 15565 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15566 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15567 if (Subtarget.needsSwapsForVSXMemOps()) { 15568 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15569 default: 15570 break; 15571 case Intrinsic::ppc_vsx_stxvw4x: 15572 case Intrinsic::ppc_vsx_stxvd2x: 15573 return expandVSXStoreForLE(N, DCI); 15574 } 15575 } 15576 break; 15577 case ISD::BSWAP: { 15578 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15579 // For subtargets without LDBRX, we can still do better than the default 15580 // expansion even for 64-bit BSWAP (LOAD). 15581 bool Is64BitBswapOn64BitTgt = 15582 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64; 15583 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) && 15584 N->getOperand(0).hasOneUse(); 15585 if (IsSingleUseNormalLd && 15586 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15587 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) { 15588 SDValue Load = N->getOperand(0); 15589 LoadSDNode *LD = cast<LoadSDNode>(Load); 15590 // Create the byte-swapping load. 15591 SDValue Ops[] = { 15592 LD->getChain(), // Chain 15593 LD->getBasePtr(), // Ptr 15594 DAG.getValueType(N->getValueType(0)) // VT 15595 }; 15596 SDValue BSLoad = 15597 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15598 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15599 MVT::i64 : MVT::i32, MVT::Other), 15600 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15601 15602 // If this is an i16 load, insert the truncate. 15603 SDValue ResVal = BSLoad; 15604 if (N->getValueType(0) == MVT::i16) 15605 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15606 15607 // First, combine the bswap away. This makes the value produced by the 15608 // load dead. 15609 DCI.CombineTo(N, ResVal); 15610 15611 // Next, combine the load away, we give it a bogus result value but a real 15612 // chain result. The result value is dead because the bswap is dead. 15613 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15614 15615 // Return N so it doesn't get rechecked! 15616 return SDValue(N, 0); 15617 } 15618 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only 15619 // before legalization so that the BUILD_PAIR is handled correctly. 15620 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt || 15621 !IsSingleUseNormalLd) 15622 return SDValue(); 15623 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0)); 15624 15625 // Can't split volatile or atomic loads. 15626 if (!LD->isSimple()) 15627 return SDValue(); 15628 SDValue BasePtr = LD->getBasePtr(); 15629 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, 15630 LD->getPointerInfo(), LD->getAlignment()); 15631 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo); 15632 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15633 DAG.getIntPtrConstant(4, dl)); 15634 MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand( 15635 LD->getMemOperand(), 4, 4); 15636 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO); 15637 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi); 15638 SDValue Res; 15639 if (Subtarget.isLittleEndian()) 15640 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo); 15641 else 15642 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 15643 SDValue TF = 15644 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15645 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1)); 15646 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF); 15647 return Res; 15648 } 15649 case PPCISD::VCMP: 15650 // If a VCMP_rec node already exists with exactly the same operands as this 15651 // node, use its result instead of this node (VCMP_rec computes both a CR6 15652 // and a normal output). 15653 // 15654 if (!N->getOperand(0).hasOneUse() && 15655 !N->getOperand(1).hasOneUse() && 15656 !N->getOperand(2).hasOneUse()) { 15657 15658 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15659 SDNode *VCMPrecNode = nullptr; 15660 15661 SDNode *LHSN = N->getOperand(0).getNode(); 15662 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15663 UI != E; ++UI) 15664 if (UI->getOpcode() == PPCISD::VCMP_rec && 15665 UI->getOperand(1) == N->getOperand(1) && 15666 UI->getOperand(2) == N->getOperand(2) && 15667 UI->getOperand(0) == N->getOperand(0)) { 15668 VCMPrecNode = *UI; 15669 break; 15670 } 15671 15672 // If there is no VCMP_rec node, or if the flag value has a single use, 15673 // don't transform this. 15674 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15675 break; 15676 15677 // Look at the (necessarily single) use of the flag value. If it has a 15678 // chain, this transformation is more complex. Note that multiple things 15679 // could use the value result, which we should ignore. 15680 SDNode *FlagUser = nullptr; 15681 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15682 FlagUser == nullptr; ++UI) { 15683 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15684 SDNode *User = *UI; 15685 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15686 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15687 FlagUser = User; 15688 break; 15689 } 15690 } 15691 } 15692 15693 // If the user is a MFOCRF instruction, we know this is safe. 15694 // Otherwise we give up for right now. 15695 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15696 return SDValue(VCMPrecNode, 0); 15697 } 15698 break; 15699 case ISD::BRCOND: { 15700 SDValue Cond = N->getOperand(1); 15701 SDValue Target = N->getOperand(2); 15702 15703 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15704 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15705 Intrinsic::loop_decrement) { 15706 15707 // We now need to make the intrinsic dead (it cannot be instruction 15708 // selected). 15709 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15710 assert(Cond.getNode()->hasOneUse() && 15711 "Counter decrement has more than one use"); 15712 15713 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15714 N->getOperand(0), Target); 15715 } 15716 } 15717 break; 15718 case ISD::BR_CC: { 15719 // If this is a branch on an altivec predicate comparison, lower this so 15720 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15721 // lowering is done pre-legalize, because the legalizer lowers the predicate 15722 // compare down to code that is difficult to reassemble. 15723 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15724 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15725 15726 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15727 // value. If so, pass-through the AND to get to the intrinsic. 15728 if (LHS.getOpcode() == ISD::AND && 15729 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15730 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15731 Intrinsic::loop_decrement && 15732 isa<ConstantSDNode>(LHS.getOperand(1)) && 15733 !isNullConstant(LHS.getOperand(1))) 15734 LHS = LHS.getOperand(0); 15735 15736 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15737 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15738 Intrinsic::loop_decrement && 15739 isa<ConstantSDNode>(RHS)) { 15740 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15741 "Counter decrement comparison is not EQ or NE"); 15742 15743 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15744 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15745 (CC == ISD::SETNE && !Val); 15746 15747 // We now need to make the intrinsic dead (it cannot be instruction 15748 // selected). 15749 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15750 assert(LHS.getNode()->hasOneUse() && 15751 "Counter decrement has more than one use"); 15752 15753 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15754 N->getOperand(0), N->getOperand(4)); 15755 } 15756 15757 int CompareOpc; 15758 bool isDot; 15759 15760 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15761 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15762 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15763 assert(isDot && "Can't compare against a vector result!"); 15764 15765 // If this is a comparison against something other than 0/1, then we know 15766 // that the condition is never/always true. 15767 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15768 if (Val != 0 && Val != 1) { 15769 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15770 return N->getOperand(0); 15771 // Always !=, turn it into an unconditional branch. 15772 return DAG.getNode(ISD::BR, dl, MVT::Other, 15773 N->getOperand(0), N->getOperand(4)); 15774 } 15775 15776 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15777 15778 // Create the PPCISD altivec 'dot' comparison node. 15779 SDValue Ops[] = { 15780 LHS.getOperand(2), // LHS of compare 15781 LHS.getOperand(3), // RHS of compare 15782 DAG.getConstant(CompareOpc, dl, MVT::i32) 15783 }; 15784 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15785 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15786 15787 // Unpack the result based on how the target uses it. 15788 PPC::Predicate CompOpc; 15789 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15790 default: // Can't happen, don't crash on invalid number though. 15791 case 0: // Branch on the value of the EQ bit of CR6. 15792 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15793 break; 15794 case 1: // Branch on the inverted value of the EQ bit of CR6. 15795 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15796 break; 15797 case 2: // Branch on the value of the LT bit of CR6. 15798 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15799 break; 15800 case 3: // Branch on the inverted value of the LT bit of CR6. 15801 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15802 break; 15803 } 15804 15805 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15806 DAG.getConstant(CompOpc, dl, MVT::i32), 15807 DAG.getRegister(PPC::CR6, MVT::i32), 15808 N->getOperand(4), CompNode.getValue(1)); 15809 } 15810 break; 15811 } 15812 case ISD::BUILD_VECTOR: 15813 return DAGCombineBuildVector(N, DCI); 15814 case ISD::ABS: 15815 return combineABS(N, DCI); 15816 case ISD::VSELECT: 15817 return combineVSelect(N, DCI); 15818 } 15819 15820 return SDValue(); 15821 } 15822 15823 SDValue 15824 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15825 SelectionDAG &DAG, 15826 SmallVectorImpl<SDNode *> &Created) const { 15827 // fold (sdiv X, pow2) 15828 EVT VT = N->getValueType(0); 15829 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15830 return SDValue(); 15831 if ((VT != MVT::i32 && VT != MVT::i64) || 15832 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2())) 15833 return SDValue(); 15834 15835 SDLoc DL(N); 15836 SDValue N0 = N->getOperand(0); 15837 15838 bool IsNegPow2 = Divisor.isNegatedPowerOf2(); 15839 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15840 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15841 15842 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15843 Created.push_back(Op.getNode()); 15844 15845 if (IsNegPow2) { 15846 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15847 Created.push_back(Op.getNode()); 15848 } 15849 15850 return Op; 15851 } 15852 15853 //===----------------------------------------------------------------------===// 15854 // Inline Assembly Support 15855 //===----------------------------------------------------------------------===// 15856 15857 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15858 KnownBits &Known, 15859 const APInt &DemandedElts, 15860 const SelectionDAG &DAG, 15861 unsigned Depth) const { 15862 Known.resetAll(); 15863 switch (Op.getOpcode()) { 15864 default: break; 15865 case PPCISD::LBRX: { 15866 // lhbrx is known to have the top bits cleared out. 15867 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15868 Known.Zero = 0xFFFF0000; 15869 break; 15870 } 15871 case ISD::INTRINSIC_WO_CHAIN: { 15872 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15873 default: break; 15874 case Intrinsic::ppc_altivec_vcmpbfp_p: 15875 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15876 case Intrinsic::ppc_altivec_vcmpequb_p: 15877 case Intrinsic::ppc_altivec_vcmpequh_p: 15878 case Intrinsic::ppc_altivec_vcmpequw_p: 15879 case Intrinsic::ppc_altivec_vcmpequd_p: 15880 case Intrinsic::ppc_altivec_vcmpequq_p: 15881 case Intrinsic::ppc_altivec_vcmpgefp_p: 15882 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15883 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15884 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15885 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15886 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15887 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15888 case Intrinsic::ppc_altivec_vcmpgtub_p: 15889 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15890 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15891 case Intrinsic::ppc_altivec_vcmpgtud_p: 15892 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15893 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15894 break; 15895 } 15896 break; 15897 } 15898 case ISD::INTRINSIC_W_CHAIN: { 15899 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 15900 default: 15901 break; 15902 case Intrinsic::ppc_load2r: 15903 // Top bits are cleared for load2r (which is the same as lhbrx). 15904 Known.Zero = 0xFFFF0000; 15905 break; 15906 } 15907 break; 15908 } 15909 } 15910 } 15911 15912 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15913 switch (Subtarget.getCPUDirective()) { 15914 default: break; 15915 case PPC::DIR_970: 15916 case PPC::DIR_PWR4: 15917 case PPC::DIR_PWR5: 15918 case PPC::DIR_PWR5X: 15919 case PPC::DIR_PWR6: 15920 case PPC::DIR_PWR6X: 15921 case PPC::DIR_PWR7: 15922 case PPC::DIR_PWR8: 15923 case PPC::DIR_PWR9: 15924 case PPC::DIR_PWR10: 15925 case PPC::DIR_PWR_FUTURE: { 15926 if (!ML) 15927 break; 15928 15929 if (!DisableInnermostLoopAlign32) { 15930 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15931 // so that we can decrease cache misses and branch-prediction misses. 15932 // Actual alignment of the loop will depend on the hotness check and other 15933 // logic in alignBlocks. 15934 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15935 return Align(32); 15936 } 15937 15938 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15939 15940 // For small loops (between 5 and 8 instructions), align to a 32-byte 15941 // boundary so that the entire loop fits in one instruction-cache line. 15942 uint64_t LoopSize = 0; 15943 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15944 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15945 LoopSize += TII->getInstSizeInBytes(*J); 15946 if (LoopSize > 32) 15947 break; 15948 } 15949 15950 if (LoopSize > 16 && LoopSize <= 32) 15951 return Align(32); 15952 15953 break; 15954 } 15955 } 15956 15957 return TargetLowering::getPrefLoopAlignment(ML); 15958 } 15959 15960 /// getConstraintType - Given a constraint, return the type of 15961 /// constraint it is for this target. 15962 PPCTargetLowering::ConstraintType 15963 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15964 if (Constraint.size() == 1) { 15965 switch (Constraint[0]) { 15966 default: break; 15967 case 'b': 15968 case 'r': 15969 case 'f': 15970 case 'd': 15971 case 'v': 15972 case 'y': 15973 return C_RegisterClass; 15974 case 'Z': 15975 // FIXME: While Z does indicate a memory constraint, it specifically 15976 // indicates an r+r address (used in conjunction with the 'y' modifier 15977 // in the replacement string). Currently, we're forcing the base 15978 // register to be r0 in the asm printer (which is interpreted as zero) 15979 // and forming the complete address in the second register. This is 15980 // suboptimal. 15981 return C_Memory; 15982 } 15983 } else if (Constraint == "wc") { // individual CR bits. 15984 return C_RegisterClass; 15985 } else if (Constraint == "wa" || Constraint == "wd" || 15986 Constraint == "wf" || Constraint == "ws" || 15987 Constraint == "wi" || Constraint == "ww") { 15988 return C_RegisterClass; // VSX registers. 15989 } 15990 return TargetLowering::getConstraintType(Constraint); 15991 } 15992 15993 /// Examine constraint type and operand type and determine a weight value. 15994 /// This object must already have been set up with the operand type 15995 /// and the current alternative constraint selected. 15996 TargetLowering::ConstraintWeight 15997 PPCTargetLowering::getSingleConstraintMatchWeight( 15998 AsmOperandInfo &info, const char *constraint) const { 15999 ConstraintWeight weight = CW_Invalid; 16000 Value *CallOperandVal = info.CallOperandVal; 16001 // If we don't have a value, we can't do a match, 16002 // but allow it at the lowest weight. 16003 if (!CallOperandVal) 16004 return CW_Default; 16005 Type *type = CallOperandVal->getType(); 16006 16007 // Look at the constraint type. 16008 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 16009 return CW_Register; // an individual CR bit. 16010 else if ((StringRef(constraint) == "wa" || 16011 StringRef(constraint) == "wd" || 16012 StringRef(constraint) == "wf") && 16013 type->isVectorTy()) 16014 return CW_Register; 16015 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 16016 return CW_Register; // just hold 64-bit integers data. 16017 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 16018 return CW_Register; 16019 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 16020 return CW_Register; 16021 16022 switch (*constraint) { 16023 default: 16024 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 16025 break; 16026 case 'b': 16027 if (type->isIntegerTy()) 16028 weight = CW_Register; 16029 break; 16030 case 'f': 16031 if (type->isFloatTy()) 16032 weight = CW_Register; 16033 break; 16034 case 'd': 16035 if (type->isDoubleTy()) 16036 weight = CW_Register; 16037 break; 16038 case 'v': 16039 if (type->isVectorTy()) 16040 weight = CW_Register; 16041 break; 16042 case 'y': 16043 weight = CW_Register; 16044 break; 16045 case 'Z': 16046 weight = CW_Memory; 16047 break; 16048 } 16049 return weight; 16050 } 16051 16052 std::pair<unsigned, const TargetRegisterClass *> 16053 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 16054 StringRef Constraint, 16055 MVT VT) const { 16056 if (Constraint.size() == 1) { 16057 // GCC RS6000 Constraint Letters 16058 switch (Constraint[0]) { 16059 case 'b': // R1-R31 16060 if (VT == MVT::i64 && Subtarget.isPPC64()) 16061 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 16062 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 16063 case 'r': // R0-R31 16064 if (VT == MVT::i64 && Subtarget.isPPC64()) 16065 return std::make_pair(0U, &PPC::G8RCRegClass); 16066 return std::make_pair(0U, &PPC::GPRCRegClass); 16067 // 'd' and 'f' constraints are both defined to be "the floating point 16068 // registers", where one is for 32-bit and the other for 64-bit. We don't 16069 // really care overly much here so just give them all the same reg classes. 16070 case 'd': 16071 case 'f': 16072 if (Subtarget.hasSPE()) { 16073 if (VT == MVT::f32 || VT == MVT::i32) 16074 return std::make_pair(0U, &PPC::GPRCRegClass); 16075 if (VT == MVT::f64 || VT == MVT::i64) 16076 return std::make_pair(0U, &PPC::SPERCRegClass); 16077 } else { 16078 if (VT == MVT::f32 || VT == MVT::i32) 16079 return std::make_pair(0U, &PPC::F4RCRegClass); 16080 if (VT == MVT::f64 || VT == MVT::i64) 16081 return std::make_pair(0U, &PPC::F8RCRegClass); 16082 } 16083 break; 16084 case 'v': 16085 if (Subtarget.hasAltivec() && VT.isVector()) 16086 return std::make_pair(0U, &PPC::VRRCRegClass); 16087 else if (Subtarget.hasVSX()) 16088 // Scalars in Altivec registers only make sense with VSX. 16089 return std::make_pair(0U, &PPC::VFRCRegClass); 16090 break; 16091 case 'y': // crrc 16092 return std::make_pair(0U, &PPC::CRRCRegClass); 16093 } 16094 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 16095 // An individual CR bit. 16096 return std::make_pair(0U, &PPC::CRBITRCRegClass); 16097 } else if ((Constraint == "wa" || Constraint == "wd" || 16098 Constraint == "wf" || Constraint == "wi") && 16099 Subtarget.hasVSX()) { 16100 // A VSX register for either a scalar (FP) or vector. There is no 16101 // support for single precision scalars on subtargets prior to Power8. 16102 if (VT.isVector()) 16103 return std::make_pair(0U, &PPC::VSRCRegClass); 16104 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16105 return std::make_pair(0U, &PPC::VSSRCRegClass); 16106 return std::make_pair(0U, &PPC::VSFRCRegClass); 16107 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 16108 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16109 return std::make_pair(0U, &PPC::VSSRCRegClass); 16110 else 16111 return std::make_pair(0U, &PPC::VSFRCRegClass); 16112 } else if (Constraint == "lr") { 16113 if (VT == MVT::i64) 16114 return std::make_pair(0U, &PPC::LR8RCRegClass); 16115 else 16116 return std::make_pair(0U, &PPC::LRRCRegClass); 16117 } 16118 16119 // Handle special cases of physical registers that are not properly handled 16120 // by the base class. 16121 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 16122 // If we name a VSX register, we can't defer to the base class because it 16123 // will not recognize the correct register (their names will be VSL{0-31} 16124 // and V{0-31} so they won't match). So we match them here. 16125 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 16126 int VSNum = atoi(Constraint.data() + 3); 16127 assert(VSNum >= 0 && VSNum <= 63 && 16128 "Attempted to access a vsr out of range"); 16129 if (VSNum < 32) 16130 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 16131 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 16132 } 16133 16134 // For float registers, we can't defer to the base class as it will match 16135 // the SPILLTOVSRRC class. 16136 if (Constraint.size() > 3 && Constraint[1] == 'f') { 16137 int RegNum = atoi(Constraint.data() + 2); 16138 if (RegNum > 31 || RegNum < 0) 16139 report_fatal_error("Invalid floating point register number"); 16140 if (VT == MVT::f32 || VT == MVT::i32) 16141 return Subtarget.hasSPE() 16142 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 16143 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 16144 if (VT == MVT::f64 || VT == MVT::i64) 16145 return Subtarget.hasSPE() 16146 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 16147 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 16148 } 16149 } 16150 16151 std::pair<unsigned, const TargetRegisterClass *> R = 16152 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 16153 16154 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 16155 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 16156 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 16157 // register. 16158 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 16159 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 16160 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 16161 PPC::GPRCRegClass.contains(R.first)) 16162 return std::make_pair(TRI->getMatchingSuperReg(R.first, 16163 PPC::sub_32, &PPC::G8RCRegClass), 16164 &PPC::G8RCRegClass); 16165 16166 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 16167 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) { 16168 R.first = PPC::CR0; 16169 R.second = &PPC::CRRCRegClass; 16170 } 16171 // FIXME: This warning should ideally be emitted in the front end. 16172 const auto &TM = getTargetMachine(); 16173 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 16174 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 16175 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 16176 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 16177 errs() << "warning: vector registers 20 to 32 are reserved in the " 16178 "default AIX AltiVec ABI and cannot be used\n"; 16179 } 16180 16181 return R; 16182 } 16183 16184 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16185 /// vector. If it is invalid, don't add anything to Ops. 16186 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16187 std::string &Constraint, 16188 std::vector<SDValue>&Ops, 16189 SelectionDAG &DAG) const { 16190 SDValue Result; 16191 16192 // Only support length 1 constraints. 16193 if (Constraint.length() > 1) return; 16194 16195 char Letter = Constraint[0]; 16196 switch (Letter) { 16197 default: break; 16198 case 'I': 16199 case 'J': 16200 case 'K': 16201 case 'L': 16202 case 'M': 16203 case 'N': 16204 case 'O': 16205 case 'P': { 16206 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 16207 if (!CST) return; // Must be an immediate to match. 16208 SDLoc dl(Op); 16209 int64_t Value = CST->getSExtValue(); 16210 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 16211 // numbers are printed as such. 16212 switch (Letter) { 16213 default: llvm_unreachable("Unknown constraint letter!"); 16214 case 'I': // "I" is a signed 16-bit constant. 16215 if (isInt<16>(Value)) 16216 Result = DAG.getTargetConstant(Value, dl, TCVT); 16217 break; 16218 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 16219 if (isShiftedUInt<16, 16>(Value)) 16220 Result = DAG.getTargetConstant(Value, dl, TCVT); 16221 break; 16222 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 16223 if (isShiftedInt<16, 16>(Value)) 16224 Result = DAG.getTargetConstant(Value, dl, TCVT); 16225 break; 16226 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 16227 if (isUInt<16>(Value)) 16228 Result = DAG.getTargetConstant(Value, dl, TCVT); 16229 break; 16230 case 'M': // "M" is a constant that is greater than 31. 16231 if (Value > 31) 16232 Result = DAG.getTargetConstant(Value, dl, TCVT); 16233 break; 16234 case 'N': // "N" is a positive constant that is an exact power of two. 16235 if (Value > 0 && isPowerOf2_64(Value)) 16236 Result = DAG.getTargetConstant(Value, dl, TCVT); 16237 break; 16238 case 'O': // "O" is the constant zero. 16239 if (Value == 0) 16240 Result = DAG.getTargetConstant(Value, dl, TCVT); 16241 break; 16242 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 16243 if (isInt<16>(-Value)) 16244 Result = DAG.getTargetConstant(Value, dl, TCVT); 16245 break; 16246 } 16247 break; 16248 } 16249 } 16250 16251 if (Result.getNode()) { 16252 Ops.push_back(Result); 16253 return; 16254 } 16255 16256 // Handle standard constraint letters. 16257 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16258 } 16259 16260 // isLegalAddressingMode - Return true if the addressing mode represented 16261 // by AM is legal for this target, for a load/store of the specified type. 16262 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16263 const AddrMode &AM, Type *Ty, 16264 unsigned AS, 16265 Instruction *I) const { 16266 // Vector type r+i form is supported since power9 as DQ form. We don't check 16267 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 16268 // imm form is preferred and the offset can be adjusted to use imm form later 16269 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 16270 // max offset to check legal addressing mode, we should be a little aggressive 16271 // to contain other offsets for that LSRUse. 16272 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 16273 return false; 16274 16275 // PPC allows a sign-extended 16-bit immediate field. 16276 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 16277 return false; 16278 16279 // No global is ever allowed as a base. 16280 if (AM.BaseGV) 16281 return false; 16282 16283 // PPC only support r+r, 16284 switch (AM.Scale) { 16285 case 0: // "r+i" or just "i", depending on HasBaseReg. 16286 break; 16287 case 1: 16288 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 16289 return false; 16290 // Otherwise we have r+r or r+i. 16291 break; 16292 case 2: 16293 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 16294 return false; 16295 // Allow 2*r as r+r. 16296 break; 16297 default: 16298 // No other scales are supported. 16299 return false; 16300 } 16301 16302 return true; 16303 } 16304 16305 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 16306 SelectionDAG &DAG) const { 16307 MachineFunction &MF = DAG.getMachineFunction(); 16308 MachineFrameInfo &MFI = MF.getFrameInfo(); 16309 MFI.setReturnAddressIsTaken(true); 16310 16311 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 16312 return SDValue(); 16313 16314 SDLoc dl(Op); 16315 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16316 16317 // Make sure the function does not optimize away the store of the RA to 16318 // the stack. 16319 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 16320 FuncInfo->setLRStoreRequired(); 16321 bool isPPC64 = Subtarget.isPPC64(); 16322 auto PtrVT = getPointerTy(MF.getDataLayout()); 16323 16324 if (Depth > 0) { 16325 // The link register (return address) is saved in the caller's frame 16326 // not the callee's stack frame. So we must get the caller's frame 16327 // address and load the return address at the LR offset from there. 16328 SDValue FrameAddr = 16329 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16330 LowerFRAMEADDR(Op, DAG), MachinePointerInfo()); 16331 SDValue Offset = 16332 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 16333 isPPC64 ? MVT::i64 : MVT::i32); 16334 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 16335 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 16336 MachinePointerInfo()); 16337 } 16338 16339 // Just load the return address off the stack. 16340 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 16341 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 16342 MachinePointerInfo()); 16343 } 16344 16345 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 16346 SelectionDAG &DAG) const { 16347 SDLoc dl(Op); 16348 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16349 16350 MachineFunction &MF = DAG.getMachineFunction(); 16351 MachineFrameInfo &MFI = MF.getFrameInfo(); 16352 MFI.setFrameAddressIsTaken(true); 16353 16354 EVT PtrVT = getPointerTy(MF.getDataLayout()); 16355 bool isPPC64 = PtrVT == MVT::i64; 16356 16357 // Naked functions never have a frame pointer, and so we use r1. For all 16358 // other functions, this decision must be delayed until during PEI. 16359 unsigned FrameReg; 16360 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 16361 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 16362 else 16363 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 16364 16365 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 16366 PtrVT); 16367 while (Depth--) 16368 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16369 FrameAddr, MachinePointerInfo()); 16370 return FrameAddr; 16371 } 16372 16373 // FIXME? Maybe this could be a TableGen attribute on some registers and 16374 // this table could be generated automatically from RegInfo. 16375 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 16376 const MachineFunction &MF) const { 16377 bool isPPC64 = Subtarget.isPPC64(); 16378 16379 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 16380 if (!is64Bit && VT != LLT::scalar(32)) 16381 report_fatal_error("Invalid register global variable type"); 16382 16383 Register Reg = StringSwitch<Register>(RegName) 16384 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 16385 .Case("r2", isPPC64 ? Register() : PPC::R2) 16386 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 16387 .Default(Register()); 16388 16389 if (Reg) 16390 return Reg; 16391 report_fatal_error("Invalid register name global variable"); 16392 } 16393 16394 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 16395 // 32-bit SVR4 ABI access everything as got-indirect. 16396 if (Subtarget.is32BitELFABI()) 16397 return true; 16398 16399 // AIX accesses everything indirectly through the TOC, which is similar to 16400 // the GOT. 16401 if (Subtarget.isAIXABI()) 16402 return true; 16403 16404 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 16405 // If it is small or large code model, module locals are accessed 16406 // indirectly by loading their address from .toc/.got. 16407 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 16408 return true; 16409 16410 // JumpTable and BlockAddress are accessed as got-indirect. 16411 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 16412 return true; 16413 16414 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 16415 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 16416 16417 return false; 16418 } 16419 16420 bool 16421 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16422 // The PowerPC target isn't yet aware of offsets. 16423 return false; 16424 } 16425 16426 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16427 const CallInst &I, 16428 MachineFunction &MF, 16429 unsigned Intrinsic) const { 16430 switch (Intrinsic) { 16431 case Intrinsic::ppc_atomicrmw_xchg_i128: 16432 case Intrinsic::ppc_atomicrmw_add_i128: 16433 case Intrinsic::ppc_atomicrmw_sub_i128: 16434 case Intrinsic::ppc_atomicrmw_nand_i128: 16435 case Intrinsic::ppc_atomicrmw_and_i128: 16436 case Intrinsic::ppc_atomicrmw_or_i128: 16437 case Intrinsic::ppc_atomicrmw_xor_i128: 16438 case Intrinsic::ppc_cmpxchg_i128: 16439 Info.opc = ISD::INTRINSIC_W_CHAIN; 16440 Info.memVT = MVT::i128; 16441 Info.ptrVal = I.getArgOperand(0); 16442 Info.offset = 0; 16443 Info.align = Align(16); 16444 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 16445 MachineMemOperand::MOVolatile; 16446 return true; 16447 case Intrinsic::ppc_atomic_load_i128: 16448 Info.opc = ISD::INTRINSIC_W_CHAIN; 16449 Info.memVT = MVT::i128; 16450 Info.ptrVal = I.getArgOperand(0); 16451 Info.offset = 0; 16452 Info.align = Align(16); 16453 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16454 return true; 16455 case Intrinsic::ppc_atomic_store_i128: 16456 Info.opc = ISD::INTRINSIC_VOID; 16457 Info.memVT = MVT::i128; 16458 Info.ptrVal = I.getArgOperand(2); 16459 Info.offset = 0; 16460 Info.align = Align(16); 16461 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16462 return true; 16463 case Intrinsic::ppc_altivec_lvx: 16464 case Intrinsic::ppc_altivec_lvxl: 16465 case Intrinsic::ppc_altivec_lvebx: 16466 case Intrinsic::ppc_altivec_lvehx: 16467 case Intrinsic::ppc_altivec_lvewx: 16468 case Intrinsic::ppc_vsx_lxvd2x: 16469 case Intrinsic::ppc_vsx_lxvw4x: 16470 case Intrinsic::ppc_vsx_lxvd2x_be: 16471 case Intrinsic::ppc_vsx_lxvw4x_be: 16472 case Intrinsic::ppc_vsx_lxvl: 16473 case Intrinsic::ppc_vsx_lxvll: { 16474 EVT VT; 16475 switch (Intrinsic) { 16476 case Intrinsic::ppc_altivec_lvebx: 16477 VT = MVT::i8; 16478 break; 16479 case Intrinsic::ppc_altivec_lvehx: 16480 VT = MVT::i16; 16481 break; 16482 case Intrinsic::ppc_altivec_lvewx: 16483 VT = MVT::i32; 16484 break; 16485 case Intrinsic::ppc_vsx_lxvd2x: 16486 case Intrinsic::ppc_vsx_lxvd2x_be: 16487 VT = MVT::v2f64; 16488 break; 16489 default: 16490 VT = MVT::v4i32; 16491 break; 16492 } 16493 16494 Info.opc = ISD::INTRINSIC_W_CHAIN; 16495 Info.memVT = VT; 16496 Info.ptrVal = I.getArgOperand(0); 16497 Info.offset = -VT.getStoreSize()+1; 16498 Info.size = 2*VT.getStoreSize()-1; 16499 Info.align = Align(1); 16500 Info.flags = MachineMemOperand::MOLoad; 16501 return true; 16502 } 16503 case Intrinsic::ppc_altivec_stvx: 16504 case Intrinsic::ppc_altivec_stvxl: 16505 case Intrinsic::ppc_altivec_stvebx: 16506 case Intrinsic::ppc_altivec_stvehx: 16507 case Intrinsic::ppc_altivec_stvewx: 16508 case Intrinsic::ppc_vsx_stxvd2x: 16509 case Intrinsic::ppc_vsx_stxvw4x: 16510 case Intrinsic::ppc_vsx_stxvd2x_be: 16511 case Intrinsic::ppc_vsx_stxvw4x_be: 16512 case Intrinsic::ppc_vsx_stxvl: 16513 case Intrinsic::ppc_vsx_stxvll: { 16514 EVT VT; 16515 switch (Intrinsic) { 16516 case Intrinsic::ppc_altivec_stvebx: 16517 VT = MVT::i8; 16518 break; 16519 case Intrinsic::ppc_altivec_stvehx: 16520 VT = MVT::i16; 16521 break; 16522 case Intrinsic::ppc_altivec_stvewx: 16523 VT = MVT::i32; 16524 break; 16525 case Intrinsic::ppc_vsx_stxvd2x: 16526 case Intrinsic::ppc_vsx_stxvd2x_be: 16527 VT = MVT::v2f64; 16528 break; 16529 default: 16530 VT = MVT::v4i32; 16531 break; 16532 } 16533 16534 Info.opc = ISD::INTRINSIC_VOID; 16535 Info.memVT = VT; 16536 Info.ptrVal = I.getArgOperand(1); 16537 Info.offset = -VT.getStoreSize()+1; 16538 Info.size = 2*VT.getStoreSize()-1; 16539 Info.align = Align(1); 16540 Info.flags = MachineMemOperand::MOStore; 16541 return true; 16542 } 16543 default: 16544 break; 16545 } 16546 16547 return false; 16548 } 16549 16550 /// It returns EVT::Other if the type should be determined using generic 16551 /// target-independent logic. 16552 EVT PPCTargetLowering::getOptimalMemOpType( 16553 const MemOp &Op, const AttributeList &FuncAttributes) const { 16554 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16555 // We should use Altivec/VSX loads and stores when available. For unaligned 16556 // addresses, unaligned VSX loads are only fast starting with the P8. 16557 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16558 (Op.isAligned(Align(16)) || 16559 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16560 return MVT::v4i32; 16561 } 16562 16563 if (Subtarget.isPPC64()) { 16564 return MVT::i64; 16565 } 16566 16567 return MVT::i32; 16568 } 16569 16570 /// Returns true if it is beneficial to convert a load of a constant 16571 /// to just the constant itself. 16572 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16573 Type *Ty) const { 16574 assert(Ty->isIntegerTy()); 16575 16576 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16577 return !(BitSize == 0 || BitSize > 64); 16578 } 16579 16580 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16581 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16582 return false; 16583 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16584 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16585 return NumBits1 == 64 && NumBits2 == 32; 16586 } 16587 16588 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16589 if (!VT1.isInteger() || !VT2.isInteger()) 16590 return false; 16591 unsigned NumBits1 = VT1.getSizeInBits(); 16592 unsigned NumBits2 = VT2.getSizeInBits(); 16593 return NumBits1 == 64 && NumBits2 == 32; 16594 } 16595 16596 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16597 // Generally speaking, zexts are not free, but they are free when they can be 16598 // folded with other operations. 16599 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16600 EVT MemVT = LD->getMemoryVT(); 16601 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16602 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16603 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16604 LD->getExtensionType() == ISD::ZEXTLOAD)) 16605 return true; 16606 } 16607 16608 // FIXME: Add other cases... 16609 // - 32-bit shifts with a zext to i64 16610 // - zext after ctlz, bswap, etc. 16611 // - zext after and by a constant mask 16612 16613 return TargetLowering::isZExtFree(Val, VT2); 16614 } 16615 16616 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16617 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16618 "invalid fpext types"); 16619 // Extending to float128 is not free. 16620 if (DestVT == MVT::f128) 16621 return false; 16622 return true; 16623 } 16624 16625 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16626 return isInt<16>(Imm) || isUInt<16>(Imm); 16627 } 16628 16629 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16630 return isInt<16>(Imm) || isUInt<16>(Imm); 16631 } 16632 16633 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 16634 MachineMemOperand::Flags, 16635 bool *Fast) const { 16636 if (DisablePPCUnaligned) 16637 return false; 16638 16639 // PowerPC supports unaligned memory access for simple non-vector types. 16640 // Although accessing unaligned addresses is not as efficient as accessing 16641 // aligned addresses, it is generally more efficient than manual expansion, 16642 // and generally only traps for software emulation when crossing page 16643 // boundaries. 16644 16645 if (!VT.isSimple()) 16646 return false; 16647 16648 if (VT.isFloatingPoint() && !VT.isVector() && 16649 !Subtarget.allowsUnalignedFPAccess()) 16650 return false; 16651 16652 if (VT.getSimpleVT().isVector()) { 16653 if (Subtarget.hasVSX()) { 16654 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16655 VT != MVT::v4f32 && VT != MVT::v4i32) 16656 return false; 16657 } else { 16658 return false; 16659 } 16660 } 16661 16662 if (VT == MVT::ppcf128) 16663 return false; 16664 16665 if (Fast) 16666 *Fast = true; 16667 16668 return true; 16669 } 16670 16671 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16672 SDValue C) const { 16673 // Check integral scalar types. 16674 if (!VT.isScalarInteger()) 16675 return false; 16676 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16677 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16678 return false; 16679 // This transformation will generate >= 2 operations. But the following 16680 // cases will generate <= 2 instructions during ISEL. So exclude them. 16681 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16682 // HW instruction, ie. MULLI 16683 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16684 // instruction is needed than case 1, ie. MULLI and RLDICR 16685 int64_t Imm = ConstNode->getSExtValue(); 16686 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16687 Imm >>= Shift; 16688 if (isInt<16>(Imm)) 16689 return false; 16690 uint64_t UImm = static_cast<uint64_t>(Imm); 16691 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16692 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16693 return true; 16694 } 16695 return false; 16696 } 16697 16698 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16699 EVT VT) const { 16700 return isFMAFasterThanFMulAndFAdd( 16701 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16702 } 16703 16704 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16705 Type *Ty) const { 16706 switch (Ty->getScalarType()->getTypeID()) { 16707 case Type::FloatTyID: 16708 case Type::DoubleTyID: 16709 return true; 16710 case Type::FP128TyID: 16711 return Subtarget.hasP9Vector(); 16712 default: 16713 return false; 16714 } 16715 } 16716 16717 // FIXME: add more patterns which are not profitable to hoist. 16718 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16719 if (!I->hasOneUse()) 16720 return true; 16721 16722 Instruction *User = I->user_back(); 16723 assert(User && "A single use instruction with no uses."); 16724 16725 switch (I->getOpcode()) { 16726 case Instruction::FMul: { 16727 // Don't break FMA, PowerPC prefers FMA. 16728 if (User->getOpcode() != Instruction::FSub && 16729 User->getOpcode() != Instruction::FAdd) 16730 return true; 16731 16732 const TargetOptions &Options = getTargetMachine().Options; 16733 const Function *F = I->getFunction(); 16734 const DataLayout &DL = F->getParent()->getDataLayout(); 16735 Type *Ty = User->getOperand(0)->getType(); 16736 16737 return !( 16738 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16739 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16740 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16741 } 16742 case Instruction::Load: { 16743 // Don't break "store (load float*)" pattern, this pattern will be combined 16744 // to "store (load int32)" in later InstCombine pass. See function 16745 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16746 // cycles than loading a 32 bit integer. 16747 LoadInst *LI = cast<LoadInst>(I); 16748 // For the loads that combineLoadToOperationType does nothing, like 16749 // ordered load, it should be profitable to hoist them. 16750 // For swifterror load, it can only be used for pointer to pointer type, so 16751 // later type check should get rid of this case. 16752 if (!LI->isUnordered()) 16753 return true; 16754 16755 if (User->getOpcode() != Instruction::Store) 16756 return true; 16757 16758 if (I->getType()->getTypeID() != Type::FloatTyID) 16759 return true; 16760 16761 return false; 16762 } 16763 default: 16764 return true; 16765 } 16766 return true; 16767 } 16768 16769 const MCPhysReg * 16770 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16771 // LR is a callee-save register, but we must treat it as clobbered by any call 16772 // site. Hence we include LR in the scratch registers, which are in turn added 16773 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16774 // to CTR, which is used by any indirect call. 16775 static const MCPhysReg ScratchRegs[] = { 16776 PPC::X12, PPC::LR8, PPC::CTR8, 0 16777 }; 16778 16779 return ScratchRegs; 16780 } 16781 16782 Register PPCTargetLowering::getExceptionPointerRegister( 16783 const Constant *PersonalityFn) const { 16784 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16785 } 16786 16787 Register PPCTargetLowering::getExceptionSelectorRegister( 16788 const Constant *PersonalityFn) const { 16789 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16790 } 16791 16792 bool 16793 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16794 EVT VT , unsigned DefinedValues) const { 16795 if (VT == MVT::v2i64) 16796 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16797 16798 if (Subtarget.hasVSX()) 16799 return true; 16800 16801 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16802 } 16803 16804 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16805 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16806 return TargetLowering::getSchedulingPreference(N); 16807 16808 return Sched::ILP; 16809 } 16810 16811 // Create a fast isel object. 16812 FastISel * 16813 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16814 const TargetLibraryInfo *LibInfo) const { 16815 return PPC::createFastISel(FuncInfo, LibInfo); 16816 } 16817 16818 // 'Inverted' means the FMA opcode after negating one multiplicand. 16819 // For example, (fma -a b c) = (fnmsub a b c) 16820 static unsigned invertFMAOpcode(unsigned Opc) { 16821 switch (Opc) { 16822 default: 16823 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16824 case ISD::FMA: 16825 return PPCISD::FNMSUB; 16826 case PPCISD::FNMSUB: 16827 return ISD::FMA; 16828 } 16829 } 16830 16831 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16832 bool LegalOps, bool OptForSize, 16833 NegatibleCost &Cost, 16834 unsigned Depth) const { 16835 if (Depth > SelectionDAG::MaxRecursionDepth) 16836 return SDValue(); 16837 16838 unsigned Opc = Op.getOpcode(); 16839 EVT VT = Op.getValueType(); 16840 SDNodeFlags Flags = Op.getNode()->getFlags(); 16841 16842 switch (Opc) { 16843 case PPCISD::FNMSUB: 16844 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16845 break; 16846 16847 const TargetOptions &Options = getTargetMachine().Options; 16848 SDValue N0 = Op.getOperand(0); 16849 SDValue N1 = Op.getOperand(1); 16850 SDValue N2 = Op.getOperand(2); 16851 SDLoc Loc(Op); 16852 16853 NegatibleCost N2Cost = NegatibleCost::Expensive; 16854 SDValue NegN2 = 16855 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16856 16857 if (!NegN2) 16858 return SDValue(); 16859 16860 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16861 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16862 // These transformations may change sign of zeroes. For example, 16863 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16864 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16865 // Try and choose the cheaper one to negate. 16866 NegatibleCost N0Cost = NegatibleCost::Expensive; 16867 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16868 N0Cost, Depth + 1); 16869 16870 NegatibleCost N1Cost = NegatibleCost::Expensive; 16871 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16872 N1Cost, Depth + 1); 16873 16874 if (NegN0 && N0Cost <= N1Cost) { 16875 Cost = std::min(N0Cost, N2Cost); 16876 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16877 } else if (NegN1) { 16878 Cost = std::min(N1Cost, N2Cost); 16879 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16880 } 16881 } 16882 16883 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16884 if (isOperationLegal(ISD::FMA, VT)) { 16885 Cost = N2Cost; 16886 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16887 } 16888 16889 break; 16890 } 16891 16892 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16893 Cost, Depth); 16894 } 16895 16896 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16897 bool PPCTargetLowering::useLoadStackGuardNode() const { 16898 if (!Subtarget.isTargetLinux()) 16899 return TargetLowering::useLoadStackGuardNode(); 16900 return true; 16901 } 16902 16903 // Override to disable global variable loading on Linux and insert AIX canary 16904 // word declaration. 16905 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16906 if (Subtarget.isAIXABI()) { 16907 M.getOrInsertGlobal(AIXSSPCanaryWordName, 16908 Type::getInt8PtrTy(M.getContext())); 16909 return; 16910 } 16911 if (!Subtarget.isTargetLinux()) 16912 return TargetLowering::insertSSPDeclarations(M); 16913 } 16914 16915 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const { 16916 if (Subtarget.isAIXABI()) 16917 return M.getGlobalVariable(AIXSSPCanaryWordName); 16918 return TargetLowering::getSDagStackGuard(M); 16919 } 16920 16921 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16922 bool ForCodeSize) const { 16923 if (!VT.isSimple() || !Subtarget.hasVSX()) 16924 return false; 16925 16926 switch(VT.getSimpleVT().SimpleTy) { 16927 default: 16928 // For FP types that are currently not supported by PPC backend, return 16929 // false. Examples: f16, f80. 16930 return false; 16931 case MVT::f32: 16932 case MVT::f64: 16933 if (Subtarget.hasPrefixInstrs()) { 16934 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 16935 return true; 16936 } 16937 LLVM_FALLTHROUGH; 16938 case MVT::ppcf128: 16939 return Imm.isPosZero(); 16940 } 16941 } 16942 16943 // For vector shift operation op, fold 16944 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16945 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16946 SelectionDAG &DAG) { 16947 SDValue N0 = N->getOperand(0); 16948 SDValue N1 = N->getOperand(1); 16949 EVT VT = N0.getValueType(); 16950 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16951 unsigned Opcode = N->getOpcode(); 16952 unsigned TargetOpcode; 16953 16954 switch (Opcode) { 16955 default: 16956 llvm_unreachable("Unexpected shift operation"); 16957 case ISD::SHL: 16958 TargetOpcode = PPCISD::SHL; 16959 break; 16960 case ISD::SRL: 16961 TargetOpcode = PPCISD::SRL; 16962 break; 16963 case ISD::SRA: 16964 TargetOpcode = PPCISD::SRA; 16965 break; 16966 } 16967 16968 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16969 N1->getOpcode() == ISD::AND) 16970 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16971 if (Mask->getZExtValue() == OpSizeInBits - 1) 16972 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16973 16974 return SDValue(); 16975 } 16976 16977 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16978 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16979 return Value; 16980 16981 SDValue N0 = N->getOperand(0); 16982 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16983 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16984 N0.getOpcode() != ISD::SIGN_EXTEND || 16985 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16986 N->getValueType(0) != MVT::i64) 16987 return SDValue(); 16988 16989 // We can't save an operation here if the value is already extended, and 16990 // the existing shift is easier to combine. 16991 SDValue ExtsSrc = N0.getOperand(0); 16992 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16993 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16994 return SDValue(); 16995 16996 SDLoc DL(N0); 16997 SDValue ShiftBy = SDValue(CN1, 0); 16998 // We want the shift amount to be i32 on the extswli, but the shift could 16999 // have an i64. 17000 if (ShiftBy.getValueType() == MVT::i64) 17001 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 17002 17003 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 17004 ShiftBy); 17005 } 17006 17007 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 17008 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 17009 return Value; 17010 17011 return SDValue(); 17012 } 17013 17014 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 17015 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 17016 return Value; 17017 17018 return SDValue(); 17019 } 17020 17021 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 17022 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 17023 // When C is zero, the equation (addi Z, -C) can be simplified to Z 17024 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 17025 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 17026 const PPCSubtarget &Subtarget) { 17027 if (!Subtarget.isPPC64()) 17028 return SDValue(); 17029 17030 SDValue LHS = N->getOperand(0); 17031 SDValue RHS = N->getOperand(1); 17032 17033 auto isZextOfCompareWithConstant = [](SDValue Op) { 17034 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 17035 Op.getValueType() != MVT::i64) 17036 return false; 17037 17038 SDValue Cmp = Op.getOperand(0); 17039 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 17040 Cmp.getOperand(0).getValueType() != MVT::i64) 17041 return false; 17042 17043 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 17044 int64_t NegConstant = 0 - Constant->getSExtValue(); 17045 // Due to the limitations of the addi instruction, 17046 // -C is required to be [-32768, 32767]. 17047 return isInt<16>(NegConstant); 17048 } 17049 17050 return false; 17051 }; 17052 17053 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 17054 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 17055 17056 // If there is a pattern, canonicalize a zext operand to the RHS. 17057 if (LHSHasPattern && !RHSHasPattern) 17058 std::swap(LHS, RHS); 17059 else if (!LHSHasPattern && !RHSHasPattern) 17060 return SDValue(); 17061 17062 SDLoc DL(N); 17063 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 17064 SDValue Cmp = RHS.getOperand(0); 17065 SDValue Z = Cmp.getOperand(0); 17066 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1)); 17067 int64_t NegConstant = 0 - Constant->getSExtValue(); 17068 17069 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 17070 default: break; 17071 case ISD::SETNE: { 17072 // when C == 0 17073 // --> addze X, (addic Z, -1).carry 17074 // / 17075 // add X, (zext(setne Z, C))-- 17076 // \ when -32768 <= -C <= 32767 && C != 0 17077 // --> addze X, (addic (addi Z, -C), -1).carry 17078 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17079 DAG.getConstant(NegConstant, DL, MVT::i64)); 17080 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17081 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17082 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 17083 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17084 SDValue(Addc.getNode(), 1)); 17085 } 17086 case ISD::SETEQ: { 17087 // when C == 0 17088 // --> addze X, (subfic Z, 0).carry 17089 // / 17090 // add X, (zext(sete Z, C))-- 17091 // \ when -32768 <= -C <= 32767 && C != 0 17092 // --> addze X, (subfic (addi Z, -C), 0).carry 17093 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17094 DAG.getConstant(NegConstant, DL, MVT::i64)); 17095 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17096 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17097 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 17098 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17099 SDValue(Subc.getNode(), 1)); 17100 } 17101 } 17102 17103 return SDValue(); 17104 } 17105 17106 // Transform 17107 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 17108 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 17109 // In this case both C1 and C2 must be known constants. 17110 // C1+C2 must fit into a 34 bit signed integer. 17111 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 17112 const PPCSubtarget &Subtarget) { 17113 if (!Subtarget.isUsingPCRelativeCalls()) 17114 return SDValue(); 17115 17116 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 17117 // If we find that node try to cast the Global Address and the Constant. 17118 SDValue LHS = N->getOperand(0); 17119 SDValue RHS = N->getOperand(1); 17120 17121 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17122 std::swap(LHS, RHS); 17123 17124 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17125 return SDValue(); 17126 17127 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 17128 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 17129 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 17130 17131 // Check that both casts succeeded. 17132 if (!GSDN || !ConstNode) 17133 return SDValue(); 17134 17135 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 17136 SDLoc DL(GSDN); 17137 17138 // The signed int offset needs to fit in 34 bits. 17139 if (!isInt<34>(NewOffset)) 17140 return SDValue(); 17141 17142 // The new global address is a copy of the old global address except 17143 // that it has the updated Offset. 17144 SDValue GA = 17145 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 17146 NewOffset, GSDN->getTargetFlags()); 17147 SDValue MatPCRel = 17148 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 17149 return MatPCRel; 17150 } 17151 17152 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 17153 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 17154 return Value; 17155 17156 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 17157 return Value; 17158 17159 return SDValue(); 17160 } 17161 17162 // Detect TRUNCATE operations on bitcasts of float128 values. 17163 // What we are looking for here is the situtation where we extract a subset 17164 // of bits from a 128 bit float. 17165 // This can be of two forms: 17166 // 1) BITCAST of f128 feeding TRUNCATE 17167 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 17168 // The reason this is required is because we do not have a legal i128 type 17169 // and so we want to prevent having to store the f128 and then reload part 17170 // of it. 17171 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 17172 DAGCombinerInfo &DCI) const { 17173 // If we are using CRBits then try that first. 17174 if (Subtarget.useCRBits()) { 17175 // Check if CRBits did anything and return that if it did. 17176 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 17177 return CRTruncValue; 17178 } 17179 17180 SDLoc dl(N); 17181 SDValue Op0 = N->getOperand(0); 17182 17183 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 17184 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 17185 EVT VT = N->getValueType(0); 17186 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17187 return SDValue(); 17188 SDValue Sub = Op0.getOperand(0); 17189 if (Sub.getOpcode() == ISD::SUB) { 17190 SDValue SubOp0 = Sub.getOperand(0); 17191 SDValue SubOp1 = Sub.getOperand(1); 17192 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 17193 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 17194 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 17195 SubOp1.getOperand(0), 17196 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 17197 } 17198 } 17199 } 17200 17201 // Looking for a truncate of i128 to i64. 17202 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 17203 return SDValue(); 17204 17205 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 17206 17207 // SRL feeding TRUNCATE. 17208 if (Op0.getOpcode() == ISD::SRL) { 17209 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 17210 // The right shift has to be by 64 bits. 17211 if (!ConstNode || ConstNode->getZExtValue() != 64) 17212 return SDValue(); 17213 17214 // Switch the element number to extract. 17215 EltToExtract = EltToExtract ? 0 : 1; 17216 // Update Op0 past the SRL. 17217 Op0 = Op0.getOperand(0); 17218 } 17219 17220 // BITCAST feeding a TRUNCATE possibly via SRL. 17221 if (Op0.getOpcode() == ISD::BITCAST && 17222 Op0.getValueType() == MVT::i128 && 17223 Op0.getOperand(0).getValueType() == MVT::f128) { 17224 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 17225 return DCI.DAG.getNode( 17226 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 17227 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 17228 } 17229 return SDValue(); 17230 } 17231 17232 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 17233 SelectionDAG &DAG = DCI.DAG; 17234 17235 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 17236 if (!ConstOpOrElement) 17237 return SDValue(); 17238 17239 // An imul is usually smaller than the alternative sequence for legal type. 17240 if (DAG.getMachineFunction().getFunction().hasMinSize() && 17241 isOperationLegal(ISD::MUL, N->getValueType(0))) 17242 return SDValue(); 17243 17244 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 17245 switch (this->Subtarget.getCPUDirective()) { 17246 default: 17247 // TODO: enhance the condition for subtarget before pwr8 17248 return false; 17249 case PPC::DIR_PWR8: 17250 // type mul add shl 17251 // scalar 4 1 1 17252 // vector 7 2 2 17253 return true; 17254 case PPC::DIR_PWR9: 17255 case PPC::DIR_PWR10: 17256 case PPC::DIR_PWR_FUTURE: 17257 // type mul add shl 17258 // scalar 5 2 2 17259 // vector 7 2 2 17260 17261 // The cycle RATIO of related operations are showed as a table above. 17262 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 17263 // scalar and vector type. For 2 instrs patterns, add/sub + shl 17264 // are 4, it is always profitable; but for 3 instrs patterns 17265 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 17266 // So we should only do it for vector type. 17267 return IsAddOne && IsNeg ? VT.isVector() : true; 17268 } 17269 }; 17270 17271 EVT VT = N->getValueType(0); 17272 SDLoc DL(N); 17273 17274 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 17275 bool IsNeg = MulAmt.isNegative(); 17276 APInt MulAmtAbs = MulAmt.abs(); 17277 17278 if ((MulAmtAbs - 1).isPowerOf2()) { 17279 // (mul x, 2^N + 1) => (add (shl x, N), x) 17280 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 17281 17282 if (!IsProfitable(IsNeg, true, VT)) 17283 return SDValue(); 17284 17285 SDValue Op0 = N->getOperand(0); 17286 SDValue Op1 = 17287 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17288 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 17289 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 17290 17291 if (!IsNeg) 17292 return Res; 17293 17294 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 17295 } else if ((MulAmtAbs + 1).isPowerOf2()) { 17296 // (mul x, 2^N - 1) => (sub (shl x, N), x) 17297 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 17298 17299 if (!IsProfitable(IsNeg, false, VT)) 17300 return SDValue(); 17301 17302 SDValue Op0 = N->getOperand(0); 17303 SDValue Op1 = 17304 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17305 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 17306 17307 if (!IsNeg) 17308 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 17309 else 17310 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 17311 17312 } else { 17313 return SDValue(); 17314 } 17315 } 17316 17317 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 17318 // in combiner since we need to check SD flags and other subtarget features. 17319 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 17320 DAGCombinerInfo &DCI) const { 17321 SDValue N0 = N->getOperand(0); 17322 SDValue N1 = N->getOperand(1); 17323 SDValue N2 = N->getOperand(2); 17324 SDNodeFlags Flags = N->getFlags(); 17325 EVT VT = N->getValueType(0); 17326 SelectionDAG &DAG = DCI.DAG; 17327 const TargetOptions &Options = getTargetMachine().Options; 17328 unsigned Opc = N->getOpcode(); 17329 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 17330 bool LegalOps = !DCI.isBeforeLegalizeOps(); 17331 SDLoc Loc(N); 17332 17333 if (!isOperationLegal(ISD::FMA, VT)) 17334 return SDValue(); 17335 17336 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 17337 // since (fnmsub a b c)=-0 while c-ab=+0. 17338 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 17339 return SDValue(); 17340 17341 // (fma (fneg a) b c) => (fnmsub a b c) 17342 // (fnmsub (fneg a) b c) => (fma a b c) 17343 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 17344 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 17345 17346 // (fma a (fneg b) c) => (fnmsub a b c) 17347 // (fnmsub a (fneg b) c) => (fma a b c) 17348 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 17349 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 17350 17351 return SDValue(); 17352 } 17353 17354 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 17355 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 17356 if (!Subtarget.is64BitELFABI()) 17357 return false; 17358 17359 // If not a tail call then no need to proceed. 17360 if (!CI->isTailCall()) 17361 return false; 17362 17363 // If sibling calls have been disabled and tail-calls aren't guaranteed 17364 // there is no reason to duplicate. 17365 auto &TM = getTargetMachine(); 17366 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 17367 return false; 17368 17369 // Can't tail call a function called indirectly, or if it has variadic args. 17370 const Function *Callee = CI->getCalledFunction(); 17371 if (!Callee || Callee->isVarArg()) 17372 return false; 17373 17374 // Make sure the callee and caller calling conventions are eligible for tco. 17375 const Function *Caller = CI->getParent()->getParent(); 17376 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 17377 CI->getCallingConv())) 17378 return false; 17379 17380 // If the function is local then we have a good chance at tail-calling it 17381 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 17382 } 17383 17384 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 17385 if (!Subtarget.hasVSX()) 17386 return false; 17387 if (Subtarget.hasP9Vector() && VT == MVT::f128) 17388 return true; 17389 return VT == MVT::f32 || VT == MVT::f64 || 17390 VT == MVT::v4f32 || VT == MVT::v2f64; 17391 } 17392 17393 bool PPCTargetLowering:: 17394 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 17395 const Value *Mask = AndI.getOperand(1); 17396 // If the mask is suitable for andi. or andis. we should sink the and. 17397 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 17398 // Can't handle constants wider than 64-bits. 17399 if (CI->getBitWidth() > 64) 17400 return false; 17401 int64_t ConstVal = CI->getZExtValue(); 17402 return isUInt<16>(ConstVal) || 17403 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 17404 } 17405 17406 // For non-constant masks, we can always use the record-form and. 17407 return true; 17408 } 17409 17410 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 17411 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 17412 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 17413 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 17414 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 17415 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 17416 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 17417 assert(Subtarget.hasP9Altivec() && 17418 "Only combine this when P9 altivec supported!"); 17419 EVT VT = N->getValueType(0); 17420 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17421 return SDValue(); 17422 17423 SelectionDAG &DAG = DCI.DAG; 17424 SDLoc dl(N); 17425 if (N->getOperand(0).getOpcode() == ISD::SUB) { 17426 // Even for signed integers, if it's known to be positive (as signed 17427 // integer) due to zero-extended inputs. 17428 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 17429 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 17430 if ((SubOpcd0 == ISD::ZERO_EXTEND || 17431 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 17432 (SubOpcd1 == ISD::ZERO_EXTEND || 17433 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 17434 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17435 N->getOperand(0)->getOperand(0), 17436 N->getOperand(0)->getOperand(1), 17437 DAG.getTargetConstant(0, dl, MVT::i32)); 17438 } 17439 17440 // For type v4i32, it can be optimized with xvnegsp + vabsduw 17441 if (N->getOperand(0).getValueType() == MVT::v4i32 && 17442 N->getOperand(0).hasOneUse()) { 17443 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17444 N->getOperand(0)->getOperand(0), 17445 N->getOperand(0)->getOperand(1), 17446 DAG.getTargetConstant(1, dl, MVT::i32)); 17447 } 17448 } 17449 17450 return SDValue(); 17451 } 17452 17453 // For type v4i32/v8ii16/v16i8, transform 17454 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 17455 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 17456 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 17457 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 17458 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 17459 DAGCombinerInfo &DCI) const { 17460 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 17461 assert(Subtarget.hasP9Altivec() && 17462 "Only combine this when P9 altivec supported!"); 17463 17464 SelectionDAG &DAG = DCI.DAG; 17465 SDLoc dl(N); 17466 SDValue Cond = N->getOperand(0); 17467 SDValue TrueOpnd = N->getOperand(1); 17468 SDValue FalseOpnd = N->getOperand(2); 17469 EVT VT = N->getOperand(1).getValueType(); 17470 17471 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 17472 FalseOpnd.getOpcode() != ISD::SUB) 17473 return SDValue(); 17474 17475 // ABSD only available for type v4i32/v8i16/v16i8 17476 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17477 return SDValue(); 17478 17479 // At least to save one more dependent computation 17480 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 17481 return SDValue(); 17482 17483 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 17484 17485 // Can only handle unsigned comparison here 17486 switch (CC) { 17487 default: 17488 return SDValue(); 17489 case ISD::SETUGT: 17490 case ISD::SETUGE: 17491 break; 17492 case ISD::SETULT: 17493 case ISD::SETULE: 17494 std::swap(TrueOpnd, FalseOpnd); 17495 break; 17496 } 17497 17498 SDValue CmpOpnd1 = Cond.getOperand(0); 17499 SDValue CmpOpnd2 = Cond.getOperand(1); 17500 17501 // SETCC CmpOpnd1 CmpOpnd2 cond 17502 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17503 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17504 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17505 TrueOpnd.getOperand(1) == CmpOpnd2 && 17506 FalseOpnd.getOperand(0) == CmpOpnd2 && 17507 FalseOpnd.getOperand(1) == CmpOpnd1) { 17508 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 17509 CmpOpnd1, CmpOpnd2, 17510 DAG.getTargetConstant(0, dl, MVT::i32)); 17511 } 17512 17513 return SDValue(); 17514 } 17515 17516 /// getAddrModeForFlags - Based on the set of address flags, select the most 17517 /// optimal instruction format to match by. 17518 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const { 17519 // This is not a node we should be handling here. 17520 if (Flags == PPC::MOF_None) 17521 return PPC::AM_None; 17522 // Unaligned D-Forms are tried first, followed by the aligned D-Forms. 17523 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm)) 17524 if ((Flags & FlagSet) == FlagSet) 17525 return PPC::AM_DForm; 17526 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm)) 17527 if ((Flags & FlagSet) == FlagSet) 17528 return PPC::AM_DSForm; 17529 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm)) 17530 if ((Flags & FlagSet) == FlagSet) 17531 return PPC::AM_DQForm; 17532 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm)) 17533 if ((Flags & FlagSet) == FlagSet) 17534 return PPC::AM_PrefixDForm; 17535 // If no other forms are selected, return an X-Form as it is the most 17536 // general addressing mode. 17537 return PPC::AM_XForm; 17538 } 17539 17540 /// Set alignment flags based on whether or not the Frame Index is aligned. 17541 /// Utilized when computing flags for address computation when selecting 17542 /// load and store instructions. 17543 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, 17544 SelectionDAG &DAG) { 17545 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR)); 17546 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N); 17547 if (!FI) 17548 return; 17549 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17550 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value(); 17551 // If this is (add $FI, $S16Imm), the alignment flags are already set 17552 // based on the immediate. We just need to clear the alignment flags 17553 // if the FI alignment is weaker. 17554 if ((FrameIndexAlign % 4) != 0) 17555 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4; 17556 if ((FrameIndexAlign % 16) != 0) 17557 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16; 17558 // If the address is a plain FrameIndex, set alignment flags based on 17559 // FI alignment. 17560 if (!IsAdd) { 17561 if ((FrameIndexAlign % 4) == 0) 17562 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17563 if ((FrameIndexAlign % 16) == 0) 17564 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17565 } 17566 } 17567 17568 /// Given a node, compute flags that are used for address computation when 17569 /// selecting load and store instructions. The flags computed are stored in 17570 /// FlagSet. This function takes into account whether the node is a constant, 17571 /// an ADD, OR, or a constant, and computes the address flags accordingly. 17572 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, 17573 SelectionDAG &DAG) { 17574 // Set the alignment flags for the node depending on if the node is 17575 // 4-byte or 16-byte aligned. 17576 auto SetAlignFlagsForImm = [&](uint64_t Imm) { 17577 if ((Imm & 0x3) == 0) 17578 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17579 if ((Imm & 0xf) == 0) 17580 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17581 }; 17582 17583 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 17584 // All 32-bit constants can be computed as LIS + Disp. 17585 const APInt &ConstImm = CN->getAPIntValue(); 17586 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants. 17587 FlagSet |= PPC::MOF_AddrIsSImm32; 17588 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17589 setAlignFlagsForFI(N, FlagSet, DAG); 17590 } 17591 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants. 17592 FlagSet |= PPC::MOF_RPlusSImm34; 17593 else // Let constant materialization handle large constants. 17594 FlagSet |= PPC::MOF_NotAddNorCst; 17595 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) { 17596 // This address can be represented as an addition of: 17597 // - Register + Imm16 (possibly a multiple of 4/16) 17598 // - Register + Imm34 17599 // - Register + PPCISD::Lo 17600 // - Register + Register 17601 // In any case, we won't have to match this as Base + Zero. 17602 SDValue RHS = N.getOperand(1); 17603 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) { 17604 const APInt &ConstImm = CN->getAPIntValue(); 17605 if (ConstImm.isSignedIntN(16)) { 17606 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates. 17607 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17608 setAlignFlagsForFI(N, FlagSet, DAG); 17609 } 17610 if (ConstImm.isSignedIntN(34)) 17611 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates. 17612 else 17613 FlagSet |= PPC::MOF_RPlusR; // Register. 17614 } else if (RHS.getOpcode() == PPCISD::Lo && 17615 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue()) 17616 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo. 17617 else 17618 FlagSet |= PPC::MOF_RPlusR; 17619 } else { // The address computation is not a constant or an addition. 17620 setAlignFlagsForFI(N, FlagSet, DAG); 17621 FlagSet |= PPC::MOF_NotAddNorCst; 17622 } 17623 } 17624 17625 static bool isPCRelNode(SDValue N) { 17626 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR || 17627 isValidPCRelNode<ConstantPoolSDNode>(N) || 17628 isValidPCRelNode<GlobalAddressSDNode>(N) || 17629 isValidPCRelNode<JumpTableSDNode>(N) || 17630 isValidPCRelNode<BlockAddressSDNode>(N)); 17631 } 17632 17633 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute 17634 /// the address flags of the load/store instruction that is to be matched. 17635 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N, 17636 SelectionDAG &DAG) const { 17637 unsigned FlagSet = PPC::MOF_None; 17638 17639 // Compute subtarget flags. 17640 if (!Subtarget.hasP9Vector()) 17641 FlagSet |= PPC::MOF_SubtargetBeforeP9; 17642 else { 17643 FlagSet |= PPC::MOF_SubtargetP9; 17644 if (Subtarget.hasPrefixInstrs()) 17645 FlagSet |= PPC::MOF_SubtargetP10; 17646 } 17647 if (Subtarget.hasSPE()) 17648 FlagSet |= PPC::MOF_SubtargetSPE; 17649 17650 // Check if we have a PCRel node and return early. 17651 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N)) 17652 return FlagSet; 17653 17654 // If the node is the paired load/store intrinsics, compute flags for 17655 // address computation and return early. 17656 unsigned ParentOp = Parent->getOpcode(); 17657 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) || 17658 (ParentOp == ISD::INTRINSIC_VOID))) { 17659 unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue(); 17660 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) { 17661 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) 17662 ? Parent->getOperand(2) 17663 : Parent->getOperand(3); 17664 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG); 17665 FlagSet |= PPC::MOF_Vector; 17666 return FlagSet; 17667 } 17668 } 17669 17670 // Mark this as something we don't want to handle here if it is atomic 17671 // or pre-increment instruction. 17672 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent)) 17673 if (LSB->isIndexed()) 17674 return PPC::MOF_None; 17675 17676 // Compute in-memory type flags. This is based on if there are scalars, 17677 // floats or vectors. 17678 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent); 17679 assert(MN && "Parent should be a MemSDNode!"); 17680 EVT MemVT = MN->getMemoryVT(); 17681 unsigned Size = MemVT.getSizeInBits(); 17682 if (MemVT.isScalarInteger()) { 17683 assert(Size <= 128 && 17684 "Not expecting scalar integers larger than 16 bytes!"); 17685 if (Size < 32) 17686 FlagSet |= PPC::MOF_SubWordInt; 17687 else if (Size == 32) 17688 FlagSet |= PPC::MOF_WordInt; 17689 else 17690 FlagSet |= PPC::MOF_DoubleWordInt; 17691 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors. 17692 if (Size == 128) 17693 FlagSet |= PPC::MOF_Vector; 17694 else if (Size == 256) { 17695 assert(Subtarget.pairedVectorMemops() && 17696 "256-bit vectors are only available when paired vector memops is " 17697 "enabled!"); 17698 FlagSet |= PPC::MOF_Vector; 17699 } else 17700 llvm_unreachable("Not expecting illegal vectors!"); 17701 } else { // Floating point type: can be scalar, f128 or vector types. 17702 if (Size == 32 || Size == 64) 17703 FlagSet |= PPC::MOF_ScalarFloat; 17704 else if (MemVT == MVT::f128 || MemVT.isVector()) 17705 FlagSet |= PPC::MOF_Vector; 17706 else 17707 llvm_unreachable("Not expecting illegal scalar floats!"); 17708 } 17709 17710 // Compute flags for address computation. 17711 computeFlagsForAddressComputation(N, FlagSet, DAG); 17712 17713 // Compute type extension flags. 17714 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) { 17715 switch (LN->getExtensionType()) { 17716 case ISD::SEXTLOAD: 17717 FlagSet |= PPC::MOF_SExt; 17718 break; 17719 case ISD::EXTLOAD: 17720 case ISD::ZEXTLOAD: 17721 FlagSet |= PPC::MOF_ZExt; 17722 break; 17723 case ISD::NON_EXTLOAD: 17724 FlagSet |= PPC::MOF_NoExt; 17725 break; 17726 } 17727 } else 17728 FlagSet |= PPC::MOF_NoExt; 17729 17730 // For integers, no extension is the same as zero extension. 17731 // We set the extension mode to zero extension so we don't have 17732 // to add separate entries in AddrModesMap for loads and stores. 17733 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) { 17734 FlagSet |= PPC::MOF_ZExt; 17735 FlagSet &= ~PPC::MOF_NoExt; 17736 } 17737 17738 // If we don't have prefixed instructions, 34-bit constants should be 17739 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms. 17740 bool IsNonP1034BitConst = 17741 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) & 17742 FlagSet) == PPC::MOF_RPlusSImm34; 17743 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR && 17744 IsNonP1034BitConst) 17745 FlagSet |= PPC::MOF_NotAddNorCst; 17746 17747 return FlagSet; 17748 } 17749 17750 /// SelectForceXFormMode - Given the specified address, force it to be 17751 /// represented as an indexed [r+r] operation (an XForm instruction). 17752 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp, 17753 SDValue &Base, 17754 SelectionDAG &DAG) const { 17755 17756 PPC::AddrMode Mode = PPC::AM_XForm; 17757 int16_t ForceXFormImm = 0; 17758 if (provablyDisjointOr(DAG, N) && 17759 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) { 17760 Disp = N.getOperand(0); 17761 Base = N.getOperand(1); 17762 return Mode; 17763 } 17764 17765 // If the address is the result of an add, we will utilize the fact that the 17766 // address calculation includes an implicit add. However, we can reduce 17767 // register pressure if we do not materialize a constant just for use as the 17768 // index register. We only get rid of the add if it is not an add of a 17769 // value and a 16-bit signed constant and both have a single use. 17770 if (N.getOpcode() == ISD::ADD && 17771 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) || 17772 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 17773 Disp = N.getOperand(0); 17774 Base = N.getOperand(1); 17775 return Mode; 17776 } 17777 17778 // Otherwise, use R0 as the base register. 17779 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17780 N.getValueType()); 17781 Base = N; 17782 17783 return Mode; 17784 } 17785 17786 bool PPCTargetLowering::splitValueIntoRegisterParts( 17787 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 17788 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 17789 EVT ValVT = Val.getValueType(); 17790 // If we are splitting a scalar integer into f64 parts (i.e. so they 17791 // can be placed into VFRC registers), we need to zero extend and 17792 // bitcast the values. This will ensure the value is placed into a 17793 // VSR using direct moves or stack operations as needed. 17794 if (PartVT == MVT::f64 && 17795 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) { 17796 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 17797 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val); 17798 Parts[0] = Val; 17799 return true; 17800 } 17801 return false; 17802 } 17803 17804 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op, 17805 SelectionDAG &DAG) const { 17806 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17807 TargetLowering::CallLoweringInfo CLI(DAG); 17808 EVT RetVT = Op.getValueType(); 17809 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 17810 SDValue Callee = 17811 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout())); 17812 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false); 17813 TargetLowering::ArgListTy Args; 17814 TargetLowering::ArgListEntry Entry; 17815 for (const SDValue &N : Op->op_values()) { 17816 EVT ArgVT = N.getValueType(); 17817 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 17818 Entry.Node = N; 17819 Entry.Ty = ArgTy; 17820 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend); 17821 Entry.IsZExt = !Entry.IsSExt; 17822 Args.push_back(Entry); 17823 } 17824 17825 SDValue InChain = DAG.getEntryNode(); 17826 SDValue TCChain = InChain; 17827 const Function &F = DAG.getMachineFunction().getFunction(); 17828 bool isTailCall = 17829 TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 17830 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()); 17831 if (isTailCall) 17832 InChain = TCChain; 17833 CLI.setDebugLoc(SDLoc(Op)) 17834 .setChain(InChain) 17835 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args)) 17836 .setTailCall(isTailCall) 17837 .setSExtResult(SignExtend) 17838 .setZExtResult(!SignExtend) 17839 .setIsPostTypeLegalization(true); 17840 return TLI.LowerCallTo(CLI).first; 17841 } 17842 17843 SDValue PPCTargetLowering::lowerLibCallBasedOnType( 17844 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op, 17845 SelectionDAG &DAG) const { 17846 if (Op.getValueType() == MVT::f32) 17847 return lowerToLibCall(LibCallFloatName, Op, DAG); 17848 17849 if (Op.getValueType() == MVT::f64) 17850 return lowerToLibCall(LibCallDoubleName, Op, DAG); 17851 17852 return SDValue(); 17853 } 17854 17855 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const { 17856 SDNodeFlags Flags = Op.getNode()->getFlags(); 17857 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() && 17858 Flags.hasNoNaNs() && Flags.hasNoInfs(); 17859 } 17860 17861 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const { 17862 return Op.getNode()->getFlags().hasApproximateFuncs(); 17863 } 17864 17865 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName, 17866 const char *LibCallFloatName, 17867 const char *LibCallDoubleNameFinite, 17868 const char *LibCallFloatNameFinite, 17869 SDValue Op, 17870 SelectionDAG &DAG) const { 17871 if (!isLowringToMASSSafe(Op)) 17872 return SDValue(); 17873 17874 if (!isLowringToMASSFiniteSafe(Op)) 17875 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op, 17876 DAG); 17877 17878 return lowerLibCallBasedOnType(LibCallFloatNameFinite, 17879 LibCallDoubleNameFinite, Op, DAG); 17880 } 17881 17882 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const { 17883 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite", 17884 "__xl_powf_finite", Op, DAG); 17885 } 17886 17887 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const { 17888 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite", 17889 "__xl_sinf_finite", Op, DAG); 17890 } 17891 17892 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const { 17893 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite", 17894 "__xl_cosf_finite", Op, DAG); 17895 } 17896 17897 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const { 17898 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite", 17899 "__xl_logf_finite", Op, DAG); 17900 } 17901 17902 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const { 17903 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite", 17904 "__xl_log10f_finite", Op, DAG); 17905 } 17906 17907 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const { 17908 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite", 17909 "__xl_expf_finite", Op, DAG); 17910 } 17911 17912 // If we happen to match to an aligned D-Form, check if the Frame Index is 17913 // adequately aligned. If it is not, reset the mode to match to X-Form. 17914 static void setXFormForUnalignedFI(SDValue N, unsigned Flags, 17915 PPC::AddrMode &Mode) { 17916 if (!isa<FrameIndexSDNode>(N)) 17917 return; 17918 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) || 17919 (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16))) 17920 Mode = PPC::AM_XForm; 17921 } 17922 17923 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), 17924 /// compute the address flags of the node, get the optimal address mode based 17925 /// on the flags, and set the Base and Disp based on the address mode. 17926 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent, 17927 SDValue N, SDValue &Disp, 17928 SDValue &Base, 17929 SelectionDAG &DAG, 17930 MaybeAlign Align) const { 17931 SDLoc DL(Parent); 17932 17933 // Compute the address flags. 17934 unsigned Flags = computeMOFlags(Parent, N, DAG); 17935 17936 // Get the optimal address mode based on the Flags. 17937 PPC::AddrMode Mode = getAddrModeForFlags(Flags); 17938 17939 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned. 17940 // Select an X-Form load if it is not. 17941 setXFormForUnalignedFI(N, Flags, Mode); 17942 17943 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node. 17944 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) { 17945 assert(Subtarget.isUsingPCRelativeCalls() && 17946 "Must be using PC-Relative calls when a valid PC-Relative node is " 17947 "present!"); 17948 Mode = PPC::AM_PCRel; 17949 } 17950 17951 // Set Base and Disp accordingly depending on the address mode. 17952 switch (Mode) { 17953 case PPC::AM_DForm: 17954 case PPC::AM_DSForm: 17955 case PPC::AM_DQForm: { 17956 // This is a register plus a 16-bit immediate. The base will be the 17957 // register and the displacement will be the immediate unless it 17958 // isn't sufficiently aligned. 17959 if (Flags & PPC::MOF_RPlusSImm16) { 17960 SDValue Op0 = N.getOperand(0); 17961 SDValue Op1 = N.getOperand(1); 17962 int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue(); 17963 if (!Align || isAligned(*Align, Imm)) { 17964 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType()); 17965 Base = Op0; 17966 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) { 17967 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17968 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17969 } 17970 break; 17971 } 17972 } 17973 // This is a register plus the @lo relocation. The base is the register 17974 // and the displacement is the global address. 17975 else if (Flags & PPC::MOF_RPlusLo) { 17976 Disp = N.getOperand(1).getOperand(0); // The global address. 17977 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 17978 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 17979 Disp.getOpcode() == ISD::TargetConstantPool || 17980 Disp.getOpcode() == ISD::TargetJumpTable); 17981 Base = N.getOperand(0); 17982 break; 17983 } 17984 // This is a constant address at most 32 bits. The base will be 17985 // zero or load-immediate-shifted and the displacement will be 17986 // the low 16 bits of the address. 17987 else if (Flags & PPC::MOF_AddrIsSImm32) { 17988 auto *CN = cast<ConstantSDNode>(N); 17989 EVT CNType = CN->getValueType(0); 17990 uint64_t CNImm = CN->getZExtValue(); 17991 // If this address fits entirely in a 16-bit sext immediate field, codegen 17992 // this as "d, 0". 17993 int16_t Imm; 17994 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) { 17995 Disp = DAG.getTargetConstant(Imm, DL, CNType); 17996 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17997 CNType); 17998 break; 17999 } 18000 // Handle 32-bit sext immediate with LIS + Addr mode. 18001 if ((CNType == MVT::i32 || isInt<32>(CNImm)) && 18002 (!Align || isAligned(*Align, CNImm))) { 18003 int32_t Addr = (int32_t)CNImm; 18004 // Otherwise, break this down into LIS + Disp. 18005 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32); 18006 Base = 18007 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32); 18008 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8; 18009 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0); 18010 break; 18011 } 18012 } 18013 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable. 18014 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout())); 18015 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 18016 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 18017 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 18018 } else 18019 Base = N; 18020 break; 18021 } 18022 case PPC::AM_PrefixDForm: { 18023 int64_t Imm34 = 0; 18024 unsigned Opcode = N.getOpcode(); 18025 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) && 18026 (isIntS34Immediate(N.getOperand(1), Imm34))) { 18027 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate. 18028 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 18029 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 18030 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 18031 else 18032 Base = N.getOperand(0); 18033 } else if (isIntS34Immediate(N, Imm34)) { 18034 // The address is a 34-bit signed immediate. 18035 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 18036 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 18037 } 18038 break; 18039 } 18040 case PPC::AM_PCRel: { 18041 // When selecting PC-Relative instructions, "Base" is not utilized as 18042 // we select the address as [PC+imm]. 18043 Disp = N; 18044 break; 18045 } 18046 case PPC::AM_None: 18047 break; 18048 default: { // By default, X-Form is always available to be selected. 18049 // When a frame index is not aligned, we also match by XForm. 18050 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N); 18051 Base = FI ? N : N.getOperand(1); 18052 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 18053 N.getValueType()) 18054 : N.getOperand(0); 18055 break; 18056 } 18057 } 18058 return Mode; 18059 } 18060 18061 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC, 18062 bool Return, 18063 bool IsVarArg) const { 18064 switch (CC) { 18065 case CallingConv::Cold: 18066 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS); 18067 default: 18068 return CC_PPC64_ELF_FIS; 18069 } 18070 } 18071 18072 bool PPCTargetLowering::shouldInlineQuadwordAtomics() const { 18073 // TODO: 16-byte atomic type support for AIX is in progress; we should be able 18074 // to inline 16-byte atomic ops on AIX too in the future. 18075 return Subtarget.isPPC64() && 18076 (EnableQuadwordAtomics || !Subtarget.getTargetTriple().isOSAIX()) && 18077 Subtarget.hasQuadwordAtomics(); 18078 } 18079 18080 TargetLowering::AtomicExpansionKind 18081 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18082 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18083 if (shouldInlineQuadwordAtomics() && Size == 128) 18084 return AtomicExpansionKind::MaskedIntrinsic; 18085 return TargetLowering::shouldExpandAtomicRMWInIR(AI); 18086 } 18087 18088 TargetLowering::AtomicExpansionKind 18089 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18090 unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits(); 18091 if (shouldInlineQuadwordAtomics() && Size == 128) 18092 return AtomicExpansionKind::MaskedIntrinsic; 18093 return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI); 18094 } 18095 18096 static Intrinsic::ID 18097 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) { 18098 switch (BinOp) { 18099 default: 18100 llvm_unreachable("Unexpected AtomicRMW BinOp"); 18101 case AtomicRMWInst::Xchg: 18102 return Intrinsic::ppc_atomicrmw_xchg_i128; 18103 case AtomicRMWInst::Add: 18104 return Intrinsic::ppc_atomicrmw_add_i128; 18105 case AtomicRMWInst::Sub: 18106 return Intrinsic::ppc_atomicrmw_sub_i128; 18107 case AtomicRMWInst::And: 18108 return Intrinsic::ppc_atomicrmw_and_i128; 18109 case AtomicRMWInst::Or: 18110 return Intrinsic::ppc_atomicrmw_or_i128; 18111 case AtomicRMWInst::Xor: 18112 return Intrinsic::ppc_atomicrmw_xor_i128; 18113 case AtomicRMWInst::Nand: 18114 return Intrinsic::ppc_atomicrmw_nand_i128; 18115 } 18116 } 18117 18118 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic( 18119 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 18120 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 18121 assert(shouldInlineQuadwordAtomics() && "Only support quadword now"); 18122 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18123 Type *ValTy = Incr->getType(); 18124 assert(ValTy->getPrimitiveSizeInBits() == 128); 18125 Function *RMW = Intrinsic::getDeclaration( 18126 M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation())); 18127 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18128 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo"); 18129 Value *IncrHi = 18130 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi"); 18131 Value *Addr = 18132 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18133 Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi}); 18134 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18135 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18136 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18137 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18138 return Builder.CreateOr( 18139 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18140 } 18141 18142 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 18143 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 18144 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 18145 assert(shouldInlineQuadwordAtomics() && "Only support quadword now"); 18146 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18147 Type *ValTy = CmpVal->getType(); 18148 assert(ValTy->getPrimitiveSizeInBits() == 128); 18149 Function *IntCmpXchg = 18150 Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128); 18151 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18152 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo"); 18153 Value *CmpHi = 18154 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi"); 18155 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo"); 18156 Value *NewHi = 18157 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi"); 18158 Value *Addr = 18159 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18160 emitLeadingFence(Builder, CI, Ord); 18161 Value *LoHi = 18162 Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi}); 18163 emitTrailingFence(Builder, CI, Ord); 18164 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18165 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18166 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18167 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18168 return Builder.CreateOr( 18169 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18170 } 18171