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 STATISTIC(NumTailCalls, "Number of tail calls"); 130 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 133 134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 135 136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 137 138 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word"; 139 140 // FIXME: Remove this once the bug has been fixed! 141 extern cl::opt<bool> ANDIGlueBug; 142 143 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 144 const PPCSubtarget &STI) 145 : TargetLowering(TM), Subtarget(STI) { 146 // Initialize map that relates the PPC addressing modes to the computed flags 147 // of a load/store instruction. The map is used to determine the optimal 148 // addressing mode when selecting load and stores. 149 initializeAddrModeMap(); 150 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 151 // arguments are at least 4/8 bytes aligned. 152 bool isPPC64 = Subtarget.isPPC64(); 153 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 154 155 // Set up the register classes. 156 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 157 if (!useSoftFloat()) { 158 if (hasSPE()) { 159 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 160 // EFPU2 APU only supports f32 161 if (!Subtarget.hasEFPU2()) 162 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 163 } else { 164 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 165 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 166 } 167 } 168 169 // Match BITREVERSE to customized fast code sequence in the td file. 170 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 171 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 172 173 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 174 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 175 176 // Custom lower inline assembly to check for special registers. 177 setOperationAction(ISD::INLINEASM, MVT::Other, Custom); 178 setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom); 179 180 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 181 for (MVT VT : MVT::integer_valuetypes()) { 182 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 183 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 184 } 185 186 if (Subtarget.isISA3_0()) { 187 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 188 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 189 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 190 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 191 } else { 192 // No extending loads from f16 or HW conversions back and forth. 193 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 194 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 195 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 196 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 197 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 198 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 199 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 200 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 201 } 202 203 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 204 205 // PowerPC has pre-inc load and store's. 206 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 207 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 208 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 209 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 210 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 211 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 212 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 213 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 214 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 215 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 216 if (!Subtarget.hasSPE()) { 217 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 218 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 219 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 220 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 221 } 222 223 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 224 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 225 for (MVT VT : ScalarIntVTs) { 226 setOperationAction(ISD::ADDC, VT, Legal); 227 setOperationAction(ISD::ADDE, VT, Legal); 228 setOperationAction(ISD::SUBC, VT, Legal); 229 setOperationAction(ISD::SUBE, VT, Legal); 230 } 231 232 if (Subtarget.useCRBits()) { 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 234 235 if (isPPC64 || Subtarget.hasFPCVT()) { 236 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 237 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 238 isPPC64 ? MVT::i64 : MVT::i32); 239 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 240 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 241 isPPC64 ? MVT::i64 : MVT::i32); 242 243 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 244 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 245 isPPC64 ? MVT::i64 : MVT::i32); 246 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 247 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 248 isPPC64 ? MVT::i64 : MVT::i32); 249 250 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 251 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 252 isPPC64 ? MVT::i64 : MVT::i32); 253 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 254 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 255 isPPC64 ? MVT::i64 : MVT::i32); 256 257 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 258 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 259 isPPC64 ? MVT::i64 : MVT::i32); 260 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 261 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 262 isPPC64 ? MVT::i64 : MVT::i32); 263 } else { 264 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 265 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 266 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 267 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 268 } 269 270 // PowerPC does not support direct load/store of condition registers. 271 setOperationAction(ISD::LOAD, MVT::i1, Custom); 272 setOperationAction(ISD::STORE, MVT::i1, Custom); 273 274 // FIXME: Remove this once the ANDI glue bug is fixed: 275 if (ANDIGlueBug) 276 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 277 278 for (MVT VT : MVT::integer_valuetypes()) { 279 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 280 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 281 setTruncStoreAction(VT, MVT::i1, Expand); 282 } 283 284 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 285 } 286 287 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 288 // PPC (the libcall is not available). 289 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 290 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 291 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 292 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 293 294 // We do not currently implement these libm ops for PowerPC. 295 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 296 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 297 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 298 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 299 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 300 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 301 302 // PowerPC has no SREM/UREM instructions unless we are on P9 303 // On P9 we may use a hardware instruction to compute the remainder. 304 // When the result of both the remainder and the division is required it is 305 // more efficient to compute the remainder from the result of the division 306 // rather than use the remainder instruction. The instructions are legalized 307 // directly because the DivRemPairsPass performs the transformation at the IR 308 // level. 309 if (Subtarget.isISA3_0()) { 310 setOperationAction(ISD::SREM, MVT::i32, Legal); 311 setOperationAction(ISD::UREM, MVT::i32, Legal); 312 setOperationAction(ISD::SREM, MVT::i64, Legal); 313 setOperationAction(ISD::UREM, MVT::i64, Legal); 314 } else { 315 setOperationAction(ISD::SREM, MVT::i32, Expand); 316 setOperationAction(ISD::UREM, MVT::i32, Expand); 317 setOperationAction(ISD::SREM, MVT::i64, Expand); 318 setOperationAction(ISD::UREM, MVT::i64, Expand); 319 } 320 321 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 322 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 323 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 324 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 325 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 326 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 327 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 328 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 329 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 330 331 // Handle constrained floating-point operations of scalar. 332 // TODO: Handle SPE specific operation. 333 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 334 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 335 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 336 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 337 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 338 339 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 340 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 341 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 342 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 343 344 if (!Subtarget.hasSPE()) { 345 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 346 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 347 } 348 349 if (Subtarget.hasVSX()) { 350 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 351 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 352 } 353 354 if (Subtarget.hasFSQRT()) { 355 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 356 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 357 } 358 359 if (Subtarget.hasFPRND()) { 360 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 361 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 362 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 363 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 364 365 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 366 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 367 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 368 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 369 } 370 371 // We don't support sin/cos/sqrt/fmod/pow 372 setOperationAction(ISD::FSIN , MVT::f64, Expand); 373 setOperationAction(ISD::FCOS , MVT::f64, Expand); 374 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 375 setOperationAction(ISD::FREM , MVT::f64, Expand); 376 setOperationAction(ISD::FPOW , MVT::f64, Expand); 377 setOperationAction(ISD::FSIN , MVT::f32, Expand); 378 setOperationAction(ISD::FCOS , MVT::f32, Expand); 379 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 380 setOperationAction(ISD::FREM , MVT::f32, Expand); 381 setOperationAction(ISD::FPOW , MVT::f32, Expand); 382 383 // MASS transformation for LLVM intrinsics with replicating fast-math flag 384 // to be consistent to PPCGenScalarMASSEntries pass 385 if (TM.getOptLevel() == CodeGenOpt::Aggressive){ 386 setOperationAction(ISD::FSIN , MVT::f64, Custom); 387 setOperationAction(ISD::FCOS , MVT::f64, Custom); 388 setOperationAction(ISD::FPOW , MVT::f64, Custom); 389 setOperationAction(ISD::FLOG, MVT::f64, Custom); 390 setOperationAction(ISD::FLOG10, MVT::f64, Custom); 391 setOperationAction(ISD::FEXP, MVT::f64, Custom); 392 setOperationAction(ISD::FSIN , MVT::f32, Custom); 393 setOperationAction(ISD::FCOS , MVT::f32, Custom); 394 setOperationAction(ISD::FPOW , MVT::f32, Custom); 395 setOperationAction(ISD::FLOG, MVT::f32, Custom); 396 setOperationAction(ISD::FLOG10, MVT::f32, Custom); 397 setOperationAction(ISD::FEXP, MVT::f32, Custom); 398 } 399 400 if (Subtarget.hasSPE()) { 401 setOperationAction(ISD::FMA , MVT::f64, Expand); 402 setOperationAction(ISD::FMA , MVT::f32, Expand); 403 } else { 404 setOperationAction(ISD::FMA , MVT::f64, Legal); 405 setOperationAction(ISD::FMA , MVT::f32, Legal); 406 } 407 408 if (Subtarget.hasSPE()) 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 411 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 412 413 // If we're enabling GP optimizations, use hardware square root 414 if (!Subtarget.hasFSQRT() && 415 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 416 Subtarget.hasFRE())) 417 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 418 419 if (!Subtarget.hasFSQRT() && 420 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 421 Subtarget.hasFRES())) 422 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 423 424 if (Subtarget.hasFCPSGN()) { 425 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 426 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 427 } else { 428 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 429 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 430 } 431 432 if (Subtarget.hasFPRND()) { 433 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 434 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 435 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 436 setOperationAction(ISD::FROUND, MVT::f64, Legal); 437 438 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 439 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 440 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 441 setOperationAction(ISD::FROUND, MVT::f32, Legal); 442 } 443 444 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 445 // to speed up scalar BSWAP64. 446 // CTPOP or CTTZ were introduced in P8/P9 respectively 447 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 448 if (Subtarget.hasP9Vector() && Subtarget.isPPC64()) 449 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 450 else 451 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 452 if (Subtarget.isISA3_0()) { 453 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 454 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 455 } else { 456 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 457 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 458 } 459 460 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 461 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 462 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 463 } else { 464 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 465 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 466 } 467 468 // PowerPC does not have ROTR 469 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 470 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 471 472 if (!Subtarget.useCRBits()) { 473 // PowerPC does not have Select 474 setOperationAction(ISD::SELECT, MVT::i32, Expand); 475 setOperationAction(ISD::SELECT, MVT::i64, Expand); 476 setOperationAction(ISD::SELECT, MVT::f32, Expand); 477 setOperationAction(ISD::SELECT, MVT::f64, Expand); 478 } 479 480 // PowerPC wants to turn select_cc of FP into fsel when possible. 481 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 482 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 483 484 // PowerPC wants to optimize integer setcc a bit 485 if (!Subtarget.useCRBits()) 486 setOperationAction(ISD::SETCC, MVT::i32, Custom); 487 488 if (Subtarget.hasFPU()) { 489 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 490 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 491 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 492 493 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 494 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 495 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 496 } 497 498 // PowerPC does not have BRCOND which requires SetCC 499 if (!Subtarget.useCRBits()) 500 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 501 502 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 503 504 if (Subtarget.hasSPE()) { 505 // SPE has built-in conversions 506 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 507 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 508 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 509 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 510 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 511 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 512 513 // SPE supports signaling compare of f32/f64. 514 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 515 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 516 } else { 517 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 518 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 519 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 520 521 // PowerPC does not have [U|S]INT_TO_FP 522 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 523 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 524 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 525 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 526 } 527 528 if (Subtarget.hasDirectMove() && isPPC64) { 529 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 530 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 531 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 532 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 533 if (TM.Options.UnsafeFPMath) { 534 setOperationAction(ISD::LRINT, MVT::f64, Legal); 535 setOperationAction(ISD::LRINT, MVT::f32, Legal); 536 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 537 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 538 setOperationAction(ISD::LROUND, MVT::f64, Legal); 539 setOperationAction(ISD::LROUND, MVT::f32, Legal); 540 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 541 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 542 } 543 } else { 544 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 545 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 546 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 547 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 548 } 549 550 // We cannot sextinreg(i1). Expand to shifts. 551 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 552 553 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 554 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 555 // support continuation, user-level threading, and etc.. As a result, no 556 // other SjLj exception interfaces are implemented and please don't build 557 // your own exception handling based on them. 558 // LLVM/Clang supports zero-cost DWARF exception handling. 559 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 560 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 561 562 // We want to legalize GlobalAddress and ConstantPool nodes into the 563 // appropriate instructions to materialize the address. 564 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 565 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 566 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 567 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 568 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 569 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 570 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 571 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 572 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 573 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 574 575 // TRAP is legal. 576 setOperationAction(ISD::TRAP, MVT::Other, Legal); 577 578 // TRAMPOLINE is custom lowered. 579 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 580 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 581 582 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 583 setOperationAction(ISD::VASTART , MVT::Other, Custom); 584 585 if (Subtarget.is64BitELFABI()) { 586 // VAARG always uses double-word chunks, so promote anything smaller. 587 setOperationAction(ISD::VAARG, MVT::i1, Promote); 588 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 589 setOperationAction(ISD::VAARG, MVT::i8, Promote); 590 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 591 setOperationAction(ISD::VAARG, MVT::i16, Promote); 592 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 593 setOperationAction(ISD::VAARG, MVT::i32, Promote); 594 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 595 setOperationAction(ISD::VAARG, MVT::Other, Expand); 596 } else if (Subtarget.is32BitELFABI()) { 597 // VAARG is custom lowered with the 32-bit SVR4 ABI. 598 setOperationAction(ISD::VAARG, MVT::Other, Custom); 599 setOperationAction(ISD::VAARG, MVT::i64, Custom); 600 } else 601 setOperationAction(ISD::VAARG, MVT::Other, Expand); 602 603 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 604 if (Subtarget.is32BitELFABI()) 605 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 606 else 607 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 608 609 // Use the default implementation. 610 setOperationAction(ISD::VAEND , MVT::Other, Expand); 611 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 612 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 613 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 614 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 615 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 616 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 617 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 618 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 619 620 // We want to custom lower some of our intrinsics. 621 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 622 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom); 623 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom); 624 625 // To handle counter-based loop conditions. 626 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 627 628 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 629 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 630 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 631 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 632 633 // Comparisons that require checking two conditions. 634 if (Subtarget.hasSPE()) { 635 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 636 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 637 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 638 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 639 } 640 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 641 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 642 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 643 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 644 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 645 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 646 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 647 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 648 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 649 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 650 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 651 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 652 653 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 654 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 655 656 if (Subtarget.has64BitSupport()) { 657 // They also have instructions for converting between i64 and fp. 658 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 659 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 660 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 661 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 662 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 663 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 664 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 665 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 666 // This is just the low 32 bits of a (signed) fp->i64 conversion. 667 // We cannot do this with Promote because i64 is not a legal type. 668 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 669 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 670 671 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 672 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 673 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 674 } 675 } else { 676 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 677 if (Subtarget.hasSPE()) { 678 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 679 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 680 } else { 681 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 682 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 683 } 684 } 685 686 // With the instructions enabled under FPCVT, we can do everything. 687 if (Subtarget.hasFPCVT()) { 688 if (Subtarget.has64BitSupport()) { 689 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 690 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 691 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 692 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 693 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 694 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 695 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 696 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 697 } 698 699 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 700 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 701 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 702 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 703 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 704 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 705 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 706 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 707 } 708 709 if (Subtarget.use64BitRegs()) { 710 // 64-bit PowerPC implementations can support i64 types directly 711 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 712 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 713 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 714 // 64-bit PowerPC wants to expand i128 shifts itself. 715 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 716 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 717 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 718 } else { 719 // 32-bit PowerPC wants to expand i64 shifts itself. 720 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 721 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 722 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 723 } 724 725 // PowerPC has better expansions for funnel shifts than the generic 726 // TargetLowering::expandFunnelShift. 727 if (Subtarget.has64BitSupport()) { 728 setOperationAction(ISD::FSHL, MVT::i64, Custom); 729 setOperationAction(ISD::FSHR, MVT::i64, Custom); 730 } 731 setOperationAction(ISD::FSHL, MVT::i32, Custom); 732 setOperationAction(ISD::FSHR, MVT::i32, Custom); 733 734 if (Subtarget.hasVSX()) { 735 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 736 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 737 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 738 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 739 } 740 741 if (Subtarget.hasAltivec()) { 742 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 743 setOperationAction(ISD::SADDSAT, VT, Legal); 744 setOperationAction(ISD::SSUBSAT, VT, Legal); 745 setOperationAction(ISD::UADDSAT, VT, Legal); 746 setOperationAction(ISD::USUBSAT, VT, Legal); 747 } 748 // First set operation action for all vector types to expand. Then we 749 // will selectively turn on ones that can be effectively codegen'd. 750 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 751 // add/sub are legal for all supported vector VT's. 752 setOperationAction(ISD::ADD, VT, Legal); 753 setOperationAction(ISD::SUB, VT, Legal); 754 755 // For v2i64, these are only valid with P8Vector. This is corrected after 756 // the loop. 757 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 758 setOperationAction(ISD::SMAX, VT, Legal); 759 setOperationAction(ISD::SMIN, VT, Legal); 760 setOperationAction(ISD::UMAX, VT, Legal); 761 setOperationAction(ISD::UMIN, VT, Legal); 762 } 763 else { 764 setOperationAction(ISD::SMAX, VT, Expand); 765 setOperationAction(ISD::SMIN, VT, Expand); 766 setOperationAction(ISD::UMAX, VT, Expand); 767 setOperationAction(ISD::UMIN, VT, Expand); 768 } 769 770 if (Subtarget.hasVSX()) { 771 setOperationAction(ISD::FMAXNUM, VT, Legal); 772 setOperationAction(ISD::FMINNUM, VT, Legal); 773 } 774 775 // Vector instructions introduced in P8 776 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 777 setOperationAction(ISD::CTPOP, VT, Legal); 778 setOperationAction(ISD::CTLZ, VT, Legal); 779 } 780 else { 781 setOperationAction(ISD::CTPOP, VT, Expand); 782 setOperationAction(ISD::CTLZ, VT, Expand); 783 } 784 785 // Vector instructions introduced in P9 786 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 787 setOperationAction(ISD::CTTZ, VT, Legal); 788 else 789 setOperationAction(ISD::CTTZ, VT, Expand); 790 791 // We promote all shuffles to v16i8. 792 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 793 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 794 795 // We promote all non-typed operations to v4i32. 796 setOperationAction(ISD::AND , VT, Promote); 797 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 798 setOperationAction(ISD::OR , VT, Promote); 799 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 800 setOperationAction(ISD::XOR , VT, Promote); 801 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 802 setOperationAction(ISD::LOAD , VT, Promote); 803 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 804 setOperationAction(ISD::SELECT, VT, Promote); 805 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 806 setOperationAction(ISD::VSELECT, VT, Legal); 807 setOperationAction(ISD::SELECT_CC, VT, Promote); 808 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 809 setOperationAction(ISD::STORE, VT, Promote); 810 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 811 812 // No other operations are legal. 813 setOperationAction(ISD::MUL , VT, Expand); 814 setOperationAction(ISD::SDIV, VT, Expand); 815 setOperationAction(ISD::SREM, VT, Expand); 816 setOperationAction(ISD::UDIV, VT, Expand); 817 setOperationAction(ISD::UREM, VT, Expand); 818 setOperationAction(ISD::FDIV, VT, Expand); 819 setOperationAction(ISD::FREM, VT, Expand); 820 setOperationAction(ISD::FNEG, VT, Expand); 821 setOperationAction(ISD::FSQRT, VT, Expand); 822 setOperationAction(ISD::FLOG, VT, Expand); 823 setOperationAction(ISD::FLOG10, VT, Expand); 824 setOperationAction(ISD::FLOG2, VT, Expand); 825 setOperationAction(ISD::FEXP, VT, Expand); 826 setOperationAction(ISD::FEXP2, VT, Expand); 827 setOperationAction(ISD::FSIN, VT, Expand); 828 setOperationAction(ISD::FCOS, VT, Expand); 829 setOperationAction(ISD::FABS, VT, Expand); 830 setOperationAction(ISD::FFLOOR, VT, Expand); 831 setOperationAction(ISD::FCEIL, VT, Expand); 832 setOperationAction(ISD::FTRUNC, VT, Expand); 833 setOperationAction(ISD::FRINT, VT, Expand); 834 setOperationAction(ISD::FNEARBYINT, VT, Expand); 835 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 836 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 837 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 838 setOperationAction(ISD::MULHU, VT, Expand); 839 setOperationAction(ISD::MULHS, VT, Expand); 840 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 841 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 842 setOperationAction(ISD::UDIVREM, VT, Expand); 843 setOperationAction(ISD::SDIVREM, VT, Expand); 844 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 845 setOperationAction(ISD::FPOW, VT, Expand); 846 setOperationAction(ISD::BSWAP, VT, Expand); 847 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 848 setOperationAction(ISD::ROTL, VT, Expand); 849 setOperationAction(ISD::ROTR, VT, Expand); 850 851 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 852 setTruncStoreAction(VT, InnerVT, Expand); 853 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 854 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 855 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 856 } 857 } 858 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 859 if (!Subtarget.hasP8Vector()) { 860 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 861 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 862 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 863 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 864 } 865 866 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 867 // with merges, splats, etc. 868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 869 870 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 871 // are cheap, so handle them before they get expanded to scalar. 872 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 873 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 874 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 875 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 876 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 877 878 setOperationAction(ISD::AND , MVT::v4i32, Legal); 879 setOperationAction(ISD::OR , MVT::v4i32, Legal); 880 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 881 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 882 setOperationAction(ISD::SELECT, MVT::v4i32, 883 Subtarget.useCRBits() ? Legal : Expand); 884 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 885 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 886 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 887 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 888 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 889 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 890 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 891 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 892 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 893 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 894 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 895 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 896 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 897 898 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 899 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 900 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 901 if (Subtarget.hasAltivec()) 902 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 903 setOperationAction(ISD::ROTL, VT, Legal); 904 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 905 if (Subtarget.hasP8Altivec()) 906 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 907 908 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 909 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 910 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 911 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 912 913 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 914 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 915 916 if (Subtarget.hasVSX()) { 917 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 918 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 919 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 920 } 921 922 if (Subtarget.hasP8Altivec()) 923 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 924 else 925 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 926 927 if (Subtarget.isISA3_1()) { 928 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 929 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 930 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 931 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 932 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 933 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 934 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 935 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 936 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 937 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 938 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 939 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 940 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 941 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 942 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 943 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 944 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 945 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 946 } 947 948 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 949 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 950 951 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 952 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 953 954 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 955 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 956 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 957 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 958 959 // Altivec does not contain unordered floating-point compare instructions 960 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 961 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 962 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 963 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 964 965 if (Subtarget.hasVSX()) { 966 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 967 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 968 if (Subtarget.hasP8Vector()) { 969 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 970 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 971 } 972 if (Subtarget.hasDirectMove() && isPPC64) { 973 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 974 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 975 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 976 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 977 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 979 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 980 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 981 } 982 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 983 984 // The nearbyint variants are not allowed to raise the inexact exception 985 // so we can only code-gen them with unsafe math. 986 if (TM.Options.UnsafeFPMath) { 987 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 988 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 989 } 990 991 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 992 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 993 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 994 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 995 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 996 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 997 setOperationAction(ISD::FROUND, MVT::f64, Legal); 998 setOperationAction(ISD::FRINT, MVT::f64, Legal); 999 1000 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 1001 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 1002 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1003 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1004 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1005 1006 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 1007 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 1008 1009 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 1010 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 1011 1012 // Share the Altivec comparison restrictions. 1013 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 1014 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 1015 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 1016 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 1017 1018 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 1019 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 1020 1021 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 1022 1023 if (Subtarget.hasP8Vector()) 1024 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 1025 1026 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 1027 1028 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 1029 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 1030 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 1031 1032 if (Subtarget.hasP8Altivec()) { 1033 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 1034 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 1035 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 1036 1037 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1038 // SRL, but not for SRA because of the instructions available: 1039 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1040 // doing 1041 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1042 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1043 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1044 1045 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1046 } 1047 else { 1048 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1049 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1050 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1051 1052 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1053 1054 // VSX v2i64 only supports non-arithmetic operations. 1055 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1056 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1057 } 1058 1059 if (Subtarget.isISA3_1()) 1060 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1061 else 1062 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1063 1064 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1065 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1066 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1067 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1068 1069 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1070 1071 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1072 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1073 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1074 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1075 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1076 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1077 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1078 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1079 1080 // Custom handling for partial vectors of integers converted to 1081 // floating point. We already have optimal handling for v2i32 through 1082 // the DAG combine, so those aren't necessary. 1083 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1084 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1085 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1086 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1087 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1088 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1089 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1090 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1091 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1092 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1093 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1094 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1095 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1096 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1097 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1098 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1099 1100 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1101 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1102 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1103 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1104 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1105 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1106 1107 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1108 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1109 1110 // Handle constrained floating-point operations of vector. 1111 // The predictor is `hasVSX` because altivec instruction has 1112 // no exception but VSX vector instruction has. 1113 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1114 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1115 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1116 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1117 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1118 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1119 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1120 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1121 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1122 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1123 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1124 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1125 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1126 1127 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1128 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1129 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1130 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1131 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1132 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1133 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1134 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1135 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1136 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1137 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1138 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1139 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1140 1141 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1142 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1143 1144 for (MVT FPT : MVT::fp_valuetypes()) 1145 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1146 1147 // Expand the SELECT to SELECT_CC 1148 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1149 1150 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1151 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1152 1153 // No implementation for these ops for PowerPC. 1154 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1155 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1156 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1157 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1158 setOperationAction(ISD::FREM, MVT::f128, Expand); 1159 } 1160 1161 if (Subtarget.hasP8Altivec()) { 1162 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1163 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1164 } 1165 1166 if (Subtarget.hasP9Vector()) { 1167 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1168 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1169 1170 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1171 // SRL, but not for SRA because of the instructions available: 1172 // VS{RL} and VS{RL}O. 1173 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1174 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1175 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1176 1177 setOperationAction(ISD::FADD, MVT::f128, Legal); 1178 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1179 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1180 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1181 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1182 1183 setOperationAction(ISD::FMA, MVT::f128, Legal); 1184 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1185 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1186 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1187 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1188 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1189 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1190 1191 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1192 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1193 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1194 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1195 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1196 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1197 1198 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1199 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1200 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1201 1202 // Handle constrained floating-point operations of fp128 1203 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1204 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1205 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1206 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1207 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1208 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1209 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1210 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1211 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1212 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1213 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1214 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1215 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1216 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1217 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1218 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1219 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1220 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1221 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1222 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1223 } else if (Subtarget.hasVSX()) { 1224 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1225 setOperationAction(ISD::STORE, MVT::f128, Promote); 1226 1227 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1228 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1229 1230 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1231 // fp_to_uint and int_to_fp. 1232 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1233 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1234 1235 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1236 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1237 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1238 setOperationAction(ISD::FABS, MVT::f128, Expand); 1239 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1240 setOperationAction(ISD::FMA, MVT::f128, Expand); 1241 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1242 1243 // Expand the fp_extend if the target type is fp128. 1244 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1245 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1246 1247 // Expand the fp_round if the source type is fp128. 1248 for (MVT VT : {MVT::f32, MVT::f64}) { 1249 setOperationAction(ISD::FP_ROUND, VT, Custom); 1250 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1251 } 1252 1253 setOperationAction(ISD::SETCC, MVT::f128, Custom); 1254 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 1255 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 1256 setOperationAction(ISD::BR_CC, MVT::f128, Expand); 1257 1258 // Lower following f128 select_cc pattern: 1259 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE 1260 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1261 1262 // We need to handle f128 SELECT_CC with integer result type. 1263 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1264 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand); 1265 } 1266 1267 if (Subtarget.hasP9Altivec()) { 1268 if (Subtarget.isISA3_1()) { 1269 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 1270 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal); 1271 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal); 1272 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal); 1273 } else { 1274 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1275 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1276 } 1277 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1278 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1279 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1280 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1281 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1282 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1283 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1284 } 1285 } 1286 1287 if (Subtarget.pairedVectorMemops()) { 1288 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1289 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1290 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1291 } 1292 if (Subtarget.hasMMA()) { 1293 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1294 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1295 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1296 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1297 } 1298 1299 if (Subtarget.has64BitSupport()) 1300 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1301 1302 if (Subtarget.isISA3_1()) 1303 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1304 1305 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1306 1307 if (!isPPC64) { 1308 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1309 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1310 } 1311 1312 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) { 1313 setMaxAtomicSizeInBitsSupported(128); 1314 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom); 1315 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom); 1316 setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom); 1317 } 1318 1319 setBooleanContents(ZeroOrOneBooleanContent); 1320 1321 if (Subtarget.hasAltivec()) { 1322 // Altivec instructions set fields to all zeros or all ones. 1323 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1324 } 1325 1326 if (!isPPC64) { 1327 // These libcalls are not available in 32-bit. 1328 setLibcallName(RTLIB::SHL_I128, nullptr); 1329 setLibcallName(RTLIB::SRL_I128, nullptr); 1330 setLibcallName(RTLIB::SRA_I128, nullptr); 1331 setLibcallName(RTLIB::MULO_I64, nullptr); 1332 } 1333 1334 if (!isPPC64) 1335 setMaxAtomicSizeInBitsSupported(32); 1336 1337 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1338 1339 // We have target-specific dag combine patterns for the following nodes: 1340 setTargetDAGCombine(ISD::ADD); 1341 setTargetDAGCombine(ISD::SHL); 1342 setTargetDAGCombine(ISD::SRA); 1343 setTargetDAGCombine(ISD::SRL); 1344 setTargetDAGCombine(ISD::MUL); 1345 setTargetDAGCombine(ISD::FMA); 1346 setTargetDAGCombine(ISD::SINT_TO_FP); 1347 setTargetDAGCombine(ISD::BUILD_VECTOR); 1348 if (Subtarget.hasFPCVT()) 1349 setTargetDAGCombine(ISD::UINT_TO_FP); 1350 setTargetDAGCombine(ISD::LOAD); 1351 setTargetDAGCombine(ISD::STORE); 1352 setTargetDAGCombine(ISD::BR_CC); 1353 if (Subtarget.useCRBits()) 1354 setTargetDAGCombine(ISD::BRCOND); 1355 setTargetDAGCombine(ISD::BSWAP); 1356 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1357 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1358 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1359 1360 setTargetDAGCombine(ISD::SIGN_EXTEND); 1361 setTargetDAGCombine(ISD::ZERO_EXTEND); 1362 setTargetDAGCombine(ISD::ANY_EXTEND); 1363 1364 setTargetDAGCombine(ISD::TRUNCATE); 1365 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1366 1367 1368 if (Subtarget.useCRBits()) { 1369 setTargetDAGCombine(ISD::TRUNCATE); 1370 setTargetDAGCombine(ISD::SETCC); 1371 setTargetDAGCombine(ISD::SELECT_CC); 1372 } 1373 1374 if (Subtarget.hasP9Altivec()) { 1375 setTargetDAGCombine(ISD::ABS); 1376 setTargetDAGCombine(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::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1608 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 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 = 1887 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1888 if (!Subtarget.hasP8Vector()) 1889 return false; 1890 1891 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1892 if (ShuffleKind == 0) { 1893 if (IsLE) 1894 return false; 1895 for (unsigned i = 0; i != 16; i += 4) 1896 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1897 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1898 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1899 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1900 return false; 1901 } else if (ShuffleKind == 2) { 1902 if (!IsLE) 1903 return false; 1904 for (unsigned i = 0; i != 16; i += 4) 1905 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1906 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1907 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1908 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1909 return false; 1910 } else if (ShuffleKind == 1) { 1911 unsigned j = IsLE ? 0 : 4; 1912 for (unsigned i = 0; i != 8; i += 4) 1913 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1914 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1915 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1916 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1917 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1918 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1919 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1920 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1921 return false; 1922 } 1923 return true; 1924 } 1925 1926 /// isVMerge - Common function, used to match vmrg* shuffles. 1927 /// 1928 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1929 unsigned LHSStart, unsigned RHSStart) { 1930 if (N->getValueType(0) != MVT::v16i8) 1931 return false; 1932 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1933 "Unsupported merge size!"); 1934 1935 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1936 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1937 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1938 LHSStart+j+i*UnitSize) || 1939 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1940 RHSStart+j+i*UnitSize)) 1941 return false; 1942 } 1943 return true; 1944 } 1945 1946 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1947 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1948 /// The ShuffleKind distinguishes between big-endian merges with two 1949 /// different inputs (0), either-endian merges with two identical inputs (1), 1950 /// and little-endian merges with two different inputs (2). For the latter, 1951 /// the input operands are swapped (see PPCInstrAltivec.td). 1952 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1953 unsigned ShuffleKind, SelectionDAG &DAG) { 1954 if (DAG.getDataLayout().isLittleEndian()) { 1955 if (ShuffleKind == 1) // unary 1956 return isVMerge(N, UnitSize, 0, 0); 1957 else if (ShuffleKind == 2) // swapped 1958 return isVMerge(N, UnitSize, 0, 16); 1959 else 1960 return false; 1961 } else { 1962 if (ShuffleKind == 1) // unary 1963 return isVMerge(N, UnitSize, 8, 8); 1964 else if (ShuffleKind == 0) // normal 1965 return isVMerge(N, UnitSize, 8, 24); 1966 else 1967 return false; 1968 } 1969 } 1970 1971 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1972 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1973 /// The ShuffleKind distinguishes between big-endian merges with two 1974 /// different inputs (0), either-endian merges with two identical inputs (1), 1975 /// and little-endian merges with two different inputs (2). For the latter, 1976 /// the input operands are swapped (see PPCInstrAltivec.td). 1977 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1978 unsigned ShuffleKind, SelectionDAG &DAG) { 1979 if (DAG.getDataLayout().isLittleEndian()) { 1980 if (ShuffleKind == 1) // unary 1981 return isVMerge(N, UnitSize, 8, 8); 1982 else if (ShuffleKind == 2) // swapped 1983 return isVMerge(N, UnitSize, 8, 24); 1984 else 1985 return false; 1986 } else { 1987 if (ShuffleKind == 1) // unary 1988 return isVMerge(N, UnitSize, 0, 0); 1989 else if (ShuffleKind == 0) // normal 1990 return isVMerge(N, UnitSize, 0, 16); 1991 else 1992 return false; 1993 } 1994 } 1995 1996 /** 1997 * Common function used to match vmrgew and vmrgow shuffles 1998 * 1999 * The indexOffset determines whether to look for even or odd words in 2000 * the shuffle mask. This is based on the of the endianness of the target 2001 * machine. 2002 * - Little Endian: 2003 * - Use offset of 0 to check for odd elements 2004 * - Use offset of 4 to check for even elements 2005 * - Big Endian: 2006 * - Use offset of 0 to check for even elements 2007 * - Use offset of 4 to check for odd elements 2008 * A detailed description of the vector element ordering for little endian and 2009 * big endian can be found at 2010 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 2011 * Targeting your applications - what little endian and big endian IBM XL C/C++ 2012 * compiler differences mean to you 2013 * 2014 * The mask to the shuffle vector instruction specifies the indices of the 2015 * elements from the two input vectors to place in the result. The elements are 2016 * numbered in array-access order, starting with the first vector. These vectors 2017 * are always of type v16i8, thus each vector will contain 16 elements of size 2018 * 8. More info on the shuffle vector can be found in the 2019 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 2020 * Language Reference. 2021 * 2022 * The RHSStartValue indicates whether the same input vectors are used (unary) 2023 * or two different input vectors are used, based on the following: 2024 * - If the instruction uses the same vector for both inputs, the range of the 2025 * indices will be 0 to 15. In this case, the RHSStart value passed should 2026 * be 0. 2027 * - If the instruction has two different vectors then the range of the 2028 * indices will be 0 to 31. In this case, the RHSStart value passed should 2029 * be 16 (indices 0-15 specify elements in the first vector while indices 16 2030 * to 31 specify elements in the second vector). 2031 * 2032 * \param[in] N The shuffle vector SD Node to analyze 2033 * \param[in] IndexOffset Specifies whether to look for even or odd elements 2034 * \param[in] RHSStartValue Specifies the starting index for the righthand input 2035 * vector to the shuffle_vector instruction 2036 * \return true iff this shuffle vector represents an even or odd word merge 2037 */ 2038 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 2039 unsigned RHSStartValue) { 2040 if (N->getValueType(0) != MVT::v16i8) 2041 return false; 2042 2043 for (unsigned i = 0; i < 2; ++i) 2044 for (unsigned j = 0; j < 4; ++j) 2045 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 2046 i*RHSStartValue+j+IndexOffset) || 2047 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 2048 i*RHSStartValue+j+IndexOffset+8)) 2049 return false; 2050 return true; 2051 } 2052 2053 /** 2054 * Determine if the specified shuffle mask is suitable for the vmrgew or 2055 * vmrgow instructions. 2056 * 2057 * \param[in] N The shuffle vector SD Node to analyze 2058 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 2059 * \param[in] ShuffleKind Identify the type of merge: 2060 * - 0 = big-endian merge with two different inputs; 2061 * - 1 = either-endian merge with two identical inputs; 2062 * - 2 = little-endian merge with two different inputs (inputs are swapped for 2063 * little-endian merges). 2064 * \param[in] DAG The current SelectionDAG 2065 * \return true iff this shuffle mask 2066 */ 2067 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 2068 unsigned ShuffleKind, SelectionDAG &DAG) { 2069 if (DAG.getDataLayout().isLittleEndian()) { 2070 unsigned indexOffset = CheckEven ? 4 : 0; 2071 if (ShuffleKind == 1) // Unary 2072 return isVMerge(N, indexOffset, 0); 2073 else if (ShuffleKind == 2) // swapped 2074 return isVMerge(N, indexOffset, 16); 2075 else 2076 return false; 2077 } 2078 else { 2079 unsigned indexOffset = CheckEven ? 0 : 4; 2080 if (ShuffleKind == 1) // Unary 2081 return isVMerge(N, indexOffset, 0); 2082 else if (ShuffleKind == 0) // Normal 2083 return isVMerge(N, indexOffset, 16); 2084 else 2085 return false; 2086 } 2087 return false; 2088 } 2089 2090 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 2091 /// amount, otherwise return -1. 2092 /// The ShuffleKind distinguishes between big-endian operations with two 2093 /// different inputs (0), either-endian operations with two identical inputs 2094 /// (1), and little-endian operations with two different inputs (2). For the 2095 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 2096 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 2097 SelectionDAG &DAG) { 2098 if (N->getValueType(0) != MVT::v16i8) 2099 return -1; 2100 2101 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2102 2103 // Find the first non-undef value in the shuffle mask. 2104 unsigned i; 2105 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 2106 /*search*/; 2107 2108 if (i == 16) return -1; // all undef. 2109 2110 // Otherwise, check to see if the rest of the elements are consecutively 2111 // numbered from this value. 2112 unsigned ShiftAmt = SVOp->getMaskElt(i); 2113 if (ShiftAmt < i) return -1; 2114 2115 ShiftAmt -= i; 2116 bool isLE = DAG.getDataLayout().isLittleEndian(); 2117 2118 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 2119 // Check the rest of the elements to see if they are consecutive. 2120 for (++i; i != 16; ++i) 2121 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2122 return -1; 2123 } else if (ShuffleKind == 1) { 2124 // Check the rest of the elements to see if they are consecutive. 2125 for (++i; i != 16; ++i) 2126 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 2127 return -1; 2128 } else 2129 return -1; 2130 2131 if (isLE) 2132 ShiftAmt = 16 - ShiftAmt; 2133 2134 return ShiftAmt; 2135 } 2136 2137 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 2138 /// specifies a splat of a single element that is suitable for input to 2139 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 2140 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 2141 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 2142 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2143 2144 // The consecutive indices need to specify an element, not part of two 2145 // different elements. So abandon ship early if this isn't the case. 2146 if (N->getMaskElt(0) % EltSize != 0) 2147 return false; 2148 2149 // This is a splat operation if each element of the permute is the same, and 2150 // if the value doesn't reference the second vector. 2151 unsigned ElementBase = N->getMaskElt(0); 2152 2153 // FIXME: Handle UNDEF elements too! 2154 if (ElementBase >= 16) 2155 return false; 2156 2157 // Check that the indices are consecutive, in the case of a multi-byte element 2158 // splatted with a v16i8 mask. 2159 for (unsigned i = 1; i != EltSize; ++i) 2160 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2161 return false; 2162 2163 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2164 if (N->getMaskElt(i) < 0) continue; 2165 for (unsigned j = 0; j != EltSize; ++j) 2166 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2167 return false; 2168 } 2169 return true; 2170 } 2171 2172 /// Check that the mask is shuffling N byte elements. Within each N byte 2173 /// element of the mask, the indices could be either in increasing or 2174 /// decreasing order as long as they are consecutive. 2175 /// \param[in] N the shuffle vector SD Node to analyze 2176 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2177 /// Word/DoubleWord/QuadWord). 2178 /// \param[in] StepLen the delta indices number among the N byte element, if 2179 /// the mask is in increasing/decreasing order then it is 1/-1. 2180 /// \return true iff the mask is shuffling N byte elements. 2181 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2182 int StepLen) { 2183 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2184 "Unexpected element width."); 2185 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2186 2187 unsigned NumOfElem = 16 / Width; 2188 unsigned MaskVal[16]; // Width is never greater than 16 2189 for (unsigned i = 0; i < NumOfElem; ++i) { 2190 MaskVal[0] = N->getMaskElt(i * Width); 2191 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2192 return false; 2193 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2194 return false; 2195 } 2196 2197 for (unsigned int j = 1; j < Width; ++j) { 2198 MaskVal[j] = N->getMaskElt(i * Width + j); 2199 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2200 return false; 2201 } 2202 } 2203 } 2204 2205 return true; 2206 } 2207 2208 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2209 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2210 if (!isNByteElemShuffleMask(N, 4, 1)) 2211 return false; 2212 2213 // Now we look at mask elements 0,4,8,12 2214 unsigned M0 = N->getMaskElt(0) / 4; 2215 unsigned M1 = N->getMaskElt(4) / 4; 2216 unsigned M2 = N->getMaskElt(8) / 4; 2217 unsigned M3 = N->getMaskElt(12) / 4; 2218 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2219 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2220 2221 // Below, let H and L be arbitrary elements of the shuffle mask 2222 // where H is in the range [4,7] and L is in the range [0,3]. 2223 // H, 1, 2, 3 or L, 5, 6, 7 2224 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2225 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2226 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2227 InsertAtByte = IsLE ? 12 : 0; 2228 Swap = M0 < 4; 2229 return true; 2230 } 2231 // 0, H, 2, 3 or 4, L, 6, 7 2232 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2233 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2234 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2235 InsertAtByte = IsLE ? 8 : 4; 2236 Swap = M1 < 4; 2237 return true; 2238 } 2239 // 0, 1, H, 3 or 4, 5, L, 7 2240 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2241 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2242 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2243 InsertAtByte = IsLE ? 4 : 8; 2244 Swap = M2 < 4; 2245 return true; 2246 } 2247 // 0, 1, 2, H or 4, 5, 6, L 2248 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2249 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2250 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2251 InsertAtByte = IsLE ? 0 : 12; 2252 Swap = M3 < 4; 2253 return true; 2254 } 2255 2256 // If both vector operands for the shuffle are the same vector, the mask will 2257 // contain only elements from the first one and the second one will be undef. 2258 if (N->getOperand(1).isUndef()) { 2259 ShiftElts = 0; 2260 Swap = true; 2261 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2262 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2263 InsertAtByte = IsLE ? 12 : 0; 2264 return true; 2265 } 2266 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2267 InsertAtByte = IsLE ? 8 : 4; 2268 return true; 2269 } 2270 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2271 InsertAtByte = IsLE ? 4 : 8; 2272 return true; 2273 } 2274 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2275 InsertAtByte = IsLE ? 0 : 12; 2276 return true; 2277 } 2278 } 2279 2280 return false; 2281 } 2282 2283 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2284 bool &Swap, bool IsLE) { 2285 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2286 // Ensure each byte index of the word is consecutive. 2287 if (!isNByteElemShuffleMask(N, 4, 1)) 2288 return false; 2289 2290 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2291 unsigned M0 = N->getMaskElt(0) / 4; 2292 unsigned M1 = N->getMaskElt(4) / 4; 2293 unsigned M2 = N->getMaskElt(8) / 4; 2294 unsigned M3 = N->getMaskElt(12) / 4; 2295 2296 // If both vector operands for the shuffle are the same vector, the mask will 2297 // contain only elements from the first one and the second one will be undef. 2298 if (N->getOperand(1).isUndef()) { 2299 assert(M0 < 4 && "Indexing into an undef vector?"); 2300 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2301 return false; 2302 2303 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2304 Swap = false; 2305 return true; 2306 } 2307 2308 // Ensure each word index of the ShuffleVector Mask is consecutive. 2309 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2310 return false; 2311 2312 if (IsLE) { 2313 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2314 // Input vectors don't need to be swapped if the leading element 2315 // of the result is one of the 3 left elements of the second vector 2316 // (or if there is no shift to be done at all). 2317 Swap = false; 2318 ShiftElts = (8 - M0) % 8; 2319 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2320 // Input vectors need to be swapped if the leading element 2321 // of the result is one of the 3 left elements of the first vector 2322 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2323 Swap = true; 2324 ShiftElts = (4 - M0) % 4; 2325 } 2326 2327 return true; 2328 } else { // BE 2329 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2330 // Input vectors don't need to be swapped if the leading element 2331 // of the result is one of the 4 elements of the first vector. 2332 Swap = false; 2333 ShiftElts = M0; 2334 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2335 // Input vectors need to be swapped if the leading element 2336 // of the result is one of the 4 elements of the right vector. 2337 Swap = true; 2338 ShiftElts = M0 - 4; 2339 } 2340 2341 return true; 2342 } 2343 } 2344 2345 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2346 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2347 2348 if (!isNByteElemShuffleMask(N, Width, -1)) 2349 return false; 2350 2351 for (int i = 0; i < 16; i += Width) 2352 if (N->getMaskElt(i) != i + Width - 1) 2353 return false; 2354 2355 return true; 2356 } 2357 2358 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2359 return isXXBRShuffleMaskHelper(N, 2); 2360 } 2361 2362 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2363 return isXXBRShuffleMaskHelper(N, 4); 2364 } 2365 2366 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2367 return isXXBRShuffleMaskHelper(N, 8); 2368 } 2369 2370 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2371 return isXXBRShuffleMaskHelper(N, 16); 2372 } 2373 2374 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2375 /// if the inputs to the instruction should be swapped and set \p DM to the 2376 /// value for the immediate. 2377 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2378 /// AND element 0 of the result comes from the first input (LE) or second input 2379 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2380 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2381 /// mask. 2382 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2383 bool &Swap, bool IsLE) { 2384 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2385 2386 // Ensure each byte index of the double word is consecutive. 2387 if (!isNByteElemShuffleMask(N, 8, 1)) 2388 return false; 2389 2390 unsigned M0 = N->getMaskElt(0) / 8; 2391 unsigned M1 = N->getMaskElt(8) / 8; 2392 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2393 2394 // If both vector operands for the shuffle are the same vector, the mask will 2395 // contain only elements from the first one and the second one will be undef. 2396 if (N->getOperand(1).isUndef()) { 2397 if ((M0 | M1) < 2) { 2398 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2399 Swap = false; 2400 return true; 2401 } else 2402 return false; 2403 } 2404 2405 if (IsLE) { 2406 if (M0 > 1 && M1 < 2) { 2407 Swap = false; 2408 } else if (M0 < 2 && M1 > 1) { 2409 M0 = (M0 + 2) % 4; 2410 M1 = (M1 + 2) % 4; 2411 Swap = true; 2412 } else 2413 return false; 2414 2415 // Note: if control flow comes here that means Swap is already set above 2416 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2417 return true; 2418 } else { // BE 2419 if (M0 < 2 && M1 > 1) { 2420 Swap = false; 2421 } else if (M0 > 1 && M1 < 2) { 2422 M0 = (M0 + 2) % 4; 2423 M1 = (M1 + 2) % 4; 2424 Swap = true; 2425 } else 2426 return false; 2427 2428 // Note: if control flow comes here that means Swap is already set above 2429 DM = (M0 << 1) + (M1 & 1); 2430 return true; 2431 } 2432 } 2433 2434 2435 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2436 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2437 /// elements are counted from the left of the vector register). 2438 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2439 SelectionDAG &DAG) { 2440 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2441 assert(isSplatShuffleMask(SVOp, EltSize)); 2442 if (DAG.getDataLayout().isLittleEndian()) 2443 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2444 else 2445 return SVOp->getMaskElt(0) / EltSize; 2446 } 2447 2448 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2449 /// by using a vspltis[bhw] instruction of the specified element size, return 2450 /// the constant being splatted. The ByteSize field indicates the number of 2451 /// bytes of each element [124] -> [bhw]. 2452 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2453 SDValue OpVal; 2454 2455 // If ByteSize of the splat is bigger than the element size of the 2456 // build_vector, then we have a case where we are checking for a splat where 2457 // multiple elements of the buildvector are folded together into a single 2458 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2459 unsigned EltSize = 16/N->getNumOperands(); 2460 if (EltSize < ByteSize) { 2461 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2462 SDValue UniquedVals[4]; 2463 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2464 2465 // See if all of the elements in the buildvector agree across. 2466 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2467 if (N->getOperand(i).isUndef()) continue; 2468 // If the element isn't a constant, bail fully out. 2469 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2470 2471 if (!UniquedVals[i&(Multiple-1)].getNode()) 2472 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2473 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2474 return SDValue(); // no match. 2475 } 2476 2477 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2478 // either constant or undef values that are identical for each chunk. See 2479 // if these chunks can form into a larger vspltis*. 2480 2481 // Check to see if all of the leading entries are either 0 or -1. If 2482 // neither, then this won't fit into the immediate field. 2483 bool LeadingZero = true; 2484 bool LeadingOnes = true; 2485 for (unsigned i = 0; i != Multiple-1; ++i) { 2486 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2487 2488 LeadingZero &= isNullConstant(UniquedVals[i]); 2489 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2490 } 2491 // Finally, check the least significant entry. 2492 if (LeadingZero) { 2493 if (!UniquedVals[Multiple-1].getNode()) 2494 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2495 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2496 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2497 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2498 } 2499 if (LeadingOnes) { 2500 if (!UniquedVals[Multiple-1].getNode()) 2501 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2502 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2503 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2504 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2505 } 2506 2507 return SDValue(); 2508 } 2509 2510 // Check to see if this buildvec has a single non-undef value in its elements. 2511 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2512 if (N->getOperand(i).isUndef()) continue; 2513 if (!OpVal.getNode()) 2514 OpVal = N->getOperand(i); 2515 else if (OpVal != N->getOperand(i)) 2516 return SDValue(); 2517 } 2518 2519 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2520 2521 unsigned ValSizeInBytes = EltSize; 2522 uint64_t Value = 0; 2523 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2524 Value = CN->getZExtValue(); 2525 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2526 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2527 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2528 } 2529 2530 // If the splat value is larger than the element value, then we can never do 2531 // this splat. The only case that we could fit the replicated bits into our 2532 // immediate field for would be zero, and we prefer to use vxor for it. 2533 if (ValSizeInBytes < ByteSize) return SDValue(); 2534 2535 // If the element value is larger than the splat value, check if it consists 2536 // of a repeated bit pattern of size ByteSize. 2537 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2538 return SDValue(); 2539 2540 // Properly sign extend the value. 2541 int MaskVal = SignExtend32(Value, ByteSize * 8); 2542 2543 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2544 if (MaskVal == 0) return SDValue(); 2545 2546 // Finally, if this value fits in a 5 bit sext field, return it 2547 if (SignExtend32<5>(MaskVal) == MaskVal) 2548 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2549 return SDValue(); 2550 } 2551 2552 //===----------------------------------------------------------------------===// 2553 // Addressing Mode Selection 2554 //===----------------------------------------------------------------------===// 2555 2556 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2557 /// or 64-bit immediate, and if the value can be accurately represented as a 2558 /// sign extension from a 16-bit value. If so, this returns true and the 2559 /// immediate. 2560 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2561 if (!isa<ConstantSDNode>(N)) 2562 return false; 2563 2564 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2565 if (N->getValueType(0) == MVT::i32) 2566 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2567 else 2568 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2569 } 2570 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2571 return isIntS16Immediate(Op.getNode(), Imm); 2572 } 2573 2574 /// Used when computing address flags for selecting loads and stores. 2575 /// If we have an OR, check if the LHS and RHS are provably disjoint. 2576 /// An OR of two provably disjoint values is equivalent to an ADD. 2577 /// Most PPC load/store instructions compute the effective address as a sum, 2578 /// so doing this conversion is useful. 2579 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) { 2580 if (N.getOpcode() != ISD::OR) 2581 return false; 2582 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2583 if (!LHSKnown.Zero.getBoolValue()) 2584 return false; 2585 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2586 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0); 2587 } 2588 2589 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2590 /// be represented as an indexed [r+r] operation. 2591 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2592 SDValue &Index, 2593 SelectionDAG &DAG) const { 2594 for (SDNode *U : N->uses()) { 2595 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) { 2596 if (Memop->getMemoryVT() == MVT::f64) { 2597 Base = N.getOperand(0); 2598 Index = N.getOperand(1); 2599 return true; 2600 } 2601 } 2602 } 2603 return false; 2604 } 2605 2606 /// isIntS34Immediate - This method tests if value of node given can be 2607 /// accurately represented as a sign extension from a 34-bit value. If so, 2608 /// this returns true and the immediate. 2609 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2610 if (!isa<ConstantSDNode>(N)) 2611 return false; 2612 2613 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2614 return isInt<34>(Imm); 2615 } 2616 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2617 return isIntS34Immediate(Op.getNode(), Imm); 2618 } 2619 2620 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2621 /// can be represented as an indexed [r+r] operation. Returns false if it 2622 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2623 /// non-zero and N can be represented by a base register plus a signed 16-bit 2624 /// displacement, make a more precise judgement by checking (displacement % \p 2625 /// EncodingAlignment). 2626 bool PPCTargetLowering::SelectAddressRegReg( 2627 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2628 MaybeAlign EncodingAlignment) const { 2629 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2630 // a [pc+imm]. 2631 if (SelectAddressPCRel(N, Base)) 2632 return false; 2633 2634 int16_t Imm = 0; 2635 if (N.getOpcode() == ISD::ADD) { 2636 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2637 // SPE load/store can only handle 8-bit offsets. 2638 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2639 return true; 2640 if (isIntS16Immediate(N.getOperand(1), Imm) && 2641 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2642 return false; // r+i 2643 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2644 return false; // r+i 2645 2646 Base = N.getOperand(0); 2647 Index = N.getOperand(1); 2648 return true; 2649 } else if (N.getOpcode() == ISD::OR) { 2650 if (isIntS16Immediate(N.getOperand(1), Imm) && 2651 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2652 return false; // r+i can fold it if we can. 2653 2654 // If this is an or of disjoint bitfields, we can codegen this as an add 2655 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2656 // disjoint. 2657 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2658 2659 if (LHSKnown.Zero.getBoolValue()) { 2660 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2661 // If all of the bits are known zero on the LHS or RHS, the add won't 2662 // carry. 2663 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2664 Base = N.getOperand(0); 2665 Index = N.getOperand(1); 2666 return true; 2667 } 2668 } 2669 } 2670 2671 return false; 2672 } 2673 2674 // If we happen to be doing an i64 load or store into a stack slot that has 2675 // less than a 4-byte alignment, then the frame-index elimination may need to 2676 // use an indexed load or store instruction (because the offset may not be a 2677 // multiple of 4). The extra register needed to hold the offset comes from the 2678 // register scavenger, and it is possible that the scavenger will need to use 2679 // an emergency spill slot. As a result, we need to make sure that a spill slot 2680 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2681 // stack slot. 2682 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2683 // FIXME: This does not handle the LWA case. 2684 if (VT != MVT::i64) 2685 return; 2686 2687 // NOTE: We'll exclude negative FIs here, which come from argument 2688 // lowering, because there are no known test cases triggering this problem 2689 // using packed structures (or similar). We can remove this exclusion if 2690 // we find such a test case. The reason why this is so test-case driven is 2691 // because this entire 'fixup' is only to prevent crashes (from the 2692 // register scavenger) on not-really-valid inputs. For example, if we have: 2693 // %a = alloca i1 2694 // %b = bitcast i1* %a to i64* 2695 // store i64* a, i64 b 2696 // then the store should really be marked as 'align 1', but is not. If it 2697 // were marked as 'align 1' then the indexed form would have been 2698 // instruction-selected initially, and the problem this 'fixup' is preventing 2699 // won't happen regardless. 2700 if (FrameIdx < 0) 2701 return; 2702 2703 MachineFunction &MF = DAG.getMachineFunction(); 2704 MachineFrameInfo &MFI = MF.getFrameInfo(); 2705 2706 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2707 return; 2708 2709 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2710 FuncInfo->setHasNonRISpills(); 2711 } 2712 2713 /// Returns true if the address N can be represented by a base register plus 2714 /// a signed 16-bit displacement [r+imm], and if it is not better 2715 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2716 /// displacements that are multiples of that value. 2717 bool PPCTargetLowering::SelectAddressRegImm( 2718 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2719 MaybeAlign EncodingAlignment) const { 2720 // FIXME dl should come from parent load or store, not from address 2721 SDLoc dl(N); 2722 2723 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2724 // a [pc+imm]. 2725 if (SelectAddressPCRel(N, Base)) 2726 return false; 2727 2728 // If this can be more profitably realized as r+r, fail. 2729 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2730 return false; 2731 2732 if (N.getOpcode() == ISD::ADD) { 2733 int16_t imm = 0; 2734 if (isIntS16Immediate(N.getOperand(1), imm) && 2735 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2736 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2737 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2738 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2739 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2740 } else { 2741 Base = N.getOperand(0); 2742 } 2743 return true; // [r+i] 2744 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2745 // Match LOAD (ADD (X, Lo(G))). 2746 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2747 && "Cannot handle constant offsets yet!"); 2748 Disp = N.getOperand(1).getOperand(0); // The global address. 2749 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2750 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2751 Disp.getOpcode() == ISD::TargetConstantPool || 2752 Disp.getOpcode() == ISD::TargetJumpTable); 2753 Base = N.getOperand(0); 2754 return true; // [&g+r] 2755 } 2756 } else if (N.getOpcode() == ISD::OR) { 2757 int16_t imm = 0; 2758 if (isIntS16Immediate(N.getOperand(1), imm) && 2759 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2760 // If this is an or of disjoint bitfields, we can codegen this as an add 2761 // (for better address arithmetic) if the LHS and RHS of the OR are 2762 // provably disjoint. 2763 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2764 2765 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2766 // If all of the bits are known zero on the LHS or RHS, the add won't 2767 // carry. 2768 if (FrameIndexSDNode *FI = 2769 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2770 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2771 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2772 } else { 2773 Base = N.getOperand(0); 2774 } 2775 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2776 return true; 2777 } 2778 } 2779 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2780 // Loading from a constant address. 2781 2782 // If this address fits entirely in a 16-bit sext immediate field, codegen 2783 // this as "d, 0" 2784 int16_t Imm; 2785 if (isIntS16Immediate(CN, Imm) && 2786 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2787 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2788 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2789 CN->getValueType(0)); 2790 return true; 2791 } 2792 2793 // Handle 32-bit sext immediates with LIS + addr mode. 2794 if ((CN->getValueType(0) == MVT::i32 || 2795 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2796 (!EncodingAlignment || 2797 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2798 int Addr = (int)CN->getZExtValue(); 2799 2800 // Otherwise, break this down into an LIS + disp. 2801 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2802 2803 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2804 MVT::i32); 2805 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2806 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2807 return true; 2808 } 2809 } 2810 2811 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2812 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2813 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2814 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2815 } else 2816 Base = N; 2817 return true; // [r+0] 2818 } 2819 2820 /// Similar to the 16-bit case but for instructions that take a 34-bit 2821 /// displacement field (prefixed loads/stores). 2822 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2823 SDValue &Base, 2824 SelectionDAG &DAG) const { 2825 // Only on 64-bit targets. 2826 if (N.getValueType() != MVT::i64) 2827 return false; 2828 2829 SDLoc dl(N); 2830 int64_t Imm = 0; 2831 2832 if (N.getOpcode() == ISD::ADD) { 2833 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2834 return false; 2835 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2836 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2837 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2838 else 2839 Base = N.getOperand(0); 2840 return true; 2841 } 2842 2843 if (N.getOpcode() == ISD::OR) { 2844 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2845 return false; 2846 // If this is an or of disjoint bitfields, we can codegen this as an add 2847 // (for better address arithmetic) if the LHS and RHS of the OR are 2848 // provably disjoint. 2849 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2850 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2851 return false; 2852 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2853 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2854 else 2855 Base = N.getOperand(0); 2856 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2857 return true; 2858 } 2859 2860 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2861 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2862 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2863 return true; 2864 } 2865 2866 return false; 2867 } 2868 2869 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2870 /// represented as an indexed [r+r] operation. 2871 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2872 SDValue &Index, 2873 SelectionDAG &DAG) const { 2874 // Check to see if we can easily represent this as an [r+r] address. This 2875 // will fail if it thinks that the address is more profitably represented as 2876 // reg+imm, e.g. where imm = 0. 2877 if (SelectAddressRegReg(N, Base, Index, DAG)) 2878 return true; 2879 2880 // If the address is the result of an add, we will utilize the fact that the 2881 // address calculation includes an implicit add. However, we can reduce 2882 // register pressure if we do not materialize a constant just for use as the 2883 // index register. We only get rid of the add if it is not an add of a 2884 // value and a 16-bit signed constant and both have a single use. 2885 int16_t imm = 0; 2886 if (N.getOpcode() == ISD::ADD && 2887 (!isIntS16Immediate(N.getOperand(1), imm) || 2888 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2889 Base = N.getOperand(0); 2890 Index = N.getOperand(1); 2891 return true; 2892 } 2893 2894 // Otherwise, do it the hard way, using R0 as the base register. 2895 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2896 N.getValueType()); 2897 Index = N; 2898 return true; 2899 } 2900 2901 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2902 Ty *PCRelCand = dyn_cast<Ty>(N); 2903 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2904 } 2905 2906 /// Returns true if this address is a PC Relative address. 2907 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2908 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2909 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2910 // This is a materialize PC Relative node. Always select this as PC Relative. 2911 Base = N; 2912 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2913 return true; 2914 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2915 isValidPCRelNode<GlobalAddressSDNode>(N) || 2916 isValidPCRelNode<JumpTableSDNode>(N) || 2917 isValidPCRelNode<BlockAddressSDNode>(N)) 2918 return true; 2919 return false; 2920 } 2921 2922 /// Returns true if we should use a direct load into vector instruction 2923 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2924 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2925 2926 // If there are any other uses other than scalar to vector, then we should 2927 // keep it as a scalar load -> direct move pattern to prevent multiple 2928 // loads. 2929 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2930 if (!LD) 2931 return false; 2932 2933 EVT MemVT = LD->getMemoryVT(); 2934 if (!MemVT.isSimple()) 2935 return false; 2936 switch(MemVT.getSimpleVT().SimpleTy) { 2937 case MVT::i64: 2938 break; 2939 case MVT::i32: 2940 if (!ST.hasP8Vector()) 2941 return false; 2942 break; 2943 case MVT::i16: 2944 case MVT::i8: 2945 if (!ST.hasP9Vector()) 2946 return false; 2947 break; 2948 default: 2949 return false; 2950 } 2951 2952 SDValue LoadedVal(N, 0); 2953 if (!LoadedVal.hasOneUse()) 2954 return false; 2955 2956 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2957 UI != UE; ++UI) 2958 if (UI.getUse().get().getResNo() == 0 && 2959 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2960 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2961 return false; 2962 2963 return true; 2964 } 2965 2966 /// getPreIndexedAddressParts - returns true by value, base pointer and 2967 /// offset pointer and addressing mode by reference if the node's address 2968 /// can be legally represented as pre-indexed load / store address. 2969 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2970 SDValue &Offset, 2971 ISD::MemIndexedMode &AM, 2972 SelectionDAG &DAG) const { 2973 if (DisablePPCPreinc) return false; 2974 2975 bool isLoad = true; 2976 SDValue Ptr; 2977 EVT VT; 2978 unsigned Alignment; 2979 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2980 Ptr = LD->getBasePtr(); 2981 VT = LD->getMemoryVT(); 2982 Alignment = LD->getAlignment(); 2983 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2984 Ptr = ST->getBasePtr(); 2985 VT = ST->getMemoryVT(); 2986 Alignment = ST->getAlignment(); 2987 isLoad = false; 2988 } else 2989 return false; 2990 2991 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2992 // instructions because we can fold these into a more efficient instruction 2993 // instead, (such as LXSD). 2994 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2995 return false; 2996 } 2997 2998 // PowerPC doesn't have preinc load/store instructions for vectors 2999 if (VT.isVector()) 3000 return false; 3001 3002 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 3003 // Common code will reject creating a pre-inc form if the base pointer 3004 // is a frame index, or if N is a store and the base pointer is either 3005 // the same as or a predecessor of the value being stored. Check for 3006 // those situations here, and try with swapped Base/Offset instead. 3007 bool Swap = false; 3008 3009 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 3010 Swap = true; 3011 else if (!isLoad) { 3012 SDValue Val = cast<StoreSDNode>(N)->getValue(); 3013 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 3014 Swap = true; 3015 } 3016 3017 if (Swap) 3018 std::swap(Base, Offset); 3019 3020 AM = ISD::PRE_INC; 3021 return true; 3022 } 3023 3024 // LDU/STU can only handle immediates that are a multiple of 4. 3025 if (VT != MVT::i64) { 3026 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 3027 return false; 3028 } else { 3029 // LDU/STU need an address with at least 4-byte alignment. 3030 if (Alignment < 4) 3031 return false; 3032 3033 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 3034 return false; 3035 } 3036 3037 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 3038 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 3039 // sext i32 to i64 when addr mode is r+i. 3040 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 3041 LD->getExtensionType() == ISD::SEXTLOAD && 3042 isa<ConstantSDNode>(Offset)) 3043 return false; 3044 } 3045 3046 AM = ISD::PRE_INC; 3047 return true; 3048 } 3049 3050 //===----------------------------------------------------------------------===// 3051 // LowerOperation implementation 3052 //===----------------------------------------------------------------------===// 3053 3054 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 3055 /// and LoOpFlags to the target MO flags. 3056 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 3057 unsigned &HiOpFlags, unsigned &LoOpFlags, 3058 const GlobalValue *GV = nullptr) { 3059 HiOpFlags = PPCII::MO_HA; 3060 LoOpFlags = PPCII::MO_LO; 3061 3062 // Don't use the pic base if not in PIC relocation model. 3063 if (IsPIC) { 3064 HiOpFlags |= PPCII::MO_PIC_FLAG; 3065 LoOpFlags |= PPCII::MO_PIC_FLAG; 3066 } 3067 } 3068 3069 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 3070 SelectionDAG &DAG) { 3071 SDLoc DL(HiPart); 3072 EVT PtrVT = HiPart.getValueType(); 3073 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 3074 3075 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 3076 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 3077 3078 // With PIC, the first instruction is actually "GR+hi(&G)". 3079 if (isPIC) 3080 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 3081 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 3082 3083 // Generate non-pic code that has direct accesses to the constant pool. 3084 // The address of the global is just (hi(&g)+lo(&g)). 3085 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 3086 } 3087 3088 static void setUsesTOCBasePtr(MachineFunction &MF) { 3089 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3090 FuncInfo->setUsesTOCBasePtr(); 3091 } 3092 3093 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 3094 setUsesTOCBasePtr(DAG.getMachineFunction()); 3095 } 3096 3097 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 3098 SDValue GA) const { 3099 const bool Is64Bit = Subtarget.isPPC64(); 3100 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 3101 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 3102 : Subtarget.isAIXABI() 3103 ? DAG.getRegister(PPC::R2, VT) 3104 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 3105 SDValue Ops[] = { GA, Reg }; 3106 return DAG.getMemIntrinsicNode( 3107 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 3108 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 3109 MachineMemOperand::MOLoad); 3110 } 3111 3112 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 3113 SelectionDAG &DAG) const { 3114 EVT PtrVT = Op.getValueType(); 3115 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3116 const Constant *C = CP->getConstVal(); 3117 3118 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3119 // The actual address of the GlobalValue is stored in the TOC. 3120 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3121 if (Subtarget.isUsingPCRelativeCalls()) { 3122 SDLoc DL(CP); 3123 EVT Ty = getPointerTy(DAG.getDataLayout()); 3124 SDValue ConstPool = DAG.getTargetConstantPool( 3125 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 3126 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 3127 } 3128 setUsesTOCBasePtr(DAG); 3129 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 3130 return getTOCEntry(DAG, SDLoc(CP), GA); 3131 } 3132 3133 unsigned MOHiFlag, MOLoFlag; 3134 bool IsPIC = isPositionIndependent(); 3135 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3136 3137 if (IsPIC && Subtarget.isSVR4ABI()) { 3138 SDValue GA = 3139 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 3140 return getTOCEntry(DAG, SDLoc(CP), GA); 3141 } 3142 3143 SDValue CPIHi = 3144 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 3145 SDValue CPILo = 3146 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 3147 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 3148 } 3149 3150 // For 64-bit PowerPC, prefer the more compact relative encodings. 3151 // This trades 32 bits per jump table entry for one or two instructions 3152 // on the jump site. 3153 unsigned PPCTargetLowering::getJumpTableEncoding() const { 3154 if (isJumpTableRelative()) 3155 return MachineJumpTableInfo::EK_LabelDifference32; 3156 3157 return TargetLowering::getJumpTableEncoding(); 3158 } 3159 3160 bool PPCTargetLowering::isJumpTableRelative() const { 3161 if (UseAbsoluteJumpTables) 3162 return false; 3163 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3164 return true; 3165 return TargetLowering::isJumpTableRelative(); 3166 } 3167 3168 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3169 SelectionDAG &DAG) const { 3170 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3171 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3172 3173 switch (getTargetMachine().getCodeModel()) { 3174 case CodeModel::Small: 3175 case CodeModel::Medium: 3176 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3177 default: 3178 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3179 getPointerTy(DAG.getDataLayout())); 3180 } 3181 } 3182 3183 const MCExpr * 3184 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3185 unsigned JTI, 3186 MCContext &Ctx) const { 3187 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3188 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3189 3190 switch (getTargetMachine().getCodeModel()) { 3191 case CodeModel::Small: 3192 case CodeModel::Medium: 3193 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3194 default: 3195 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3196 } 3197 } 3198 3199 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3200 EVT PtrVT = Op.getValueType(); 3201 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3202 3203 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3204 if (Subtarget.isUsingPCRelativeCalls()) { 3205 SDLoc DL(JT); 3206 EVT Ty = getPointerTy(DAG.getDataLayout()); 3207 SDValue GA = 3208 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3209 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3210 return MatAddr; 3211 } 3212 3213 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3214 // The actual address of the GlobalValue is stored in the TOC. 3215 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3216 setUsesTOCBasePtr(DAG); 3217 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3218 return getTOCEntry(DAG, SDLoc(JT), GA); 3219 } 3220 3221 unsigned MOHiFlag, MOLoFlag; 3222 bool IsPIC = isPositionIndependent(); 3223 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3224 3225 if (IsPIC && Subtarget.isSVR4ABI()) { 3226 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3227 PPCII::MO_PIC_FLAG); 3228 return getTOCEntry(DAG, SDLoc(GA), GA); 3229 } 3230 3231 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3232 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3233 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3234 } 3235 3236 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3237 SelectionDAG &DAG) const { 3238 EVT PtrVT = Op.getValueType(); 3239 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3240 const BlockAddress *BA = BASDN->getBlockAddress(); 3241 3242 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3243 if (Subtarget.isUsingPCRelativeCalls()) { 3244 SDLoc DL(BASDN); 3245 EVT Ty = getPointerTy(DAG.getDataLayout()); 3246 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3247 PPCII::MO_PCREL_FLAG); 3248 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3249 return MatAddr; 3250 } 3251 3252 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3253 // The actual BlockAddress is stored in the TOC. 3254 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3255 setUsesTOCBasePtr(DAG); 3256 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3257 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3258 } 3259 3260 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3261 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3262 return getTOCEntry( 3263 DAG, SDLoc(BASDN), 3264 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3265 3266 unsigned MOHiFlag, MOLoFlag; 3267 bool IsPIC = isPositionIndependent(); 3268 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3269 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3270 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3271 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3272 } 3273 3274 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3275 SelectionDAG &DAG) const { 3276 if (Subtarget.isAIXABI()) 3277 return LowerGlobalTLSAddressAIX(Op, DAG); 3278 3279 return LowerGlobalTLSAddressLinux(Op, DAG); 3280 } 3281 3282 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3283 SelectionDAG &DAG) const { 3284 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3285 3286 if (DAG.getTarget().useEmulatedTLS()) 3287 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3288 3289 SDLoc dl(GA); 3290 const GlobalValue *GV = GA->getGlobal(); 3291 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3292 3293 // The general-dynamic model is the only access model supported for now, so 3294 // all the GlobalTLSAddress nodes are lowered with this model. 3295 // We need to generate two TOC entries, one for the variable offset, one for 3296 // the region handle. The global address for the TOC entry of the region 3297 // handle is created with the MO_TLSGDM_FLAG flag and the global address 3298 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG. 3299 SDValue VariableOffsetTGA = 3300 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3301 SDValue RegionHandleTGA = 3302 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG); 3303 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3304 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3305 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3306 RegionHandle); 3307 } 3308 3309 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3310 SelectionDAG &DAG) const { 3311 // FIXME: TLS addresses currently use medium model code sequences, 3312 // which is the most useful form. Eventually support for small and 3313 // large models could be added if users need it, at the cost of 3314 // additional complexity. 3315 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3316 if (DAG.getTarget().useEmulatedTLS()) 3317 return LowerToTLSEmulatedModel(GA, DAG); 3318 3319 SDLoc dl(GA); 3320 const GlobalValue *GV = GA->getGlobal(); 3321 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3322 bool is64bit = Subtarget.isPPC64(); 3323 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3324 PICLevel::Level picLevel = M->getPICLevel(); 3325 3326 const TargetMachine &TM = getTargetMachine(); 3327 TLSModel::Model Model = TM.getTLSModel(GV); 3328 3329 if (Model == TLSModel::LocalExec) { 3330 if (Subtarget.isUsingPCRelativeCalls()) { 3331 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3332 SDValue TGA = DAG.getTargetGlobalAddress( 3333 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3334 SDValue MatAddr = 3335 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3336 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3337 } 3338 3339 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3340 PPCII::MO_TPREL_HA); 3341 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3342 PPCII::MO_TPREL_LO); 3343 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3344 : DAG.getRegister(PPC::R2, MVT::i32); 3345 3346 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3347 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3348 } 3349 3350 if (Model == TLSModel::InitialExec) { 3351 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3352 SDValue TGA = DAG.getTargetGlobalAddress( 3353 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3354 SDValue TGATLS = DAG.getTargetGlobalAddress( 3355 GV, dl, PtrVT, 0, 3356 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3357 SDValue TPOffset; 3358 if (IsPCRel) { 3359 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3360 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3361 MachinePointerInfo()); 3362 } else { 3363 SDValue GOTPtr; 3364 if (is64bit) { 3365 setUsesTOCBasePtr(DAG); 3366 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3367 GOTPtr = 3368 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3369 } else { 3370 if (!TM.isPositionIndependent()) 3371 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3372 else if (picLevel == PICLevel::SmallPIC) 3373 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3374 else 3375 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3376 } 3377 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3378 } 3379 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3380 } 3381 3382 if (Model == TLSModel::GeneralDynamic) { 3383 if (Subtarget.isUsingPCRelativeCalls()) { 3384 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3385 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3386 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3387 } 3388 3389 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3390 SDValue GOTPtr; 3391 if (is64bit) { 3392 setUsesTOCBasePtr(DAG); 3393 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3394 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3395 GOTReg, TGA); 3396 } else { 3397 if (picLevel == PICLevel::SmallPIC) 3398 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3399 else 3400 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3401 } 3402 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3403 GOTPtr, TGA, TGA); 3404 } 3405 3406 if (Model == TLSModel::LocalDynamic) { 3407 if (Subtarget.isUsingPCRelativeCalls()) { 3408 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3409 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3410 SDValue MatPCRel = 3411 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3412 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3413 } 3414 3415 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3416 SDValue GOTPtr; 3417 if (is64bit) { 3418 setUsesTOCBasePtr(DAG); 3419 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3420 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3421 GOTReg, TGA); 3422 } else { 3423 if (picLevel == PICLevel::SmallPIC) 3424 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3425 else 3426 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3427 } 3428 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3429 PtrVT, GOTPtr, TGA, TGA); 3430 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3431 PtrVT, TLSAddr, TGA); 3432 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3433 } 3434 3435 llvm_unreachable("Unknown TLS model!"); 3436 } 3437 3438 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3439 SelectionDAG &DAG) const { 3440 EVT PtrVT = Op.getValueType(); 3441 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3442 SDLoc DL(GSDN); 3443 const GlobalValue *GV = GSDN->getGlobal(); 3444 3445 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3446 // The actual address of the GlobalValue is stored in the TOC. 3447 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3448 if (Subtarget.isUsingPCRelativeCalls()) { 3449 EVT Ty = getPointerTy(DAG.getDataLayout()); 3450 if (isAccessedAsGotIndirect(Op)) { 3451 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3452 PPCII::MO_PCREL_FLAG | 3453 PPCII::MO_GOT_FLAG); 3454 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3455 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3456 MachinePointerInfo()); 3457 return Load; 3458 } else { 3459 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3460 PPCII::MO_PCREL_FLAG); 3461 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3462 } 3463 } 3464 setUsesTOCBasePtr(DAG); 3465 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3466 return getTOCEntry(DAG, DL, GA); 3467 } 3468 3469 unsigned MOHiFlag, MOLoFlag; 3470 bool IsPIC = isPositionIndependent(); 3471 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3472 3473 if (IsPIC && Subtarget.isSVR4ABI()) { 3474 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3475 GSDN->getOffset(), 3476 PPCII::MO_PIC_FLAG); 3477 return getTOCEntry(DAG, DL, GA); 3478 } 3479 3480 SDValue GAHi = 3481 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3482 SDValue GALo = 3483 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3484 3485 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3486 } 3487 3488 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3489 bool IsStrict = Op->isStrictFPOpcode(); 3490 ISD::CondCode CC = 3491 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get(); 3492 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0); 3493 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1); 3494 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 3495 EVT LHSVT = LHS.getValueType(); 3496 SDLoc dl(Op); 3497 3498 // Soften the setcc with libcall if it is fp128. 3499 if (LHSVT == MVT::f128) { 3500 assert(!Subtarget.hasP9Vector() && 3501 "SETCC for f128 is already legal under Power9!"); 3502 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain, 3503 Op->getOpcode() == ISD::STRICT_FSETCCS); 3504 if (RHS.getNode()) 3505 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS, 3506 DAG.getCondCode(CC)); 3507 if (IsStrict) 3508 return DAG.getMergeValues({LHS, Chain}, dl); 3509 return LHS; 3510 } 3511 3512 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!"); 3513 3514 if (Op.getValueType() == MVT::v2i64) { 3515 // When the operands themselves are v2i64 values, we need to do something 3516 // special because VSX has no underlying comparison operations for these. 3517 if (LHS.getValueType() == MVT::v2i64) { 3518 // Equality can be handled by casting to the legal type for Altivec 3519 // comparisons, everything else needs to be expanded. 3520 if (CC != ISD::SETEQ && CC != ISD::SETNE) 3521 return SDValue(); 3522 SDValue SetCC32 = DAG.getSetCC( 3523 dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS), 3524 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC); 3525 int ShuffV[] = {1, 0, 3, 2}; 3526 SDValue Shuff = 3527 DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV); 3528 return DAG.getBitcast(MVT::v2i64, 3529 DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR, 3530 dl, MVT::v4i32, Shuff, SetCC32)); 3531 } 3532 3533 // We handle most of these in the usual way. 3534 return Op; 3535 } 3536 3537 // If we're comparing for equality to zero, expose the fact that this is 3538 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3539 // fold the new nodes. 3540 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3541 return V; 3542 3543 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 3544 // Leave comparisons against 0 and -1 alone for now, since they're usually 3545 // optimized. FIXME: revisit this when we can custom lower all setcc 3546 // optimizations. 3547 if (C->isAllOnes() || C->isZero()) 3548 return SDValue(); 3549 } 3550 3551 // If we have an integer seteq/setne, turn it into a compare against zero 3552 // by xor'ing the rhs with the lhs, which is faster than setting a 3553 // condition register, reading it back out, and masking the correct bit. The 3554 // normal approach here uses sub to do this instead of xor. Using xor exposes 3555 // the result to other bit-twiddling opportunities. 3556 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3557 EVT VT = Op.getValueType(); 3558 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS); 3559 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3560 } 3561 return SDValue(); 3562 } 3563 3564 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3565 SDNode *Node = Op.getNode(); 3566 EVT VT = Node->getValueType(0); 3567 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3568 SDValue InChain = Node->getOperand(0); 3569 SDValue VAListPtr = Node->getOperand(1); 3570 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3571 SDLoc dl(Node); 3572 3573 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3574 3575 // gpr_index 3576 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3577 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3578 InChain = GprIndex.getValue(1); 3579 3580 if (VT == MVT::i64) { 3581 // Check if GprIndex is even 3582 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3583 DAG.getConstant(1, dl, MVT::i32)); 3584 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3585 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3586 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3587 DAG.getConstant(1, dl, MVT::i32)); 3588 // Align GprIndex to be even if it isn't 3589 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3590 GprIndex); 3591 } 3592 3593 // fpr index is 1 byte after gpr 3594 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3595 DAG.getConstant(1, dl, MVT::i32)); 3596 3597 // fpr 3598 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3599 FprPtr, MachinePointerInfo(SV), MVT::i8); 3600 InChain = FprIndex.getValue(1); 3601 3602 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3603 DAG.getConstant(8, dl, MVT::i32)); 3604 3605 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3606 DAG.getConstant(4, dl, MVT::i32)); 3607 3608 // areas 3609 SDValue OverflowArea = 3610 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3611 InChain = OverflowArea.getValue(1); 3612 3613 SDValue RegSaveArea = 3614 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3615 InChain = RegSaveArea.getValue(1); 3616 3617 // select overflow_area if index > 8 3618 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3619 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3620 3621 // adjustment constant gpr_index * 4/8 3622 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3623 VT.isInteger() ? GprIndex : FprIndex, 3624 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3625 MVT::i32)); 3626 3627 // OurReg = RegSaveArea + RegConstant 3628 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3629 RegConstant); 3630 3631 // Floating types are 32 bytes into RegSaveArea 3632 if (VT.isFloatingPoint()) 3633 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3634 DAG.getConstant(32, dl, MVT::i32)); 3635 3636 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3637 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3638 VT.isInteger() ? GprIndex : FprIndex, 3639 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3640 MVT::i32)); 3641 3642 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3643 VT.isInteger() ? VAListPtr : FprPtr, 3644 MachinePointerInfo(SV), MVT::i8); 3645 3646 // determine if we should load from reg_save_area or overflow_area 3647 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3648 3649 // increase overflow_area by 4/8 if gpr/fpr > 8 3650 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3651 DAG.getConstant(VT.isInteger() ? 4 : 8, 3652 dl, MVT::i32)); 3653 3654 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3655 OverflowAreaPlusN); 3656 3657 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3658 MachinePointerInfo(), MVT::i32); 3659 3660 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3661 } 3662 3663 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3664 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3665 3666 // We have to copy the entire va_list struct: 3667 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3668 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3669 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3670 false, true, false, MachinePointerInfo(), 3671 MachinePointerInfo()); 3672 } 3673 3674 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3675 SelectionDAG &DAG) const { 3676 if (Subtarget.isAIXABI()) 3677 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3678 3679 return Op.getOperand(0); 3680 } 3681 3682 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const { 3683 MachineFunction &MF = DAG.getMachineFunction(); 3684 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>(); 3685 3686 assert((Op.getOpcode() == ISD::INLINEASM || 3687 Op.getOpcode() == ISD::INLINEASM_BR) && 3688 "Expecting Inline ASM node."); 3689 3690 // If an LR store is already known to be required then there is not point in 3691 // checking this ASM as well. 3692 if (MFI.isLRStoreRequired()) 3693 return Op; 3694 3695 // Inline ASM nodes have an optional last operand that is an incoming Flag of 3696 // type MVT::Glue. We want to ignore this last operand if that is the case. 3697 unsigned NumOps = Op.getNumOperands(); 3698 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue) 3699 --NumOps; 3700 3701 // Check all operands that may contain the LR. 3702 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 3703 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue(); 3704 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 3705 ++i; // Skip the ID value. 3706 3707 switch (InlineAsm::getKind(Flags)) { 3708 default: 3709 llvm_unreachable("Bad flags!"); 3710 case InlineAsm::Kind_RegUse: 3711 case InlineAsm::Kind_Imm: 3712 case InlineAsm::Kind_Mem: 3713 i += NumVals; 3714 break; 3715 case InlineAsm::Kind_Clobber: 3716 case InlineAsm::Kind_RegDef: 3717 case InlineAsm::Kind_RegDefEarlyClobber: { 3718 for (; NumVals; --NumVals, ++i) { 3719 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg(); 3720 if (Reg != PPC::LR && Reg != PPC::LR8) 3721 continue; 3722 MFI.setLRStoreRequired(); 3723 return Op; 3724 } 3725 break; 3726 } 3727 } 3728 } 3729 3730 return Op; 3731 } 3732 3733 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3734 SelectionDAG &DAG) const { 3735 if (Subtarget.isAIXABI()) 3736 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3737 3738 SDValue Chain = Op.getOperand(0); 3739 SDValue Trmp = Op.getOperand(1); // trampoline 3740 SDValue FPtr = Op.getOperand(2); // nested function 3741 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3742 SDLoc dl(Op); 3743 3744 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3745 bool isPPC64 = (PtrVT == MVT::i64); 3746 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3747 3748 TargetLowering::ArgListTy Args; 3749 TargetLowering::ArgListEntry Entry; 3750 3751 Entry.Ty = IntPtrTy; 3752 Entry.Node = Trmp; Args.push_back(Entry); 3753 3754 // TrampSize == (isPPC64 ? 48 : 40); 3755 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3756 isPPC64 ? MVT::i64 : MVT::i32); 3757 Args.push_back(Entry); 3758 3759 Entry.Node = FPtr; Args.push_back(Entry); 3760 Entry.Node = Nest; Args.push_back(Entry); 3761 3762 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3763 TargetLowering::CallLoweringInfo CLI(DAG); 3764 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3765 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3766 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3767 3768 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3769 return CallResult.second; 3770 } 3771 3772 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3773 MachineFunction &MF = DAG.getMachineFunction(); 3774 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3775 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3776 3777 SDLoc dl(Op); 3778 3779 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3780 // vastart just stores the address of the VarArgsFrameIndex slot into the 3781 // memory location argument. 3782 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3783 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3784 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3785 MachinePointerInfo(SV)); 3786 } 3787 3788 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3789 // We suppose the given va_list is already allocated. 3790 // 3791 // typedef struct { 3792 // char gpr; /* index into the array of 8 GPRs 3793 // * stored in the register save area 3794 // * gpr=0 corresponds to r3, 3795 // * gpr=1 to r4, etc. 3796 // */ 3797 // char fpr; /* index into the array of 8 FPRs 3798 // * stored in the register save area 3799 // * fpr=0 corresponds to f1, 3800 // * fpr=1 to f2, etc. 3801 // */ 3802 // char *overflow_arg_area; 3803 // /* location on stack that holds 3804 // * the next overflow argument 3805 // */ 3806 // char *reg_save_area; 3807 // /* where r3:r10 and f1:f8 (if saved) 3808 // * are stored 3809 // */ 3810 // } va_list[1]; 3811 3812 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3813 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3814 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3815 PtrVT); 3816 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3817 PtrVT); 3818 3819 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3820 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3821 3822 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3823 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3824 3825 uint64_t FPROffset = 1; 3826 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3827 3828 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3829 3830 // Store first byte : number of int regs 3831 SDValue firstStore = 3832 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3833 MachinePointerInfo(SV), MVT::i8); 3834 uint64_t nextOffset = FPROffset; 3835 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3836 ConstFPROffset); 3837 3838 // Store second byte : number of float regs 3839 SDValue secondStore = 3840 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3841 MachinePointerInfo(SV, nextOffset), MVT::i8); 3842 nextOffset += StackOffset; 3843 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3844 3845 // Store second word : arguments given on stack 3846 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3847 MachinePointerInfo(SV, nextOffset)); 3848 nextOffset += FrameOffset; 3849 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3850 3851 // Store third word : arguments given in registers 3852 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3853 MachinePointerInfo(SV, nextOffset)); 3854 } 3855 3856 /// FPR - The set of FP registers that should be allocated for arguments 3857 /// on Darwin and AIX. 3858 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3859 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3860 PPC::F11, PPC::F12, PPC::F13}; 3861 3862 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3863 /// the stack. 3864 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3865 unsigned PtrByteSize) { 3866 unsigned ArgSize = ArgVT.getStoreSize(); 3867 if (Flags.isByVal()) 3868 ArgSize = Flags.getByValSize(); 3869 3870 // Round up to multiples of the pointer size, except for array members, 3871 // which are always packed. 3872 if (!Flags.isInConsecutiveRegs()) 3873 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3874 3875 return ArgSize; 3876 } 3877 3878 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3879 /// on the stack. 3880 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3881 ISD::ArgFlagsTy Flags, 3882 unsigned PtrByteSize) { 3883 Align Alignment(PtrByteSize); 3884 3885 // Altivec parameters are padded to a 16 byte boundary. 3886 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3887 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3888 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3889 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3890 Alignment = Align(16); 3891 3892 // ByVal parameters are aligned as requested. 3893 if (Flags.isByVal()) { 3894 auto BVAlign = Flags.getNonZeroByValAlign(); 3895 if (BVAlign > PtrByteSize) { 3896 if (BVAlign.value() % PtrByteSize != 0) 3897 llvm_unreachable( 3898 "ByVal alignment is not a multiple of the pointer size"); 3899 3900 Alignment = BVAlign; 3901 } 3902 } 3903 3904 // Array members are always packed to their original alignment. 3905 if (Flags.isInConsecutiveRegs()) { 3906 // If the array member was split into multiple registers, the first 3907 // needs to be aligned to the size of the full type. (Except for 3908 // ppcf128, which is only aligned as its f64 components.) 3909 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3910 Alignment = Align(OrigVT.getStoreSize()); 3911 else 3912 Alignment = Align(ArgVT.getStoreSize()); 3913 } 3914 3915 return Alignment; 3916 } 3917 3918 /// CalculateStackSlotUsed - Return whether this argument will use its 3919 /// stack slot (instead of being passed in registers). ArgOffset, 3920 /// AvailableFPRs, and AvailableVRs must hold the current argument 3921 /// position, and will be updated to account for this argument. 3922 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3923 unsigned PtrByteSize, unsigned LinkageSize, 3924 unsigned ParamAreaSize, unsigned &ArgOffset, 3925 unsigned &AvailableFPRs, 3926 unsigned &AvailableVRs) { 3927 bool UseMemory = false; 3928 3929 // Respect alignment of argument on the stack. 3930 Align Alignment = 3931 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3932 ArgOffset = alignTo(ArgOffset, Alignment); 3933 // If there's no space left in the argument save area, we must 3934 // use memory (this check also catches zero-sized arguments). 3935 if (ArgOffset >= LinkageSize + ParamAreaSize) 3936 UseMemory = true; 3937 3938 // Allocate argument on the stack. 3939 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3940 if (Flags.isInConsecutiveRegsLast()) 3941 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3942 // If we overran the argument save area, we must use memory 3943 // (this check catches arguments passed partially in memory) 3944 if (ArgOffset > LinkageSize + ParamAreaSize) 3945 UseMemory = true; 3946 3947 // However, if the argument is actually passed in an FPR or a VR, 3948 // we don't use memory after all. 3949 if (!Flags.isByVal()) { 3950 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3951 if (AvailableFPRs > 0) { 3952 --AvailableFPRs; 3953 return false; 3954 } 3955 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3956 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3957 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3958 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3959 if (AvailableVRs > 0) { 3960 --AvailableVRs; 3961 return false; 3962 } 3963 } 3964 3965 return UseMemory; 3966 } 3967 3968 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3969 /// ensure minimum alignment required for target. 3970 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3971 unsigned NumBytes) { 3972 return alignTo(NumBytes, Lowering->getStackAlign()); 3973 } 3974 3975 SDValue PPCTargetLowering::LowerFormalArguments( 3976 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3977 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3978 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3979 if (Subtarget.isAIXABI()) 3980 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3981 InVals); 3982 if (Subtarget.is64BitELFABI()) 3983 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3984 InVals); 3985 assert(Subtarget.is32BitELFABI()); 3986 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3987 InVals); 3988 } 3989 3990 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3991 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3992 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3993 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3994 3995 // 32-bit SVR4 ABI Stack Frame Layout: 3996 // +-----------------------------------+ 3997 // +--> | Back chain | 3998 // | +-----------------------------------+ 3999 // | | Floating-point register save area | 4000 // | +-----------------------------------+ 4001 // | | General register save area | 4002 // | +-----------------------------------+ 4003 // | | CR save word | 4004 // | +-----------------------------------+ 4005 // | | VRSAVE save word | 4006 // | +-----------------------------------+ 4007 // | | Alignment padding | 4008 // | +-----------------------------------+ 4009 // | | Vector register save area | 4010 // | +-----------------------------------+ 4011 // | | Local variable space | 4012 // | +-----------------------------------+ 4013 // | | Parameter list area | 4014 // | +-----------------------------------+ 4015 // | | LR save word | 4016 // | +-----------------------------------+ 4017 // SP--> +--- | Back chain | 4018 // +-----------------------------------+ 4019 // 4020 // Specifications: 4021 // System V Application Binary Interface PowerPC Processor Supplement 4022 // AltiVec Technology Programming Interface Manual 4023 4024 MachineFunction &MF = DAG.getMachineFunction(); 4025 MachineFrameInfo &MFI = MF.getFrameInfo(); 4026 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4027 4028 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4029 // Potential tail calls could cause overwriting of argument stack slots. 4030 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4031 (CallConv == CallingConv::Fast)); 4032 const Align PtrAlign(4); 4033 4034 // Assign locations to all of the incoming arguments. 4035 SmallVector<CCValAssign, 16> ArgLocs; 4036 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4037 *DAG.getContext()); 4038 4039 // Reserve space for the linkage area on the stack. 4040 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4041 CCInfo.AllocateStack(LinkageSize, PtrAlign); 4042 if (useSoftFloat()) 4043 CCInfo.PreAnalyzeFormalArguments(Ins); 4044 4045 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 4046 CCInfo.clearWasPPCF128(); 4047 4048 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4049 CCValAssign &VA = ArgLocs[i]; 4050 4051 // Arguments stored in registers. 4052 if (VA.isRegLoc()) { 4053 const TargetRegisterClass *RC; 4054 EVT ValVT = VA.getValVT(); 4055 4056 switch (ValVT.getSimpleVT().SimpleTy) { 4057 default: 4058 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 4059 case MVT::i1: 4060 case MVT::i32: 4061 RC = &PPC::GPRCRegClass; 4062 break; 4063 case MVT::f32: 4064 if (Subtarget.hasP8Vector()) 4065 RC = &PPC::VSSRCRegClass; 4066 else if (Subtarget.hasSPE()) 4067 RC = &PPC::GPRCRegClass; 4068 else 4069 RC = &PPC::F4RCRegClass; 4070 break; 4071 case MVT::f64: 4072 if (Subtarget.hasVSX()) 4073 RC = &PPC::VSFRCRegClass; 4074 else if (Subtarget.hasSPE()) 4075 // SPE passes doubles in GPR pairs. 4076 RC = &PPC::GPRCRegClass; 4077 else 4078 RC = &PPC::F8RCRegClass; 4079 break; 4080 case MVT::v16i8: 4081 case MVT::v8i16: 4082 case MVT::v4i32: 4083 RC = &PPC::VRRCRegClass; 4084 break; 4085 case MVT::v4f32: 4086 RC = &PPC::VRRCRegClass; 4087 break; 4088 case MVT::v2f64: 4089 case MVT::v2i64: 4090 RC = &PPC::VRRCRegClass; 4091 break; 4092 } 4093 4094 SDValue ArgValue; 4095 // Transform the arguments stored in physical registers into 4096 // virtual ones. 4097 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 4098 assert(i + 1 < e && "No second half of double precision argument"); 4099 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC); 4100 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 4101 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 4102 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 4103 if (!Subtarget.isLittleEndian()) 4104 std::swap (ArgValueLo, ArgValueHi); 4105 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 4106 ArgValueHi); 4107 } else { 4108 Register Reg = MF.addLiveIn(VA.getLocReg(), RC); 4109 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 4110 ValVT == MVT::i1 ? MVT::i32 : ValVT); 4111 if (ValVT == MVT::i1) 4112 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 4113 } 4114 4115 InVals.push_back(ArgValue); 4116 } else { 4117 // Argument stored in memory. 4118 assert(VA.isMemLoc()); 4119 4120 // Get the extended size of the argument type in stack 4121 unsigned ArgSize = VA.getLocVT().getStoreSize(); 4122 // Get the actual size of the argument type 4123 unsigned ObjSize = VA.getValVT().getStoreSize(); 4124 unsigned ArgOffset = VA.getLocMemOffset(); 4125 // Stack objects in PPC32 are right justified. 4126 ArgOffset += ArgSize - ObjSize; 4127 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 4128 4129 // Create load nodes to retrieve arguments from the stack. 4130 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4131 InVals.push_back( 4132 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 4133 } 4134 } 4135 4136 // Assign locations to all of the incoming aggregate by value arguments. 4137 // Aggregates passed by value are stored in the local variable space of the 4138 // caller's stack frame, right above the parameter list area. 4139 SmallVector<CCValAssign, 16> ByValArgLocs; 4140 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4141 ByValArgLocs, *DAG.getContext()); 4142 4143 // Reserve stack space for the allocations in CCInfo. 4144 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 4145 4146 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 4147 4148 // Area that is at least reserved in the caller of this function. 4149 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 4150 MinReservedArea = std::max(MinReservedArea, LinkageSize); 4151 4152 // Set the size that is at least reserved in caller of this function. Tail 4153 // call optimized function's reserved stack space needs to be aligned so that 4154 // taking the difference between two stack areas will result in an aligned 4155 // stack. 4156 MinReservedArea = 4157 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4158 FuncInfo->setMinReservedArea(MinReservedArea); 4159 4160 SmallVector<SDValue, 8> MemOps; 4161 4162 // If the function takes variable number of arguments, make a frame index for 4163 // the start of the first vararg value... for expansion of llvm.va_start. 4164 if (isVarArg) { 4165 static const MCPhysReg GPArgRegs[] = { 4166 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4167 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4168 }; 4169 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 4170 4171 static const MCPhysReg FPArgRegs[] = { 4172 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 4173 PPC::F8 4174 }; 4175 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 4176 4177 if (useSoftFloat() || hasSPE()) 4178 NumFPArgRegs = 0; 4179 4180 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 4181 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 4182 4183 // Make room for NumGPArgRegs and NumFPArgRegs. 4184 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 4185 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 4186 4187 FuncInfo->setVarArgsStackOffset( 4188 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4189 CCInfo.getNextStackOffset(), true)); 4190 4191 FuncInfo->setVarArgsFrameIndex( 4192 MFI.CreateStackObject(Depth, Align(8), false)); 4193 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4194 4195 // The fixed integer arguments of a variadic function are stored to the 4196 // VarArgsFrameIndex on the stack so that they may be loaded by 4197 // dereferencing the result of va_next. 4198 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 4199 // Get an existing live-in vreg, or add a new one. 4200 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 4201 if (!VReg) 4202 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 4203 4204 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4205 SDValue Store = 4206 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4207 MemOps.push_back(Store); 4208 // Increment the address by four for the next argument to store 4209 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4210 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4211 } 4212 4213 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 4214 // is set. 4215 // The double arguments are stored to the VarArgsFrameIndex 4216 // on the stack. 4217 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 4218 // Get an existing live-in vreg, or add a new one. 4219 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 4220 if (!VReg) 4221 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 4222 4223 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 4224 SDValue Store = 4225 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4226 MemOps.push_back(Store); 4227 // Increment the address by eight for the next argument to store 4228 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4229 PtrVT); 4230 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4231 } 4232 } 4233 4234 if (!MemOps.empty()) 4235 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4236 4237 return Chain; 4238 } 4239 4240 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4241 // value to MVT::i64 and then truncate to the correct register size. 4242 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4243 EVT ObjectVT, SelectionDAG &DAG, 4244 SDValue ArgVal, 4245 const SDLoc &dl) const { 4246 if (Flags.isSExt()) 4247 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4248 DAG.getValueType(ObjectVT)); 4249 else if (Flags.isZExt()) 4250 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4251 DAG.getValueType(ObjectVT)); 4252 4253 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4254 } 4255 4256 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4257 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4258 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4259 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4260 // TODO: add description of PPC stack frame format, or at least some docs. 4261 // 4262 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4263 bool isLittleEndian = Subtarget.isLittleEndian(); 4264 MachineFunction &MF = DAG.getMachineFunction(); 4265 MachineFrameInfo &MFI = MF.getFrameInfo(); 4266 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4267 4268 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4269 "fastcc not supported on varargs functions"); 4270 4271 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4272 // Potential tail calls could cause overwriting of argument stack slots. 4273 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4274 (CallConv == CallingConv::Fast)); 4275 unsigned PtrByteSize = 8; 4276 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4277 4278 static const MCPhysReg GPR[] = { 4279 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4280 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4281 }; 4282 static const MCPhysReg VR[] = { 4283 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4284 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4285 }; 4286 4287 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4288 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4289 const unsigned Num_VR_Regs = array_lengthof(VR); 4290 4291 // Do a first pass over the arguments to determine whether the ABI 4292 // guarantees that our caller has allocated the parameter save area 4293 // on its stack frame. In the ELFv1 ABI, this is always the case; 4294 // in the ELFv2 ABI, it is true if this is a vararg function or if 4295 // any parameter is located in a stack slot. 4296 4297 bool HasParameterArea = !isELFv2ABI || isVarArg; 4298 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4299 unsigned NumBytes = LinkageSize; 4300 unsigned AvailableFPRs = Num_FPR_Regs; 4301 unsigned AvailableVRs = Num_VR_Regs; 4302 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4303 if (Ins[i].Flags.isNest()) 4304 continue; 4305 4306 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4307 PtrByteSize, LinkageSize, ParamAreaSize, 4308 NumBytes, AvailableFPRs, AvailableVRs)) 4309 HasParameterArea = true; 4310 } 4311 4312 // Add DAG nodes to load the arguments or copy them out of registers. On 4313 // entry to a function on PPC, the arguments start after the linkage area, 4314 // although the first ones are often in registers. 4315 4316 unsigned ArgOffset = LinkageSize; 4317 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4318 SmallVector<SDValue, 8> MemOps; 4319 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4320 unsigned CurArgIdx = 0; 4321 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4322 SDValue ArgVal; 4323 bool needsLoad = false; 4324 EVT ObjectVT = Ins[ArgNo].VT; 4325 EVT OrigVT = Ins[ArgNo].ArgVT; 4326 unsigned ObjSize = ObjectVT.getStoreSize(); 4327 unsigned ArgSize = ObjSize; 4328 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4329 if (Ins[ArgNo].isOrigArg()) { 4330 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4331 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4332 } 4333 // We re-align the argument offset for each argument, except when using the 4334 // fast calling convention, when we need to make sure we do that only when 4335 // we'll actually use a stack slot. 4336 unsigned CurArgOffset; 4337 Align Alignment; 4338 auto ComputeArgOffset = [&]() { 4339 /* Respect alignment of argument on the stack. */ 4340 Alignment = 4341 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4342 ArgOffset = alignTo(ArgOffset, Alignment); 4343 CurArgOffset = ArgOffset; 4344 }; 4345 4346 if (CallConv != CallingConv::Fast) { 4347 ComputeArgOffset(); 4348 4349 /* Compute GPR index associated with argument offset. */ 4350 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4351 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4352 } 4353 4354 // FIXME the codegen can be much improved in some cases. 4355 // We do not have to keep everything in memory. 4356 if (Flags.isByVal()) { 4357 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4358 4359 if (CallConv == CallingConv::Fast) 4360 ComputeArgOffset(); 4361 4362 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4363 ObjSize = Flags.getByValSize(); 4364 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4365 // Empty aggregate parameters do not take up registers. Examples: 4366 // struct { } a; 4367 // union { } b; 4368 // int c[0]; 4369 // etc. However, we have to provide a place-holder in InVals, so 4370 // pretend we have an 8-byte item at the current address for that 4371 // purpose. 4372 if (!ObjSize) { 4373 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4374 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4375 InVals.push_back(FIN); 4376 continue; 4377 } 4378 4379 // Create a stack object covering all stack doublewords occupied 4380 // by the argument. If the argument is (fully or partially) on 4381 // the stack, or if the argument is fully in registers but the 4382 // caller has allocated the parameter save anyway, we can refer 4383 // directly to the caller's stack frame. Otherwise, create a 4384 // local copy in our own frame. 4385 int FI; 4386 if (HasParameterArea || 4387 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4388 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4389 else 4390 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4391 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4392 4393 // Handle aggregates smaller than 8 bytes. 4394 if (ObjSize < PtrByteSize) { 4395 // The value of the object is its address, which differs from the 4396 // address of the enclosing doubleword on big-endian systems. 4397 SDValue Arg = FIN; 4398 if (!isLittleEndian) { 4399 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4400 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4401 } 4402 InVals.push_back(Arg); 4403 4404 if (GPR_idx != Num_GPR_Regs) { 4405 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4406 FuncInfo->addLiveInAttr(VReg, Flags); 4407 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4408 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8); 4409 SDValue Store = 4410 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4411 MachinePointerInfo(&*FuncArg), ObjType); 4412 MemOps.push_back(Store); 4413 } 4414 // Whether we copied from a register or not, advance the offset 4415 // into the parameter save area by a full doubleword. 4416 ArgOffset += PtrByteSize; 4417 continue; 4418 } 4419 4420 // The value of the object is its address, which is the address of 4421 // its first stack doubleword. 4422 InVals.push_back(FIN); 4423 4424 // Store whatever pieces of the object are in registers to memory. 4425 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4426 if (GPR_idx == Num_GPR_Regs) 4427 break; 4428 4429 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4430 FuncInfo->addLiveInAttr(VReg, Flags); 4431 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4432 SDValue Addr = FIN; 4433 if (j) { 4434 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4435 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4436 } 4437 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4438 MachinePointerInfo(&*FuncArg, j)); 4439 MemOps.push_back(Store); 4440 ++GPR_idx; 4441 } 4442 ArgOffset += ArgSize; 4443 continue; 4444 } 4445 4446 switch (ObjectVT.getSimpleVT().SimpleTy) { 4447 default: llvm_unreachable("Unhandled argument type!"); 4448 case MVT::i1: 4449 case MVT::i32: 4450 case MVT::i64: 4451 if (Flags.isNest()) { 4452 // The 'nest' parameter, if any, is passed in R11. 4453 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4454 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4455 4456 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4457 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4458 4459 break; 4460 } 4461 4462 // These can be scalar arguments or elements of an integer array type 4463 // passed directly. Clang may use those instead of "byval" aggregate 4464 // types to avoid forcing arguments to memory unnecessarily. 4465 if (GPR_idx != Num_GPR_Regs) { 4466 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4467 FuncInfo->addLiveInAttr(VReg, Flags); 4468 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4469 4470 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4471 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4472 // value to MVT::i64 and then truncate to the correct register size. 4473 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4474 } else { 4475 if (CallConv == CallingConv::Fast) 4476 ComputeArgOffset(); 4477 4478 needsLoad = true; 4479 ArgSize = PtrByteSize; 4480 } 4481 if (CallConv != CallingConv::Fast || needsLoad) 4482 ArgOffset += 8; 4483 break; 4484 4485 case MVT::f32: 4486 case MVT::f64: 4487 // These can be scalar arguments or elements of a float array type 4488 // passed directly. The latter are used to implement ELFv2 homogenous 4489 // float aggregates. 4490 if (FPR_idx != Num_FPR_Regs) { 4491 unsigned VReg; 4492 4493 if (ObjectVT == MVT::f32) 4494 VReg = MF.addLiveIn(FPR[FPR_idx], 4495 Subtarget.hasP8Vector() 4496 ? &PPC::VSSRCRegClass 4497 : &PPC::F4RCRegClass); 4498 else 4499 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4500 ? &PPC::VSFRCRegClass 4501 : &PPC::F8RCRegClass); 4502 4503 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4504 ++FPR_idx; 4505 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4506 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4507 // once we support fp <-> gpr moves. 4508 4509 // This can only ever happen in the presence of f32 array types, 4510 // since otherwise we never run out of FPRs before running out 4511 // of GPRs. 4512 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4513 FuncInfo->addLiveInAttr(VReg, Flags); 4514 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4515 4516 if (ObjectVT == MVT::f32) { 4517 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4518 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4519 DAG.getConstant(32, dl, MVT::i32)); 4520 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4521 } 4522 4523 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4524 } else { 4525 if (CallConv == CallingConv::Fast) 4526 ComputeArgOffset(); 4527 4528 needsLoad = true; 4529 } 4530 4531 // When passing an array of floats, the array occupies consecutive 4532 // space in the argument area; only round up to the next doubleword 4533 // at the end of the array. Otherwise, each float takes 8 bytes. 4534 if (CallConv != CallingConv::Fast || needsLoad) { 4535 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4536 ArgOffset += ArgSize; 4537 if (Flags.isInConsecutiveRegsLast()) 4538 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4539 } 4540 break; 4541 case MVT::v4f32: 4542 case MVT::v4i32: 4543 case MVT::v8i16: 4544 case MVT::v16i8: 4545 case MVT::v2f64: 4546 case MVT::v2i64: 4547 case MVT::v1i128: 4548 case MVT::f128: 4549 // These can be scalar arguments or elements of a vector array type 4550 // passed directly. The latter are used to implement ELFv2 homogenous 4551 // vector aggregates. 4552 if (VR_idx != Num_VR_Regs) { 4553 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4554 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4555 ++VR_idx; 4556 } else { 4557 if (CallConv == CallingConv::Fast) 4558 ComputeArgOffset(); 4559 needsLoad = true; 4560 } 4561 if (CallConv != CallingConv::Fast || needsLoad) 4562 ArgOffset += 16; 4563 break; 4564 } 4565 4566 // We need to load the argument to a virtual register if we determined 4567 // above that we ran out of physical registers of the appropriate type. 4568 if (needsLoad) { 4569 if (ObjSize < ArgSize && !isLittleEndian) 4570 CurArgOffset += ArgSize - ObjSize; 4571 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4572 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4573 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4574 } 4575 4576 InVals.push_back(ArgVal); 4577 } 4578 4579 // Area that is at least reserved in the caller of this function. 4580 unsigned MinReservedArea; 4581 if (HasParameterArea) 4582 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4583 else 4584 MinReservedArea = LinkageSize; 4585 4586 // Set the size that is at least reserved in caller of this function. Tail 4587 // call optimized functions' reserved stack space needs to be aligned so that 4588 // taking the difference between two stack areas will result in an aligned 4589 // stack. 4590 MinReservedArea = 4591 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4592 FuncInfo->setMinReservedArea(MinReservedArea); 4593 4594 // If the function takes variable number of arguments, make a frame index for 4595 // the start of the first vararg value... for expansion of llvm.va_start. 4596 // On ELFv2ABI spec, it writes: 4597 // C programs that are intended to be *portable* across different compilers 4598 // and architectures must use the header file <stdarg.h> to deal with variable 4599 // argument lists. 4600 if (isVarArg && MFI.hasVAStart()) { 4601 int Depth = ArgOffset; 4602 4603 FuncInfo->setVarArgsFrameIndex( 4604 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4605 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4606 4607 // If this function is vararg, store any remaining integer argument regs 4608 // to their spots on the stack so that they may be loaded by dereferencing 4609 // the result of va_next. 4610 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4611 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4612 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4613 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4614 SDValue Store = 4615 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4616 MemOps.push_back(Store); 4617 // Increment the address by four for the next argument to store 4618 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4619 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4620 } 4621 } 4622 4623 if (!MemOps.empty()) 4624 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4625 4626 return Chain; 4627 } 4628 4629 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4630 /// adjusted to accommodate the arguments for the tailcall. 4631 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4632 unsigned ParamSize) { 4633 4634 if (!isTailCall) return 0; 4635 4636 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4637 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4638 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4639 // Remember only if the new adjustment is bigger. 4640 if (SPDiff < FI->getTailCallSPDelta()) 4641 FI->setTailCallSPDelta(SPDiff); 4642 4643 return SPDiff; 4644 } 4645 4646 static bool isFunctionGlobalAddress(SDValue Callee); 4647 4648 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4649 const TargetMachine &TM) { 4650 // It does not make sense to call callsShareTOCBase() with a caller that 4651 // is PC Relative since PC Relative callers do not have a TOC. 4652 #ifndef NDEBUG 4653 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4654 assert(!STICaller->isUsingPCRelativeCalls() && 4655 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4656 #endif 4657 4658 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4659 // don't have enough information to determine if the caller and callee share 4660 // the same TOC base, so we have to pessimistically assume they don't for 4661 // correctness. 4662 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4663 if (!G) 4664 return false; 4665 4666 const GlobalValue *GV = G->getGlobal(); 4667 4668 // If the callee is preemptable, then the static linker will use a plt-stub 4669 // which saves the toc to the stack, and needs a nop after the call 4670 // instruction to convert to a toc-restore. 4671 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4672 return false; 4673 4674 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4675 // We may need a TOC restore in the situation where the caller requires a 4676 // valid TOC but the callee is PC Relative and does not. 4677 const Function *F = dyn_cast<Function>(GV); 4678 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4679 4680 // If we have an Alias we can try to get the function from there. 4681 if (Alias) { 4682 const GlobalObject *GlobalObj = Alias->getAliaseeObject(); 4683 F = dyn_cast<Function>(GlobalObj); 4684 } 4685 4686 // If we still have no valid function pointer we do not have enough 4687 // information to determine if the callee uses PC Relative calls so we must 4688 // assume that it does. 4689 if (!F) 4690 return false; 4691 4692 // If the callee uses PC Relative we cannot guarantee that the callee won't 4693 // clobber the TOC of the caller and so we must assume that the two 4694 // functions do not share a TOC base. 4695 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4696 if (STICallee->isUsingPCRelativeCalls()) 4697 return false; 4698 4699 // If the GV is not a strong definition then we need to assume it can be 4700 // replaced by another function at link time. The function that replaces 4701 // it may not share the same TOC as the caller since the callee may be 4702 // replaced by a PC Relative version of the same function. 4703 if (!GV->isStrongDefinitionForLinker()) 4704 return false; 4705 4706 // The medium and large code models are expected to provide a sufficiently 4707 // large TOC to provide all data addressing needs of a module with a 4708 // single TOC. 4709 if (CodeModel::Medium == TM.getCodeModel() || 4710 CodeModel::Large == TM.getCodeModel()) 4711 return true; 4712 4713 // Any explicitly-specified sections and section prefixes must also match. 4714 // Also, if we're using -ffunction-sections, then each function is always in 4715 // a different section (the same is true for COMDAT functions). 4716 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4717 GV->getSection() != Caller->getSection()) 4718 return false; 4719 if (const auto *F = dyn_cast<Function>(GV)) { 4720 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4721 return false; 4722 } 4723 4724 return true; 4725 } 4726 4727 static bool 4728 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4729 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4730 assert(Subtarget.is64BitELFABI()); 4731 4732 const unsigned PtrByteSize = 8; 4733 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4734 4735 static const MCPhysReg GPR[] = { 4736 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4737 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4738 }; 4739 static const MCPhysReg VR[] = { 4740 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4741 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4742 }; 4743 4744 const unsigned NumGPRs = array_lengthof(GPR); 4745 const unsigned NumFPRs = 13; 4746 const unsigned NumVRs = array_lengthof(VR); 4747 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4748 4749 unsigned NumBytes = LinkageSize; 4750 unsigned AvailableFPRs = NumFPRs; 4751 unsigned AvailableVRs = NumVRs; 4752 4753 for (const ISD::OutputArg& Param : Outs) { 4754 if (Param.Flags.isNest()) continue; 4755 4756 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4757 LinkageSize, ParamAreaSize, NumBytes, 4758 AvailableFPRs, AvailableVRs)) 4759 return true; 4760 } 4761 return false; 4762 } 4763 4764 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4765 if (CB.arg_size() != CallerFn->arg_size()) 4766 return false; 4767 4768 auto CalleeArgIter = CB.arg_begin(); 4769 auto CalleeArgEnd = CB.arg_end(); 4770 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4771 4772 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4773 const Value* CalleeArg = *CalleeArgIter; 4774 const Value* CallerArg = &(*CallerArgIter); 4775 if (CalleeArg == CallerArg) 4776 continue; 4777 4778 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4779 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4780 // } 4781 // 1st argument of callee is undef and has the same type as caller. 4782 if (CalleeArg->getType() == CallerArg->getType() && 4783 isa<UndefValue>(CalleeArg)) 4784 continue; 4785 4786 return false; 4787 } 4788 4789 return true; 4790 } 4791 4792 // Returns true if TCO is possible between the callers and callees 4793 // calling conventions. 4794 static bool 4795 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4796 CallingConv::ID CalleeCC) { 4797 // Tail calls are possible with fastcc and ccc. 4798 auto isTailCallableCC = [] (CallingConv::ID CC){ 4799 return CC == CallingConv::C || CC == CallingConv::Fast; 4800 }; 4801 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4802 return false; 4803 4804 // We can safely tail call both fastcc and ccc callees from a c calling 4805 // convention caller. If the caller is fastcc, we may have less stack space 4806 // than a non-fastcc caller with the same signature so disable tail-calls in 4807 // that case. 4808 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4809 } 4810 4811 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4812 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4813 const SmallVectorImpl<ISD::OutputArg> &Outs, 4814 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4815 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4816 4817 if (DisableSCO && !TailCallOpt) return false; 4818 4819 // Variadic argument functions are not supported. 4820 if (isVarArg) return false; 4821 4822 auto &Caller = DAG.getMachineFunction().getFunction(); 4823 // Check that the calling conventions are compatible for tco. 4824 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4825 return false; 4826 4827 // Caller contains any byval parameter is not supported. 4828 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4829 return false; 4830 4831 // Callee contains any byval parameter is not supported, too. 4832 // Note: This is a quick work around, because in some cases, e.g. 4833 // caller's stack size > callee's stack size, we are still able to apply 4834 // sibling call optimization. For example, gcc is able to do SCO for caller1 4835 // in the following example, but not for caller2. 4836 // struct test { 4837 // long int a; 4838 // char ary[56]; 4839 // } gTest; 4840 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4841 // b->a = v.a; 4842 // return 0; 4843 // } 4844 // void caller1(struct test a, struct test c, struct test *b) { 4845 // callee(gTest, b); } 4846 // void caller2(struct test *b) { callee(gTest, b); } 4847 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4848 return false; 4849 4850 // If callee and caller use different calling conventions, we cannot pass 4851 // parameters on stack since offsets for the parameter area may be different. 4852 if (Caller.getCallingConv() != CalleeCC && 4853 needStackSlotPassParameters(Subtarget, Outs)) 4854 return false; 4855 4856 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4857 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4858 // callee potentially have different TOC bases then we cannot tail call since 4859 // we need to restore the TOC pointer after the call. 4860 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4861 // We cannot guarantee this for indirect calls or calls to external functions. 4862 // When PC-Relative addressing is used, the concept of the TOC is no longer 4863 // applicable so this check is not required. 4864 // Check first for indirect calls. 4865 if (!Subtarget.isUsingPCRelativeCalls() && 4866 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4867 return false; 4868 4869 // Check if we share the TOC base. 4870 if (!Subtarget.isUsingPCRelativeCalls() && 4871 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4872 return false; 4873 4874 // TCO allows altering callee ABI, so we don't have to check further. 4875 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4876 return true; 4877 4878 if (DisableSCO) return false; 4879 4880 // If callee use the same argument list that caller is using, then we can 4881 // apply SCO on this case. If it is not, then we need to check if callee needs 4882 // stack for passing arguments. 4883 // PC Relative tail calls may not have a CallBase. 4884 // If there is no CallBase we cannot verify if we have the same argument 4885 // list so assume that we don't have the same argument list. 4886 if (CB && !hasSameArgumentList(&Caller, *CB) && 4887 needStackSlotPassParameters(Subtarget, Outs)) 4888 return false; 4889 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4890 return false; 4891 4892 return true; 4893 } 4894 4895 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4896 /// for tail call optimization. Targets which want to do tail call 4897 /// optimization should implement this function. 4898 bool 4899 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4900 CallingConv::ID CalleeCC, 4901 bool isVarArg, 4902 const SmallVectorImpl<ISD::InputArg> &Ins, 4903 SelectionDAG& DAG) const { 4904 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4905 return false; 4906 4907 // Variable argument functions are not supported. 4908 if (isVarArg) 4909 return false; 4910 4911 MachineFunction &MF = DAG.getMachineFunction(); 4912 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4913 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4914 // Functions containing by val parameters are not supported. 4915 for (unsigned i = 0; i != Ins.size(); i++) { 4916 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4917 if (Flags.isByVal()) return false; 4918 } 4919 4920 // Non-PIC/GOT tail calls are supported. 4921 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4922 return true; 4923 4924 // At the moment we can only do local tail calls (in same module, hidden 4925 // or protected) if we are generating PIC. 4926 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4927 return G->getGlobal()->hasHiddenVisibility() 4928 || G->getGlobal()->hasProtectedVisibility(); 4929 } 4930 4931 return false; 4932 } 4933 4934 /// isCallCompatibleAddress - Return the immediate to use if the specified 4935 /// 32-bit value is representable in the immediate field of a BxA instruction. 4936 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4937 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4938 if (!C) return nullptr; 4939 4940 int Addr = C->getZExtValue(); 4941 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4942 SignExtend32<26>(Addr) != Addr) 4943 return nullptr; // Top 6 bits have to be sext of immediate. 4944 4945 return DAG 4946 .getConstant( 4947 (int)C->getZExtValue() >> 2, SDLoc(Op), 4948 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4949 .getNode(); 4950 } 4951 4952 namespace { 4953 4954 struct TailCallArgumentInfo { 4955 SDValue Arg; 4956 SDValue FrameIdxOp; 4957 int FrameIdx = 0; 4958 4959 TailCallArgumentInfo() = default; 4960 }; 4961 4962 } // end anonymous namespace 4963 4964 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4965 static void StoreTailCallArgumentsToStackSlot( 4966 SelectionDAG &DAG, SDValue Chain, 4967 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4968 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4969 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4970 SDValue Arg = TailCallArgs[i].Arg; 4971 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4972 int FI = TailCallArgs[i].FrameIdx; 4973 // Store relative to framepointer. 4974 MemOpChains.push_back(DAG.getStore( 4975 Chain, dl, Arg, FIN, 4976 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4977 } 4978 } 4979 4980 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4981 /// the appropriate stack slot for the tail call optimized function call. 4982 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4983 SDValue OldRetAddr, SDValue OldFP, 4984 int SPDiff, const SDLoc &dl) { 4985 if (SPDiff) { 4986 // Calculate the new stack slot for the return address. 4987 MachineFunction &MF = DAG.getMachineFunction(); 4988 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4989 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4990 bool isPPC64 = Subtarget.isPPC64(); 4991 int SlotSize = isPPC64 ? 8 : 4; 4992 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4993 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4994 NewRetAddrLoc, true); 4995 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4996 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4997 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4998 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4999 } 5000 return Chain; 5001 } 5002 5003 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5004 /// the position of the argument. 5005 static void 5006 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5007 SDValue Arg, int SPDiff, unsigned ArgOffset, 5008 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5009 int Offset = ArgOffset + SPDiff; 5010 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5011 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5012 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5013 SDValue FIN = DAG.getFrameIndex(FI, VT); 5014 TailCallArgumentInfo Info; 5015 Info.Arg = Arg; 5016 Info.FrameIdxOp = FIN; 5017 Info.FrameIdx = FI; 5018 TailCallArguments.push_back(Info); 5019 } 5020 5021 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5022 /// stack slot. Returns the chain as result and the loaded frame pointers in 5023 /// LROpOut/FPOpout. Used when tail calling. 5024 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5025 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5026 SDValue &FPOpOut, const SDLoc &dl) const { 5027 if (SPDiff) { 5028 // Load the LR and FP stack slot for later adjusting. 5029 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5030 LROpOut = getReturnAddrFrameIndex(DAG); 5031 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5032 Chain = SDValue(LROpOut.getNode(), 1); 5033 } 5034 return Chain; 5035 } 5036 5037 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5038 /// by "Src" to address "Dst" of size "Size". Alignment information is 5039 /// specified by the specific parameter attribute. The copy will be passed as 5040 /// a byval function parameter. 5041 /// Sometimes what we are copying is the end of a larger object, the part that 5042 /// does not fit in registers. 5043 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5044 SDValue Chain, ISD::ArgFlagsTy Flags, 5045 SelectionDAG &DAG, const SDLoc &dl) { 5046 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5047 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5048 Flags.getNonZeroByValAlign(), false, false, false, 5049 MachinePointerInfo(), MachinePointerInfo()); 5050 } 5051 5052 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5053 /// tail calls. 5054 static void LowerMemOpCallTo( 5055 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5056 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5057 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5058 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5059 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5060 if (!isTailCall) { 5061 if (isVector) { 5062 SDValue StackPtr; 5063 if (isPPC64) 5064 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5065 else 5066 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5067 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5068 DAG.getConstant(ArgOffset, dl, PtrVT)); 5069 } 5070 MemOpChains.push_back( 5071 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5072 // Calculate and remember argument location. 5073 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5074 TailCallArguments); 5075 } 5076 5077 static void 5078 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5079 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5080 SDValue FPOp, 5081 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5082 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5083 // might overwrite each other in case of tail call optimization. 5084 SmallVector<SDValue, 8> MemOpChains2; 5085 // Do not flag preceding copytoreg stuff together with the following stuff. 5086 InFlag = SDValue(); 5087 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5088 MemOpChains2, dl); 5089 if (!MemOpChains2.empty()) 5090 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5091 5092 // Store the return address to the appropriate stack slot. 5093 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5094 5095 // Emit callseq_end just before tailcall node. 5096 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5097 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5098 InFlag = Chain.getValue(1); 5099 } 5100 5101 // Is this global address that of a function that can be called by name? (as 5102 // opposed to something that must hold a descriptor for an indirect call). 5103 static bool isFunctionGlobalAddress(SDValue Callee) { 5104 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5105 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5106 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5107 return false; 5108 5109 return G->getGlobal()->getValueType()->isFunctionTy(); 5110 } 5111 5112 return false; 5113 } 5114 5115 SDValue PPCTargetLowering::LowerCallResult( 5116 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5117 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5118 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5119 SmallVector<CCValAssign, 16> RVLocs; 5120 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5121 *DAG.getContext()); 5122 5123 CCRetInfo.AnalyzeCallResult( 5124 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5125 ? RetCC_PPC_Cold 5126 : RetCC_PPC); 5127 5128 // Copy all of the result registers out of their specified physreg. 5129 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5130 CCValAssign &VA = RVLocs[i]; 5131 assert(VA.isRegLoc() && "Can only return in registers!"); 5132 5133 SDValue Val; 5134 5135 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5136 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5137 InFlag); 5138 Chain = Lo.getValue(1); 5139 InFlag = Lo.getValue(2); 5140 VA = RVLocs[++i]; // skip ahead to next loc 5141 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5142 InFlag); 5143 Chain = Hi.getValue(1); 5144 InFlag = Hi.getValue(2); 5145 if (!Subtarget.isLittleEndian()) 5146 std::swap (Lo, Hi); 5147 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5148 } else { 5149 Val = DAG.getCopyFromReg(Chain, dl, 5150 VA.getLocReg(), VA.getLocVT(), InFlag); 5151 Chain = Val.getValue(1); 5152 InFlag = Val.getValue(2); 5153 } 5154 5155 switch (VA.getLocInfo()) { 5156 default: llvm_unreachable("Unknown loc info!"); 5157 case CCValAssign::Full: break; 5158 case CCValAssign::AExt: 5159 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5160 break; 5161 case CCValAssign::ZExt: 5162 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5163 DAG.getValueType(VA.getValVT())); 5164 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5165 break; 5166 case CCValAssign::SExt: 5167 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5168 DAG.getValueType(VA.getValVT())); 5169 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5170 break; 5171 } 5172 5173 InVals.push_back(Val); 5174 } 5175 5176 return Chain; 5177 } 5178 5179 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5180 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5181 // PatchPoint calls are not indirect. 5182 if (isPatchPoint) 5183 return false; 5184 5185 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 5186 return false; 5187 5188 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5189 // becuase the immediate function pointer points to a descriptor instead of 5190 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5191 // pointer immediate points to the global entry point, while the BLA would 5192 // need to jump to the local entry point (see rL211174). 5193 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5194 isBLACompatibleAddress(Callee, DAG)) 5195 return false; 5196 5197 return true; 5198 } 5199 5200 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5201 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5202 return Subtarget.isAIXABI() || 5203 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5204 } 5205 5206 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5207 const Function &Caller, const SDValue &Callee, 5208 const PPCSubtarget &Subtarget, 5209 const TargetMachine &TM, 5210 bool IsStrictFPCall = false) { 5211 if (CFlags.IsTailCall) 5212 return PPCISD::TC_RETURN; 5213 5214 unsigned RetOpc = 0; 5215 // This is a call through a function pointer. 5216 if (CFlags.IsIndirect) { 5217 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5218 // indirect calls. The save of the caller's TOC pointer to the stack will be 5219 // inserted into the DAG as part of call lowering. The restore of the TOC 5220 // pointer is modeled by using a pseudo instruction for the call opcode that 5221 // represents the 2 instruction sequence of an indirect branch and link, 5222 // immediately followed by a load of the TOC pointer from the the stack save 5223 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5224 // as it is not saved or used. 5225 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5226 : PPCISD::BCTRL; 5227 } else if (Subtarget.isUsingPCRelativeCalls()) { 5228 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5229 RetOpc = PPCISD::CALL_NOTOC; 5230 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5231 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5232 // immediately following the call instruction if the caller and callee may 5233 // have different TOC bases. At link time if the linker determines the calls 5234 // may not share a TOC base, the call is redirected to a trampoline inserted 5235 // by the linker. The trampoline will (among other things) save the callers 5236 // TOC pointer at an ABI designated offset in the linkage area and the 5237 // linker will rewrite the nop to be a load of the TOC pointer from the 5238 // linkage area into gpr2. 5239 RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5240 : PPCISD::CALL_NOP; 5241 else 5242 RetOpc = PPCISD::CALL; 5243 if (IsStrictFPCall) { 5244 switch (RetOpc) { 5245 default: 5246 llvm_unreachable("Unknown call opcode"); 5247 case PPCISD::BCTRL_LOAD_TOC: 5248 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM; 5249 break; 5250 case PPCISD::BCTRL: 5251 RetOpc = PPCISD::BCTRL_RM; 5252 break; 5253 case PPCISD::CALL_NOTOC: 5254 RetOpc = PPCISD::CALL_NOTOC_RM; 5255 break; 5256 case PPCISD::CALL: 5257 RetOpc = PPCISD::CALL_RM; 5258 break; 5259 case PPCISD::CALL_NOP: 5260 RetOpc = PPCISD::CALL_NOP_RM; 5261 break; 5262 } 5263 } 5264 return RetOpc; 5265 } 5266 5267 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5268 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5269 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5270 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5271 return SDValue(Dest, 0); 5272 5273 // Returns true if the callee is local, and false otherwise. 5274 auto isLocalCallee = [&]() { 5275 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5276 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5277 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5278 5279 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5280 !isa_and_nonnull<GlobalIFunc>(GV); 5281 }; 5282 5283 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5284 // a static relocation model causes some versions of GNU LD (2.17.50, at 5285 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5286 // built with secure-PLT. 5287 bool UsePlt = 5288 Subtarget.is32BitELFABI() && !isLocalCallee() && 5289 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5290 5291 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5292 const TargetMachine &TM = Subtarget.getTargetMachine(); 5293 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5294 MCSymbolXCOFF *S = 5295 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5296 5297 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5298 return DAG.getMCSymbol(S, PtrVT); 5299 }; 5300 5301 if (isFunctionGlobalAddress(Callee)) { 5302 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5303 5304 if (Subtarget.isAIXABI()) { 5305 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5306 return getAIXFuncEntryPointSymbolSDNode(GV); 5307 } 5308 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5309 UsePlt ? PPCII::MO_PLT : 0); 5310 } 5311 5312 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5313 const char *SymName = S->getSymbol(); 5314 if (Subtarget.isAIXABI()) { 5315 // If there exists a user-declared function whose name is the same as the 5316 // ExternalSymbol's, then we pick up the user-declared version. 5317 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5318 if (const Function *F = 5319 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5320 return getAIXFuncEntryPointSymbolSDNode(F); 5321 5322 // On AIX, direct function calls reference the symbol for the function's 5323 // entry point, which is named by prepending a "." before the function's 5324 // C-linkage name. A Qualname is returned here because an external 5325 // function entry point is a csect with XTY_ER property. 5326 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5327 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5328 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5329 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5330 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5331 return Sec->getQualNameSymbol(); 5332 }; 5333 5334 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5335 } 5336 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5337 UsePlt ? PPCII::MO_PLT : 0); 5338 } 5339 5340 // No transformation needed. 5341 assert(Callee.getNode() && "What no callee?"); 5342 return Callee; 5343 } 5344 5345 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5346 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5347 "Expected a CALLSEQ_STARTSDNode."); 5348 5349 // The last operand is the chain, except when the node has glue. If the node 5350 // has glue, then the last operand is the glue, and the chain is the second 5351 // last operand. 5352 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5353 if (LastValue.getValueType() != MVT::Glue) 5354 return LastValue; 5355 5356 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5357 } 5358 5359 // Creates the node that moves a functions address into the count register 5360 // to prepare for an indirect call instruction. 5361 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5362 SDValue &Glue, SDValue &Chain, 5363 const SDLoc &dl) { 5364 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5365 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5366 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5367 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5368 // The glue is the second value produced. 5369 Glue = Chain.getValue(1); 5370 } 5371 5372 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5373 SDValue &Glue, SDValue &Chain, 5374 SDValue CallSeqStart, 5375 const CallBase *CB, const SDLoc &dl, 5376 bool hasNest, 5377 const PPCSubtarget &Subtarget) { 5378 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5379 // entry point, but to the function descriptor (the function entry point 5380 // address is part of the function descriptor though). 5381 // The function descriptor is a three doubleword structure with the 5382 // following fields: function entry point, TOC base address and 5383 // environment pointer. 5384 // Thus for a call through a function pointer, the following actions need 5385 // to be performed: 5386 // 1. Save the TOC of the caller in the TOC save area of its stack 5387 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5388 // 2. Load the address of the function entry point from the function 5389 // descriptor. 5390 // 3. Load the TOC of the callee from the function descriptor into r2. 5391 // 4. Load the environment pointer from the function descriptor into 5392 // r11. 5393 // 5. Branch to the function entry point address. 5394 // 6. On return of the callee, the TOC of the caller needs to be 5395 // restored (this is done in FinishCall()). 5396 // 5397 // The loads are scheduled at the beginning of the call sequence, and the 5398 // register copies are flagged together to ensure that no other 5399 // operations can be scheduled in between. E.g. without flagging the 5400 // copies together, a TOC access in the caller could be scheduled between 5401 // the assignment of the callee TOC and the branch to the callee, which leads 5402 // to incorrect code. 5403 5404 // Start by loading the function address from the descriptor. 5405 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5406 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5407 ? (MachineMemOperand::MODereferenceable | 5408 MachineMemOperand::MOInvariant) 5409 : MachineMemOperand::MONone; 5410 5411 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5412 5413 // Registers used in building the DAG. 5414 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5415 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5416 5417 // Offsets of descriptor members. 5418 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5419 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5420 5421 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5422 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5423 5424 // One load for the functions entry point address. 5425 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5426 Alignment, MMOFlags); 5427 5428 // One for loading the TOC anchor for the module that contains the called 5429 // function. 5430 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5431 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5432 SDValue TOCPtr = 5433 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5434 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5435 5436 // One for loading the environment pointer. 5437 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5438 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5439 SDValue LoadEnvPtr = 5440 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5441 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5442 5443 5444 // Then copy the newly loaded TOC anchor to the TOC pointer. 5445 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5446 Chain = TOCVal.getValue(0); 5447 Glue = TOCVal.getValue(1); 5448 5449 // If the function call has an explicit 'nest' parameter, it takes the 5450 // place of the environment pointer. 5451 assert((!hasNest || !Subtarget.isAIXABI()) && 5452 "Nest parameter is not supported on AIX."); 5453 if (!hasNest) { 5454 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5455 Chain = EnvVal.getValue(0); 5456 Glue = EnvVal.getValue(1); 5457 } 5458 5459 // The rest of the indirect call sequence is the same as the non-descriptor 5460 // DAG. 5461 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5462 } 5463 5464 static void 5465 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5466 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5467 SelectionDAG &DAG, 5468 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5469 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5470 const PPCSubtarget &Subtarget) { 5471 const bool IsPPC64 = Subtarget.isPPC64(); 5472 // MVT for a general purpose register. 5473 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5474 5475 // First operand is always the chain. 5476 Ops.push_back(Chain); 5477 5478 // If it's a direct call pass the callee as the second operand. 5479 if (!CFlags.IsIndirect) 5480 Ops.push_back(Callee); 5481 else { 5482 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5483 5484 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5485 // on the stack (this would have been done in `LowerCall_64SVR4` or 5486 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5487 // represents both the indirect branch and a load that restores the TOC 5488 // pointer from the linkage area. The operand for the TOC restore is an add 5489 // of the TOC save offset to the stack pointer. This must be the second 5490 // operand: after the chain input but before any other variadic arguments. 5491 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5492 // saved or used. 5493 if (isTOCSaveRestoreRequired(Subtarget)) { 5494 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5495 5496 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5497 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5498 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5499 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5500 Ops.push_back(AddTOC); 5501 } 5502 5503 // Add the register used for the environment pointer. 5504 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5505 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5506 RegVT)); 5507 5508 5509 // Add CTR register as callee so a bctr can be emitted later. 5510 if (CFlags.IsTailCall) 5511 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5512 } 5513 5514 // If this is a tail call add stack pointer delta. 5515 if (CFlags.IsTailCall) 5516 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5517 5518 // Add argument registers to the end of the list so that they are known live 5519 // into the call. 5520 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5521 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5522 RegsToPass[i].second.getValueType())); 5523 5524 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5525 // no way to mark dependencies as implicit here. 5526 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5527 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5528 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5529 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5530 5531 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5532 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5533 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5534 5535 // Add a register mask operand representing the call-preserved registers. 5536 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5537 const uint32_t *Mask = 5538 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5539 assert(Mask && "Missing call preserved mask for calling convention"); 5540 Ops.push_back(DAG.getRegisterMask(Mask)); 5541 5542 // If the glue is valid, it is the last operand. 5543 if (Glue.getNode()) 5544 Ops.push_back(Glue); 5545 } 5546 5547 SDValue PPCTargetLowering::FinishCall( 5548 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5549 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5550 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5551 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5552 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5553 5554 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5555 Subtarget.isAIXABI()) 5556 setUsesTOCBasePtr(DAG); 5557 5558 unsigned CallOpc = 5559 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5560 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false); 5561 5562 if (!CFlags.IsIndirect) 5563 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5564 else if (Subtarget.usesFunctionDescriptors()) 5565 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5566 dl, CFlags.HasNest, Subtarget); 5567 else 5568 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5569 5570 // Build the operand list for the call instruction. 5571 SmallVector<SDValue, 8> Ops; 5572 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5573 SPDiff, Subtarget); 5574 5575 // Emit tail call. 5576 if (CFlags.IsTailCall) { 5577 // Indirect tail call when using PC Relative calls do not have the same 5578 // constraints. 5579 assert(((Callee.getOpcode() == ISD::Register && 5580 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5581 Callee.getOpcode() == ISD::TargetExternalSymbol || 5582 Callee.getOpcode() == ISD::TargetGlobalAddress || 5583 isa<ConstantSDNode>(Callee) || 5584 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5585 "Expecting a global address, external symbol, absolute value, " 5586 "register or an indirect tail call when PC Relative calls are " 5587 "used."); 5588 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5589 assert(CallOpc == PPCISD::TC_RETURN && 5590 "Unexpected call opcode for a tail call."); 5591 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5592 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5593 } 5594 5595 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5596 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5597 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5598 Glue = Chain.getValue(1); 5599 5600 // When performing tail call optimization the callee pops its arguments off 5601 // the stack. Account for this here so these bytes can be pushed back on in 5602 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5603 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5604 getTargetMachine().Options.GuaranteedTailCallOpt) 5605 ? NumBytes 5606 : 0; 5607 5608 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5609 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5610 Glue, dl); 5611 Glue = Chain.getValue(1); 5612 5613 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5614 DAG, InVals); 5615 } 5616 5617 SDValue 5618 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5619 SmallVectorImpl<SDValue> &InVals) const { 5620 SelectionDAG &DAG = CLI.DAG; 5621 SDLoc &dl = CLI.DL; 5622 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5623 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5624 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5625 SDValue Chain = CLI.Chain; 5626 SDValue Callee = CLI.Callee; 5627 bool &isTailCall = CLI.IsTailCall; 5628 CallingConv::ID CallConv = CLI.CallConv; 5629 bool isVarArg = CLI.IsVarArg; 5630 bool isPatchPoint = CLI.IsPatchPoint; 5631 const CallBase *CB = CLI.CB; 5632 5633 if (isTailCall) { 5634 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5635 isTailCall = false; 5636 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5637 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5638 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5639 else 5640 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5641 Ins, DAG); 5642 if (isTailCall) { 5643 ++NumTailCalls; 5644 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5645 ++NumSiblingCalls; 5646 5647 // PC Relative calls no longer guarantee that the callee is a Global 5648 // Address Node. The callee could be an indirect tail call in which 5649 // case the SDValue for the callee could be a load (to load the address 5650 // of a function pointer) or it may be a register copy (to move the 5651 // address of the callee from a function parameter into a virtual 5652 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5653 assert((Subtarget.isUsingPCRelativeCalls() || 5654 isa<GlobalAddressSDNode>(Callee)) && 5655 "Callee should be an llvm::Function object."); 5656 5657 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5658 << "\nTCO callee: "); 5659 LLVM_DEBUG(Callee.dump()); 5660 } 5661 } 5662 5663 if (!isTailCall && CB && CB->isMustTailCall()) 5664 report_fatal_error("failed to perform tail call elimination on a call " 5665 "site marked musttail"); 5666 5667 // When long calls (i.e. indirect calls) are always used, calls are always 5668 // made via function pointer. If we have a function name, first translate it 5669 // into a pointer. 5670 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5671 !isTailCall) 5672 Callee = LowerGlobalAddress(Callee, DAG); 5673 5674 CallFlags CFlags( 5675 CallConv, isTailCall, isVarArg, isPatchPoint, 5676 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5677 // hasNest 5678 Subtarget.is64BitELFABI() && 5679 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5680 CLI.NoMerge); 5681 5682 if (Subtarget.isAIXABI()) 5683 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5684 InVals, CB); 5685 5686 assert(Subtarget.isSVR4ABI()); 5687 if (Subtarget.isPPC64()) 5688 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5689 InVals, CB); 5690 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5691 InVals, CB); 5692 } 5693 5694 SDValue PPCTargetLowering::LowerCall_32SVR4( 5695 SDValue Chain, SDValue Callee, CallFlags CFlags, 5696 const SmallVectorImpl<ISD::OutputArg> &Outs, 5697 const SmallVectorImpl<SDValue> &OutVals, 5698 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5699 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5700 const CallBase *CB) const { 5701 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5702 // of the 32-bit SVR4 ABI stack frame layout. 5703 5704 const CallingConv::ID CallConv = CFlags.CallConv; 5705 const bool IsVarArg = CFlags.IsVarArg; 5706 const bool IsTailCall = CFlags.IsTailCall; 5707 5708 assert((CallConv == CallingConv::C || 5709 CallConv == CallingConv::Cold || 5710 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5711 5712 const Align PtrAlign(4); 5713 5714 MachineFunction &MF = DAG.getMachineFunction(); 5715 5716 // Mark this function as potentially containing a function that contains a 5717 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5718 // and restoring the callers stack pointer in this functions epilog. This is 5719 // done because by tail calling the called function might overwrite the value 5720 // in this function's (MF) stack pointer stack slot 0(SP). 5721 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5722 CallConv == CallingConv::Fast) 5723 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5724 5725 // Count how many bytes are to be pushed on the stack, including the linkage 5726 // area, parameter list area and the part of the local variable space which 5727 // contains copies of aggregates which are passed by value. 5728 5729 // Assign locations to all of the outgoing arguments. 5730 SmallVector<CCValAssign, 16> ArgLocs; 5731 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5732 5733 // Reserve space for the linkage area on the stack. 5734 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5735 PtrAlign); 5736 if (useSoftFloat()) 5737 CCInfo.PreAnalyzeCallOperands(Outs); 5738 5739 if (IsVarArg) { 5740 // Handle fixed and variable vector arguments differently. 5741 // Fixed vector arguments go into registers as long as registers are 5742 // available. Variable vector arguments always go into memory. 5743 unsigned NumArgs = Outs.size(); 5744 5745 for (unsigned i = 0; i != NumArgs; ++i) { 5746 MVT ArgVT = Outs[i].VT; 5747 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5748 bool Result; 5749 5750 if (Outs[i].IsFixed) { 5751 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5752 CCInfo); 5753 } else { 5754 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5755 ArgFlags, CCInfo); 5756 } 5757 5758 if (Result) { 5759 #ifndef NDEBUG 5760 errs() << "Call operand #" << i << " has unhandled type " 5761 << EVT(ArgVT).getEVTString() << "\n"; 5762 #endif 5763 llvm_unreachable(nullptr); 5764 } 5765 } 5766 } else { 5767 // All arguments are treated the same. 5768 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5769 } 5770 CCInfo.clearWasPPCF128(); 5771 5772 // Assign locations to all of the outgoing aggregate by value arguments. 5773 SmallVector<CCValAssign, 16> ByValArgLocs; 5774 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5775 5776 // Reserve stack space for the allocations in CCInfo. 5777 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5778 5779 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5780 5781 // Size of the linkage area, parameter list area and the part of the local 5782 // space variable where copies of aggregates which are passed by value are 5783 // stored. 5784 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5785 5786 // Calculate by how many bytes the stack has to be adjusted in case of tail 5787 // call optimization. 5788 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5789 5790 // Adjust the stack pointer for the new arguments... 5791 // These operations are automatically eliminated by the prolog/epilog pass 5792 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5793 SDValue CallSeqStart = Chain; 5794 5795 // Load the return address and frame pointer so it can be moved somewhere else 5796 // later. 5797 SDValue LROp, FPOp; 5798 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5799 5800 // Set up a copy of the stack pointer for use loading and storing any 5801 // arguments that may not fit in the registers available for argument 5802 // passing. 5803 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5804 5805 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5806 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5807 SmallVector<SDValue, 8> MemOpChains; 5808 5809 bool seenFloatArg = false; 5810 // Walk the register/memloc assignments, inserting copies/loads. 5811 // i - Tracks the index into the list of registers allocated for the call 5812 // RealArgIdx - Tracks the index into the list of actual function arguments 5813 // j - Tracks the index into the list of byval arguments 5814 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5815 i != e; 5816 ++i, ++RealArgIdx) { 5817 CCValAssign &VA = ArgLocs[i]; 5818 SDValue Arg = OutVals[RealArgIdx]; 5819 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5820 5821 if (Flags.isByVal()) { 5822 // Argument is an aggregate which is passed by value, thus we need to 5823 // create a copy of it in the local variable space of the current stack 5824 // frame (which is the stack frame of the caller) and pass the address of 5825 // this copy to the callee. 5826 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5827 CCValAssign &ByValVA = ByValArgLocs[j++]; 5828 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5829 5830 // Memory reserved in the local variable space of the callers stack frame. 5831 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5832 5833 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5834 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5835 StackPtr, PtrOff); 5836 5837 // Create a copy of the argument in the local area of the current 5838 // stack frame. 5839 SDValue MemcpyCall = 5840 CreateCopyOfByValArgument(Arg, PtrOff, 5841 CallSeqStart.getNode()->getOperand(0), 5842 Flags, DAG, dl); 5843 5844 // This must go outside the CALLSEQ_START..END. 5845 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5846 SDLoc(MemcpyCall)); 5847 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5848 NewCallSeqStart.getNode()); 5849 Chain = CallSeqStart = NewCallSeqStart; 5850 5851 // Pass the address of the aggregate copy on the stack either in a 5852 // physical register or in the parameter list area of the current stack 5853 // frame to the callee. 5854 Arg = PtrOff; 5855 } 5856 5857 // When useCRBits() is true, there can be i1 arguments. 5858 // It is because getRegisterType(MVT::i1) => MVT::i1, 5859 // and for other integer types getRegisterType() => MVT::i32. 5860 // Extend i1 and ensure callee will get i32. 5861 if (Arg.getValueType() == MVT::i1) 5862 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5863 dl, MVT::i32, Arg); 5864 5865 if (VA.isRegLoc()) { 5866 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5867 // Put argument in a physical register. 5868 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5869 bool IsLE = Subtarget.isLittleEndian(); 5870 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5871 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5872 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5873 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5874 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5875 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5876 SVal.getValue(0))); 5877 } else 5878 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5879 } else { 5880 // Put argument in the parameter list area of the current stack frame. 5881 assert(VA.isMemLoc()); 5882 unsigned LocMemOffset = VA.getLocMemOffset(); 5883 5884 if (!IsTailCall) { 5885 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5886 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5887 StackPtr, PtrOff); 5888 5889 MemOpChains.push_back( 5890 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5891 } else { 5892 // Calculate and remember argument location. 5893 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5894 TailCallArguments); 5895 } 5896 } 5897 } 5898 5899 if (!MemOpChains.empty()) 5900 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5901 5902 // Build a sequence of copy-to-reg nodes chained together with token chain 5903 // and flag operands which copy the outgoing args into the appropriate regs. 5904 SDValue InFlag; 5905 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5906 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5907 RegsToPass[i].second, InFlag); 5908 InFlag = Chain.getValue(1); 5909 } 5910 5911 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5912 // registers. 5913 if (IsVarArg) { 5914 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5915 SDValue Ops[] = { Chain, InFlag }; 5916 5917 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5918 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5919 5920 InFlag = Chain.getValue(1); 5921 } 5922 5923 if (IsTailCall) 5924 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5925 TailCallArguments); 5926 5927 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5928 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5929 } 5930 5931 // Copy an argument into memory, being careful to do this outside the 5932 // call sequence for the call to which the argument belongs. 5933 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5934 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5935 SelectionDAG &DAG, const SDLoc &dl) const { 5936 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5937 CallSeqStart.getNode()->getOperand(0), 5938 Flags, DAG, dl); 5939 // The MEMCPY must go outside the CALLSEQ_START..END. 5940 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5941 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5942 SDLoc(MemcpyCall)); 5943 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5944 NewCallSeqStart.getNode()); 5945 return NewCallSeqStart; 5946 } 5947 5948 SDValue PPCTargetLowering::LowerCall_64SVR4( 5949 SDValue Chain, SDValue Callee, CallFlags CFlags, 5950 const SmallVectorImpl<ISD::OutputArg> &Outs, 5951 const SmallVectorImpl<SDValue> &OutVals, 5952 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5953 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5954 const CallBase *CB) const { 5955 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5956 bool isLittleEndian = Subtarget.isLittleEndian(); 5957 unsigned NumOps = Outs.size(); 5958 bool IsSibCall = false; 5959 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5960 5961 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5962 unsigned PtrByteSize = 8; 5963 5964 MachineFunction &MF = DAG.getMachineFunction(); 5965 5966 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5967 IsSibCall = true; 5968 5969 // Mark this function as potentially containing a function that contains a 5970 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5971 // and restoring the callers stack pointer in this functions epilog. This is 5972 // done because by tail calling the called function might overwrite the value 5973 // in this function's (MF) stack pointer stack slot 0(SP). 5974 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5975 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5976 5977 assert(!(IsFastCall && CFlags.IsVarArg) && 5978 "fastcc not supported on varargs functions"); 5979 5980 // Count how many bytes are to be pushed on the stack, including the linkage 5981 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5982 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5983 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5984 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5985 unsigned NumBytes = LinkageSize; 5986 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5987 5988 static const MCPhysReg GPR[] = { 5989 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5990 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5991 }; 5992 static const MCPhysReg VR[] = { 5993 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5994 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5995 }; 5996 5997 const unsigned NumGPRs = array_lengthof(GPR); 5998 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5999 const unsigned NumVRs = array_lengthof(VR); 6000 6001 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6002 // can be passed to the callee in registers. 6003 // For the fast calling convention, there is another check below. 6004 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6005 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6006 if (!HasParameterArea) { 6007 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6008 unsigned AvailableFPRs = NumFPRs; 6009 unsigned AvailableVRs = NumVRs; 6010 unsigned NumBytesTmp = NumBytes; 6011 for (unsigned i = 0; i != NumOps; ++i) { 6012 if (Outs[i].Flags.isNest()) continue; 6013 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6014 PtrByteSize, LinkageSize, ParamAreaSize, 6015 NumBytesTmp, AvailableFPRs, AvailableVRs)) 6016 HasParameterArea = true; 6017 } 6018 } 6019 6020 // When using the fast calling convention, we don't provide backing for 6021 // arguments that will be in registers. 6022 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6023 6024 // Avoid allocating parameter area for fastcc functions if all the arguments 6025 // can be passed in the registers. 6026 if (IsFastCall) 6027 HasParameterArea = false; 6028 6029 // Add up all the space actually used. 6030 for (unsigned i = 0; i != NumOps; ++i) { 6031 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6032 EVT ArgVT = Outs[i].VT; 6033 EVT OrigVT = Outs[i].ArgVT; 6034 6035 if (Flags.isNest()) 6036 continue; 6037 6038 if (IsFastCall) { 6039 if (Flags.isByVal()) { 6040 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6041 if (NumGPRsUsed > NumGPRs) 6042 HasParameterArea = true; 6043 } else { 6044 switch (ArgVT.getSimpleVT().SimpleTy) { 6045 default: llvm_unreachable("Unexpected ValueType for argument!"); 6046 case MVT::i1: 6047 case MVT::i32: 6048 case MVT::i64: 6049 if (++NumGPRsUsed <= NumGPRs) 6050 continue; 6051 break; 6052 case MVT::v4i32: 6053 case MVT::v8i16: 6054 case MVT::v16i8: 6055 case MVT::v2f64: 6056 case MVT::v2i64: 6057 case MVT::v1i128: 6058 case MVT::f128: 6059 if (++NumVRsUsed <= NumVRs) 6060 continue; 6061 break; 6062 case MVT::v4f32: 6063 if (++NumVRsUsed <= NumVRs) 6064 continue; 6065 break; 6066 case MVT::f32: 6067 case MVT::f64: 6068 if (++NumFPRsUsed <= NumFPRs) 6069 continue; 6070 break; 6071 } 6072 HasParameterArea = true; 6073 } 6074 } 6075 6076 /* Respect alignment of argument on the stack. */ 6077 auto Alignement = 6078 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6079 NumBytes = alignTo(NumBytes, Alignement); 6080 6081 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6082 if (Flags.isInConsecutiveRegsLast()) 6083 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6084 } 6085 6086 unsigned NumBytesActuallyUsed = NumBytes; 6087 6088 // In the old ELFv1 ABI, 6089 // the prolog code of the callee may store up to 8 GPR argument registers to 6090 // the stack, allowing va_start to index over them in memory if its varargs. 6091 // Because we cannot tell if this is needed on the caller side, we have to 6092 // conservatively assume that it is needed. As such, make sure we have at 6093 // least enough stack space for the caller to store the 8 GPRs. 6094 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6095 // really requires memory operands, e.g. a vararg function. 6096 if (HasParameterArea) 6097 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6098 else 6099 NumBytes = LinkageSize; 6100 6101 // Tail call needs the stack to be aligned. 6102 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6103 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6104 6105 int SPDiff = 0; 6106 6107 // Calculate by how many bytes the stack has to be adjusted in case of tail 6108 // call optimization. 6109 if (!IsSibCall) 6110 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6111 6112 // To protect arguments on the stack from being clobbered in a tail call, 6113 // force all the loads to happen before doing any other lowering. 6114 if (CFlags.IsTailCall) 6115 Chain = DAG.getStackArgumentTokenFactor(Chain); 6116 6117 // Adjust the stack pointer for the new arguments... 6118 // These operations are automatically eliminated by the prolog/epilog pass 6119 if (!IsSibCall) 6120 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6121 SDValue CallSeqStart = Chain; 6122 6123 // Load the return address and frame pointer so it can be move somewhere else 6124 // later. 6125 SDValue LROp, FPOp; 6126 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6127 6128 // Set up a copy of the stack pointer for use loading and storing any 6129 // arguments that may not fit in the registers available for argument 6130 // passing. 6131 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6132 6133 // Figure out which arguments are going to go in registers, and which in 6134 // memory. Also, if this is a vararg function, floating point operations 6135 // must be stored to our stack, and loaded into integer regs as well, if 6136 // any integer regs are available for argument passing. 6137 unsigned ArgOffset = LinkageSize; 6138 6139 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6140 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6141 6142 SmallVector<SDValue, 8> MemOpChains; 6143 for (unsigned i = 0; i != NumOps; ++i) { 6144 SDValue Arg = OutVals[i]; 6145 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6146 EVT ArgVT = Outs[i].VT; 6147 EVT OrigVT = Outs[i].ArgVT; 6148 6149 // PtrOff will be used to store the current argument to the stack if a 6150 // register cannot be found for it. 6151 SDValue PtrOff; 6152 6153 // We re-align the argument offset for each argument, except when using the 6154 // fast calling convention, when we need to make sure we do that only when 6155 // we'll actually use a stack slot. 6156 auto ComputePtrOff = [&]() { 6157 /* Respect alignment of argument on the stack. */ 6158 auto Alignment = 6159 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6160 ArgOffset = alignTo(ArgOffset, Alignment); 6161 6162 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6163 6164 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6165 }; 6166 6167 if (!IsFastCall) { 6168 ComputePtrOff(); 6169 6170 /* Compute GPR index associated with argument offset. */ 6171 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6172 GPR_idx = std::min(GPR_idx, NumGPRs); 6173 } 6174 6175 // Promote integers to 64-bit values. 6176 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6177 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6178 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6179 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6180 } 6181 6182 // FIXME memcpy is used way more than necessary. Correctness first. 6183 // Note: "by value" is code for passing a structure by value, not 6184 // basic types. 6185 if (Flags.isByVal()) { 6186 // Note: Size includes alignment padding, so 6187 // struct x { short a; char b; } 6188 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6189 // These are the proper values we need for right-justifying the 6190 // aggregate in a parameter register. 6191 unsigned Size = Flags.getByValSize(); 6192 6193 // An empty aggregate parameter takes up no storage and no 6194 // registers. 6195 if (Size == 0) 6196 continue; 6197 6198 if (IsFastCall) 6199 ComputePtrOff(); 6200 6201 // All aggregates smaller than 8 bytes must be passed right-justified. 6202 if (Size==1 || Size==2 || Size==4) { 6203 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6204 if (GPR_idx != NumGPRs) { 6205 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6206 MachinePointerInfo(), VT); 6207 MemOpChains.push_back(Load.getValue(1)); 6208 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6209 6210 ArgOffset += PtrByteSize; 6211 continue; 6212 } 6213 } 6214 6215 if (GPR_idx == NumGPRs && Size < 8) { 6216 SDValue AddPtr = PtrOff; 6217 if (!isLittleEndian) { 6218 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6219 PtrOff.getValueType()); 6220 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6221 } 6222 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6223 CallSeqStart, 6224 Flags, DAG, dl); 6225 ArgOffset += PtrByteSize; 6226 continue; 6227 } 6228 // Copy the object to parameter save area if it can not be entirely passed 6229 // by registers. 6230 // FIXME: we only need to copy the parts which need to be passed in 6231 // parameter save area. For the parts passed by registers, we don't need 6232 // to copy them to the stack although we need to allocate space for them 6233 // in parameter save area. 6234 if ((NumGPRs - GPR_idx) * PtrByteSize < Size) 6235 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6236 CallSeqStart, 6237 Flags, DAG, dl); 6238 6239 // When a register is available, pass a small aggregate right-justified. 6240 if (Size < 8 && GPR_idx != NumGPRs) { 6241 // The easiest way to get this right-justified in a register 6242 // is to copy the structure into the rightmost portion of a 6243 // local variable slot, then load the whole slot into the 6244 // register. 6245 // FIXME: The memcpy seems to produce pretty awful code for 6246 // small aggregates, particularly for packed ones. 6247 // FIXME: It would be preferable to use the slot in the 6248 // parameter save area instead of a new local variable. 6249 SDValue AddPtr = PtrOff; 6250 if (!isLittleEndian) { 6251 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6252 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6253 } 6254 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6255 CallSeqStart, 6256 Flags, DAG, dl); 6257 6258 // Load the slot into the register. 6259 SDValue Load = 6260 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6261 MemOpChains.push_back(Load.getValue(1)); 6262 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6263 6264 // Done with this argument. 6265 ArgOffset += PtrByteSize; 6266 continue; 6267 } 6268 6269 // For aggregates larger than PtrByteSize, copy the pieces of the 6270 // object that fit into registers from the parameter save area. 6271 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6272 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6273 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6274 if (GPR_idx != NumGPRs) { 6275 SDValue Load = 6276 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6277 MemOpChains.push_back(Load.getValue(1)); 6278 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6279 ArgOffset += PtrByteSize; 6280 } else { 6281 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6282 break; 6283 } 6284 } 6285 continue; 6286 } 6287 6288 switch (Arg.getSimpleValueType().SimpleTy) { 6289 default: llvm_unreachable("Unexpected ValueType for argument!"); 6290 case MVT::i1: 6291 case MVT::i32: 6292 case MVT::i64: 6293 if (Flags.isNest()) { 6294 // The 'nest' parameter, if any, is passed in R11. 6295 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6296 break; 6297 } 6298 6299 // These can be scalar arguments or elements of an integer array type 6300 // passed directly. Clang may use those instead of "byval" aggregate 6301 // types to avoid forcing arguments to memory unnecessarily. 6302 if (GPR_idx != NumGPRs) { 6303 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6304 } else { 6305 if (IsFastCall) 6306 ComputePtrOff(); 6307 6308 assert(HasParameterArea && 6309 "Parameter area must exist to pass an argument in memory."); 6310 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6311 true, CFlags.IsTailCall, false, MemOpChains, 6312 TailCallArguments, dl); 6313 if (IsFastCall) 6314 ArgOffset += PtrByteSize; 6315 } 6316 if (!IsFastCall) 6317 ArgOffset += PtrByteSize; 6318 break; 6319 case MVT::f32: 6320 case MVT::f64: { 6321 // These can be scalar arguments or elements of a float array type 6322 // passed directly. The latter are used to implement ELFv2 homogenous 6323 // float aggregates. 6324 6325 // Named arguments go into FPRs first, and once they overflow, the 6326 // remaining arguments go into GPRs and then the parameter save area. 6327 // Unnamed arguments for vararg functions always go to GPRs and 6328 // then the parameter save area. For now, put all arguments to vararg 6329 // routines always in both locations (FPR *and* GPR or stack slot). 6330 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6331 bool NeededLoad = false; 6332 6333 // First load the argument into the next available FPR. 6334 if (FPR_idx != NumFPRs) 6335 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6336 6337 // Next, load the argument into GPR or stack slot if needed. 6338 if (!NeedGPROrStack) 6339 ; 6340 else if (GPR_idx != NumGPRs && !IsFastCall) { 6341 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6342 // once we support fp <-> gpr moves. 6343 6344 // In the non-vararg case, this can only ever happen in the 6345 // presence of f32 array types, since otherwise we never run 6346 // out of FPRs before running out of GPRs. 6347 SDValue ArgVal; 6348 6349 // Double values are always passed in a single GPR. 6350 if (Arg.getValueType() != MVT::f32) { 6351 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6352 6353 // Non-array float values are extended and passed in a GPR. 6354 } else if (!Flags.isInConsecutiveRegs()) { 6355 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6356 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6357 6358 // If we have an array of floats, we collect every odd element 6359 // together with its predecessor into one GPR. 6360 } else if (ArgOffset % PtrByteSize != 0) { 6361 SDValue Lo, Hi; 6362 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6363 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6364 if (!isLittleEndian) 6365 std::swap(Lo, Hi); 6366 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6367 6368 // The final element, if even, goes into the first half of a GPR. 6369 } else if (Flags.isInConsecutiveRegsLast()) { 6370 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6371 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6372 if (!isLittleEndian) 6373 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6374 DAG.getConstant(32, dl, MVT::i32)); 6375 6376 // Non-final even elements are skipped; they will be handled 6377 // together the with subsequent argument on the next go-around. 6378 } else 6379 ArgVal = SDValue(); 6380 6381 if (ArgVal.getNode()) 6382 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6383 } else { 6384 if (IsFastCall) 6385 ComputePtrOff(); 6386 6387 // Single-precision floating-point values are mapped to the 6388 // second (rightmost) word of the stack doubleword. 6389 if (Arg.getValueType() == MVT::f32 && 6390 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6391 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6392 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6393 } 6394 6395 assert(HasParameterArea && 6396 "Parameter area must exist to pass an argument in memory."); 6397 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6398 true, CFlags.IsTailCall, false, MemOpChains, 6399 TailCallArguments, dl); 6400 6401 NeededLoad = true; 6402 } 6403 // When passing an array of floats, the array occupies consecutive 6404 // space in the argument area; only round up to the next doubleword 6405 // at the end of the array. Otherwise, each float takes 8 bytes. 6406 if (!IsFastCall || NeededLoad) { 6407 ArgOffset += (Arg.getValueType() == MVT::f32 && 6408 Flags.isInConsecutiveRegs()) ? 4 : 8; 6409 if (Flags.isInConsecutiveRegsLast()) 6410 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6411 } 6412 break; 6413 } 6414 case MVT::v4f32: 6415 case MVT::v4i32: 6416 case MVT::v8i16: 6417 case MVT::v16i8: 6418 case MVT::v2f64: 6419 case MVT::v2i64: 6420 case MVT::v1i128: 6421 case MVT::f128: 6422 // These can be scalar arguments or elements of a vector array type 6423 // passed directly. The latter are used to implement ELFv2 homogenous 6424 // vector aggregates. 6425 6426 // For a varargs call, named arguments go into VRs or on the stack as 6427 // usual; unnamed arguments always go to the stack or the corresponding 6428 // GPRs when within range. For now, we always put the value in both 6429 // locations (or even all three). 6430 if (CFlags.IsVarArg) { 6431 assert(HasParameterArea && 6432 "Parameter area must exist if we have a varargs call."); 6433 // We could elide this store in the case where the object fits 6434 // entirely in R registers. Maybe later. 6435 SDValue Store = 6436 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6437 MemOpChains.push_back(Store); 6438 if (VR_idx != NumVRs) { 6439 SDValue Load = 6440 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6441 MemOpChains.push_back(Load.getValue(1)); 6442 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6443 } 6444 ArgOffset += 16; 6445 for (unsigned i=0; i<16; i+=PtrByteSize) { 6446 if (GPR_idx == NumGPRs) 6447 break; 6448 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6449 DAG.getConstant(i, dl, PtrVT)); 6450 SDValue Load = 6451 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6452 MemOpChains.push_back(Load.getValue(1)); 6453 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6454 } 6455 break; 6456 } 6457 6458 // Non-varargs Altivec params go into VRs or on the stack. 6459 if (VR_idx != NumVRs) { 6460 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6461 } else { 6462 if (IsFastCall) 6463 ComputePtrOff(); 6464 6465 assert(HasParameterArea && 6466 "Parameter area must exist to pass an argument in memory."); 6467 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6468 true, CFlags.IsTailCall, true, MemOpChains, 6469 TailCallArguments, dl); 6470 if (IsFastCall) 6471 ArgOffset += 16; 6472 } 6473 6474 if (!IsFastCall) 6475 ArgOffset += 16; 6476 break; 6477 } 6478 } 6479 6480 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6481 "mismatch in size of parameter area"); 6482 (void)NumBytesActuallyUsed; 6483 6484 if (!MemOpChains.empty()) 6485 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6486 6487 // Check if this is an indirect call (MTCTR/BCTRL). 6488 // See prepareDescriptorIndirectCall and buildCallOperands for more 6489 // information about calls through function pointers in the 64-bit SVR4 ABI. 6490 if (CFlags.IsIndirect) { 6491 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6492 // caller in the TOC save area. 6493 if (isTOCSaveRestoreRequired(Subtarget)) { 6494 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6495 // Load r2 into a virtual register and store it to the TOC save area. 6496 setUsesTOCBasePtr(DAG); 6497 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6498 // TOC save area offset. 6499 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6500 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6501 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6502 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6503 MachinePointerInfo::getStack( 6504 DAG.getMachineFunction(), TOCSaveOffset)); 6505 } 6506 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6507 // This does not mean the MTCTR instruction must use R12; it's easier 6508 // to model this as an extra parameter, so do that. 6509 if (isELFv2ABI && !CFlags.IsPatchPoint) 6510 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6511 } 6512 6513 // Build a sequence of copy-to-reg nodes chained together with token chain 6514 // and flag operands which copy the outgoing args into the appropriate regs. 6515 SDValue InFlag; 6516 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6517 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6518 RegsToPass[i].second, InFlag); 6519 InFlag = Chain.getValue(1); 6520 } 6521 6522 if (CFlags.IsTailCall && !IsSibCall) 6523 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6524 TailCallArguments); 6525 6526 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6527 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6528 } 6529 6530 // Returns true when the shadow of a general purpose argument register 6531 // in the parameter save area is aligned to at least 'RequiredAlign'. 6532 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6533 assert(RequiredAlign.value() <= 16 && 6534 "Required alignment greater than stack alignment."); 6535 switch (Reg) { 6536 default: 6537 report_fatal_error("called on invalid register."); 6538 case PPC::R5: 6539 case PPC::R9: 6540 case PPC::X3: 6541 case PPC::X5: 6542 case PPC::X7: 6543 case PPC::X9: 6544 // These registers are 16 byte aligned which is the most strict aligment 6545 // we can support. 6546 return true; 6547 case PPC::R3: 6548 case PPC::R7: 6549 case PPC::X4: 6550 case PPC::X6: 6551 case PPC::X8: 6552 case PPC::X10: 6553 // The shadow of these registers in the PSA is 8 byte aligned. 6554 return RequiredAlign <= 8; 6555 case PPC::R4: 6556 case PPC::R6: 6557 case PPC::R8: 6558 case PPC::R10: 6559 return RequiredAlign <= 4; 6560 } 6561 } 6562 6563 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6564 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6565 CCState &S) { 6566 AIXCCState &State = static_cast<AIXCCState &>(S); 6567 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6568 State.getMachineFunction().getSubtarget()); 6569 const bool IsPPC64 = Subtarget.isPPC64(); 6570 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6571 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6572 6573 if (ValVT == MVT::f128) 6574 report_fatal_error("f128 is unimplemented on AIX."); 6575 6576 if (ArgFlags.isNest()) 6577 report_fatal_error("Nest arguments are unimplemented."); 6578 6579 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6580 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6581 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6582 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6583 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6584 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6585 6586 static const MCPhysReg VR[] = {// Vector registers. 6587 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6588 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6589 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6590 6591 if (ArgFlags.isByVal()) { 6592 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6593 report_fatal_error("Pass-by-value arguments with alignment greater than " 6594 "register width are not supported."); 6595 6596 const unsigned ByValSize = ArgFlags.getByValSize(); 6597 6598 // An empty aggregate parameter takes up no storage and no registers, 6599 // but needs a MemLoc for a stack slot for the formal arguments side. 6600 if (ByValSize == 0) { 6601 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6602 State.getNextStackOffset(), RegVT, 6603 LocInfo)); 6604 return false; 6605 } 6606 6607 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6608 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6609 for (const unsigned E = Offset + StackSize; Offset < E; 6610 Offset += PtrAlign.value()) { 6611 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6612 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6613 else { 6614 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6615 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6616 LocInfo)); 6617 break; 6618 } 6619 } 6620 return false; 6621 } 6622 6623 // Arguments always reserve parameter save area. 6624 switch (ValVT.SimpleTy) { 6625 default: 6626 report_fatal_error("Unhandled value type for argument."); 6627 case MVT::i64: 6628 // i64 arguments should have been split to i32 for PPC32. 6629 assert(IsPPC64 && "PPC32 should have split i64 values."); 6630 LLVM_FALLTHROUGH; 6631 case MVT::i1: 6632 case MVT::i32: { 6633 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6634 // AIX integer arguments are always passed in register width. 6635 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6636 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6637 : CCValAssign::LocInfo::ZExt; 6638 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6639 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6640 else 6641 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6642 6643 return false; 6644 } 6645 case MVT::f32: 6646 case MVT::f64: { 6647 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6648 const unsigned StoreSize = LocVT.getStoreSize(); 6649 // Floats are always 4-byte aligned in the PSA on AIX. 6650 // This includes f64 in 64-bit mode for ABI compatibility. 6651 const unsigned Offset = 6652 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6653 unsigned FReg = State.AllocateReg(FPR); 6654 if (FReg) 6655 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6656 6657 // Reserve and initialize GPRs or initialize the PSA as required. 6658 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6659 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6660 assert(FReg && "An FPR should be available when a GPR is reserved."); 6661 if (State.isVarArg()) { 6662 // Successfully reserved GPRs are only initialized for vararg calls. 6663 // Custom handling is required for: 6664 // f64 in PPC32 needs to be split into 2 GPRs. 6665 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6666 State.addLoc( 6667 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6668 } 6669 } else { 6670 // If there are insufficient GPRs, the PSA needs to be initialized. 6671 // Initialization occurs even if an FPR was initialized for 6672 // compatibility with the AIX XL compiler. The full memory for the 6673 // argument will be initialized even if a prior word is saved in GPR. 6674 // A custom memLoc is used when the argument also passes in FPR so 6675 // that the callee handling can skip over it easily. 6676 State.addLoc( 6677 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6678 LocInfo) 6679 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6680 break; 6681 } 6682 } 6683 6684 return false; 6685 } 6686 case MVT::v4f32: 6687 case MVT::v4i32: 6688 case MVT::v8i16: 6689 case MVT::v16i8: 6690 case MVT::v2i64: 6691 case MVT::v2f64: 6692 case MVT::v1i128: { 6693 const unsigned VecSize = 16; 6694 const Align VecAlign(VecSize); 6695 6696 if (!State.isVarArg()) { 6697 // If there are vector registers remaining we don't consume any stack 6698 // space. 6699 if (unsigned VReg = State.AllocateReg(VR)) { 6700 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6701 return false; 6702 } 6703 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6704 // might be allocated in the portion of the PSA that is shadowed by the 6705 // GPRs. 6706 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6707 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6708 return false; 6709 } 6710 6711 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6712 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6713 6714 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6715 // Burn any underaligned registers and their shadowed stack space until 6716 // we reach the required alignment. 6717 while (NextRegIndex != GPRs.size() && 6718 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6719 // Shadow allocate register and its stack shadow. 6720 unsigned Reg = State.AllocateReg(GPRs); 6721 State.AllocateStack(PtrSize, PtrAlign); 6722 assert(Reg && "Allocating register unexpectedly failed."); 6723 (void)Reg; 6724 NextRegIndex = State.getFirstUnallocated(GPRs); 6725 } 6726 6727 // Vectors that are passed as fixed arguments are handled differently. 6728 // They are passed in VRs if any are available (unlike arguments passed 6729 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6730 // functions) 6731 if (State.isFixed(ValNo)) { 6732 if (unsigned VReg = State.AllocateReg(VR)) { 6733 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6734 // Shadow allocate GPRs and stack space even though we pass in a VR. 6735 for (unsigned I = 0; I != VecSize; I += PtrSize) 6736 State.AllocateReg(GPRs); 6737 State.AllocateStack(VecSize, VecAlign); 6738 return false; 6739 } 6740 // No vector registers remain so pass on the stack. 6741 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6742 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6743 return false; 6744 } 6745 6746 // If all GPRS are consumed then we pass the argument fully on the stack. 6747 if (NextRegIndex == GPRs.size()) { 6748 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6749 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6750 return false; 6751 } 6752 6753 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6754 // half of the argument, and then need to pass the remaining half on the 6755 // stack. 6756 if (GPRs[NextRegIndex] == PPC::R9) { 6757 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6758 State.addLoc( 6759 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6760 6761 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6762 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6763 assert(FirstReg && SecondReg && 6764 "Allocating R9 or R10 unexpectedly failed."); 6765 State.addLoc( 6766 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6767 State.addLoc( 6768 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6769 return false; 6770 } 6771 6772 // We have enough GPRs to fully pass the vector argument, and we have 6773 // already consumed any underaligned registers. Start with the custom 6774 // MemLoc and then the custom RegLocs. 6775 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6776 State.addLoc( 6777 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6778 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6779 const unsigned Reg = State.AllocateReg(GPRs); 6780 assert(Reg && "Failed to allocated register for vararg vector argument"); 6781 State.addLoc( 6782 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6783 } 6784 return false; 6785 } 6786 } 6787 return true; 6788 } 6789 6790 // So far, this function is only used by LowerFormalArguments_AIX() 6791 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6792 bool IsPPC64, 6793 bool HasP8Vector, 6794 bool HasVSX) { 6795 assert((IsPPC64 || SVT != MVT::i64) && 6796 "i64 should have been split for 32-bit codegen."); 6797 6798 switch (SVT) { 6799 default: 6800 report_fatal_error("Unexpected value type for formal argument"); 6801 case MVT::i1: 6802 case MVT::i32: 6803 case MVT::i64: 6804 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6805 case MVT::f32: 6806 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass; 6807 case MVT::f64: 6808 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass; 6809 case MVT::v4f32: 6810 case MVT::v4i32: 6811 case MVT::v8i16: 6812 case MVT::v16i8: 6813 case MVT::v2i64: 6814 case MVT::v2f64: 6815 case MVT::v1i128: 6816 return &PPC::VRRCRegClass; 6817 } 6818 } 6819 6820 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6821 SelectionDAG &DAG, SDValue ArgValue, 6822 MVT LocVT, const SDLoc &dl) { 6823 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6824 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6825 6826 if (Flags.isSExt()) 6827 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6828 DAG.getValueType(ValVT)); 6829 else if (Flags.isZExt()) 6830 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6831 DAG.getValueType(ValVT)); 6832 6833 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6834 } 6835 6836 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6837 const unsigned LASize = FL->getLinkageSize(); 6838 6839 if (PPC::GPRCRegClass.contains(Reg)) { 6840 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6841 "Reg must be a valid argument register!"); 6842 return LASize + 4 * (Reg - PPC::R3); 6843 } 6844 6845 if (PPC::G8RCRegClass.contains(Reg)) { 6846 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6847 "Reg must be a valid argument register!"); 6848 return LASize + 8 * (Reg - PPC::X3); 6849 } 6850 6851 llvm_unreachable("Only general purpose registers expected."); 6852 } 6853 6854 // AIX ABI Stack Frame Layout: 6855 // 6856 // Low Memory +--------------------------------------------+ 6857 // SP +---> | Back chain | ---+ 6858 // | +--------------------------------------------+ | 6859 // | | Saved Condition Register | | 6860 // | +--------------------------------------------+ | 6861 // | | Saved Linkage Register | | 6862 // | +--------------------------------------------+ | Linkage Area 6863 // | | Reserved for compilers | | 6864 // | +--------------------------------------------+ | 6865 // | | Reserved for binders | | 6866 // | +--------------------------------------------+ | 6867 // | | Saved TOC pointer | ---+ 6868 // | +--------------------------------------------+ 6869 // | | Parameter save area | 6870 // | +--------------------------------------------+ 6871 // | | Alloca space | 6872 // | +--------------------------------------------+ 6873 // | | Local variable space | 6874 // | +--------------------------------------------+ 6875 // | | Float/int conversion temporary | 6876 // | +--------------------------------------------+ 6877 // | | Save area for AltiVec registers | 6878 // | +--------------------------------------------+ 6879 // | | AltiVec alignment padding | 6880 // | +--------------------------------------------+ 6881 // | | Save area for VRSAVE register | 6882 // | +--------------------------------------------+ 6883 // | | Save area for General Purpose registers | 6884 // | +--------------------------------------------+ 6885 // | | Save area for Floating Point registers | 6886 // | +--------------------------------------------+ 6887 // +---- | Back chain | 6888 // High Memory +--------------------------------------------+ 6889 // 6890 // Specifications: 6891 // AIX 7.2 Assembler Language Reference 6892 // Subroutine linkage convention 6893 6894 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6895 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6896 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6897 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6898 6899 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6900 CallConv == CallingConv::Fast) && 6901 "Unexpected calling convention!"); 6902 6903 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6904 report_fatal_error("Tail call support is unimplemented on AIX."); 6905 6906 if (useSoftFloat()) 6907 report_fatal_error("Soft float support is unimplemented on AIX."); 6908 6909 const PPCSubtarget &Subtarget = 6910 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6911 6912 const bool IsPPC64 = Subtarget.isPPC64(); 6913 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6914 6915 // Assign locations to all of the incoming arguments. 6916 SmallVector<CCValAssign, 16> ArgLocs; 6917 MachineFunction &MF = DAG.getMachineFunction(); 6918 MachineFrameInfo &MFI = MF.getFrameInfo(); 6919 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6920 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6921 6922 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6923 // Reserve space for the linkage area on the stack. 6924 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6925 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6926 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6927 6928 SmallVector<SDValue, 8> MemOps; 6929 6930 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6931 CCValAssign &VA = ArgLocs[I++]; 6932 MVT LocVT = VA.getLocVT(); 6933 MVT ValVT = VA.getValVT(); 6934 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6935 // For compatibility with the AIX XL compiler, the float args in the 6936 // parameter save area are initialized even if the argument is available 6937 // in register. The caller is required to initialize both the register 6938 // and memory, however, the callee can choose to expect it in either. 6939 // The memloc is dismissed here because the argument is retrieved from 6940 // the register. 6941 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6942 continue; 6943 6944 auto HandleMemLoc = [&]() { 6945 const unsigned LocSize = LocVT.getStoreSize(); 6946 const unsigned ValSize = ValVT.getStoreSize(); 6947 assert((ValSize <= LocSize) && 6948 "Object size is larger than size of MemLoc"); 6949 int CurArgOffset = VA.getLocMemOffset(); 6950 // Objects are right-justified because AIX is big-endian. 6951 if (LocSize > ValSize) 6952 CurArgOffset += LocSize - ValSize; 6953 // Potential tail calls could cause overwriting of argument stack slots. 6954 const bool IsImmutable = 6955 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6956 (CallConv == CallingConv::Fast)); 6957 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6958 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6959 SDValue ArgValue = 6960 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6961 InVals.push_back(ArgValue); 6962 }; 6963 6964 // Vector arguments to VaArg functions are passed both on the stack, and 6965 // in any available GPRs. Load the value from the stack and add the GPRs 6966 // as live ins. 6967 if (VA.isMemLoc() && VA.needsCustom()) { 6968 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 6969 assert(isVarArg && "Only use custom memloc for vararg."); 6970 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 6971 // matching custom RegLocs. 6972 const unsigned OriginalValNo = VA.getValNo(); 6973 (void)OriginalValNo; 6974 6975 auto HandleCustomVecRegLoc = [&]() { 6976 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 6977 "Missing custom RegLoc."); 6978 VA = ArgLocs[I++]; 6979 assert(VA.getValVT().isVector() && 6980 "Unexpected Val type for custom RegLoc."); 6981 assert(VA.getValNo() == OriginalValNo && 6982 "ValNo mismatch between custom MemLoc and RegLoc."); 6983 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 6984 MF.addLiveIn(VA.getLocReg(), 6985 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 6986 Subtarget.hasVSX())); 6987 }; 6988 6989 HandleMemLoc(); 6990 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 6991 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 6992 // R10. 6993 HandleCustomVecRegLoc(); 6994 HandleCustomVecRegLoc(); 6995 6996 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 6997 // we passed the vector in R5, R6, R7 and R8. 6998 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 6999 assert(!IsPPC64 && 7000 "Only 2 custom RegLocs expected for 64-bit codegen."); 7001 HandleCustomVecRegLoc(); 7002 HandleCustomVecRegLoc(); 7003 } 7004 7005 continue; 7006 } 7007 7008 if (VA.isRegLoc()) { 7009 if (VA.getValVT().isScalarInteger()) 7010 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7011 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) { 7012 switch (VA.getValVT().SimpleTy) { 7013 default: 7014 report_fatal_error("Unhandled value type for argument."); 7015 case MVT::f32: 7016 FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint); 7017 break; 7018 case MVT::f64: 7019 FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint); 7020 break; 7021 } 7022 } else if (VA.getValVT().isVector()) { 7023 switch (VA.getValVT().SimpleTy) { 7024 default: 7025 report_fatal_error("Unhandled value type for argument."); 7026 case MVT::v16i8: 7027 FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar); 7028 break; 7029 case MVT::v8i16: 7030 FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort); 7031 break; 7032 case MVT::v4i32: 7033 case MVT::v2i64: 7034 case MVT::v1i128: 7035 FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt); 7036 break; 7037 case MVT::v4f32: 7038 case MVT::v2f64: 7039 FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat); 7040 break; 7041 } 7042 } 7043 } 7044 7045 if (Flags.isByVal() && VA.isMemLoc()) { 7046 const unsigned Size = 7047 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7048 PtrByteSize); 7049 const int FI = MF.getFrameInfo().CreateFixedObject( 7050 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7051 /* IsAliased */ true); 7052 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7053 InVals.push_back(FIN); 7054 7055 continue; 7056 } 7057 7058 if (Flags.isByVal()) { 7059 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7060 7061 const MCPhysReg ArgReg = VA.getLocReg(); 7062 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7063 7064 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7065 report_fatal_error("Over aligned byvals not supported yet."); 7066 7067 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7068 const int FI = MF.getFrameInfo().CreateFixedObject( 7069 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7070 /* IsAliased */ true); 7071 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7072 InVals.push_back(FIN); 7073 7074 // Add live ins for all the RegLocs for the same ByVal. 7075 const TargetRegisterClass *RegClass = 7076 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7077 7078 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7079 unsigned Offset) { 7080 const Register VReg = MF.addLiveIn(PhysReg, RegClass); 7081 // Since the callers side has left justified the aggregate in the 7082 // register, we can simply store the entire register into the stack 7083 // slot. 7084 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7085 // The store to the fixedstack object is needed becuase accessing a 7086 // field of the ByVal will use a gep and load. Ideally we will optimize 7087 // to extracting the value from the register directly, and elide the 7088 // stores when the arguments address is not taken, but that will need to 7089 // be future work. 7090 SDValue Store = DAG.getStore( 7091 CopyFrom.getValue(1), dl, CopyFrom, 7092 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7093 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7094 7095 MemOps.push_back(Store); 7096 }; 7097 7098 unsigned Offset = 0; 7099 HandleRegLoc(VA.getLocReg(), Offset); 7100 Offset += PtrByteSize; 7101 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7102 Offset += PtrByteSize) { 7103 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7104 "RegLocs should be for ByVal argument."); 7105 7106 const CCValAssign RL = ArgLocs[I++]; 7107 HandleRegLoc(RL.getLocReg(), Offset); 7108 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7109 } 7110 7111 if (Offset != StackSize) { 7112 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7113 "Expected MemLoc for remaining bytes."); 7114 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7115 // Consume the MemLoc.The InVal has already been emitted, so nothing 7116 // more needs to be done. 7117 ++I; 7118 } 7119 7120 continue; 7121 } 7122 7123 if (VA.isRegLoc() && !VA.needsCustom()) { 7124 MVT::SimpleValueType SVT = ValVT.SimpleTy; 7125 Register VReg = 7126 MF.addLiveIn(VA.getLocReg(), 7127 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7128 Subtarget.hasVSX())); 7129 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7130 if (ValVT.isScalarInteger() && 7131 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7132 ArgValue = 7133 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7134 } 7135 InVals.push_back(ArgValue); 7136 continue; 7137 } 7138 if (VA.isMemLoc()) { 7139 HandleMemLoc(); 7140 continue; 7141 } 7142 } 7143 7144 // On AIX a minimum of 8 words is saved to the parameter save area. 7145 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7146 // Area that is at least reserved in the caller of this function. 7147 unsigned CallerReservedArea = 7148 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7149 7150 // Set the size that is at least reserved in caller of this function. Tail 7151 // call optimized function's reserved stack space needs to be aligned so 7152 // that taking the difference between two stack areas will result in an 7153 // aligned stack. 7154 CallerReservedArea = 7155 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7156 FuncInfo->setMinReservedArea(CallerReservedArea); 7157 7158 if (isVarArg) { 7159 FuncInfo->setVarArgsFrameIndex( 7160 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7161 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7162 7163 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7164 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7165 7166 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7167 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7168 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7169 7170 // The fixed integer arguments of a variadic function are stored to the 7171 // VarArgsFrameIndex on the stack so that they may be loaded by 7172 // dereferencing the result of va_next. 7173 for (unsigned GPRIndex = 7174 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7175 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7176 7177 const Register VReg = 7178 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7179 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7180 7181 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7182 SDValue Store = 7183 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7184 MemOps.push_back(Store); 7185 // Increment the address for the next argument to store. 7186 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7187 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7188 } 7189 } 7190 7191 if (!MemOps.empty()) 7192 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7193 7194 return Chain; 7195 } 7196 7197 SDValue PPCTargetLowering::LowerCall_AIX( 7198 SDValue Chain, SDValue Callee, CallFlags CFlags, 7199 const SmallVectorImpl<ISD::OutputArg> &Outs, 7200 const SmallVectorImpl<SDValue> &OutVals, 7201 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7202 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7203 const CallBase *CB) const { 7204 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7205 // AIX ABI stack frame layout. 7206 7207 assert((CFlags.CallConv == CallingConv::C || 7208 CFlags.CallConv == CallingConv::Cold || 7209 CFlags.CallConv == CallingConv::Fast) && 7210 "Unexpected calling convention!"); 7211 7212 if (CFlags.IsPatchPoint) 7213 report_fatal_error("This call type is unimplemented on AIX."); 7214 7215 const PPCSubtarget& Subtarget = 7216 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7217 7218 MachineFunction &MF = DAG.getMachineFunction(); 7219 SmallVector<CCValAssign, 16> ArgLocs; 7220 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7221 *DAG.getContext()); 7222 7223 // Reserve space for the linkage save area (LSA) on the stack. 7224 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7225 // [SP][CR][LR][2 x reserved][TOC]. 7226 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7227 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7228 const bool IsPPC64 = Subtarget.isPPC64(); 7229 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7230 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7231 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7232 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7233 7234 // The prolog code of the callee may store up to 8 GPR argument registers to 7235 // the stack, allowing va_start to index over them in memory if the callee 7236 // is variadic. 7237 // Because we cannot tell if this is needed on the caller side, we have to 7238 // conservatively assume that it is needed. As such, make sure we have at 7239 // least enough stack space for the caller to store the 8 GPRs. 7240 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7241 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7242 CCInfo.getNextStackOffset()); 7243 7244 // Adjust the stack pointer for the new arguments... 7245 // These operations are automatically eliminated by the prolog/epilog pass. 7246 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7247 SDValue CallSeqStart = Chain; 7248 7249 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7250 SmallVector<SDValue, 8> MemOpChains; 7251 7252 // Set up a copy of the stack pointer for loading and storing any 7253 // arguments that may not fit in the registers available for argument 7254 // passing. 7255 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7256 : DAG.getRegister(PPC::R1, MVT::i32); 7257 7258 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7259 const unsigned ValNo = ArgLocs[I].getValNo(); 7260 SDValue Arg = OutVals[ValNo]; 7261 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7262 7263 if (Flags.isByVal()) { 7264 const unsigned ByValSize = Flags.getByValSize(); 7265 7266 // Nothing to do for zero-sized ByVals on the caller side. 7267 if (!ByValSize) { 7268 ++I; 7269 continue; 7270 } 7271 7272 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7273 return DAG.getExtLoad( 7274 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7275 (LoadOffset != 0) 7276 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7277 : Arg, 7278 MachinePointerInfo(), VT); 7279 }; 7280 7281 unsigned LoadOffset = 0; 7282 7283 // Initialize registers, which are fully occupied by the by-val argument. 7284 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7285 SDValue Load = GetLoad(PtrVT, LoadOffset); 7286 MemOpChains.push_back(Load.getValue(1)); 7287 LoadOffset += PtrByteSize; 7288 const CCValAssign &ByValVA = ArgLocs[I++]; 7289 assert(ByValVA.getValNo() == ValNo && 7290 "Unexpected location for pass-by-value argument."); 7291 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7292 } 7293 7294 if (LoadOffset == ByValSize) 7295 continue; 7296 7297 // There must be one more loc to handle the remainder. 7298 assert(ArgLocs[I].getValNo() == ValNo && 7299 "Expected additional location for by-value argument."); 7300 7301 if (ArgLocs[I].isMemLoc()) { 7302 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7303 const CCValAssign &ByValVA = ArgLocs[I++]; 7304 ISD::ArgFlagsTy MemcpyFlags = Flags; 7305 // Only memcpy the bytes that don't pass in register. 7306 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7307 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7308 (LoadOffset != 0) 7309 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7310 : Arg, 7311 DAG.getObjectPtrOffset(dl, StackPtr, 7312 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7313 CallSeqStart, MemcpyFlags, DAG, dl); 7314 continue; 7315 } 7316 7317 // Initialize the final register residue. 7318 // Any residue that occupies the final by-val arg register must be 7319 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7320 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7321 // 2 and 1 byte loads. 7322 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7323 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7324 "Unexpected register residue for by-value argument."); 7325 SDValue ResidueVal; 7326 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7327 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7328 const MVT VT = 7329 N == 1 ? MVT::i8 7330 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7331 SDValue Load = GetLoad(VT, LoadOffset); 7332 MemOpChains.push_back(Load.getValue(1)); 7333 LoadOffset += N; 7334 Bytes += N; 7335 7336 // By-val arguments are passed left-justfied in register. 7337 // Every load here needs to be shifted, otherwise a full register load 7338 // should have been used. 7339 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7340 "Unexpected load emitted during handling of pass-by-value " 7341 "argument."); 7342 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7343 EVT ShiftAmountTy = 7344 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7345 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7346 SDValue ShiftedLoad = 7347 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7348 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7349 ShiftedLoad) 7350 : ShiftedLoad; 7351 } 7352 7353 const CCValAssign &ByValVA = ArgLocs[I++]; 7354 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7355 continue; 7356 } 7357 7358 CCValAssign &VA = ArgLocs[I++]; 7359 const MVT LocVT = VA.getLocVT(); 7360 const MVT ValVT = VA.getValVT(); 7361 7362 switch (VA.getLocInfo()) { 7363 default: 7364 report_fatal_error("Unexpected argument extension type."); 7365 case CCValAssign::Full: 7366 break; 7367 case CCValAssign::ZExt: 7368 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7369 break; 7370 case CCValAssign::SExt: 7371 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7372 break; 7373 } 7374 7375 if (VA.isRegLoc() && !VA.needsCustom()) { 7376 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7377 continue; 7378 } 7379 7380 // Vector arguments passed to VarArg functions need custom handling when 7381 // they are passed (at least partially) in GPRs. 7382 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7383 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7384 // Store value to its stack slot. 7385 SDValue PtrOff = 7386 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7387 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7388 SDValue Store = 7389 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7390 MemOpChains.push_back(Store); 7391 const unsigned OriginalValNo = VA.getValNo(); 7392 // Then load the GPRs from the stack 7393 unsigned LoadOffset = 0; 7394 auto HandleCustomVecRegLoc = [&]() { 7395 assert(I != E && "Unexpected end of CCvalAssigns."); 7396 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7397 "Expected custom RegLoc."); 7398 CCValAssign RegVA = ArgLocs[I++]; 7399 assert(RegVA.getValNo() == OriginalValNo && 7400 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7401 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7402 DAG.getConstant(LoadOffset, dl, PtrVT)); 7403 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7404 MemOpChains.push_back(Load.getValue(1)); 7405 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7406 LoadOffset += PtrByteSize; 7407 }; 7408 7409 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7410 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7411 // R10. 7412 HandleCustomVecRegLoc(); 7413 HandleCustomVecRegLoc(); 7414 7415 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7416 ArgLocs[I].getValNo() == OriginalValNo) { 7417 assert(!IsPPC64 && 7418 "Only 2 custom RegLocs expected for 64-bit codegen."); 7419 HandleCustomVecRegLoc(); 7420 HandleCustomVecRegLoc(); 7421 } 7422 7423 continue; 7424 } 7425 7426 if (VA.isMemLoc()) { 7427 SDValue PtrOff = 7428 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7429 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7430 MemOpChains.push_back( 7431 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7432 7433 continue; 7434 } 7435 7436 if (!ValVT.isFloatingPoint()) 7437 report_fatal_error( 7438 "Unexpected register handling for calling convention."); 7439 7440 // Custom handling is used for GPR initializations for vararg float 7441 // arguments. 7442 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7443 LocVT.isInteger() && 7444 "Custom register handling only expected for VarArg."); 7445 7446 SDValue ArgAsInt = 7447 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7448 7449 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7450 // f32 in 32-bit GPR 7451 // f64 in 64-bit GPR 7452 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7453 else if (Arg.getValueType().getFixedSizeInBits() < 7454 LocVT.getFixedSizeInBits()) 7455 // f32 in 64-bit GPR. 7456 RegsToPass.push_back(std::make_pair( 7457 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7458 else { 7459 // f64 in two 32-bit GPRs 7460 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7461 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7462 "Unexpected custom register for argument!"); 7463 CCValAssign &GPR1 = VA; 7464 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7465 DAG.getConstant(32, dl, MVT::i8)); 7466 RegsToPass.push_back(std::make_pair( 7467 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7468 7469 if (I != E) { 7470 // If only 1 GPR was available, there will only be one custom GPR and 7471 // the argument will also pass in memory. 7472 CCValAssign &PeekArg = ArgLocs[I]; 7473 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7474 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7475 CCValAssign &GPR2 = ArgLocs[I++]; 7476 RegsToPass.push_back(std::make_pair( 7477 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7478 } 7479 } 7480 } 7481 } 7482 7483 if (!MemOpChains.empty()) 7484 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7485 7486 // For indirect calls, we need to save the TOC base to the stack for 7487 // restoration after the call. 7488 if (CFlags.IsIndirect) { 7489 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7490 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7491 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7492 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7493 const unsigned TOCSaveOffset = 7494 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7495 7496 setUsesTOCBasePtr(DAG); 7497 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7498 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7499 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7500 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7501 Chain = DAG.getStore( 7502 Val.getValue(1), dl, Val, AddPtr, 7503 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7504 } 7505 7506 // Build a sequence of copy-to-reg nodes chained together with token chain 7507 // and flag operands which copy the outgoing args into the appropriate regs. 7508 SDValue InFlag; 7509 for (auto Reg : RegsToPass) { 7510 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7511 InFlag = Chain.getValue(1); 7512 } 7513 7514 const int SPDiff = 0; 7515 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7516 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7517 } 7518 7519 bool 7520 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7521 MachineFunction &MF, bool isVarArg, 7522 const SmallVectorImpl<ISD::OutputArg> &Outs, 7523 LLVMContext &Context) const { 7524 SmallVector<CCValAssign, 16> RVLocs; 7525 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7526 return CCInfo.CheckReturn( 7527 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7528 ? RetCC_PPC_Cold 7529 : RetCC_PPC); 7530 } 7531 7532 SDValue 7533 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7534 bool isVarArg, 7535 const SmallVectorImpl<ISD::OutputArg> &Outs, 7536 const SmallVectorImpl<SDValue> &OutVals, 7537 const SDLoc &dl, SelectionDAG &DAG) const { 7538 SmallVector<CCValAssign, 16> RVLocs; 7539 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7540 *DAG.getContext()); 7541 CCInfo.AnalyzeReturn(Outs, 7542 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7543 ? RetCC_PPC_Cold 7544 : RetCC_PPC); 7545 7546 SDValue Flag; 7547 SmallVector<SDValue, 4> RetOps(1, Chain); 7548 7549 // Copy the result values into the output registers. 7550 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7551 CCValAssign &VA = RVLocs[i]; 7552 assert(VA.isRegLoc() && "Can only return in registers!"); 7553 7554 SDValue Arg = OutVals[RealResIdx]; 7555 7556 switch (VA.getLocInfo()) { 7557 default: llvm_unreachable("Unknown loc info!"); 7558 case CCValAssign::Full: break; 7559 case CCValAssign::AExt: 7560 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7561 break; 7562 case CCValAssign::ZExt: 7563 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7564 break; 7565 case CCValAssign::SExt: 7566 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7567 break; 7568 } 7569 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7570 bool isLittleEndian = Subtarget.isLittleEndian(); 7571 // Legalize ret f64 -> ret 2 x i32. 7572 SDValue SVal = 7573 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7574 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7575 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7576 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7577 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7578 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7579 Flag = Chain.getValue(1); 7580 VA = RVLocs[++i]; // skip ahead to next loc 7581 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7582 } else 7583 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7584 Flag = Chain.getValue(1); 7585 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7586 } 7587 7588 RetOps[0] = Chain; // Update chain. 7589 7590 // Add the flag if we have it. 7591 if (Flag.getNode()) 7592 RetOps.push_back(Flag); 7593 7594 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7595 } 7596 7597 SDValue 7598 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7599 SelectionDAG &DAG) const { 7600 SDLoc dl(Op); 7601 7602 // Get the correct type for integers. 7603 EVT IntVT = Op.getValueType(); 7604 7605 // Get the inputs. 7606 SDValue Chain = Op.getOperand(0); 7607 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7608 // Build a DYNAREAOFFSET node. 7609 SDValue Ops[2] = {Chain, FPSIdx}; 7610 SDVTList VTs = DAG.getVTList(IntVT); 7611 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7612 } 7613 7614 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7615 SelectionDAG &DAG) const { 7616 // When we pop the dynamic allocation we need to restore the SP link. 7617 SDLoc dl(Op); 7618 7619 // Get the correct type for pointers. 7620 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7621 7622 // Construct the stack pointer operand. 7623 bool isPPC64 = Subtarget.isPPC64(); 7624 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7625 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7626 7627 // Get the operands for the STACKRESTORE. 7628 SDValue Chain = Op.getOperand(0); 7629 SDValue SaveSP = Op.getOperand(1); 7630 7631 // Load the old link SP. 7632 SDValue LoadLinkSP = 7633 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7634 7635 // Restore the stack pointer. 7636 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7637 7638 // Store the old link SP. 7639 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7640 } 7641 7642 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7643 MachineFunction &MF = DAG.getMachineFunction(); 7644 bool isPPC64 = Subtarget.isPPC64(); 7645 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7646 7647 // Get current frame pointer save index. The users of this index will be 7648 // primarily DYNALLOC instructions. 7649 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7650 int RASI = FI->getReturnAddrSaveIndex(); 7651 7652 // If the frame pointer save index hasn't been defined yet. 7653 if (!RASI) { 7654 // Find out what the fix offset of the frame pointer save area. 7655 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7656 // Allocate the frame index for frame pointer save area. 7657 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7658 // Save the result. 7659 FI->setReturnAddrSaveIndex(RASI); 7660 } 7661 return DAG.getFrameIndex(RASI, PtrVT); 7662 } 7663 7664 SDValue 7665 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7666 MachineFunction &MF = DAG.getMachineFunction(); 7667 bool isPPC64 = Subtarget.isPPC64(); 7668 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7669 7670 // Get current frame pointer save index. The users of this index will be 7671 // primarily DYNALLOC instructions. 7672 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7673 int FPSI = FI->getFramePointerSaveIndex(); 7674 7675 // If the frame pointer save index hasn't been defined yet. 7676 if (!FPSI) { 7677 // Find out what the fix offset of the frame pointer save area. 7678 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7679 // Allocate the frame index for frame pointer save area. 7680 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7681 // Save the result. 7682 FI->setFramePointerSaveIndex(FPSI); 7683 } 7684 return DAG.getFrameIndex(FPSI, PtrVT); 7685 } 7686 7687 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7688 SelectionDAG &DAG) const { 7689 MachineFunction &MF = DAG.getMachineFunction(); 7690 // Get the inputs. 7691 SDValue Chain = Op.getOperand(0); 7692 SDValue Size = Op.getOperand(1); 7693 SDLoc dl(Op); 7694 7695 // Get the correct type for pointers. 7696 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7697 // Negate the size. 7698 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7699 DAG.getConstant(0, dl, PtrVT), Size); 7700 // Construct a node for the frame pointer save index. 7701 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7702 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7703 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7704 if (hasInlineStackProbe(MF)) 7705 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7706 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7707 } 7708 7709 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7710 SelectionDAG &DAG) const { 7711 MachineFunction &MF = DAG.getMachineFunction(); 7712 7713 bool isPPC64 = Subtarget.isPPC64(); 7714 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7715 7716 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7717 return DAG.getFrameIndex(FI, PtrVT); 7718 } 7719 7720 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7721 SelectionDAG &DAG) const { 7722 SDLoc DL(Op); 7723 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7724 DAG.getVTList(MVT::i32, MVT::Other), 7725 Op.getOperand(0), Op.getOperand(1)); 7726 } 7727 7728 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7729 SelectionDAG &DAG) const { 7730 SDLoc DL(Op); 7731 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7732 Op.getOperand(0), Op.getOperand(1)); 7733 } 7734 7735 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7736 if (Op.getValueType().isVector()) 7737 return LowerVectorLoad(Op, DAG); 7738 7739 assert(Op.getValueType() == MVT::i1 && 7740 "Custom lowering only for i1 loads"); 7741 7742 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7743 7744 SDLoc dl(Op); 7745 LoadSDNode *LD = cast<LoadSDNode>(Op); 7746 7747 SDValue Chain = LD->getChain(); 7748 SDValue BasePtr = LD->getBasePtr(); 7749 MachineMemOperand *MMO = LD->getMemOperand(); 7750 7751 SDValue NewLD = 7752 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7753 BasePtr, MVT::i8, MMO); 7754 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7755 7756 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7757 return DAG.getMergeValues(Ops, dl); 7758 } 7759 7760 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7761 if (Op.getOperand(1).getValueType().isVector()) 7762 return LowerVectorStore(Op, DAG); 7763 7764 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7765 "Custom lowering only for i1 stores"); 7766 7767 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7768 7769 SDLoc dl(Op); 7770 StoreSDNode *ST = cast<StoreSDNode>(Op); 7771 7772 SDValue Chain = ST->getChain(); 7773 SDValue BasePtr = ST->getBasePtr(); 7774 SDValue Value = ST->getValue(); 7775 MachineMemOperand *MMO = ST->getMemOperand(); 7776 7777 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7778 Value); 7779 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7780 } 7781 7782 // FIXME: Remove this once the ANDI glue bug is fixed: 7783 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7784 assert(Op.getValueType() == MVT::i1 && 7785 "Custom lowering only for i1 results"); 7786 7787 SDLoc DL(Op); 7788 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7789 } 7790 7791 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7792 SelectionDAG &DAG) const { 7793 7794 // Implements a vector truncate that fits in a vector register as a shuffle. 7795 // We want to legalize vector truncates down to where the source fits in 7796 // a vector register (and target is therefore smaller than vector register 7797 // size). At that point legalization will try to custom lower the sub-legal 7798 // result and get here - where we can contain the truncate as a single target 7799 // operation. 7800 7801 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7802 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7803 // 7804 // We will implement it for big-endian ordering as this (where x denotes 7805 // undefined): 7806 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7807 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7808 // 7809 // The same operation in little-endian ordering will be: 7810 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7811 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7812 7813 EVT TrgVT = Op.getValueType(); 7814 assert(TrgVT.isVector() && "Vector type expected."); 7815 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7816 EVT EltVT = TrgVT.getVectorElementType(); 7817 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7818 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7819 !isPowerOf2_32(EltVT.getSizeInBits())) 7820 return SDValue(); 7821 7822 SDValue N1 = Op.getOperand(0); 7823 EVT SrcVT = N1.getValueType(); 7824 unsigned SrcSize = SrcVT.getSizeInBits(); 7825 if (SrcSize > 256 || 7826 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7827 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7828 return SDValue(); 7829 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7830 return SDValue(); 7831 7832 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7833 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7834 7835 SDLoc DL(Op); 7836 SDValue Op1, Op2; 7837 if (SrcSize == 256) { 7838 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7839 EVT SplitVT = 7840 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7841 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7842 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7843 DAG.getConstant(0, DL, VecIdxTy)); 7844 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7845 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7846 } 7847 else { 7848 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7849 Op2 = DAG.getUNDEF(WideVT); 7850 } 7851 7852 // First list the elements we want to keep. 7853 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7854 SmallVector<int, 16> ShuffV; 7855 if (Subtarget.isLittleEndian()) 7856 for (unsigned i = 0; i < TrgNumElts; ++i) 7857 ShuffV.push_back(i * SizeMult); 7858 else 7859 for (unsigned i = 1; i <= TrgNumElts; ++i) 7860 ShuffV.push_back(i * SizeMult - 1); 7861 7862 // Populate the remaining elements with undefs. 7863 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7864 // ShuffV.push_back(i + WideNumElts); 7865 ShuffV.push_back(WideNumElts + 1); 7866 7867 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7868 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7869 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7870 } 7871 7872 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7873 /// possible. 7874 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7875 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7876 EVT ResVT = Op.getValueType(); 7877 EVT CmpVT = Op.getOperand(0).getValueType(); 7878 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7879 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7880 SDLoc dl(Op); 7881 7882 // Without power9-vector, we don't have native instruction for f128 comparison. 7883 // Following transformation to libcall is needed for setcc: 7884 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7885 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7886 SDValue Z = DAG.getSetCC( 7887 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7888 LHS, RHS, CC); 7889 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7890 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7891 } 7892 7893 // Not FP, or using SPE? Not a fsel. 7894 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7895 Subtarget.hasSPE()) 7896 return Op; 7897 7898 SDNodeFlags Flags = Op.getNode()->getFlags(); 7899 7900 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7901 // presence of infinities. 7902 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7903 switch (CC) { 7904 default: 7905 break; 7906 case ISD::SETOGT: 7907 case ISD::SETGT: 7908 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7909 case ISD::SETOLT: 7910 case ISD::SETLT: 7911 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7912 } 7913 } 7914 7915 // We might be able to do better than this under some circumstances, but in 7916 // general, fsel-based lowering of select is a finite-math-only optimization. 7917 // For more information, see section F.3 of the 2.06 ISA specification. 7918 // With ISA 3.0 7919 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7920 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7921 return Op; 7922 7923 // If the RHS of the comparison is a 0.0, we don't need to do the 7924 // subtraction at all. 7925 SDValue Sel1; 7926 if (isFloatingPointZero(RHS)) 7927 switch (CC) { 7928 default: break; // SETUO etc aren't handled by fsel. 7929 case ISD::SETNE: 7930 std::swap(TV, FV); 7931 LLVM_FALLTHROUGH; 7932 case ISD::SETEQ: 7933 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7934 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7935 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7936 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7937 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7938 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7939 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7940 case ISD::SETULT: 7941 case ISD::SETLT: 7942 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7943 LLVM_FALLTHROUGH; 7944 case ISD::SETOGE: 7945 case ISD::SETGE: 7946 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7947 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7948 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7949 case ISD::SETUGT: 7950 case ISD::SETGT: 7951 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7952 LLVM_FALLTHROUGH; 7953 case ISD::SETOLE: 7954 case ISD::SETLE: 7955 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7956 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7957 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7958 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7959 } 7960 7961 SDValue Cmp; 7962 switch (CC) { 7963 default: break; // SETUO etc aren't handled by fsel. 7964 case ISD::SETNE: 7965 std::swap(TV, FV); 7966 LLVM_FALLTHROUGH; 7967 case ISD::SETEQ: 7968 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7969 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7970 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7971 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7972 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7973 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7974 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7975 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7976 case ISD::SETULT: 7977 case ISD::SETLT: 7978 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7979 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7980 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7981 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7982 case ISD::SETOGE: 7983 case ISD::SETGE: 7984 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7985 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7986 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7987 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7988 case ISD::SETUGT: 7989 case ISD::SETGT: 7990 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7991 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7992 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7993 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7994 case ISD::SETOLE: 7995 case ISD::SETLE: 7996 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7997 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7998 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7999 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8000 } 8001 return Op; 8002 } 8003 8004 static unsigned getPPCStrictOpcode(unsigned Opc) { 8005 switch (Opc) { 8006 default: 8007 llvm_unreachable("No strict version of this opcode!"); 8008 case PPCISD::FCTIDZ: 8009 return PPCISD::STRICT_FCTIDZ; 8010 case PPCISD::FCTIWZ: 8011 return PPCISD::STRICT_FCTIWZ; 8012 case PPCISD::FCTIDUZ: 8013 return PPCISD::STRICT_FCTIDUZ; 8014 case PPCISD::FCTIWUZ: 8015 return PPCISD::STRICT_FCTIWUZ; 8016 case PPCISD::FCFID: 8017 return PPCISD::STRICT_FCFID; 8018 case PPCISD::FCFIDU: 8019 return PPCISD::STRICT_FCFIDU; 8020 case PPCISD::FCFIDS: 8021 return PPCISD::STRICT_FCFIDS; 8022 case PPCISD::FCFIDUS: 8023 return PPCISD::STRICT_FCFIDUS; 8024 } 8025 } 8026 8027 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8028 const PPCSubtarget &Subtarget) { 8029 SDLoc dl(Op); 8030 bool IsStrict = Op->isStrictFPOpcode(); 8031 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8032 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8033 8034 // TODO: Any other flags to propagate? 8035 SDNodeFlags Flags; 8036 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8037 8038 // For strict nodes, source is the second operand. 8039 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8040 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8041 assert(Src.getValueType().isFloatingPoint()); 8042 if (Src.getValueType() == MVT::f32) { 8043 if (IsStrict) { 8044 Src = 8045 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8046 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8047 Chain = Src.getValue(1); 8048 } else 8049 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8050 } 8051 SDValue Conv; 8052 unsigned Opc = ISD::DELETED_NODE; 8053 switch (Op.getSimpleValueType().SimpleTy) { 8054 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8055 case MVT::i32: 8056 Opc = IsSigned ? PPCISD::FCTIWZ 8057 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8058 break; 8059 case MVT::i64: 8060 assert((IsSigned || Subtarget.hasFPCVT()) && 8061 "i64 FP_TO_UINT is supported only with FPCVT"); 8062 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8063 } 8064 if (IsStrict) { 8065 Opc = getPPCStrictOpcode(Opc); 8066 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8067 {Chain, Src}, Flags); 8068 } else { 8069 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8070 } 8071 return Conv; 8072 } 8073 8074 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8075 SelectionDAG &DAG, 8076 const SDLoc &dl) const { 8077 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8078 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8079 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8080 bool IsStrict = Op->isStrictFPOpcode(); 8081 8082 // Convert the FP value to an int value through memory. 8083 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8084 (IsSigned || Subtarget.hasFPCVT()); 8085 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8086 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8087 MachinePointerInfo MPI = 8088 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8089 8090 // Emit a store to the stack slot. 8091 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8092 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8093 if (i32Stack) { 8094 MachineFunction &MF = DAG.getMachineFunction(); 8095 Alignment = Align(4); 8096 MachineMemOperand *MMO = 8097 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8098 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8099 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8100 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8101 } else 8102 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8103 8104 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8105 // add in a bias on big endian. 8106 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8107 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8108 DAG.getConstant(4, dl, FIPtr.getValueType())); 8109 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8110 } 8111 8112 RLI.Chain = Chain; 8113 RLI.Ptr = FIPtr; 8114 RLI.MPI = MPI; 8115 RLI.Alignment = Alignment; 8116 } 8117 8118 /// Custom lowers floating point to integer conversions to use 8119 /// the direct move instructions available in ISA 2.07 to avoid the 8120 /// need for load/store combinations. 8121 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8122 SelectionDAG &DAG, 8123 const SDLoc &dl) const { 8124 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8125 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8126 if (Op->isStrictFPOpcode()) 8127 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8128 else 8129 return Mov; 8130 } 8131 8132 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8133 const SDLoc &dl) const { 8134 bool IsStrict = Op->isStrictFPOpcode(); 8135 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8136 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8137 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8138 EVT SrcVT = Src.getValueType(); 8139 EVT DstVT = Op.getValueType(); 8140 8141 // FP to INT conversions are legal for f128. 8142 if (SrcVT == MVT::f128) 8143 return Subtarget.hasP9Vector() ? Op : SDValue(); 8144 8145 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8146 // PPC (the libcall is not available). 8147 if (SrcVT == MVT::ppcf128) { 8148 if (DstVT == MVT::i32) { 8149 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8150 // set other fast-math flags to FP operations in both strict and 8151 // non-strict cases. (FP_TO_SINT, FSUB) 8152 SDNodeFlags Flags; 8153 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8154 8155 if (IsSigned) { 8156 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8157 DAG.getIntPtrConstant(0, dl)); 8158 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8159 DAG.getIntPtrConstant(1, dl)); 8160 8161 // Add the two halves of the long double in round-to-zero mode, and use 8162 // a smaller FP_TO_SINT. 8163 if (IsStrict) { 8164 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8165 DAG.getVTList(MVT::f64, MVT::Other), 8166 {Op.getOperand(0), Lo, Hi}, Flags); 8167 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8168 DAG.getVTList(MVT::i32, MVT::Other), 8169 {Res.getValue(1), Res}, Flags); 8170 } else { 8171 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8172 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8173 } 8174 } else { 8175 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8176 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8177 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8178 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8179 if (IsStrict) { 8180 // Sel = Src < 0x80000000 8181 // FltOfs = select Sel, 0.0, 0x80000000 8182 // IntOfs = select Sel, 0, 0x80000000 8183 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8184 SDValue Chain = Op.getOperand(0); 8185 EVT SetCCVT = 8186 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8187 EVT DstSetCCVT = 8188 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8189 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8190 Chain, true); 8191 Chain = Sel.getValue(1); 8192 8193 SDValue FltOfs = DAG.getSelect( 8194 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8195 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8196 8197 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8198 DAG.getVTList(SrcVT, MVT::Other), 8199 {Chain, Src, FltOfs}, Flags); 8200 Chain = Val.getValue(1); 8201 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8202 DAG.getVTList(DstVT, MVT::Other), 8203 {Chain, Val}, Flags); 8204 Chain = SInt.getValue(1); 8205 SDValue IntOfs = DAG.getSelect( 8206 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8207 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8208 return DAG.getMergeValues({Result, Chain}, dl); 8209 } else { 8210 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8211 // FIXME: generated code sucks. 8212 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8213 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8214 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8215 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8216 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8217 } 8218 } 8219 } 8220 8221 return SDValue(); 8222 } 8223 8224 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8225 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8226 8227 ReuseLoadInfo RLI; 8228 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8229 8230 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8231 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8232 } 8233 8234 // We're trying to insert a regular store, S, and then a load, L. If the 8235 // incoming value, O, is a load, we might just be able to have our load use the 8236 // address used by O. However, we don't know if anything else will store to 8237 // that address before we can load from it. To prevent this situation, we need 8238 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8239 // the same chain operand as O, we create a token factor from the chain results 8240 // of O and L, and we replace all uses of O's chain result with that token 8241 // factor (see spliceIntoChain below for this last part). 8242 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8243 ReuseLoadInfo &RLI, 8244 SelectionDAG &DAG, 8245 ISD::LoadExtType ET) const { 8246 // Conservatively skip reusing for constrained FP nodes. 8247 if (Op->isStrictFPOpcode()) 8248 return false; 8249 8250 SDLoc dl(Op); 8251 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8252 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8253 if (ET == ISD::NON_EXTLOAD && 8254 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8255 isOperationLegalOrCustom(Op.getOpcode(), 8256 Op.getOperand(0).getValueType())) { 8257 8258 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8259 return true; 8260 } 8261 8262 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8263 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8264 LD->isNonTemporal()) 8265 return false; 8266 if (LD->getMemoryVT() != MemVT) 8267 return false; 8268 8269 // If the result of the load is an illegal type, then we can't build a 8270 // valid chain for reuse since the legalised loads and token factor node that 8271 // ties the legalised loads together uses a different output chain then the 8272 // illegal load. 8273 if (!isTypeLegal(LD->getValueType(0))) 8274 return false; 8275 8276 RLI.Ptr = LD->getBasePtr(); 8277 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8278 assert(LD->getAddressingMode() == ISD::PRE_INC && 8279 "Non-pre-inc AM on PPC?"); 8280 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8281 LD->getOffset()); 8282 } 8283 8284 RLI.Chain = LD->getChain(); 8285 RLI.MPI = LD->getPointerInfo(); 8286 RLI.IsDereferenceable = LD->isDereferenceable(); 8287 RLI.IsInvariant = LD->isInvariant(); 8288 RLI.Alignment = LD->getAlign(); 8289 RLI.AAInfo = LD->getAAInfo(); 8290 RLI.Ranges = LD->getRanges(); 8291 8292 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8293 return true; 8294 } 8295 8296 // Given the head of the old chain, ResChain, insert a token factor containing 8297 // it and NewResChain, and make users of ResChain now be users of that token 8298 // factor. 8299 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8300 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8301 SDValue NewResChain, 8302 SelectionDAG &DAG) const { 8303 if (!ResChain) 8304 return; 8305 8306 SDLoc dl(NewResChain); 8307 8308 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8309 NewResChain, DAG.getUNDEF(MVT::Other)); 8310 assert(TF.getNode() != NewResChain.getNode() && 8311 "A new TF really is required here"); 8312 8313 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8314 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8315 } 8316 8317 /// Analyze profitability of direct move 8318 /// prefer float load to int load plus direct move 8319 /// when there is no integer use of int load 8320 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8321 SDNode *Origin = Op.getOperand(0).getNode(); 8322 if (Origin->getOpcode() != ISD::LOAD) 8323 return true; 8324 8325 // If there is no LXSIBZX/LXSIHZX, like Power8, 8326 // prefer direct move if the memory size is 1 or 2 bytes. 8327 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8328 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8329 return true; 8330 8331 for (SDNode::use_iterator UI = Origin->use_begin(), 8332 UE = Origin->use_end(); 8333 UI != UE; ++UI) { 8334 8335 // Only look at the users of the loaded value. 8336 if (UI.getUse().get().getResNo() != 0) 8337 continue; 8338 8339 if (UI->getOpcode() != ISD::SINT_TO_FP && 8340 UI->getOpcode() != ISD::UINT_TO_FP && 8341 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8342 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8343 return true; 8344 } 8345 8346 return false; 8347 } 8348 8349 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8350 const PPCSubtarget &Subtarget, 8351 SDValue Chain = SDValue()) { 8352 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8353 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8354 SDLoc dl(Op); 8355 8356 // TODO: Any other flags to propagate? 8357 SDNodeFlags Flags; 8358 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8359 8360 // If we have FCFIDS, then use it when converting to single-precision. 8361 // Otherwise, convert to double-precision and then round. 8362 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8363 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8364 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8365 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8366 if (Op->isStrictFPOpcode()) { 8367 if (!Chain) 8368 Chain = Op.getOperand(0); 8369 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8370 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8371 } else 8372 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8373 } 8374 8375 /// Custom lowers integer to floating point conversions to use 8376 /// the direct move instructions available in ISA 2.07 to avoid the 8377 /// need for load/store combinations. 8378 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8379 SelectionDAG &DAG, 8380 const SDLoc &dl) const { 8381 assert((Op.getValueType() == MVT::f32 || 8382 Op.getValueType() == MVT::f64) && 8383 "Invalid floating point type as target of conversion"); 8384 assert(Subtarget.hasFPCVT() && 8385 "Int to FP conversions with direct moves require FPCVT"); 8386 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8387 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8388 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8389 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8390 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8391 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8392 return convertIntToFP(Op, Mov, DAG, Subtarget); 8393 } 8394 8395 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8396 8397 EVT VecVT = Vec.getValueType(); 8398 assert(VecVT.isVector() && "Expected a vector type."); 8399 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8400 8401 EVT EltVT = VecVT.getVectorElementType(); 8402 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8403 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8404 8405 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8406 SmallVector<SDValue, 16> Ops(NumConcat); 8407 Ops[0] = Vec; 8408 SDValue UndefVec = DAG.getUNDEF(VecVT); 8409 for (unsigned i = 1; i < NumConcat; ++i) 8410 Ops[i] = UndefVec; 8411 8412 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8413 } 8414 8415 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8416 const SDLoc &dl) const { 8417 bool IsStrict = Op->isStrictFPOpcode(); 8418 unsigned Opc = Op.getOpcode(); 8419 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8420 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8421 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8422 "Unexpected conversion type"); 8423 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8424 "Supports conversions to v2f64/v4f32 only."); 8425 8426 // TODO: Any other flags to propagate? 8427 SDNodeFlags Flags; 8428 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8429 8430 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8431 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8432 8433 SDValue Wide = widenVec(DAG, Src, dl); 8434 EVT WideVT = Wide.getValueType(); 8435 unsigned WideNumElts = WideVT.getVectorNumElements(); 8436 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8437 8438 SmallVector<int, 16> ShuffV; 8439 for (unsigned i = 0; i < WideNumElts; ++i) 8440 ShuffV.push_back(i + WideNumElts); 8441 8442 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8443 int SaveElts = FourEltRes ? 4 : 2; 8444 if (Subtarget.isLittleEndian()) 8445 for (int i = 0; i < SaveElts; i++) 8446 ShuffV[i * Stride] = i; 8447 else 8448 for (int i = 1; i <= SaveElts; i++) 8449 ShuffV[i * Stride - 1] = i - 1; 8450 8451 SDValue ShuffleSrc2 = 8452 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8453 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8454 8455 SDValue Extend; 8456 if (SignedConv) { 8457 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8458 EVT ExtVT = Src.getValueType(); 8459 if (Subtarget.hasP9Altivec()) 8460 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8461 IntermediateVT.getVectorNumElements()); 8462 8463 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8464 DAG.getValueType(ExtVT)); 8465 } else 8466 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8467 8468 if (IsStrict) 8469 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8470 {Op.getOperand(0), Extend}, Flags); 8471 8472 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8473 } 8474 8475 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8476 SelectionDAG &DAG) const { 8477 SDLoc dl(Op); 8478 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8479 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8480 bool IsStrict = Op->isStrictFPOpcode(); 8481 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8482 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8483 8484 // TODO: Any other flags to propagate? 8485 SDNodeFlags Flags; 8486 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8487 8488 EVT InVT = Src.getValueType(); 8489 EVT OutVT = Op.getValueType(); 8490 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8491 isOperationCustom(Op.getOpcode(), InVT)) 8492 return LowerINT_TO_FPVector(Op, DAG, dl); 8493 8494 // Conversions to f128 are legal. 8495 if (Op.getValueType() == MVT::f128) 8496 return Subtarget.hasP9Vector() ? Op : SDValue(); 8497 8498 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8499 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8500 return SDValue(); 8501 8502 if (Src.getValueType() == MVT::i1) { 8503 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8504 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8505 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8506 if (IsStrict) 8507 return DAG.getMergeValues({Sel, Chain}, dl); 8508 else 8509 return Sel; 8510 } 8511 8512 // If we have direct moves, we can do all the conversion, skip the store/load 8513 // however, without FPCVT we can't do most conversions. 8514 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8515 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8516 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8517 8518 assert((IsSigned || Subtarget.hasFPCVT()) && 8519 "UINT_TO_FP is supported only with FPCVT"); 8520 8521 if (Src.getValueType() == MVT::i64) { 8522 SDValue SINT = Src; 8523 // When converting to single-precision, we actually need to convert 8524 // to double-precision first and then round to single-precision. 8525 // To avoid double-rounding effects during that operation, we have 8526 // to prepare the input operand. Bits that might be truncated when 8527 // converting to double-precision are replaced by a bit that won't 8528 // be lost at this stage, but is below the single-precision rounding 8529 // position. 8530 // 8531 // However, if -enable-unsafe-fp-math is in effect, accept double 8532 // rounding to avoid the extra overhead. 8533 if (Op.getValueType() == MVT::f32 && 8534 !Subtarget.hasFPCVT() && 8535 !DAG.getTarget().Options.UnsafeFPMath) { 8536 8537 // Twiddle input to make sure the low 11 bits are zero. (If this 8538 // is the case, we are guaranteed the value will fit into the 53 bit 8539 // mantissa of an IEEE double-precision value without rounding.) 8540 // If any of those low 11 bits were not zero originally, make sure 8541 // bit 12 (value 2048) is set instead, so that the final rounding 8542 // to single-precision gets the correct result. 8543 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8544 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8545 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8546 Round, DAG.getConstant(2047, dl, MVT::i64)); 8547 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8548 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8549 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8550 8551 // However, we cannot use that value unconditionally: if the magnitude 8552 // of the input value is small, the bit-twiddling we did above might 8553 // end up visibly changing the output. Fortunately, in that case, we 8554 // don't need to twiddle bits since the original input will convert 8555 // exactly to double-precision floating-point already. Therefore, 8556 // construct a conditional to use the original value if the top 11 8557 // bits are all sign-bit copies, and use the rounded value computed 8558 // above otherwise. 8559 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8560 SINT, DAG.getConstant(53, dl, MVT::i32)); 8561 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8562 Cond, DAG.getConstant(1, dl, MVT::i64)); 8563 Cond = DAG.getSetCC( 8564 dl, 8565 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8566 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8567 8568 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8569 } 8570 8571 ReuseLoadInfo RLI; 8572 SDValue Bits; 8573 8574 MachineFunction &MF = DAG.getMachineFunction(); 8575 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8576 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8577 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8578 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8579 } else if (Subtarget.hasLFIWAX() && 8580 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8581 MachineMemOperand *MMO = 8582 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8583 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8584 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8585 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8586 DAG.getVTList(MVT::f64, MVT::Other), 8587 Ops, MVT::i32, MMO); 8588 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8589 } else if (Subtarget.hasFPCVT() && 8590 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8591 MachineMemOperand *MMO = 8592 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8593 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8594 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8595 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8596 DAG.getVTList(MVT::f64, MVT::Other), 8597 Ops, MVT::i32, MMO); 8598 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8599 } else if (((Subtarget.hasLFIWAX() && 8600 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8601 (Subtarget.hasFPCVT() && 8602 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8603 SINT.getOperand(0).getValueType() == MVT::i32) { 8604 MachineFrameInfo &MFI = MF.getFrameInfo(); 8605 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8606 8607 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8608 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8609 8610 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8611 MachinePointerInfo::getFixedStack( 8612 DAG.getMachineFunction(), FrameIdx)); 8613 Chain = Store; 8614 8615 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8616 "Expected an i32 store"); 8617 8618 RLI.Ptr = FIdx; 8619 RLI.Chain = Chain; 8620 RLI.MPI = 8621 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8622 RLI.Alignment = Align(4); 8623 8624 MachineMemOperand *MMO = 8625 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8626 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8627 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8628 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8629 PPCISD::LFIWZX : PPCISD::LFIWAX, 8630 dl, DAG.getVTList(MVT::f64, MVT::Other), 8631 Ops, MVT::i32, MMO); 8632 Chain = Bits.getValue(1); 8633 } else 8634 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8635 8636 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8637 if (IsStrict) 8638 Chain = FP.getValue(1); 8639 8640 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8641 if (IsStrict) 8642 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8643 DAG.getVTList(MVT::f32, MVT::Other), 8644 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8645 else 8646 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8647 DAG.getIntPtrConstant(0, dl)); 8648 } 8649 return FP; 8650 } 8651 8652 assert(Src.getValueType() == MVT::i32 && 8653 "Unhandled INT_TO_FP type in custom expander!"); 8654 // Since we only generate this in 64-bit mode, we can take advantage of 8655 // 64-bit registers. In particular, sign extend the input value into the 8656 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8657 // then lfd it and fcfid it. 8658 MachineFunction &MF = DAG.getMachineFunction(); 8659 MachineFrameInfo &MFI = MF.getFrameInfo(); 8660 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8661 8662 SDValue Ld; 8663 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8664 ReuseLoadInfo RLI; 8665 bool ReusingLoad; 8666 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8667 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8668 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8669 8670 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8671 MachinePointerInfo::getFixedStack( 8672 DAG.getMachineFunction(), FrameIdx)); 8673 Chain = Store; 8674 8675 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8676 "Expected an i32 store"); 8677 8678 RLI.Ptr = FIdx; 8679 RLI.Chain = Chain; 8680 RLI.MPI = 8681 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8682 RLI.Alignment = Align(4); 8683 } 8684 8685 MachineMemOperand *MMO = 8686 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8687 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8688 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8689 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8690 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8691 MVT::i32, MMO); 8692 Chain = Ld.getValue(1); 8693 if (ReusingLoad) 8694 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8695 } else { 8696 assert(Subtarget.isPPC64() && 8697 "i32->FP without LFIWAX supported only on PPC64"); 8698 8699 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8700 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8701 8702 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8703 8704 // STD the extended value into the stack slot. 8705 SDValue Store = DAG.getStore( 8706 Chain, dl, Ext64, FIdx, 8707 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8708 Chain = Store; 8709 8710 // Load the value as a double. 8711 Ld = DAG.getLoad( 8712 MVT::f64, dl, Chain, FIdx, 8713 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8714 Chain = Ld.getValue(1); 8715 } 8716 8717 // FCFID it and return it. 8718 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8719 if (IsStrict) 8720 Chain = FP.getValue(1); 8721 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8722 if (IsStrict) 8723 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8724 DAG.getVTList(MVT::f32, MVT::Other), 8725 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8726 else 8727 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8728 DAG.getIntPtrConstant(0, dl)); 8729 } 8730 return FP; 8731 } 8732 8733 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8734 SelectionDAG &DAG) const { 8735 SDLoc dl(Op); 8736 /* 8737 The rounding mode is in bits 30:31 of FPSR, and has the following 8738 settings: 8739 00 Round to nearest 8740 01 Round to 0 8741 10 Round to +inf 8742 11 Round to -inf 8743 8744 FLT_ROUNDS, on the other hand, expects the following: 8745 -1 Undefined 8746 0 Round to 0 8747 1 Round to nearest 8748 2 Round to +inf 8749 3 Round to -inf 8750 8751 To perform the conversion, we do: 8752 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8753 */ 8754 8755 MachineFunction &MF = DAG.getMachineFunction(); 8756 EVT VT = Op.getValueType(); 8757 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8758 8759 // Save FP Control Word to register 8760 SDValue Chain = Op.getOperand(0); 8761 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8762 Chain = MFFS.getValue(1); 8763 8764 SDValue CWD; 8765 if (isTypeLegal(MVT::i64)) { 8766 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8767 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8768 } else { 8769 // Save FP register to stack slot 8770 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8771 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8772 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8773 8774 // Load FP Control Word from low 32 bits of stack slot. 8775 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8776 "Stack slot adjustment is valid only on big endian subtargets!"); 8777 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8778 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8779 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8780 Chain = CWD.getValue(1); 8781 } 8782 8783 // Transform as necessary 8784 SDValue CWD1 = 8785 DAG.getNode(ISD::AND, dl, MVT::i32, 8786 CWD, DAG.getConstant(3, dl, MVT::i32)); 8787 SDValue CWD2 = 8788 DAG.getNode(ISD::SRL, dl, MVT::i32, 8789 DAG.getNode(ISD::AND, dl, MVT::i32, 8790 DAG.getNode(ISD::XOR, dl, MVT::i32, 8791 CWD, DAG.getConstant(3, dl, MVT::i32)), 8792 DAG.getConstant(3, dl, MVT::i32)), 8793 DAG.getConstant(1, dl, MVT::i32)); 8794 8795 SDValue RetVal = 8796 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8797 8798 RetVal = 8799 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8800 dl, VT, RetVal); 8801 8802 return DAG.getMergeValues({RetVal, Chain}, dl); 8803 } 8804 8805 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8806 EVT VT = Op.getValueType(); 8807 unsigned BitWidth = VT.getSizeInBits(); 8808 SDLoc dl(Op); 8809 assert(Op.getNumOperands() == 3 && 8810 VT == Op.getOperand(1).getValueType() && 8811 "Unexpected SHL!"); 8812 8813 // Expand into a bunch of logical ops. Note that these ops 8814 // depend on the PPC behavior for oversized shift amounts. 8815 SDValue Lo = Op.getOperand(0); 8816 SDValue Hi = Op.getOperand(1); 8817 SDValue Amt = Op.getOperand(2); 8818 EVT AmtVT = Amt.getValueType(); 8819 8820 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8821 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8822 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8823 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8824 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8825 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8826 DAG.getConstant(-BitWidth, dl, AmtVT)); 8827 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8828 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8829 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8830 SDValue OutOps[] = { OutLo, OutHi }; 8831 return DAG.getMergeValues(OutOps, dl); 8832 } 8833 8834 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8835 EVT VT = Op.getValueType(); 8836 SDLoc dl(Op); 8837 unsigned BitWidth = VT.getSizeInBits(); 8838 assert(Op.getNumOperands() == 3 && 8839 VT == Op.getOperand(1).getValueType() && 8840 "Unexpected SRL!"); 8841 8842 // Expand into a bunch of logical ops. Note that these ops 8843 // depend on the PPC behavior for oversized shift amounts. 8844 SDValue Lo = Op.getOperand(0); 8845 SDValue Hi = Op.getOperand(1); 8846 SDValue Amt = Op.getOperand(2); 8847 EVT AmtVT = Amt.getValueType(); 8848 8849 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8850 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8851 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8852 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8853 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8854 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8855 DAG.getConstant(-BitWidth, dl, AmtVT)); 8856 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8857 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8858 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8859 SDValue OutOps[] = { OutLo, OutHi }; 8860 return DAG.getMergeValues(OutOps, dl); 8861 } 8862 8863 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8864 SDLoc dl(Op); 8865 EVT VT = Op.getValueType(); 8866 unsigned BitWidth = VT.getSizeInBits(); 8867 assert(Op.getNumOperands() == 3 && 8868 VT == Op.getOperand(1).getValueType() && 8869 "Unexpected SRA!"); 8870 8871 // Expand into a bunch of logical ops, followed by a select_cc. 8872 SDValue Lo = Op.getOperand(0); 8873 SDValue Hi = Op.getOperand(1); 8874 SDValue Amt = Op.getOperand(2); 8875 EVT AmtVT = Amt.getValueType(); 8876 8877 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8878 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8879 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8880 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8881 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8882 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8883 DAG.getConstant(-BitWidth, dl, AmtVT)); 8884 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8885 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8886 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8887 Tmp4, Tmp6, ISD::SETLE); 8888 SDValue OutOps[] = { OutLo, OutHi }; 8889 return DAG.getMergeValues(OutOps, dl); 8890 } 8891 8892 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8893 SelectionDAG &DAG) const { 8894 SDLoc dl(Op); 8895 EVT VT = Op.getValueType(); 8896 unsigned BitWidth = VT.getSizeInBits(); 8897 8898 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8899 SDValue X = Op.getOperand(0); 8900 SDValue Y = Op.getOperand(1); 8901 SDValue Z = Op.getOperand(2); 8902 EVT AmtVT = Z.getValueType(); 8903 8904 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8905 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8906 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8907 // on PowerPC shift by BW being well defined. 8908 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8909 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8910 SDValue SubZ = 8911 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8912 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8913 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8914 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8915 } 8916 8917 //===----------------------------------------------------------------------===// 8918 // Vector related lowering. 8919 // 8920 8921 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8922 /// element size of SplatSize. Cast the result to VT. 8923 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8924 SelectionDAG &DAG, const SDLoc &dl) { 8925 static const MVT VTys[] = { // canonical VT to use for each size. 8926 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8927 }; 8928 8929 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8930 8931 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8932 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8933 SplatSize = 1; 8934 Val = 0xFF; 8935 } 8936 8937 EVT CanonicalVT = VTys[SplatSize-1]; 8938 8939 // Build a canonical splat for this value. 8940 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8941 } 8942 8943 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8944 /// specified intrinsic ID. 8945 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8946 const SDLoc &dl, EVT DestVT = MVT::Other) { 8947 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8948 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8949 DAG.getConstant(IID, dl, MVT::i32), Op); 8950 } 8951 8952 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8953 /// specified intrinsic ID. 8954 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8955 SelectionDAG &DAG, const SDLoc &dl, 8956 EVT DestVT = MVT::Other) { 8957 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8958 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8959 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8960 } 8961 8962 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8963 /// specified intrinsic ID. 8964 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8965 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8966 EVT DestVT = MVT::Other) { 8967 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8968 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8969 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8970 } 8971 8972 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8973 /// amount. The result has the specified value type. 8974 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8975 SelectionDAG &DAG, const SDLoc &dl) { 8976 // Force LHS/RHS to be the right type. 8977 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8978 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8979 8980 int Ops[16]; 8981 for (unsigned i = 0; i != 16; ++i) 8982 Ops[i] = i + Amt; 8983 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8984 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8985 } 8986 8987 /// Do we have an efficient pattern in a .td file for this node? 8988 /// 8989 /// \param V - pointer to the BuildVectorSDNode being matched 8990 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8991 /// 8992 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8993 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8994 /// the opposite is true (expansion is beneficial) are: 8995 /// - The node builds a vector out of integers that are not 32 or 64-bits 8996 /// - The node builds a vector out of constants 8997 /// - The node is a "load-and-splat" 8998 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8999 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9000 bool HasDirectMove, 9001 bool HasP8Vector) { 9002 EVT VecVT = V->getValueType(0); 9003 bool RightType = VecVT == MVT::v2f64 || 9004 (HasP8Vector && VecVT == MVT::v4f32) || 9005 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9006 if (!RightType) 9007 return false; 9008 9009 bool IsSplat = true; 9010 bool IsLoad = false; 9011 SDValue Op0 = V->getOperand(0); 9012 9013 // This function is called in a block that confirms the node is not a constant 9014 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9015 // different constants. 9016 if (V->isConstant()) 9017 return false; 9018 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9019 if (V->getOperand(i).isUndef()) 9020 return false; 9021 // We want to expand nodes that represent load-and-splat even if the 9022 // loaded value is a floating point truncation or conversion to int. 9023 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9024 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9025 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9026 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9027 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9028 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9029 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9030 IsLoad = true; 9031 // If the operands are different or the input is not a load and has more 9032 // uses than just this BV node, then it isn't a splat. 9033 if (V->getOperand(i) != Op0 || 9034 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9035 IsSplat = false; 9036 } 9037 return !(IsSplat && IsLoad); 9038 } 9039 9040 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9041 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9042 9043 SDLoc dl(Op); 9044 SDValue Op0 = Op->getOperand(0); 9045 9046 if ((Op.getValueType() != MVT::f128) || 9047 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9048 (Op0.getOperand(0).getValueType() != MVT::i64) || 9049 (Op0.getOperand(1).getValueType() != MVT::i64)) 9050 return SDValue(); 9051 9052 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9053 Op0.getOperand(1)); 9054 } 9055 9056 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9057 const SDValue *InputLoad = &Op; 9058 if (InputLoad->getOpcode() == ISD::BITCAST) 9059 InputLoad = &InputLoad->getOperand(0); 9060 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9061 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9062 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9063 InputLoad = &InputLoad->getOperand(0); 9064 } 9065 if (InputLoad->getOpcode() != ISD::LOAD) 9066 return nullptr; 9067 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9068 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9069 } 9070 9071 // Convert the argument APFloat to a single precision APFloat if there is no 9072 // loss in information during the conversion to single precision APFloat and the 9073 // resulting number is not a denormal number. Return true if successful. 9074 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9075 APFloat APFloatToConvert = ArgAPFloat; 9076 bool LosesInfo = true; 9077 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9078 &LosesInfo); 9079 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9080 if (Success) 9081 ArgAPFloat = APFloatToConvert; 9082 return Success; 9083 } 9084 9085 // Bitcast the argument APInt to a double and convert it to a single precision 9086 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9087 // argument if there is no loss in information during the conversion from 9088 // double to single precision APFloat and the resulting number is not a denormal 9089 // number. Return true if successful. 9090 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9091 double DpValue = ArgAPInt.bitsToDouble(); 9092 APFloat APFloatDp(DpValue); 9093 bool Success = convertToNonDenormSingle(APFloatDp); 9094 if (Success) 9095 ArgAPInt = APFloatDp.bitcastToAPInt(); 9096 return Success; 9097 } 9098 9099 // Nondestructive check for convertTonNonDenormSingle. 9100 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 9101 // Only convert if it loses info, since XXSPLTIDP should 9102 // handle the other case. 9103 APFloat APFloatToConvert = ArgAPFloat; 9104 bool LosesInfo = true; 9105 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9106 &LosesInfo); 9107 9108 return (!LosesInfo && !APFloatToConvert.isDenormal()); 9109 } 9110 9111 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op, 9112 unsigned &Opcode) { 9113 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0)); 9114 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode)) 9115 return false; 9116 9117 EVT Ty = Op->getValueType(0); 9118 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending 9119 // as we cannot handle extending loads for these types. 9120 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) && 9121 ISD::isNON_EXTLoad(InputNode)) 9122 return true; 9123 9124 EVT MemVT = InputNode->getMemoryVT(); 9125 // For v8i16 and v16i8 types, extending loads can be handled as long as the 9126 // memory VT is the same vector element VT type. 9127 // The loads feeding into the v8i16 and v16i8 types will be extending because 9128 // scalar i8/i16 are not legal types. 9129 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) && 9130 (MemVT == Ty.getVectorElementType())) 9131 return true; 9132 9133 if (Ty == MVT::v2i64) { 9134 // Check the extend type, when the input type is i32, and the output vector 9135 // type is v2i64. 9136 if (MemVT == MVT::i32) { 9137 if (ISD::isZEXTLoad(InputNode)) 9138 Opcode = PPCISD::ZEXT_LD_SPLAT; 9139 if (ISD::isSEXTLoad(InputNode)) 9140 Opcode = PPCISD::SEXT_LD_SPLAT; 9141 } 9142 return true; 9143 } 9144 return false; 9145 } 9146 9147 // If this is a case we can't handle, return null and let the default 9148 // expansion code take care of it. If we CAN select this case, and if it 9149 // selects to a single instruction, return Op. Otherwise, if we can codegen 9150 // this case more efficiently than a constant pool load, lower it to the 9151 // sequence of ops that should be used. 9152 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9153 SelectionDAG &DAG) const { 9154 SDLoc dl(Op); 9155 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9156 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9157 9158 // Check if this is a splat of a constant value. 9159 APInt APSplatBits, APSplatUndef; 9160 unsigned SplatBitSize; 9161 bool HasAnyUndefs; 9162 bool BVNIsConstantSplat = 9163 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9164 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9165 9166 // If it is a splat of a double, check if we can shrink it to a 32 bit 9167 // non-denormal float which when converted back to double gives us the same 9168 // double. This is to exploit the XXSPLTIDP instruction. 9169 // If we lose precision, we use XXSPLTI32DX. 9170 if (BVNIsConstantSplat && (SplatBitSize == 64) && 9171 Subtarget.hasPrefixInstrs()) { 9172 // Check the type first to short-circuit so we don't modify APSplatBits if 9173 // this block isn't executed. 9174 if ((Op->getValueType(0) == MVT::v2f64) && 9175 convertToNonDenormSingle(APSplatBits)) { 9176 SDValue SplatNode = DAG.getNode( 9177 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9178 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9179 return DAG.getBitcast(Op.getValueType(), SplatNode); 9180 } else { 9181 // We may lose precision, so we have to use XXSPLTI32DX. 9182 9183 uint32_t Hi = 9184 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 9185 uint32_t Lo = 9186 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 9187 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 9188 9189 if (!Hi || !Lo) 9190 // If either load is 0, then we should generate XXLXOR to set to 0. 9191 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 9192 9193 if (Hi) 9194 SplatNode = DAG.getNode( 9195 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9196 DAG.getTargetConstant(0, dl, MVT::i32), 9197 DAG.getTargetConstant(Hi, dl, MVT::i32)); 9198 9199 if (Lo) 9200 SplatNode = 9201 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9202 DAG.getTargetConstant(1, dl, MVT::i32), 9203 DAG.getTargetConstant(Lo, dl, MVT::i32)); 9204 9205 return DAG.getBitcast(Op.getValueType(), SplatNode); 9206 } 9207 } 9208 9209 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9210 unsigned NewOpcode = PPCISD::LD_SPLAT; 9211 9212 // Handle load-and-splat patterns as we have instructions that will do this 9213 // in one go. 9214 if (DAG.isSplatValue(Op, true) && 9215 isValidSplatLoad(Subtarget, Op, NewOpcode)) { 9216 const SDValue *InputLoad = &Op.getOperand(0); 9217 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9218 9219 // If the input load is an extending load, it will be an i32 -> i64 9220 // extending load and isValidSplatLoad() will update NewOpcode. 9221 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits(); 9222 unsigned ElementSize = 9223 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2); 9224 9225 assert(((ElementSize == 2 * MemorySize) 9226 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || 9227 NewOpcode == PPCISD::SEXT_LD_SPLAT) 9228 : (NewOpcode == PPCISD::LD_SPLAT)) && 9229 "Unmatched element size and opcode!\n"); 9230 9231 // Checking for a single use of this load, we have to check for vector 9232 // width (128 bits) / ElementSize uses (since each operand of the 9233 // BUILD_VECTOR is a separate use of the value. 9234 unsigned NumUsesOfInputLD = 128 / ElementSize; 9235 for (SDValue BVInOp : Op->ops()) 9236 if (BVInOp.isUndef()) 9237 NumUsesOfInputLD--; 9238 9239 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector: 9240 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index 9241 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index 9242 // 15", but funciton IsValidSplatLoad() now will only return true when 9243 // the data at index 0 is not nullptr. So we will not get into trouble for 9244 // these cases. 9245 // 9246 // case 1 - lfiwzx/lfiwax 9247 // 1.1: load result is i32 and is sign/zero extend to i64; 9248 // 1.2: build a v2i64 vector type with above loaded value; 9249 // 1.3: the vector has only one value at index 0, others are all undef; 9250 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute. 9251 if (NumUsesOfInputLD == 1 && 9252 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT && 9253 !Subtarget.isLittleEndian() && Subtarget.hasVSX() && 9254 Subtarget.hasLFIWAX())) 9255 return SDValue(); 9256 9257 // case 2 - lxvr[hb]x 9258 // 2.1: load result is at most i16; 9259 // 2.2: build a vector with above loaded value; 9260 // 2.3: the vector has only one value at index 0, others are all undef; 9261 // 2.4: on LE target, so that lxvr[hb]x does not need any permute. 9262 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() && 9263 Subtarget.isISA3_1() && ElementSize <= 16) 9264 return SDValue(); 9265 9266 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9267 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9268 Subtarget.hasVSX()) { 9269 SDValue Ops[] = { 9270 LD->getChain(), // Chain 9271 LD->getBasePtr(), // Ptr 9272 DAG.getValueType(Op.getValueType()) // VT 9273 }; 9274 SDValue LdSplt = DAG.getMemIntrinsicNode( 9275 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops, 9276 LD->getMemoryVT(), LD->getMemOperand()); 9277 // Replace all uses of the output chain of the original load with the 9278 // output chain of the new load. 9279 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9280 LdSplt.getValue(1)); 9281 return LdSplt; 9282 } 9283 } 9284 9285 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9286 // 32-bits can be lowered to VSX instructions under certain conditions. 9287 // Without VSX, there is no pattern more efficient than expanding the node. 9288 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9289 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9290 Subtarget.hasP8Vector())) 9291 return Op; 9292 return SDValue(); 9293 } 9294 9295 uint64_t SplatBits = APSplatBits.getZExtValue(); 9296 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9297 unsigned SplatSize = SplatBitSize / 8; 9298 9299 // First, handle single instruction cases. 9300 9301 // All zeros? 9302 if (SplatBits == 0) { 9303 // Canonicalize all zero vectors to be v4i32. 9304 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9305 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9306 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9307 } 9308 return Op; 9309 } 9310 9311 // We have XXSPLTIW for constant splats four bytes wide. 9312 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9313 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9314 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9315 // turned into a 4-byte splat of 0xABABABAB. 9316 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9317 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9318 Op.getValueType(), DAG, dl); 9319 9320 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9321 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9322 dl); 9323 9324 // We have XXSPLTIB for constant splats one byte wide. 9325 if (Subtarget.hasP9Vector() && SplatSize == 1) 9326 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9327 dl); 9328 9329 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9330 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9331 (32-SplatBitSize)); 9332 if (SextVal >= -16 && SextVal <= 15) 9333 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9334 dl); 9335 9336 // Two instruction sequences. 9337 9338 // If this value is in the range [-32,30] and is even, use: 9339 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9340 // If this value is in the range [17,31] and is odd, use: 9341 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9342 // If this value is in the range [-31,-17] and is odd, use: 9343 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9344 // Note the last two are three-instruction sequences. 9345 if (SextVal >= -32 && SextVal <= 31) { 9346 // To avoid having these optimizations undone by constant folding, 9347 // we convert to a pseudo that will be expanded later into one of 9348 // the above forms. 9349 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9350 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9351 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9352 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9353 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9354 if (VT == Op.getValueType()) 9355 return RetVal; 9356 else 9357 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9358 } 9359 9360 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9361 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9362 // for fneg/fabs. 9363 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9364 // Make -1 and vspltisw -1: 9365 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9366 9367 // Make the VSLW intrinsic, computing 0x8000_0000. 9368 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9369 OnesV, DAG, dl); 9370 9371 // xor by OnesV to invert it. 9372 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9373 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9374 } 9375 9376 // Check to see if this is a wide variety of vsplti*, binop self cases. 9377 static const signed char SplatCsts[] = { 9378 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9379 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9380 }; 9381 9382 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9383 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9384 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9385 int i = SplatCsts[idx]; 9386 9387 // Figure out what shift amount will be used by altivec if shifted by i in 9388 // this splat size. 9389 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9390 9391 // vsplti + shl self. 9392 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9393 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9394 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9395 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9396 Intrinsic::ppc_altivec_vslw 9397 }; 9398 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9399 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9400 } 9401 9402 // vsplti + srl self. 9403 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9404 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9405 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9406 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9407 Intrinsic::ppc_altivec_vsrw 9408 }; 9409 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9410 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9411 } 9412 9413 // vsplti + rol self. 9414 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9415 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9416 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9417 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9418 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9419 Intrinsic::ppc_altivec_vrlw 9420 }; 9421 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9422 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9423 } 9424 9425 // t = vsplti c, result = vsldoi t, t, 1 9426 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9427 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9428 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9429 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9430 } 9431 // t = vsplti c, result = vsldoi t, t, 2 9432 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9433 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9434 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9435 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9436 } 9437 // t = vsplti c, result = vsldoi t, t, 3 9438 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9439 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9440 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9441 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9442 } 9443 } 9444 9445 return SDValue(); 9446 } 9447 9448 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9449 /// the specified operations to build the shuffle. 9450 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9451 SDValue RHS, SelectionDAG &DAG, 9452 const SDLoc &dl) { 9453 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9454 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9455 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9456 9457 enum { 9458 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9459 OP_VMRGHW, 9460 OP_VMRGLW, 9461 OP_VSPLTISW0, 9462 OP_VSPLTISW1, 9463 OP_VSPLTISW2, 9464 OP_VSPLTISW3, 9465 OP_VSLDOI4, 9466 OP_VSLDOI8, 9467 OP_VSLDOI12 9468 }; 9469 9470 if (OpNum == OP_COPY) { 9471 if (LHSID == (1*9+2)*9+3) return LHS; 9472 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9473 return RHS; 9474 } 9475 9476 SDValue OpLHS, OpRHS; 9477 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9478 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9479 9480 int ShufIdxs[16]; 9481 switch (OpNum) { 9482 default: llvm_unreachable("Unknown i32 permute!"); 9483 case OP_VMRGHW: 9484 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9485 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9486 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9487 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9488 break; 9489 case OP_VMRGLW: 9490 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9491 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9492 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9493 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9494 break; 9495 case OP_VSPLTISW0: 9496 for (unsigned i = 0; i != 16; ++i) 9497 ShufIdxs[i] = (i&3)+0; 9498 break; 9499 case OP_VSPLTISW1: 9500 for (unsigned i = 0; i != 16; ++i) 9501 ShufIdxs[i] = (i&3)+4; 9502 break; 9503 case OP_VSPLTISW2: 9504 for (unsigned i = 0; i != 16; ++i) 9505 ShufIdxs[i] = (i&3)+8; 9506 break; 9507 case OP_VSPLTISW3: 9508 for (unsigned i = 0; i != 16; ++i) 9509 ShufIdxs[i] = (i&3)+12; 9510 break; 9511 case OP_VSLDOI4: 9512 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9513 case OP_VSLDOI8: 9514 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9515 case OP_VSLDOI12: 9516 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9517 } 9518 EVT VT = OpLHS.getValueType(); 9519 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9520 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9521 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9522 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9523 } 9524 9525 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9526 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9527 /// SDValue. 9528 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9529 SelectionDAG &DAG) const { 9530 const unsigned BytesInVector = 16; 9531 bool IsLE = Subtarget.isLittleEndian(); 9532 SDLoc dl(N); 9533 SDValue V1 = N->getOperand(0); 9534 SDValue V2 = N->getOperand(1); 9535 unsigned ShiftElts = 0, InsertAtByte = 0; 9536 bool Swap = false; 9537 9538 // Shifts required to get the byte we want at element 7. 9539 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9540 0, 15, 14, 13, 12, 11, 10, 9}; 9541 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9542 1, 2, 3, 4, 5, 6, 7, 8}; 9543 9544 ArrayRef<int> Mask = N->getMask(); 9545 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9546 9547 // For each mask element, find out if we're just inserting something 9548 // from V2 into V1 or vice versa. 9549 // Possible permutations inserting an element from V2 into V1: 9550 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9551 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9552 // ... 9553 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9554 // Inserting from V1 into V2 will be similar, except mask range will be 9555 // [16,31]. 9556 9557 bool FoundCandidate = false; 9558 // If both vector operands for the shuffle are the same vector, the mask 9559 // will contain only elements from the first one and the second one will be 9560 // undef. 9561 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9562 // Go through the mask of half-words to find an element that's being moved 9563 // from one vector to the other. 9564 for (unsigned i = 0; i < BytesInVector; ++i) { 9565 unsigned CurrentElement = Mask[i]; 9566 // If 2nd operand is undefined, we should only look for element 7 in the 9567 // Mask. 9568 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9569 continue; 9570 9571 bool OtherElementsInOrder = true; 9572 // Examine the other elements in the Mask to see if they're in original 9573 // order. 9574 for (unsigned j = 0; j < BytesInVector; ++j) { 9575 if (j == i) 9576 continue; 9577 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9578 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9579 // in which we always assume we're always picking from the 1st operand. 9580 int MaskOffset = 9581 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9582 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9583 OtherElementsInOrder = false; 9584 break; 9585 } 9586 } 9587 // If other elements are in original order, we record the number of shifts 9588 // we need to get the element we want into element 7. Also record which byte 9589 // in the vector we should insert into. 9590 if (OtherElementsInOrder) { 9591 // If 2nd operand is undefined, we assume no shifts and no swapping. 9592 if (V2.isUndef()) { 9593 ShiftElts = 0; 9594 Swap = false; 9595 } else { 9596 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9597 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9598 : BigEndianShifts[CurrentElement & 0xF]; 9599 Swap = CurrentElement < BytesInVector; 9600 } 9601 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9602 FoundCandidate = true; 9603 break; 9604 } 9605 } 9606 9607 if (!FoundCandidate) 9608 return SDValue(); 9609 9610 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9611 // optionally with VECSHL if shift is required. 9612 if (Swap) 9613 std::swap(V1, V2); 9614 if (V2.isUndef()) 9615 V2 = V1; 9616 if (ShiftElts) { 9617 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9618 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9619 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9620 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9621 } 9622 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9623 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9624 } 9625 9626 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9627 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9628 /// SDValue. 9629 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9630 SelectionDAG &DAG) const { 9631 const unsigned NumHalfWords = 8; 9632 const unsigned BytesInVector = NumHalfWords * 2; 9633 // Check that the shuffle is on half-words. 9634 if (!isNByteElemShuffleMask(N, 2, 1)) 9635 return SDValue(); 9636 9637 bool IsLE = Subtarget.isLittleEndian(); 9638 SDLoc dl(N); 9639 SDValue V1 = N->getOperand(0); 9640 SDValue V2 = N->getOperand(1); 9641 unsigned ShiftElts = 0, InsertAtByte = 0; 9642 bool Swap = false; 9643 9644 // Shifts required to get the half-word we want at element 3. 9645 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9646 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9647 9648 uint32_t Mask = 0; 9649 uint32_t OriginalOrderLow = 0x1234567; 9650 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9651 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9652 // 32-bit space, only need 4-bit nibbles per element. 9653 for (unsigned i = 0; i < NumHalfWords; ++i) { 9654 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9655 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9656 } 9657 9658 // For each mask element, find out if we're just inserting something 9659 // from V2 into V1 or vice versa. Possible permutations inserting an element 9660 // from V2 into V1: 9661 // X, 1, 2, 3, 4, 5, 6, 7 9662 // 0, X, 2, 3, 4, 5, 6, 7 9663 // 0, 1, X, 3, 4, 5, 6, 7 9664 // 0, 1, 2, X, 4, 5, 6, 7 9665 // 0, 1, 2, 3, X, 5, 6, 7 9666 // 0, 1, 2, 3, 4, X, 6, 7 9667 // 0, 1, 2, 3, 4, 5, X, 7 9668 // 0, 1, 2, 3, 4, 5, 6, X 9669 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9670 9671 bool FoundCandidate = false; 9672 // Go through the mask of half-words to find an element that's being moved 9673 // from one vector to the other. 9674 for (unsigned i = 0; i < NumHalfWords; ++i) { 9675 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9676 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9677 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9678 uint32_t TargetOrder = 0x0; 9679 9680 // If both vector operands for the shuffle are the same vector, the mask 9681 // will contain only elements from the first one and the second one will be 9682 // undef. 9683 if (V2.isUndef()) { 9684 ShiftElts = 0; 9685 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9686 TargetOrder = OriginalOrderLow; 9687 Swap = false; 9688 // Skip if not the correct element or mask of other elements don't equal 9689 // to our expected order. 9690 if (MaskOneElt == VINSERTHSrcElem && 9691 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9692 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9693 FoundCandidate = true; 9694 break; 9695 } 9696 } else { // If both operands are defined. 9697 // Target order is [8,15] if the current mask is between [0,7]. 9698 TargetOrder = 9699 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9700 // Skip if mask of other elements don't equal our expected order. 9701 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9702 // We only need the last 3 bits for the number of shifts. 9703 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9704 : BigEndianShifts[MaskOneElt & 0x7]; 9705 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9706 Swap = MaskOneElt < NumHalfWords; 9707 FoundCandidate = true; 9708 break; 9709 } 9710 } 9711 } 9712 9713 if (!FoundCandidate) 9714 return SDValue(); 9715 9716 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9717 // optionally with VECSHL if shift is required. 9718 if (Swap) 9719 std::swap(V1, V2); 9720 if (V2.isUndef()) 9721 V2 = V1; 9722 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9723 if (ShiftElts) { 9724 // Double ShiftElts because we're left shifting on v16i8 type. 9725 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9726 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9727 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9728 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9729 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9730 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9731 } 9732 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9733 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9734 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9735 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9736 } 9737 9738 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9739 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9740 /// return the default SDValue. 9741 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9742 SelectionDAG &DAG) const { 9743 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9744 // to v16i8. Peek through the bitcasts to get the actual operands. 9745 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9746 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9747 9748 auto ShuffleMask = SVN->getMask(); 9749 SDValue VecShuffle(SVN, 0); 9750 SDLoc DL(SVN); 9751 9752 // Check that we have a four byte shuffle. 9753 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9754 return SDValue(); 9755 9756 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9757 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9758 std::swap(LHS, RHS); 9759 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9760 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9761 } 9762 9763 // Ensure that the RHS is a vector of constants. 9764 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9765 if (!BVN) 9766 return SDValue(); 9767 9768 // Check if RHS is a splat of 4-bytes (or smaller). 9769 APInt APSplatValue, APSplatUndef; 9770 unsigned SplatBitSize; 9771 bool HasAnyUndefs; 9772 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9773 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9774 SplatBitSize > 32) 9775 return SDValue(); 9776 9777 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9778 // The instruction splats a constant C into two words of the source vector 9779 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9780 // Thus we check that the shuffle mask is the equivalent of 9781 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9782 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9783 // within each word are consecutive, so we only need to check the first byte. 9784 SDValue Index; 9785 bool IsLE = Subtarget.isLittleEndian(); 9786 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9787 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9788 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9789 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9790 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9791 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9792 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9793 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9794 else 9795 return SDValue(); 9796 9797 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9798 // for XXSPLTI32DX. 9799 unsigned SplatVal = APSplatValue.getZExtValue(); 9800 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9801 SplatVal |= (SplatVal << SplatBitSize); 9802 9803 SDValue SplatNode = DAG.getNode( 9804 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9805 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9806 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9807 } 9808 9809 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9810 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9811 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9812 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9813 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9814 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9815 assert(Op.getValueType() == MVT::v1i128 && 9816 "Only set v1i128 as custom, other type shouldn't reach here!"); 9817 SDLoc dl(Op); 9818 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9819 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9820 unsigned SHLAmt = N1.getConstantOperandVal(0); 9821 if (SHLAmt % 8 == 0) { 9822 SmallVector<int, 16> Mask(16, 0); 9823 std::iota(Mask.begin(), Mask.end(), 0); 9824 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9825 if (SDValue Shuffle = 9826 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9827 DAG.getUNDEF(MVT::v16i8), Mask)) 9828 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9829 } 9830 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9831 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9832 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9833 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9834 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9835 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9836 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9837 } 9838 9839 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9840 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9841 /// return the code it can be lowered into. Worst case, it can always be 9842 /// lowered into a vperm. 9843 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9844 SelectionDAG &DAG) const { 9845 SDLoc dl(Op); 9846 SDValue V1 = Op.getOperand(0); 9847 SDValue V2 = Op.getOperand(1); 9848 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9849 9850 // Any nodes that were combined in the target-independent combiner prior 9851 // to vector legalization will not be sent to the target combine. Try to 9852 // combine it here. 9853 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9854 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9855 return NewShuffle; 9856 Op = NewShuffle; 9857 SVOp = cast<ShuffleVectorSDNode>(Op); 9858 V1 = Op.getOperand(0); 9859 V2 = Op.getOperand(1); 9860 } 9861 EVT VT = Op.getValueType(); 9862 bool isLittleEndian = Subtarget.isLittleEndian(); 9863 9864 unsigned ShiftElts, InsertAtByte; 9865 bool Swap = false; 9866 9867 // If this is a load-and-splat, we can do that with a single instruction 9868 // in some cases. However if the load has multiple uses, we don't want to 9869 // combine it because that will just produce multiple loads. 9870 bool IsPermutedLoad = false; 9871 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9872 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9873 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9874 InputLoad->hasOneUse()) { 9875 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9876 int SplatIdx = 9877 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9878 9879 // The splat index for permuted loads will be in the left half of the vector 9880 // which is strictly wider than the loaded value by 8 bytes. So we need to 9881 // adjust the splat index to point to the correct address in memory. 9882 if (IsPermutedLoad) { 9883 assert((isLittleEndian || IsFourByte) && 9884 "Unexpected size for permuted load on big endian target"); 9885 SplatIdx += IsFourByte ? 2 : 1; 9886 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9887 "Splat of a value outside of the loaded memory"); 9888 } 9889 9890 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9891 // For 4-byte load-and-splat, we need Power9. 9892 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9893 uint64_t Offset = 0; 9894 if (IsFourByte) 9895 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9896 else 9897 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9898 9899 // If the width of the load is the same as the width of the splat, 9900 // loading with an offset would load the wrong memory. 9901 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9902 Offset = 0; 9903 9904 SDValue BasePtr = LD->getBasePtr(); 9905 if (Offset != 0) 9906 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9907 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9908 SDValue Ops[] = { 9909 LD->getChain(), // Chain 9910 BasePtr, // BasePtr 9911 DAG.getValueType(Op.getValueType()) // VT 9912 }; 9913 SDVTList VTL = 9914 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9915 SDValue LdSplt = 9916 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9917 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9918 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9919 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9920 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9921 return LdSplt; 9922 } 9923 } 9924 if (Subtarget.hasP9Vector() && 9925 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9926 isLittleEndian)) { 9927 if (Swap) 9928 std::swap(V1, V2); 9929 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9930 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9931 if (ShiftElts) { 9932 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9933 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9934 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9935 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9936 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9937 } 9938 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9939 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9940 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9941 } 9942 9943 if (Subtarget.hasPrefixInstrs()) { 9944 SDValue SplatInsertNode; 9945 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9946 return SplatInsertNode; 9947 } 9948 9949 if (Subtarget.hasP9Altivec()) { 9950 SDValue NewISDNode; 9951 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9952 return NewISDNode; 9953 9954 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9955 return NewISDNode; 9956 } 9957 9958 if (Subtarget.hasVSX() && 9959 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9960 if (Swap) 9961 std::swap(V1, V2); 9962 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9963 SDValue Conv2 = 9964 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9965 9966 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9967 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9968 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9969 } 9970 9971 if (Subtarget.hasVSX() && 9972 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9973 if (Swap) 9974 std::swap(V1, V2); 9975 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9976 SDValue Conv2 = 9977 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9978 9979 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9980 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9981 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9982 } 9983 9984 if (Subtarget.hasP9Vector()) { 9985 if (PPC::isXXBRHShuffleMask(SVOp)) { 9986 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9987 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9988 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9989 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9990 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9991 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9992 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9993 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9994 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9995 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9996 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9997 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9998 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9999 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 10000 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 10001 } 10002 } 10003 10004 if (Subtarget.hasVSX()) { 10005 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 10006 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 10007 10008 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10009 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 10010 DAG.getConstant(SplatIdx, dl, MVT::i32)); 10011 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 10012 } 10013 10014 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 10015 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 10016 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 10017 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 10018 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 10019 } 10020 } 10021 10022 // Cases that are handled by instructions that take permute immediates 10023 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 10024 // selected by the instruction selector. 10025 if (V2.isUndef()) { 10026 if (PPC::isSplatShuffleMask(SVOp, 1) || 10027 PPC::isSplatShuffleMask(SVOp, 2) || 10028 PPC::isSplatShuffleMask(SVOp, 4) || 10029 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 10030 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 10031 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 10032 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 10033 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 10034 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 10035 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 10036 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 10037 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 10038 (Subtarget.hasP8Altivec() && ( 10039 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 10040 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 10041 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 10042 return Op; 10043 } 10044 } 10045 10046 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10047 // and produce a fixed permutation. If any of these match, do not lower to 10048 // VPERM. 10049 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10050 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10051 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10052 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10053 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10054 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10055 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10056 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10057 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10058 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10059 (Subtarget.hasP8Altivec() && ( 10060 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10061 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10062 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10063 return Op; 10064 10065 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10066 // perfect shuffle table to emit an optimal matching sequence. 10067 ArrayRef<int> PermMask = SVOp->getMask(); 10068 10069 unsigned PFIndexes[4]; 10070 bool isFourElementShuffle = true; 10071 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 10072 unsigned EltNo = 8; // Start out undef. 10073 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10074 if (PermMask[i*4+j] < 0) 10075 continue; // Undef, ignore it. 10076 10077 unsigned ByteSource = PermMask[i*4+j]; 10078 if ((ByteSource & 3) != j) { 10079 isFourElementShuffle = false; 10080 break; 10081 } 10082 10083 if (EltNo == 8) { 10084 EltNo = ByteSource/4; 10085 } else if (EltNo != ByteSource/4) { 10086 isFourElementShuffle = false; 10087 break; 10088 } 10089 } 10090 PFIndexes[i] = EltNo; 10091 } 10092 10093 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10094 // perfect shuffle vector to determine if it is cost effective to do this as 10095 // discrete instructions, or whether we should use a vperm. 10096 // For now, we skip this for little endian until such time as we have a 10097 // little-endian perfect shuffle table. 10098 if (isFourElementShuffle && !isLittleEndian) { 10099 // Compute the index in the perfect shuffle table. 10100 unsigned PFTableIndex = 10101 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10102 10103 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10104 unsigned Cost = (PFEntry >> 30); 10105 10106 // Determining when to avoid vperm is tricky. Many things affect the cost 10107 // of vperm, particularly how many times the perm mask needs to be computed. 10108 // For example, if the perm mask can be hoisted out of a loop or is already 10109 // used (perhaps because there are multiple permutes with the same shuffle 10110 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10111 // the loop requires an extra register. 10112 // 10113 // As a compromise, we only emit discrete instructions if the shuffle can be 10114 // generated in 3 or fewer operations. When we have loop information 10115 // available, if this block is within a loop, we should avoid using vperm 10116 // for 3-operation perms and use a constant pool load instead. 10117 if (Cost < 3) 10118 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10119 } 10120 10121 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10122 // vector that will get spilled to the constant pool. 10123 if (V2.isUndef()) V2 = V1; 10124 10125 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10126 // that it is in input element units, not in bytes. Convert now. 10127 10128 // For little endian, the order of the input vectors is reversed, and 10129 // the permutation mask is complemented with respect to 31. This is 10130 // necessary to produce proper semantics with the big-endian-biased vperm 10131 // instruction. 10132 EVT EltVT = V1.getValueType().getVectorElementType(); 10133 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10134 10135 SmallVector<SDValue, 16> ResultMask; 10136 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10137 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10138 10139 for (unsigned j = 0; j != BytesPerElement; ++j) 10140 if (isLittleEndian) 10141 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10142 dl, MVT::i32)); 10143 else 10144 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10145 MVT::i32)); 10146 } 10147 10148 ShufflesHandledWithVPERM++; 10149 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10150 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10151 LLVM_DEBUG(SVOp->dump()); 10152 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10153 LLVM_DEBUG(VPermMask.dump()); 10154 10155 if (isLittleEndian) 10156 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10157 V2, V1, VPermMask); 10158 else 10159 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10160 V1, V2, VPermMask); 10161 } 10162 10163 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10164 /// vector comparison. If it is, return true and fill in Opc/isDot with 10165 /// information about the intrinsic. 10166 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10167 bool &isDot, const PPCSubtarget &Subtarget) { 10168 unsigned IntrinsicID = 10169 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10170 CompareOpc = -1; 10171 isDot = false; 10172 switch (IntrinsicID) { 10173 default: 10174 return false; 10175 // Comparison predicates. 10176 case Intrinsic::ppc_altivec_vcmpbfp_p: 10177 CompareOpc = 966; 10178 isDot = true; 10179 break; 10180 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10181 CompareOpc = 198; 10182 isDot = true; 10183 break; 10184 case Intrinsic::ppc_altivec_vcmpequb_p: 10185 CompareOpc = 6; 10186 isDot = true; 10187 break; 10188 case Intrinsic::ppc_altivec_vcmpequh_p: 10189 CompareOpc = 70; 10190 isDot = true; 10191 break; 10192 case Intrinsic::ppc_altivec_vcmpequw_p: 10193 CompareOpc = 134; 10194 isDot = true; 10195 break; 10196 case Intrinsic::ppc_altivec_vcmpequd_p: 10197 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10198 CompareOpc = 199; 10199 isDot = true; 10200 } else 10201 return false; 10202 break; 10203 case Intrinsic::ppc_altivec_vcmpneb_p: 10204 case Intrinsic::ppc_altivec_vcmpneh_p: 10205 case Intrinsic::ppc_altivec_vcmpnew_p: 10206 case Intrinsic::ppc_altivec_vcmpnezb_p: 10207 case Intrinsic::ppc_altivec_vcmpnezh_p: 10208 case Intrinsic::ppc_altivec_vcmpnezw_p: 10209 if (Subtarget.hasP9Altivec()) { 10210 switch (IntrinsicID) { 10211 default: 10212 llvm_unreachable("Unknown comparison intrinsic."); 10213 case Intrinsic::ppc_altivec_vcmpneb_p: 10214 CompareOpc = 7; 10215 break; 10216 case Intrinsic::ppc_altivec_vcmpneh_p: 10217 CompareOpc = 71; 10218 break; 10219 case Intrinsic::ppc_altivec_vcmpnew_p: 10220 CompareOpc = 135; 10221 break; 10222 case Intrinsic::ppc_altivec_vcmpnezb_p: 10223 CompareOpc = 263; 10224 break; 10225 case Intrinsic::ppc_altivec_vcmpnezh_p: 10226 CompareOpc = 327; 10227 break; 10228 case Intrinsic::ppc_altivec_vcmpnezw_p: 10229 CompareOpc = 391; 10230 break; 10231 } 10232 isDot = true; 10233 } else 10234 return false; 10235 break; 10236 case Intrinsic::ppc_altivec_vcmpgefp_p: 10237 CompareOpc = 454; 10238 isDot = true; 10239 break; 10240 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10241 CompareOpc = 710; 10242 isDot = true; 10243 break; 10244 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10245 CompareOpc = 774; 10246 isDot = true; 10247 break; 10248 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10249 CompareOpc = 838; 10250 isDot = true; 10251 break; 10252 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10253 CompareOpc = 902; 10254 isDot = true; 10255 break; 10256 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10257 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10258 CompareOpc = 967; 10259 isDot = true; 10260 } else 10261 return false; 10262 break; 10263 case Intrinsic::ppc_altivec_vcmpgtub_p: 10264 CompareOpc = 518; 10265 isDot = true; 10266 break; 10267 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10268 CompareOpc = 582; 10269 isDot = true; 10270 break; 10271 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10272 CompareOpc = 646; 10273 isDot = true; 10274 break; 10275 case Intrinsic::ppc_altivec_vcmpgtud_p: 10276 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10277 CompareOpc = 711; 10278 isDot = true; 10279 } else 10280 return false; 10281 break; 10282 10283 case Intrinsic::ppc_altivec_vcmpequq: 10284 case Intrinsic::ppc_altivec_vcmpgtsq: 10285 case Intrinsic::ppc_altivec_vcmpgtuq: 10286 if (!Subtarget.isISA3_1()) 10287 return false; 10288 switch (IntrinsicID) { 10289 default: 10290 llvm_unreachable("Unknown comparison intrinsic."); 10291 case Intrinsic::ppc_altivec_vcmpequq: 10292 CompareOpc = 455; 10293 break; 10294 case Intrinsic::ppc_altivec_vcmpgtsq: 10295 CompareOpc = 903; 10296 break; 10297 case Intrinsic::ppc_altivec_vcmpgtuq: 10298 CompareOpc = 647; 10299 break; 10300 } 10301 break; 10302 10303 // VSX predicate comparisons use the same infrastructure 10304 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10305 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10306 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10307 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10308 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10309 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10310 if (Subtarget.hasVSX()) { 10311 switch (IntrinsicID) { 10312 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10313 CompareOpc = 99; 10314 break; 10315 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10316 CompareOpc = 115; 10317 break; 10318 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10319 CompareOpc = 107; 10320 break; 10321 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10322 CompareOpc = 67; 10323 break; 10324 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10325 CompareOpc = 83; 10326 break; 10327 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10328 CompareOpc = 75; 10329 break; 10330 } 10331 isDot = true; 10332 } else 10333 return false; 10334 break; 10335 10336 // Normal Comparisons. 10337 case Intrinsic::ppc_altivec_vcmpbfp: 10338 CompareOpc = 966; 10339 break; 10340 case Intrinsic::ppc_altivec_vcmpeqfp: 10341 CompareOpc = 198; 10342 break; 10343 case Intrinsic::ppc_altivec_vcmpequb: 10344 CompareOpc = 6; 10345 break; 10346 case Intrinsic::ppc_altivec_vcmpequh: 10347 CompareOpc = 70; 10348 break; 10349 case Intrinsic::ppc_altivec_vcmpequw: 10350 CompareOpc = 134; 10351 break; 10352 case Intrinsic::ppc_altivec_vcmpequd: 10353 if (Subtarget.hasP8Altivec()) 10354 CompareOpc = 199; 10355 else 10356 return false; 10357 break; 10358 case Intrinsic::ppc_altivec_vcmpneb: 10359 case Intrinsic::ppc_altivec_vcmpneh: 10360 case Intrinsic::ppc_altivec_vcmpnew: 10361 case Intrinsic::ppc_altivec_vcmpnezb: 10362 case Intrinsic::ppc_altivec_vcmpnezh: 10363 case Intrinsic::ppc_altivec_vcmpnezw: 10364 if (Subtarget.hasP9Altivec()) 10365 switch (IntrinsicID) { 10366 default: 10367 llvm_unreachable("Unknown comparison intrinsic."); 10368 case Intrinsic::ppc_altivec_vcmpneb: 10369 CompareOpc = 7; 10370 break; 10371 case Intrinsic::ppc_altivec_vcmpneh: 10372 CompareOpc = 71; 10373 break; 10374 case Intrinsic::ppc_altivec_vcmpnew: 10375 CompareOpc = 135; 10376 break; 10377 case Intrinsic::ppc_altivec_vcmpnezb: 10378 CompareOpc = 263; 10379 break; 10380 case Intrinsic::ppc_altivec_vcmpnezh: 10381 CompareOpc = 327; 10382 break; 10383 case Intrinsic::ppc_altivec_vcmpnezw: 10384 CompareOpc = 391; 10385 break; 10386 } 10387 else 10388 return false; 10389 break; 10390 case Intrinsic::ppc_altivec_vcmpgefp: 10391 CompareOpc = 454; 10392 break; 10393 case Intrinsic::ppc_altivec_vcmpgtfp: 10394 CompareOpc = 710; 10395 break; 10396 case Intrinsic::ppc_altivec_vcmpgtsb: 10397 CompareOpc = 774; 10398 break; 10399 case Intrinsic::ppc_altivec_vcmpgtsh: 10400 CompareOpc = 838; 10401 break; 10402 case Intrinsic::ppc_altivec_vcmpgtsw: 10403 CompareOpc = 902; 10404 break; 10405 case Intrinsic::ppc_altivec_vcmpgtsd: 10406 if (Subtarget.hasP8Altivec()) 10407 CompareOpc = 967; 10408 else 10409 return false; 10410 break; 10411 case Intrinsic::ppc_altivec_vcmpgtub: 10412 CompareOpc = 518; 10413 break; 10414 case Intrinsic::ppc_altivec_vcmpgtuh: 10415 CompareOpc = 582; 10416 break; 10417 case Intrinsic::ppc_altivec_vcmpgtuw: 10418 CompareOpc = 646; 10419 break; 10420 case Intrinsic::ppc_altivec_vcmpgtud: 10421 if (Subtarget.hasP8Altivec()) 10422 CompareOpc = 711; 10423 else 10424 return false; 10425 break; 10426 case Intrinsic::ppc_altivec_vcmpequq_p: 10427 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10428 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10429 if (!Subtarget.isISA3_1()) 10430 return false; 10431 switch (IntrinsicID) { 10432 default: 10433 llvm_unreachable("Unknown comparison intrinsic."); 10434 case Intrinsic::ppc_altivec_vcmpequq_p: 10435 CompareOpc = 455; 10436 break; 10437 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10438 CompareOpc = 903; 10439 break; 10440 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10441 CompareOpc = 647; 10442 break; 10443 } 10444 isDot = true; 10445 break; 10446 } 10447 return true; 10448 } 10449 10450 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10451 /// lower, do it, otherwise return null. 10452 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10453 SelectionDAG &DAG) const { 10454 unsigned IntrinsicID = 10455 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10456 10457 SDLoc dl(Op); 10458 10459 switch (IntrinsicID) { 10460 case Intrinsic::thread_pointer: 10461 // Reads the thread pointer register, used for __builtin_thread_pointer. 10462 if (Subtarget.isPPC64()) 10463 return DAG.getRegister(PPC::X13, MVT::i64); 10464 return DAG.getRegister(PPC::R2, MVT::i32); 10465 10466 case Intrinsic::ppc_mma_disassemble_acc: 10467 case Intrinsic::ppc_vsx_disassemble_pair: { 10468 int NumVecs = 2; 10469 SDValue WideVec = Op.getOperand(1); 10470 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10471 NumVecs = 4; 10472 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10473 } 10474 SmallVector<SDValue, 4> RetOps; 10475 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10476 SDValue Extract = DAG.getNode( 10477 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10478 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10479 : VecNo, 10480 dl, getPointerTy(DAG.getDataLayout()))); 10481 RetOps.push_back(Extract); 10482 } 10483 return DAG.getMergeValues(RetOps, dl); 10484 } 10485 10486 case Intrinsic::ppc_unpack_longdouble: { 10487 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10488 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) && 10489 "Argument of long double unpack must be 0 or 1!"); 10490 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1), 10491 DAG.getConstant(!!(Idx->getSExtValue()), dl, 10492 Idx->getValueType(0))); 10493 } 10494 10495 case Intrinsic::ppc_compare_exp_lt: 10496 case Intrinsic::ppc_compare_exp_gt: 10497 case Intrinsic::ppc_compare_exp_eq: 10498 case Intrinsic::ppc_compare_exp_uo: { 10499 unsigned Pred; 10500 switch (IntrinsicID) { 10501 case Intrinsic::ppc_compare_exp_lt: 10502 Pred = PPC::PRED_LT; 10503 break; 10504 case Intrinsic::ppc_compare_exp_gt: 10505 Pred = PPC::PRED_GT; 10506 break; 10507 case Intrinsic::ppc_compare_exp_eq: 10508 Pred = PPC::PRED_EQ; 10509 break; 10510 case Intrinsic::ppc_compare_exp_uo: 10511 Pred = PPC::PRED_UN; 10512 break; 10513 } 10514 return SDValue( 10515 DAG.getMachineNode( 10516 PPC::SELECT_CC_I4, dl, MVT::i32, 10517 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32, 10518 Op.getOperand(1), Op.getOperand(2)), 10519 0), 10520 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10521 DAG.getTargetConstant(Pred, dl, MVT::i32)}), 10522 0); 10523 } 10524 case Intrinsic::ppc_test_data_class_d: 10525 case Intrinsic::ppc_test_data_class_f: { 10526 unsigned CmprOpc = PPC::XSTSTDCDP; 10527 if (IntrinsicID == Intrinsic::ppc_test_data_class_f) 10528 CmprOpc = PPC::XSTSTDCSP; 10529 return SDValue( 10530 DAG.getMachineNode( 10531 PPC::SELECT_CC_I4, dl, MVT::i32, 10532 {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2), 10533 Op.getOperand(1)), 10534 0), 10535 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10536 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}), 10537 0); 10538 } 10539 case Intrinsic::ppc_convert_f128_to_ppcf128: 10540 case Intrinsic::ppc_convert_ppcf128_to_f128: { 10541 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128 10542 ? RTLIB::CONVERT_PPCF128_F128 10543 : RTLIB::CONVERT_F128_PPCF128; 10544 MakeLibCallOptions CallOptions; 10545 std::pair<SDValue, SDValue> Result = 10546 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions, 10547 dl, SDValue()); 10548 return Result.first; 10549 } 10550 } 10551 10552 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10553 // opcode number of the comparison. 10554 int CompareOpc; 10555 bool isDot; 10556 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10557 return SDValue(); // Don't custom lower most intrinsics. 10558 10559 // If this is a non-dot comparison, make the VCMP node and we are done. 10560 if (!isDot) { 10561 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10562 Op.getOperand(1), Op.getOperand(2), 10563 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10564 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10565 } 10566 10567 // Create the PPCISD altivec 'dot' comparison node. 10568 SDValue Ops[] = { 10569 Op.getOperand(2), // LHS 10570 Op.getOperand(3), // RHS 10571 DAG.getConstant(CompareOpc, dl, MVT::i32) 10572 }; 10573 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10574 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10575 10576 // Now that we have the comparison, emit a copy from the CR to a GPR. 10577 // This is flagged to the above dot comparison. 10578 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10579 DAG.getRegister(PPC::CR6, MVT::i32), 10580 CompNode.getValue(1)); 10581 10582 // Unpack the result based on how the target uses it. 10583 unsigned BitNo; // Bit # of CR6. 10584 bool InvertBit; // Invert result? 10585 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10586 default: // Can't happen, don't crash on invalid number though. 10587 case 0: // Return the value of the EQ bit of CR6. 10588 BitNo = 0; InvertBit = false; 10589 break; 10590 case 1: // Return the inverted value of the EQ bit of CR6. 10591 BitNo = 0; InvertBit = true; 10592 break; 10593 case 2: // Return the value of the LT bit of CR6. 10594 BitNo = 2; InvertBit = false; 10595 break; 10596 case 3: // Return the inverted value of the LT bit of CR6. 10597 BitNo = 2; InvertBit = true; 10598 break; 10599 } 10600 10601 // Shift the bit into the low position. 10602 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10603 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10604 // Isolate the bit. 10605 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10606 DAG.getConstant(1, dl, MVT::i32)); 10607 10608 // If we are supposed to, toggle the bit. 10609 if (InvertBit) 10610 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10611 DAG.getConstant(1, dl, MVT::i32)); 10612 return Flags; 10613 } 10614 10615 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10616 SelectionDAG &DAG) const { 10617 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10618 // the beginning of the argument list. 10619 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10620 SDLoc DL(Op); 10621 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10622 case Intrinsic::ppc_cfence: { 10623 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10624 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10625 SDValue Val = Op.getOperand(ArgStart + 1); 10626 EVT Ty = Val.getValueType(); 10627 if (Ty == MVT::i128) { 10628 // FIXME: Testing one of two paired registers is sufficient to guarantee 10629 // ordering? 10630 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val); 10631 } 10632 return SDValue( 10633 DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10634 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val), 10635 Op.getOperand(0)), 10636 0); 10637 } 10638 default: 10639 break; 10640 } 10641 return SDValue(); 10642 } 10643 10644 // Lower scalar BSWAP64 to xxbrd. 10645 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10646 SDLoc dl(Op); 10647 if (!Subtarget.isPPC64()) 10648 return Op; 10649 // MTVSRDD 10650 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10651 Op.getOperand(0)); 10652 // XXBRD 10653 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10654 // MFVSRD 10655 int VectorIndex = 0; 10656 if (Subtarget.isLittleEndian()) 10657 VectorIndex = 1; 10658 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10659 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10660 return Op; 10661 } 10662 10663 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10664 // compared to a value that is atomically loaded (atomic loads zero-extend). 10665 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10666 SelectionDAG &DAG) const { 10667 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10668 "Expecting an atomic compare-and-swap here."); 10669 SDLoc dl(Op); 10670 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10671 EVT MemVT = AtomicNode->getMemoryVT(); 10672 if (MemVT.getSizeInBits() >= 32) 10673 return Op; 10674 10675 SDValue CmpOp = Op.getOperand(2); 10676 // If this is already correctly zero-extended, leave it alone. 10677 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10678 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10679 return Op; 10680 10681 // Clear the high bits of the compare operand. 10682 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10683 SDValue NewCmpOp = 10684 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10685 DAG.getConstant(MaskVal, dl, MVT::i32)); 10686 10687 // Replace the existing compare operand with the properly zero-extended one. 10688 SmallVector<SDValue, 4> Ops; 10689 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10690 Ops.push_back(AtomicNode->getOperand(i)); 10691 Ops[2] = NewCmpOp; 10692 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10693 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10694 auto NodeTy = 10695 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10696 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10697 } 10698 10699 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op, 10700 SelectionDAG &DAG) const { 10701 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode()); 10702 EVT MemVT = N->getMemoryVT(); 10703 assert(MemVT.getSimpleVT() == MVT::i128 && 10704 "Expect quadword atomic operations"); 10705 SDLoc dl(N); 10706 unsigned Opc = N->getOpcode(); 10707 switch (Opc) { 10708 case ISD::ATOMIC_LOAD: { 10709 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be 10710 // lowered to ppc instructions by pattern matching instruction selector. 10711 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other); 10712 SmallVector<SDValue, 4> Ops{ 10713 N->getOperand(0), 10714 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)}; 10715 for (int I = 1, E = N->getNumOperands(); I < E; ++I) 10716 Ops.push_back(N->getOperand(I)); 10717 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys, 10718 Ops, MemVT, N->getMemOperand()); 10719 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal); 10720 SDValue ValHi = 10721 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1)); 10722 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi, 10723 DAG.getConstant(64, dl, MVT::i32)); 10724 SDValue Val = 10725 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi}); 10726 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other}, 10727 {Val, LoadedVal.getValue(2)}); 10728 } 10729 case ISD::ATOMIC_STORE: { 10730 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be 10731 // lowered to ppc instructions by pattern matching instruction selector. 10732 SDVTList Tys = DAG.getVTList(MVT::Other); 10733 SmallVector<SDValue, 4> Ops{ 10734 N->getOperand(0), 10735 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)}; 10736 SDValue Val = N->getOperand(2); 10737 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val); 10738 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val, 10739 DAG.getConstant(64, dl, MVT::i32)); 10740 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi); 10741 Ops.push_back(ValLo); 10742 Ops.push_back(ValHi); 10743 Ops.push_back(N->getOperand(1)); 10744 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT, 10745 N->getMemOperand()); 10746 } 10747 default: 10748 llvm_unreachable("Unexpected atomic opcode"); 10749 } 10750 } 10751 10752 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10753 SelectionDAG &DAG) const { 10754 SDLoc dl(Op); 10755 // Create a stack slot that is 16-byte aligned. 10756 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10757 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10758 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10759 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10760 10761 // Store the input value into Value#0 of the stack slot. 10762 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10763 MachinePointerInfo()); 10764 // Load it out. 10765 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10766 } 10767 10768 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10769 SelectionDAG &DAG) const { 10770 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10771 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10772 10773 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10774 10775 EVT VT = Op.getValueType(); 10776 SDLoc dl(Op); 10777 SDValue V1 = Op.getOperand(0); 10778 SDValue V2 = Op.getOperand(1); 10779 10780 if (VT == MVT::v2f64 && C) 10781 return Op; 10782 10783 if (Subtarget.hasP9Vector()) { 10784 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way 10785 // because on P10, it allows this specific insert_vector_elt load pattern to 10786 // utilize the refactored load and store infrastructure in order to exploit 10787 // prefixed loads. 10788 // On targets with inexpensive direct moves (Power9 and up), a 10789 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer 10790 // load since a single precision load will involve conversion to double 10791 // precision on the load followed by another conversion to single precision. 10792 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) && 10793 (isa<LoadSDNode>(V2))) { 10794 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1); 10795 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2); 10796 SDValue InsVecElt = 10797 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector, 10798 BitcastLoad, Op.getOperand(2)); 10799 return DAG.getBitcast(MVT::v4f32, InsVecElt); 10800 } 10801 } 10802 10803 if (Subtarget.isISA3_1()) { 10804 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64()) 10805 return SDValue(); 10806 // On P10, we have legal lowering for constant and variable indices for 10807 // all vectors. 10808 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10809 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64) 10810 return Op; 10811 } 10812 10813 // Before P10, we have legal lowering for constant indices but not for 10814 // variable ones. 10815 if (!C) 10816 return SDValue(); 10817 10818 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10819 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10820 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10821 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10822 unsigned InsertAtElement = C->getZExtValue(); 10823 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10824 if (Subtarget.isLittleEndian()) { 10825 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10826 } 10827 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10828 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10829 } 10830 return Op; 10831 } 10832 10833 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10834 SelectionDAG &DAG) const { 10835 SDLoc dl(Op); 10836 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10837 SDValue LoadChain = LN->getChain(); 10838 SDValue BasePtr = LN->getBasePtr(); 10839 EVT VT = Op.getValueType(); 10840 10841 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10842 return Op; 10843 10844 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10845 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10846 // 2 or 4 vsx registers. 10847 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10848 "Type unsupported without MMA"); 10849 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10850 "Type unsupported without paired vector support"); 10851 Align Alignment = LN->getAlign(); 10852 SmallVector<SDValue, 4> Loads; 10853 SmallVector<SDValue, 4> LoadChains; 10854 unsigned NumVecs = VT.getSizeInBits() / 128; 10855 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10856 SDValue Load = 10857 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10858 LN->getPointerInfo().getWithOffset(Idx * 16), 10859 commonAlignment(Alignment, Idx * 16), 10860 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10861 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10862 DAG.getConstant(16, dl, BasePtr.getValueType())); 10863 Loads.push_back(Load); 10864 LoadChains.push_back(Load.getValue(1)); 10865 } 10866 if (Subtarget.isLittleEndian()) { 10867 std::reverse(Loads.begin(), Loads.end()); 10868 std::reverse(LoadChains.begin(), LoadChains.end()); 10869 } 10870 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10871 SDValue Value = 10872 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10873 dl, VT, Loads); 10874 SDValue RetOps[] = {Value, TF}; 10875 return DAG.getMergeValues(RetOps, dl); 10876 } 10877 10878 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10879 SelectionDAG &DAG) const { 10880 SDLoc dl(Op); 10881 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10882 SDValue StoreChain = SN->getChain(); 10883 SDValue BasePtr = SN->getBasePtr(); 10884 SDValue Value = SN->getValue(); 10885 EVT StoreVT = Value.getValueType(); 10886 10887 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10888 return Op; 10889 10890 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10891 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10892 // underlying registers individually. 10893 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10894 "Type unsupported without MMA"); 10895 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10896 "Type unsupported without paired vector support"); 10897 Align Alignment = SN->getAlign(); 10898 SmallVector<SDValue, 4> Stores; 10899 unsigned NumVecs = 2; 10900 if (StoreVT == MVT::v512i1) { 10901 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10902 NumVecs = 4; 10903 } 10904 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10905 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10906 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10907 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 10908 SDValue Store = 10909 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10910 SN->getPointerInfo().getWithOffset(Idx * 16), 10911 commonAlignment(Alignment, Idx * 16), 10912 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10913 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10914 DAG.getConstant(16, dl, BasePtr.getValueType())); 10915 Stores.push_back(Store); 10916 } 10917 SDValue TF = DAG.getTokenFactor(dl, Stores); 10918 return TF; 10919 } 10920 10921 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10922 SDLoc dl(Op); 10923 if (Op.getValueType() == MVT::v4i32) { 10924 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10925 10926 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10927 // +16 as shift amt. 10928 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10929 SDValue RHSSwap = // = vrlw RHS, 16 10930 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10931 10932 // Shrinkify inputs to v8i16. 10933 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10934 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10935 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10936 10937 // Low parts multiplied together, generating 32-bit results (we ignore the 10938 // top parts). 10939 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10940 LHS, RHS, DAG, dl, MVT::v4i32); 10941 10942 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10943 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10944 // Shift the high parts up 16 bits. 10945 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10946 Neg16, DAG, dl); 10947 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10948 } else if (Op.getValueType() == MVT::v16i8) { 10949 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10950 bool isLittleEndian = Subtarget.isLittleEndian(); 10951 10952 // Multiply the even 8-bit parts, producing 16-bit sums. 10953 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10954 LHS, RHS, DAG, dl, MVT::v8i16); 10955 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10956 10957 // Multiply the odd 8-bit parts, producing 16-bit sums. 10958 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10959 LHS, RHS, DAG, dl, MVT::v8i16); 10960 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10961 10962 // Merge the results together. Because vmuleub and vmuloub are 10963 // instructions with a big-endian bias, we must reverse the 10964 // element numbering and reverse the meaning of "odd" and "even" 10965 // when generating little endian code. 10966 int Ops[16]; 10967 for (unsigned i = 0; i != 8; ++i) { 10968 if (isLittleEndian) { 10969 Ops[i*2 ] = 2*i; 10970 Ops[i*2+1] = 2*i+16; 10971 } else { 10972 Ops[i*2 ] = 2*i+1; 10973 Ops[i*2+1] = 2*i+1+16; 10974 } 10975 } 10976 if (isLittleEndian) 10977 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10978 else 10979 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10980 } else { 10981 llvm_unreachable("Unknown mul to lower!"); 10982 } 10983 } 10984 10985 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10986 bool IsStrict = Op->isStrictFPOpcode(); 10987 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10988 !Subtarget.hasP9Vector()) 10989 return SDValue(); 10990 10991 return Op; 10992 } 10993 10994 // Custom lowering for fpext vf32 to v2f64 10995 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10996 10997 assert(Op.getOpcode() == ISD::FP_EXTEND && 10998 "Should only be called for ISD::FP_EXTEND"); 10999 11000 // FIXME: handle extends from half precision float vectors on P9. 11001 // We only want to custom lower an extend from v2f32 to v2f64. 11002 if (Op.getValueType() != MVT::v2f64 || 11003 Op.getOperand(0).getValueType() != MVT::v2f32) 11004 return SDValue(); 11005 11006 SDLoc dl(Op); 11007 SDValue Op0 = Op.getOperand(0); 11008 11009 switch (Op0.getOpcode()) { 11010 default: 11011 return SDValue(); 11012 case ISD::EXTRACT_SUBVECTOR: { 11013 assert(Op0.getNumOperands() == 2 && 11014 isa<ConstantSDNode>(Op0->getOperand(1)) && 11015 "Node should have 2 operands with second one being a constant!"); 11016 11017 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 11018 return SDValue(); 11019 11020 // Custom lower is only done for high or low doubleword. 11021 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 11022 if (Idx % 2 != 0) 11023 return SDValue(); 11024 11025 // Since input is v4f32, at this point Idx is either 0 or 2. 11026 // Shift to get the doubleword position we want. 11027 int DWord = Idx >> 1; 11028 11029 // High and low word positions are different on little endian. 11030 if (Subtarget.isLittleEndian()) 11031 DWord ^= 0x1; 11032 11033 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 11034 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 11035 } 11036 case ISD::FADD: 11037 case ISD::FMUL: 11038 case ISD::FSUB: { 11039 SDValue NewLoad[2]; 11040 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 11041 // Ensure both input are loads. 11042 SDValue LdOp = Op0.getOperand(i); 11043 if (LdOp.getOpcode() != ISD::LOAD) 11044 return SDValue(); 11045 // Generate new load node. 11046 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 11047 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11048 NewLoad[i] = DAG.getMemIntrinsicNode( 11049 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11050 LD->getMemoryVT(), LD->getMemOperand()); 11051 } 11052 SDValue NewOp = 11053 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 11054 NewLoad[1], Op0.getNode()->getFlags()); 11055 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 11056 DAG.getConstant(0, dl, MVT::i32)); 11057 } 11058 case ISD::LOAD: { 11059 LoadSDNode *LD = cast<LoadSDNode>(Op0); 11060 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11061 SDValue NewLd = DAG.getMemIntrinsicNode( 11062 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11063 LD->getMemoryVT(), LD->getMemOperand()); 11064 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 11065 DAG.getConstant(0, dl, MVT::i32)); 11066 } 11067 } 11068 llvm_unreachable("ERROR:Should return for all cases within swtich."); 11069 } 11070 11071 /// LowerOperation - Provide custom lowering hooks for some operations. 11072 /// 11073 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11074 switch (Op.getOpcode()) { 11075 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 11076 case ISD::FPOW: return lowerPow(Op, DAG); 11077 case ISD::FSIN: return lowerSin(Op, DAG); 11078 case ISD::FCOS: return lowerCos(Op, DAG); 11079 case ISD::FLOG: return lowerLog(Op, DAG); 11080 case ISD::FLOG10: return lowerLog10(Op, DAG); 11081 case ISD::FEXP: return lowerExp(Op, DAG); 11082 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 11083 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 11084 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 11085 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 11086 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 11087 case ISD::STRICT_FSETCC: 11088 case ISD::STRICT_FSETCCS: 11089 case ISD::SETCC: return LowerSETCC(Op, DAG); 11090 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 11091 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 11092 11093 case ISD::INLINEASM: 11094 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG); 11095 // Variable argument lowering. 11096 case ISD::VASTART: return LowerVASTART(Op, DAG); 11097 case ISD::VAARG: return LowerVAARG(Op, DAG); 11098 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 11099 11100 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 11101 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 11102 case ISD::GET_DYNAMIC_AREA_OFFSET: 11103 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 11104 11105 // Exception handling lowering. 11106 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11107 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11108 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11109 11110 case ISD::LOAD: return LowerLOAD(Op, DAG); 11111 case ISD::STORE: return LowerSTORE(Op, DAG); 11112 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11113 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11114 case ISD::STRICT_FP_TO_UINT: 11115 case ISD::STRICT_FP_TO_SINT: 11116 case ISD::FP_TO_UINT: 11117 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11118 case ISD::STRICT_UINT_TO_FP: 11119 case ISD::STRICT_SINT_TO_FP: 11120 case ISD::UINT_TO_FP: 11121 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11122 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 11123 11124 // Lower 64-bit shifts. 11125 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11126 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11127 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11128 11129 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 11130 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 11131 11132 // Vector-related lowering. 11133 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11134 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11135 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11136 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11137 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11138 case ISD::MUL: return LowerMUL(Op, DAG); 11139 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11140 case ISD::STRICT_FP_ROUND: 11141 case ISD::FP_ROUND: 11142 return LowerFP_ROUND(Op, DAG); 11143 case ISD::ROTL: return LowerROTL(Op, DAG); 11144 11145 // For counter-based loop handling. 11146 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11147 11148 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11149 11150 // Frame & Return address. 11151 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11152 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11153 11154 case ISD::INTRINSIC_VOID: 11155 return LowerINTRINSIC_VOID(Op, DAG); 11156 case ISD::BSWAP: 11157 return LowerBSWAP(Op, DAG); 11158 case ISD::ATOMIC_CMP_SWAP: 11159 return LowerATOMIC_CMP_SWAP(Op, DAG); 11160 case ISD::ATOMIC_STORE: 11161 return LowerATOMIC_LOAD_STORE(Op, DAG); 11162 } 11163 } 11164 11165 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11166 SmallVectorImpl<SDValue>&Results, 11167 SelectionDAG &DAG) const { 11168 SDLoc dl(N); 11169 switch (N->getOpcode()) { 11170 default: 11171 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11172 case ISD::ATOMIC_LOAD: { 11173 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG); 11174 Results.push_back(Res); 11175 Results.push_back(Res.getValue(1)); 11176 break; 11177 } 11178 case ISD::READCYCLECOUNTER: { 11179 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11180 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11181 11182 Results.push_back( 11183 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11184 Results.push_back(RTB.getValue(2)); 11185 break; 11186 } 11187 case ISD::INTRINSIC_W_CHAIN: { 11188 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11189 Intrinsic::loop_decrement) 11190 break; 11191 11192 assert(N->getValueType(0) == MVT::i1 && 11193 "Unexpected result type for CTR decrement intrinsic"); 11194 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11195 N->getValueType(0)); 11196 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11197 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11198 N->getOperand(1)); 11199 11200 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11201 Results.push_back(NewInt.getValue(1)); 11202 break; 11203 } 11204 case ISD::INTRINSIC_WO_CHAIN: { 11205 switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) { 11206 case Intrinsic::ppc_pack_longdouble: 11207 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 11208 N->getOperand(2), N->getOperand(1))); 11209 break; 11210 case Intrinsic::ppc_convert_f128_to_ppcf128: 11211 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG)); 11212 break; 11213 } 11214 break; 11215 } 11216 case ISD::VAARG: { 11217 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11218 return; 11219 11220 EVT VT = N->getValueType(0); 11221 11222 if (VT == MVT::i64) { 11223 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11224 11225 Results.push_back(NewNode); 11226 Results.push_back(NewNode.getValue(1)); 11227 } 11228 return; 11229 } 11230 case ISD::STRICT_FP_TO_SINT: 11231 case ISD::STRICT_FP_TO_UINT: 11232 case ISD::FP_TO_SINT: 11233 case ISD::FP_TO_UINT: { 11234 // LowerFP_TO_INT() can only handle f32 and f64. 11235 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11236 MVT::ppcf128) 11237 return; 11238 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl); 11239 Results.push_back(LoweredValue); 11240 if (N->isStrictFPOpcode()) 11241 Results.push_back(LoweredValue.getValue(1)); 11242 return; 11243 } 11244 case ISD::TRUNCATE: { 11245 if (!N->getValueType(0).isVector()) 11246 return; 11247 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11248 if (Lowered) 11249 Results.push_back(Lowered); 11250 return; 11251 } 11252 case ISD::FSHL: 11253 case ISD::FSHR: 11254 // Don't handle funnel shifts here. 11255 return; 11256 case ISD::BITCAST: 11257 // Don't handle bitcast here. 11258 return; 11259 case ISD::FP_EXTEND: 11260 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11261 if (Lowered) 11262 Results.push_back(Lowered); 11263 return; 11264 } 11265 } 11266 11267 //===----------------------------------------------------------------------===// 11268 // Other Lowering Code 11269 //===----------------------------------------------------------------------===// 11270 11271 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) { 11272 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11273 Function *Func = Intrinsic::getDeclaration(M, Id); 11274 return Builder.CreateCall(Func, {}); 11275 } 11276 11277 // The mappings for emitLeading/TrailingFence is taken from 11278 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11279 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11280 Instruction *Inst, 11281 AtomicOrdering Ord) const { 11282 if (Ord == AtomicOrdering::SequentiallyConsistent) 11283 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11284 if (isReleaseOrStronger(Ord)) 11285 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11286 return nullptr; 11287 } 11288 11289 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11290 Instruction *Inst, 11291 AtomicOrdering Ord) const { 11292 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11293 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11294 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11295 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11296 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11297 return Builder.CreateCall( 11298 Intrinsic::getDeclaration( 11299 Builder.GetInsertBlock()->getParent()->getParent(), 11300 Intrinsic::ppc_cfence, {Inst->getType()}), 11301 {Inst}); 11302 // FIXME: Can use isync for rmw operation. 11303 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11304 } 11305 return nullptr; 11306 } 11307 11308 MachineBasicBlock * 11309 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11310 unsigned AtomicSize, 11311 unsigned BinOpcode, 11312 unsigned CmpOpcode, 11313 unsigned CmpPred) const { 11314 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11315 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11316 11317 auto LoadMnemonic = PPC::LDARX; 11318 auto StoreMnemonic = PPC::STDCX; 11319 switch (AtomicSize) { 11320 default: 11321 llvm_unreachable("Unexpected size of atomic entity"); 11322 case 1: 11323 LoadMnemonic = PPC::LBARX; 11324 StoreMnemonic = PPC::STBCX; 11325 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11326 break; 11327 case 2: 11328 LoadMnemonic = PPC::LHARX; 11329 StoreMnemonic = PPC::STHCX; 11330 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11331 break; 11332 case 4: 11333 LoadMnemonic = PPC::LWARX; 11334 StoreMnemonic = PPC::STWCX; 11335 break; 11336 case 8: 11337 LoadMnemonic = PPC::LDARX; 11338 StoreMnemonic = PPC::STDCX; 11339 break; 11340 } 11341 11342 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11343 MachineFunction *F = BB->getParent(); 11344 MachineFunction::iterator It = ++BB->getIterator(); 11345 11346 Register dest = MI.getOperand(0).getReg(); 11347 Register ptrA = MI.getOperand(1).getReg(); 11348 Register ptrB = MI.getOperand(2).getReg(); 11349 Register incr = MI.getOperand(3).getReg(); 11350 DebugLoc dl = MI.getDebugLoc(); 11351 11352 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11353 MachineBasicBlock *loop2MBB = 11354 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11355 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11356 F->insert(It, loopMBB); 11357 if (CmpOpcode) 11358 F->insert(It, loop2MBB); 11359 F->insert(It, exitMBB); 11360 exitMBB->splice(exitMBB->begin(), BB, 11361 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11362 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11363 11364 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11365 Register TmpReg = (!BinOpcode) ? incr : 11366 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11367 : &PPC::GPRCRegClass); 11368 11369 // thisMBB: 11370 // ... 11371 // fallthrough --> loopMBB 11372 BB->addSuccessor(loopMBB); 11373 11374 // loopMBB: 11375 // l[wd]arx dest, ptr 11376 // add r0, dest, incr 11377 // st[wd]cx. r0, ptr 11378 // bne- loopMBB 11379 // fallthrough --> exitMBB 11380 11381 // For max/min... 11382 // loopMBB: 11383 // l[wd]arx dest, ptr 11384 // cmpl?[wd] incr, dest 11385 // bgt exitMBB 11386 // loop2MBB: 11387 // st[wd]cx. dest, ptr 11388 // bne- loopMBB 11389 // fallthrough --> exitMBB 11390 11391 BB = loopMBB; 11392 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11393 .addReg(ptrA).addReg(ptrB); 11394 if (BinOpcode) 11395 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11396 if (CmpOpcode) { 11397 // Signed comparisons of byte or halfword values must be sign-extended. 11398 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11399 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11400 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11401 ExtReg).addReg(dest); 11402 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11403 .addReg(incr).addReg(ExtReg); 11404 } else 11405 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11406 .addReg(incr).addReg(dest); 11407 11408 BuildMI(BB, dl, TII->get(PPC::BCC)) 11409 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11410 BB->addSuccessor(loop2MBB); 11411 BB->addSuccessor(exitMBB); 11412 BB = loop2MBB; 11413 } 11414 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11415 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11416 BuildMI(BB, dl, TII->get(PPC::BCC)) 11417 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11418 BB->addSuccessor(loopMBB); 11419 BB->addSuccessor(exitMBB); 11420 11421 // exitMBB: 11422 // ... 11423 BB = exitMBB; 11424 return BB; 11425 } 11426 11427 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 11428 switch(MI.getOpcode()) { 11429 default: 11430 return false; 11431 case PPC::COPY: 11432 return TII->isSignExtended(MI); 11433 case PPC::LHA: 11434 case PPC::LHA8: 11435 case PPC::LHAU: 11436 case PPC::LHAU8: 11437 case PPC::LHAUX: 11438 case PPC::LHAUX8: 11439 case PPC::LHAX: 11440 case PPC::LHAX8: 11441 case PPC::LWA: 11442 case PPC::LWAUX: 11443 case PPC::LWAX: 11444 case PPC::LWAX_32: 11445 case PPC::LWA_32: 11446 case PPC::PLHA: 11447 case PPC::PLHA8: 11448 case PPC::PLHA8pc: 11449 case PPC::PLHApc: 11450 case PPC::PLWA: 11451 case PPC::PLWA8: 11452 case PPC::PLWA8pc: 11453 case PPC::PLWApc: 11454 case PPC::EXTSB: 11455 case PPC::EXTSB8: 11456 case PPC::EXTSB8_32_64: 11457 case PPC::EXTSB8_rec: 11458 case PPC::EXTSB_rec: 11459 case PPC::EXTSH: 11460 case PPC::EXTSH8: 11461 case PPC::EXTSH8_32_64: 11462 case PPC::EXTSH8_rec: 11463 case PPC::EXTSH_rec: 11464 case PPC::EXTSW: 11465 case PPC::EXTSWSLI: 11466 case PPC::EXTSWSLI_32_64: 11467 case PPC::EXTSWSLI_32_64_rec: 11468 case PPC::EXTSWSLI_rec: 11469 case PPC::EXTSW_32: 11470 case PPC::EXTSW_32_64: 11471 case PPC::EXTSW_32_64_rec: 11472 case PPC::EXTSW_rec: 11473 case PPC::SRAW: 11474 case PPC::SRAWI: 11475 case PPC::SRAWI_rec: 11476 case PPC::SRAW_rec: 11477 return true; 11478 } 11479 return false; 11480 } 11481 11482 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11483 MachineInstr &MI, MachineBasicBlock *BB, 11484 bool is8bit, // operation 11485 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11486 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11487 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 11488 11489 // If this is a signed comparison and the value being compared is not known 11490 // to be sign extended, sign extend it here. 11491 DebugLoc dl = MI.getDebugLoc(); 11492 MachineFunction *F = BB->getParent(); 11493 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11494 Register incr = MI.getOperand(3).getReg(); 11495 bool IsSignExtended = Register::isVirtualRegister(incr) && 11496 isSignExtended(*RegInfo.getVRegDef(incr), TII); 11497 11498 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11499 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11500 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11501 .addReg(MI.getOperand(3).getReg()); 11502 MI.getOperand(3).setReg(ValueReg); 11503 } 11504 // If we support part-word atomic mnemonics, just use them 11505 if (Subtarget.hasPartwordAtomics()) 11506 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11507 CmpPred); 11508 11509 // In 64 bit mode we have to use 64 bits for addresses, even though the 11510 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11511 // registers without caring whether they're 32 or 64, but here we're 11512 // doing actual arithmetic on the addresses. 11513 bool is64bit = Subtarget.isPPC64(); 11514 bool isLittleEndian = Subtarget.isLittleEndian(); 11515 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11516 11517 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11518 MachineFunction::iterator It = ++BB->getIterator(); 11519 11520 Register dest = MI.getOperand(0).getReg(); 11521 Register ptrA = MI.getOperand(1).getReg(); 11522 Register ptrB = MI.getOperand(2).getReg(); 11523 11524 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11525 MachineBasicBlock *loop2MBB = 11526 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11527 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11528 F->insert(It, loopMBB); 11529 if (CmpOpcode) 11530 F->insert(It, loop2MBB); 11531 F->insert(It, exitMBB); 11532 exitMBB->splice(exitMBB->begin(), BB, 11533 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11534 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11535 11536 const TargetRegisterClass *RC = 11537 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11538 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11539 11540 Register PtrReg = RegInfo.createVirtualRegister(RC); 11541 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11542 Register ShiftReg = 11543 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11544 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11545 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11546 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11547 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11548 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11549 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11550 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11551 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11552 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC); 11553 Register Ptr1Reg; 11554 Register TmpReg = 11555 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11556 11557 // thisMBB: 11558 // ... 11559 // fallthrough --> loopMBB 11560 BB->addSuccessor(loopMBB); 11561 11562 // The 4-byte load must be aligned, while a char or short may be 11563 // anywhere in the word. Hence all this nasty bookkeeping code. 11564 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11565 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11566 // xori shift, shift1, 24 [16] 11567 // rlwinm ptr, ptr1, 0, 0, 29 11568 // slw incr2, incr, shift 11569 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11570 // slw mask, mask2, shift 11571 // loopMBB: 11572 // lwarx tmpDest, ptr 11573 // add tmp, tmpDest, incr2 11574 // andc tmp2, tmpDest, mask 11575 // and tmp3, tmp, mask 11576 // or tmp4, tmp3, tmp2 11577 // stwcx. tmp4, ptr 11578 // bne- loopMBB 11579 // fallthrough --> exitMBB 11580 // srw SrwDest, tmpDest, shift 11581 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31 11582 if (ptrA != ZeroReg) { 11583 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11584 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11585 .addReg(ptrA) 11586 .addReg(ptrB); 11587 } else { 11588 Ptr1Reg = ptrB; 11589 } 11590 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11591 // mode. 11592 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11593 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11594 .addImm(3) 11595 .addImm(27) 11596 .addImm(is8bit ? 28 : 27); 11597 if (!isLittleEndian) 11598 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11599 .addReg(Shift1Reg) 11600 .addImm(is8bit ? 24 : 16); 11601 if (is64bit) 11602 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11603 .addReg(Ptr1Reg) 11604 .addImm(0) 11605 .addImm(61); 11606 else 11607 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11608 .addReg(Ptr1Reg) 11609 .addImm(0) 11610 .addImm(0) 11611 .addImm(29); 11612 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11613 if (is8bit) 11614 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11615 else { 11616 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11617 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11618 .addReg(Mask3Reg) 11619 .addImm(65535); 11620 } 11621 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11622 .addReg(Mask2Reg) 11623 .addReg(ShiftReg); 11624 11625 BB = loopMBB; 11626 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11627 .addReg(ZeroReg) 11628 .addReg(PtrReg); 11629 if (BinOpcode) 11630 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11631 .addReg(Incr2Reg) 11632 .addReg(TmpDestReg); 11633 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11634 .addReg(TmpDestReg) 11635 .addReg(MaskReg); 11636 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11637 if (CmpOpcode) { 11638 // For unsigned comparisons, we can directly compare the shifted values. 11639 // For signed comparisons we shift and sign extend. 11640 Register SReg = RegInfo.createVirtualRegister(GPRC); 11641 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11642 .addReg(TmpDestReg) 11643 .addReg(MaskReg); 11644 unsigned ValueReg = SReg; 11645 unsigned CmpReg = Incr2Reg; 11646 if (CmpOpcode == PPC::CMPW) { 11647 ValueReg = RegInfo.createVirtualRegister(GPRC); 11648 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11649 .addReg(SReg) 11650 .addReg(ShiftReg); 11651 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11652 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11653 .addReg(ValueReg); 11654 ValueReg = ValueSReg; 11655 CmpReg = incr; 11656 } 11657 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11658 .addReg(CmpReg) 11659 .addReg(ValueReg); 11660 BuildMI(BB, dl, TII->get(PPC::BCC)) 11661 .addImm(CmpPred) 11662 .addReg(PPC::CR0) 11663 .addMBB(exitMBB); 11664 BB->addSuccessor(loop2MBB); 11665 BB->addSuccessor(exitMBB); 11666 BB = loop2MBB; 11667 } 11668 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11669 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11670 .addReg(Tmp4Reg) 11671 .addReg(ZeroReg) 11672 .addReg(PtrReg); 11673 BuildMI(BB, dl, TII->get(PPC::BCC)) 11674 .addImm(PPC::PRED_NE) 11675 .addReg(PPC::CR0) 11676 .addMBB(loopMBB); 11677 BB->addSuccessor(loopMBB); 11678 BB->addSuccessor(exitMBB); 11679 11680 // exitMBB: 11681 // ... 11682 BB = exitMBB; 11683 // Since the shift amount is not a constant, we need to clear 11684 // the upper bits with a separate RLWINM. 11685 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest) 11686 .addReg(SrwDestReg) 11687 .addImm(0) 11688 .addImm(is8bit ? 24 : 16) 11689 .addImm(31); 11690 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg) 11691 .addReg(TmpDestReg) 11692 .addReg(ShiftReg); 11693 return BB; 11694 } 11695 11696 llvm::MachineBasicBlock * 11697 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11698 MachineBasicBlock *MBB) const { 11699 DebugLoc DL = MI.getDebugLoc(); 11700 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11701 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11702 11703 MachineFunction *MF = MBB->getParent(); 11704 MachineRegisterInfo &MRI = MF->getRegInfo(); 11705 11706 const BasicBlock *BB = MBB->getBasicBlock(); 11707 MachineFunction::iterator I = ++MBB->getIterator(); 11708 11709 Register DstReg = MI.getOperand(0).getReg(); 11710 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11711 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11712 Register mainDstReg = MRI.createVirtualRegister(RC); 11713 Register restoreDstReg = MRI.createVirtualRegister(RC); 11714 11715 MVT PVT = getPointerTy(MF->getDataLayout()); 11716 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11717 "Invalid Pointer Size!"); 11718 // For v = setjmp(buf), we generate 11719 // 11720 // thisMBB: 11721 // SjLjSetup mainMBB 11722 // bl mainMBB 11723 // v_restore = 1 11724 // b sinkMBB 11725 // 11726 // mainMBB: 11727 // buf[LabelOffset] = LR 11728 // v_main = 0 11729 // 11730 // sinkMBB: 11731 // v = phi(main, restore) 11732 // 11733 11734 MachineBasicBlock *thisMBB = MBB; 11735 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11736 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11737 MF->insert(I, mainMBB); 11738 MF->insert(I, sinkMBB); 11739 11740 MachineInstrBuilder MIB; 11741 11742 // Transfer the remainder of BB and its successor edges to sinkMBB. 11743 sinkMBB->splice(sinkMBB->begin(), MBB, 11744 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11745 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11746 11747 // Note that the structure of the jmp_buf used here is not compatible 11748 // with that used by libc, and is not designed to be. Specifically, it 11749 // stores only those 'reserved' registers that LLVM does not otherwise 11750 // understand how to spill. Also, by convention, by the time this 11751 // intrinsic is called, Clang has already stored the frame address in the 11752 // first slot of the buffer and stack address in the third. Following the 11753 // X86 target code, we'll store the jump address in the second slot. We also 11754 // need to save the TOC pointer (R2) to handle jumps between shared 11755 // libraries, and that will be stored in the fourth slot. The thread 11756 // identifier (R13) is not affected. 11757 11758 // thisMBB: 11759 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11760 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11761 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11762 11763 // Prepare IP either in reg. 11764 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11765 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11766 Register BufReg = MI.getOperand(1).getReg(); 11767 11768 if (Subtarget.is64BitELFABI()) { 11769 setUsesTOCBasePtr(*MBB->getParent()); 11770 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11771 .addReg(PPC::X2) 11772 .addImm(TOCOffset) 11773 .addReg(BufReg) 11774 .cloneMemRefs(MI); 11775 } 11776 11777 // Naked functions never have a base pointer, and so we use r1. For all 11778 // other functions, this decision must be delayed until during PEI. 11779 unsigned BaseReg; 11780 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11781 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11782 else 11783 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11784 11785 MIB = BuildMI(*thisMBB, MI, DL, 11786 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11787 .addReg(BaseReg) 11788 .addImm(BPOffset) 11789 .addReg(BufReg) 11790 .cloneMemRefs(MI); 11791 11792 // Setup 11793 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11794 MIB.addRegMask(TRI->getNoPreservedMask()); 11795 11796 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11797 11798 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11799 .addMBB(mainMBB); 11800 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11801 11802 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11803 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11804 11805 // mainMBB: 11806 // mainDstReg = 0 11807 MIB = 11808 BuildMI(mainMBB, DL, 11809 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11810 11811 // Store IP 11812 if (Subtarget.isPPC64()) { 11813 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11814 .addReg(LabelReg) 11815 .addImm(LabelOffset) 11816 .addReg(BufReg); 11817 } else { 11818 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11819 .addReg(LabelReg) 11820 .addImm(LabelOffset) 11821 .addReg(BufReg); 11822 } 11823 MIB.cloneMemRefs(MI); 11824 11825 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11826 mainMBB->addSuccessor(sinkMBB); 11827 11828 // sinkMBB: 11829 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11830 TII->get(PPC::PHI), DstReg) 11831 .addReg(mainDstReg).addMBB(mainMBB) 11832 .addReg(restoreDstReg).addMBB(thisMBB); 11833 11834 MI.eraseFromParent(); 11835 return sinkMBB; 11836 } 11837 11838 MachineBasicBlock * 11839 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11840 MachineBasicBlock *MBB) const { 11841 DebugLoc DL = MI.getDebugLoc(); 11842 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11843 11844 MachineFunction *MF = MBB->getParent(); 11845 MachineRegisterInfo &MRI = MF->getRegInfo(); 11846 11847 MVT PVT = getPointerTy(MF->getDataLayout()); 11848 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11849 "Invalid Pointer Size!"); 11850 11851 const TargetRegisterClass *RC = 11852 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11853 Register Tmp = MRI.createVirtualRegister(RC); 11854 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11855 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11856 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11857 unsigned BP = 11858 (PVT == MVT::i64) 11859 ? PPC::X30 11860 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11861 : PPC::R30); 11862 11863 MachineInstrBuilder MIB; 11864 11865 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11866 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11867 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11868 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11869 11870 Register BufReg = MI.getOperand(0).getReg(); 11871 11872 // Reload FP (the jumped-to function may not have had a 11873 // frame pointer, and if so, then its r31 will be restored 11874 // as necessary). 11875 if (PVT == MVT::i64) { 11876 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11877 .addImm(0) 11878 .addReg(BufReg); 11879 } else { 11880 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11881 .addImm(0) 11882 .addReg(BufReg); 11883 } 11884 MIB.cloneMemRefs(MI); 11885 11886 // Reload IP 11887 if (PVT == MVT::i64) { 11888 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11889 .addImm(LabelOffset) 11890 .addReg(BufReg); 11891 } else { 11892 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11893 .addImm(LabelOffset) 11894 .addReg(BufReg); 11895 } 11896 MIB.cloneMemRefs(MI); 11897 11898 // Reload SP 11899 if (PVT == MVT::i64) { 11900 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11901 .addImm(SPOffset) 11902 .addReg(BufReg); 11903 } else { 11904 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11905 .addImm(SPOffset) 11906 .addReg(BufReg); 11907 } 11908 MIB.cloneMemRefs(MI); 11909 11910 // Reload BP 11911 if (PVT == MVT::i64) { 11912 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11913 .addImm(BPOffset) 11914 .addReg(BufReg); 11915 } else { 11916 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11917 .addImm(BPOffset) 11918 .addReg(BufReg); 11919 } 11920 MIB.cloneMemRefs(MI); 11921 11922 // Reload TOC 11923 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11924 setUsesTOCBasePtr(*MBB->getParent()); 11925 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11926 .addImm(TOCOffset) 11927 .addReg(BufReg) 11928 .cloneMemRefs(MI); 11929 } 11930 11931 // Jump 11932 BuildMI(*MBB, MI, DL, 11933 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11934 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11935 11936 MI.eraseFromParent(); 11937 return MBB; 11938 } 11939 11940 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11941 // If the function specifically requests inline stack probes, emit them. 11942 if (MF.getFunction().hasFnAttribute("probe-stack")) 11943 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11944 "inline-asm"; 11945 return false; 11946 } 11947 11948 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11949 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11950 unsigned StackAlign = TFI->getStackAlignment(); 11951 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11952 "Unexpected stack alignment"); 11953 // The default stack probe size is 4096 if the function has no 11954 // stack-probe-size attribute. 11955 unsigned StackProbeSize = 4096; 11956 const Function &Fn = MF.getFunction(); 11957 if (Fn.hasFnAttribute("stack-probe-size")) 11958 Fn.getFnAttribute("stack-probe-size") 11959 .getValueAsString() 11960 .getAsInteger(0, StackProbeSize); 11961 // Round down to the stack alignment. 11962 StackProbeSize &= ~(StackAlign - 1); 11963 return StackProbeSize ? StackProbeSize : StackAlign; 11964 } 11965 11966 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11967 // into three phases. In the first phase, it uses pseudo instruction 11968 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11969 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11970 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11971 // MaxCallFrameSize so that it can calculate correct data area pointer. 11972 MachineBasicBlock * 11973 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11974 MachineBasicBlock *MBB) const { 11975 const bool isPPC64 = Subtarget.isPPC64(); 11976 MachineFunction *MF = MBB->getParent(); 11977 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11978 DebugLoc DL = MI.getDebugLoc(); 11979 const unsigned ProbeSize = getStackProbeSize(*MF); 11980 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11981 MachineRegisterInfo &MRI = MF->getRegInfo(); 11982 // The CFG of probing stack looks as 11983 // +-----+ 11984 // | MBB | 11985 // +--+--+ 11986 // | 11987 // +----v----+ 11988 // +--->+ TestMBB +---+ 11989 // | +----+----+ | 11990 // | | | 11991 // | +-----v----+ | 11992 // +---+ BlockMBB | | 11993 // +----------+ | 11994 // | 11995 // +---------+ | 11996 // | TailMBB +<--+ 11997 // +---------+ 11998 // In MBB, calculate previous frame pointer and final stack pointer. 11999 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 12000 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 12001 // TailMBB is spliced via \p MI. 12002 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 12003 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 12004 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 12005 12006 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 12007 MF->insert(MBBIter, TestMBB); 12008 MF->insert(MBBIter, BlockMBB); 12009 MF->insert(MBBIter, TailMBB); 12010 12011 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 12012 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12013 12014 Register DstReg = MI.getOperand(0).getReg(); 12015 Register NegSizeReg = MI.getOperand(1).getReg(); 12016 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 12017 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12018 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12019 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12020 12021 // Since value of NegSizeReg might be realigned in prologepilog, insert a 12022 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 12023 // NegSize. 12024 unsigned ProbeOpc; 12025 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 12026 ProbeOpc = 12027 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 12028 else 12029 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 12030 // and NegSizeReg will be allocated in the same phyreg to avoid 12031 // redundant copy when NegSizeReg has only one use which is current MI and 12032 // will be replaced by PREPARE_PROBED_ALLOCA then. 12033 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 12034 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 12035 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 12036 .addDef(ActualNegSizeReg) 12037 .addReg(NegSizeReg) 12038 .add(MI.getOperand(2)) 12039 .add(MI.getOperand(3)); 12040 12041 // Calculate final stack pointer, which equals to SP + ActualNegSize. 12042 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 12043 FinalStackPtr) 12044 .addReg(SPReg) 12045 .addReg(ActualNegSizeReg); 12046 12047 // Materialize a scratch register for update. 12048 int64_t NegProbeSize = -(int64_t)ProbeSize; 12049 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 12050 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12051 if (!isInt<16>(NegProbeSize)) { 12052 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12053 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 12054 .addImm(NegProbeSize >> 16); 12055 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 12056 ScratchReg) 12057 .addReg(TempReg) 12058 .addImm(NegProbeSize & 0xFFFF); 12059 } else 12060 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 12061 .addImm(NegProbeSize); 12062 12063 { 12064 // Probing leading residual part. 12065 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12066 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 12067 .addReg(ActualNegSizeReg) 12068 .addReg(ScratchReg); 12069 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12070 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 12071 .addReg(Div) 12072 .addReg(ScratchReg); 12073 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12074 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 12075 .addReg(Mul) 12076 .addReg(ActualNegSizeReg); 12077 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12078 .addReg(FramePointer) 12079 .addReg(SPReg) 12080 .addReg(NegMod); 12081 } 12082 12083 { 12084 // Remaining part should be multiple of ProbeSize. 12085 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 12086 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 12087 .addReg(SPReg) 12088 .addReg(FinalStackPtr); 12089 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 12090 .addImm(PPC::PRED_EQ) 12091 .addReg(CmpResult) 12092 .addMBB(TailMBB); 12093 TestMBB->addSuccessor(BlockMBB); 12094 TestMBB->addSuccessor(TailMBB); 12095 } 12096 12097 { 12098 // Touch the block. 12099 // |P...|P...|P... 12100 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12101 .addReg(FramePointer) 12102 .addReg(SPReg) 12103 .addReg(ScratchReg); 12104 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 12105 BlockMBB->addSuccessor(TestMBB); 12106 } 12107 12108 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 12109 // DYNAREAOFFSET pseudo instruction to get the future result. 12110 Register MaxCallFrameSizeReg = 12111 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12112 BuildMI(TailMBB, DL, 12113 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 12114 MaxCallFrameSizeReg) 12115 .add(MI.getOperand(2)) 12116 .add(MI.getOperand(3)); 12117 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 12118 .addReg(SPReg) 12119 .addReg(MaxCallFrameSizeReg); 12120 12121 // Splice instructions after MI to TailMBB. 12122 TailMBB->splice(TailMBB->end(), MBB, 12123 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 12124 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 12125 MBB->addSuccessor(TestMBB); 12126 12127 // Delete the pseudo instruction. 12128 MI.eraseFromParent(); 12129 12130 ++NumDynamicAllocaProbed; 12131 return TailMBB; 12132 } 12133 12134 MachineBasicBlock * 12135 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 12136 MachineBasicBlock *BB) const { 12137 if (MI.getOpcode() == TargetOpcode::STACKMAP || 12138 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 12139 if (Subtarget.is64BitELFABI() && 12140 MI.getOpcode() == TargetOpcode::PATCHPOINT && 12141 !Subtarget.isUsingPCRelativeCalls()) { 12142 // Call lowering should have added an r2 operand to indicate a dependence 12143 // on the TOC base pointer value. It can't however, because there is no 12144 // way to mark the dependence as implicit there, and so the stackmap code 12145 // will confuse it with a regular operand. Instead, add the dependence 12146 // here. 12147 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 12148 } 12149 12150 return emitPatchPoint(MI, BB); 12151 } 12152 12153 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 12154 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 12155 return emitEHSjLjSetJmp(MI, BB); 12156 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 12157 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 12158 return emitEHSjLjLongJmp(MI, BB); 12159 } 12160 12161 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12162 12163 // To "insert" these instructions we actually have to insert their 12164 // control-flow patterns. 12165 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12166 MachineFunction::iterator It = ++BB->getIterator(); 12167 12168 MachineFunction *F = BB->getParent(); 12169 MachineRegisterInfo &MRI = F->getRegInfo(); 12170 12171 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12172 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 12173 MI.getOpcode() == PPC::SELECT_I8) { 12174 SmallVector<MachineOperand, 2> Cond; 12175 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12176 MI.getOpcode() == PPC::SELECT_CC_I8) 12177 Cond.push_back(MI.getOperand(4)); 12178 else 12179 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 12180 Cond.push_back(MI.getOperand(1)); 12181 12182 DebugLoc dl = MI.getDebugLoc(); 12183 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 12184 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 12185 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 12186 MI.getOpcode() == PPC::SELECT_CC_F8 || 12187 MI.getOpcode() == PPC::SELECT_CC_F16 || 12188 MI.getOpcode() == PPC::SELECT_CC_VRRC || 12189 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 12190 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 12191 MI.getOpcode() == PPC::SELECT_CC_VSRC || 12192 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 12193 MI.getOpcode() == PPC::SELECT_CC_SPE || 12194 MI.getOpcode() == PPC::SELECT_F4 || 12195 MI.getOpcode() == PPC::SELECT_F8 || 12196 MI.getOpcode() == PPC::SELECT_F16 || 12197 MI.getOpcode() == PPC::SELECT_SPE || 12198 MI.getOpcode() == PPC::SELECT_SPE4 || 12199 MI.getOpcode() == PPC::SELECT_VRRC || 12200 MI.getOpcode() == PPC::SELECT_VSFRC || 12201 MI.getOpcode() == PPC::SELECT_VSSRC || 12202 MI.getOpcode() == PPC::SELECT_VSRC) { 12203 // The incoming instruction knows the destination vreg to set, the 12204 // condition code register to branch on, the true/false values to 12205 // select between, and a branch opcode to use. 12206 12207 // thisMBB: 12208 // ... 12209 // TrueVal = ... 12210 // cmpTY ccX, r1, r2 12211 // bCC copy1MBB 12212 // fallthrough --> copy0MBB 12213 MachineBasicBlock *thisMBB = BB; 12214 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12215 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12216 DebugLoc dl = MI.getDebugLoc(); 12217 F->insert(It, copy0MBB); 12218 F->insert(It, sinkMBB); 12219 12220 // Transfer the remainder of BB and its successor edges to sinkMBB. 12221 sinkMBB->splice(sinkMBB->begin(), BB, 12222 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12223 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12224 12225 // Next, add the true and fallthrough blocks as its successors. 12226 BB->addSuccessor(copy0MBB); 12227 BB->addSuccessor(sinkMBB); 12228 12229 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 12230 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 12231 MI.getOpcode() == PPC::SELECT_F16 || 12232 MI.getOpcode() == PPC::SELECT_SPE4 || 12233 MI.getOpcode() == PPC::SELECT_SPE || 12234 MI.getOpcode() == PPC::SELECT_VRRC || 12235 MI.getOpcode() == PPC::SELECT_VSFRC || 12236 MI.getOpcode() == PPC::SELECT_VSSRC || 12237 MI.getOpcode() == PPC::SELECT_VSRC) { 12238 BuildMI(BB, dl, TII->get(PPC::BC)) 12239 .addReg(MI.getOperand(1).getReg()) 12240 .addMBB(sinkMBB); 12241 } else { 12242 unsigned SelectPred = MI.getOperand(4).getImm(); 12243 BuildMI(BB, dl, TII->get(PPC::BCC)) 12244 .addImm(SelectPred) 12245 .addReg(MI.getOperand(1).getReg()) 12246 .addMBB(sinkMBB); 12247 } 12248 12249 // copy0MBB: 12250 // %FalseValue = ... 12251 // # fallthrough to sinkMBB 12252 BB = copy0MBB; 12253 12254 // Update machine-CFG edges 12255 BB->addSuccessor(sinkMBB); 12256 12257 // sinkMBB: 12258 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12259 // ... 12260 BB = sinkMBB; 12261 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 12262 .addReg(MI.getOperand(3).getReg()) 12263 .addMBB(copy0MBB) 12264 .addReg(MI.getOperand(2).getReg()) 12265 .addMBB(thisMBB); 12266 } else if (MI.getOpcode() == PPC::ReadTB) { 12267 // To read the 64-bit time-base register on a 32-bit target, we read the 12268 // two halves. Should the counter have wrapped while it was being read, we 12269 // need to try again. 12270 // ... 12271 // readLoop: 12272 // mfspr Rx,TBU # load from TBU 12273 // mfspr Ry,TB # load from TB 12274 // mfspr Rz,TBU # load from TBU 12275 // cmpw crX,Rx,Rz # check if 'old'='new' 12276 // bne readLoop # branch if they're not equal 12277 // ... 12278 12279 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 12280 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12281 DebugLoc dl = MI.getDebugLoc(); 12282 F->insert(It, readMBB); 12283 F->insert(It, sinkMBB); 12284 12285 // Transfer the remainder of BB and its successor edges to sinkMBB. 12286 sinkMBB->splice(sinkMBB->begin(), BB, 12287 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12288 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12289 12290 BB->addSuccessor(readMBB); 12291 BB = readMBB; 12292 12293 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12294 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12295 Register LoReg = MI.getOperand(0).getReg(); 12296 Register HiReg = MI.getOperand(1).getReg(); 12297 12298 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12299 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12300 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12301 12302 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12303 12304 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12305 .addReg(HiReg) 12306 .addReg(ReadAgainReg); 12307 BuildMI(BB, dl, TII->get(PPC::BCC)) 12308 .addImm(PPC::PRED_NE) 12309 .addReg(CmpReg) 12310 .addMBB(readMBB); 12311 12312 BB->addSuccessor(readMBB); 12313 BB->addSuccessor(sinkMBB); 12314 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12315 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12316 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12317 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12318 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12319 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12320 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12321 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12322 12323 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12324 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12325 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12326 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12327 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12328 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12329 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12330 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12331 12332 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12333 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12334 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12335 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12336 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12337 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12338 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12339 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12340 12341 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12342 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12343 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12344 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12345 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12346 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12347 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12348 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12349 12350 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12351 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12352 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12353 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12354 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12355 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12356 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12357 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12358 12359 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12360 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12361 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12362 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12363 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12364 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12365 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12366 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12367 12368 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12369 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12370 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12371 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12372 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12373 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12374 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12375 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12376 12377 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12378 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12379 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12380 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12381 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12382 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12383 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12384 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12385 12386 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12387 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12388 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12389 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12390 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12391 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12392 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12393 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12394 12395 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12396 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12397 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12398 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12399 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12400 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12401 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12402 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12403 12404 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12405 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12406 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12407 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12408 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12409 BB = EmitAtomicBinary(MI, BB, 4, 0); 12410 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12411 BB = EmitAtomicBinary(MI, BB, 8, 0); 12412 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12413 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12414 (Subtarget.hasPartwordAtomics() && 12415 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12416 (Subtarget.hasPartwordAtomics() && 12417 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12418 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12419 12420 auto LoadMnemonic = PPC::LDARX; 12421 auto StoreMnemonic = PPC::STDCX; 12422 switch (MI.getOpcode()) { 12423 default: 12424 llvm_unreachable("Compare and swap of unknown size"); 12425 case PPC::ATOMIC_CMP_SWAP_I8: 12426 LoadMnemonic = PPC::LBARX; 12427 StoreMnemonic = PPC::STBCX; 12428 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12429 break; 12430 case PPC::ATOMIC_CMP_SWAP_I16: 12431 LoadMnemonic = PPC::LHARX; 12432 StoreMnemonic = PPC::STHCX; 12433 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12434 break; 12435 case PPC::ATOMIC_CMP_SWAP_I32: 12436 LoadMnemonic = PPC::LWARX; 12437 StoreMnemonic = PPC::STWCX; 12438 break; 12439 case PPC::ATOMIC_CMP_SWAP_I64: 12440 LoadMnemonic = PPC::LDARX; 12441 StoreMnemonic = PPC::STDCX; 12442 break; 12443 } 12444 Register dest = MI.getOperand(0).getReg(); 12445 Register ptrA = MI.getOperand(1).getReg(); 12446 Register ptrB = MI.getOperand(2).getReg(); 12447 Register oldval = MI.getOperand(3).getReg(); 12448 Register newval = MI.getOperand(4).getReg(); 12449 DebugLoc dl = MI.getDebugLoc(); 12450 12451 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12452 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12453 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12454 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12455 F->insert(It, loop1MBB); 12456 F->insert(It, loop2MBB); 12457 F->insert(It, midMBB); 12458 F->insert(It, exitMBB); 12459 exitMBB->splice(exitMBB->begin(), BB, 12460 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12461 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12462 12463 // thisMBB: 12464 // ... 12465 // fallthrough --> loopMBB 12466 BB->addSuccessor(loop1MBB); 12467 12468 // loop1MBB: 12469 // l[bhwd]arx dest, ptr 12470 // cmp[wd] dest, oldval 12471 // bne- midMBB 12472 // loop2MBB: 12473 // st[bhwd]cx. newval, ptr 12474 // bne- loopMBB 12475 // b exitBB 12476 // midMBB: 12477 // st[bhwd]cx. dest, ptr 12478 // exitBB: 12479 BB = loop1MBB; 12480 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12481 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12482 .addReg(oldval) 12483 .addReg(dest); 12484 BuildMI(BB, dl, TII->get(PPC::BCC)) 12485 .addImm(PPC::PRED_NE) 12486 .addReg(PPC::CR0) 12487 .addMBB(midMBB); 12488 BB->addSuccessor(loop2MBB); 12489 BB->addSuccessor(midMBB); 12490 12491 BB = loop2MBB; 12492 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12493 .addReg(newval) 12494 .addReg(ptrA) 12495 .addReg(ptrB); 12496 BuildMI(BB, dl, TII->get(PPC::BCC)) 12497 .addImm(PPC::PRED_NE) 12498 .addReg(PPC::CR0) 12499 .addMBB(loop1MBB); 12500 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12501 BB->addSuccessor(loop1MBB); 12502 BB->addSuccessor(exitMBB); 12503 12504 BB = midMBB; 12505 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12506 .addReg(dest) 12507 .addReg(ptrA) 12508 .addReg(ptrB); 12509 BB->addSuccessor(exitMBB); 12510 12511 // exitMBB: 12512 // ... 12513 BB = exitMBB; 12514 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12515 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12516 // We must use 64-bit registers for addresses when targeting 64-bit, 12517 // since we're actually doing arithmetic on them. Other registers 12518 // can be 32-bit. 12519 bool is64bit = Subtarget.isPPC64(); 12520 bool isLittleEndian = Subtarget.isLittleEndian(); 12521 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12522 12523 Register dest = MI.getOperand(0).getReg(); 12524 Register ptrA = MI.getOperand(1).getReg(); 12525 Register ptrB = MI.getOperand(2).getReg(); 12526 Register oldval = MI.getOperand(3).getReg(); 12527 Register newval = MI.getOperand(4).getReg(); 12528 DebugLoc dl = MI.getDebugLoc(); 12529 12530 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12531 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12532 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12533 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12534 F->insert(It, loop1MBB); 12535 F->insert(It, loop2MBB); 12536 F->insert(It, midMBB); 12537 F->insert(It, exitMBB); 12538 exitMBB->splice(exitMBB->begin(), BB, 12539 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12540 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12541 12542 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12543 const TargetRegisterClass *RC = 12544 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12545 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12546 12547 Register PtrReg = RegInfo.createVirtualRegister(RC); 12548 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12549 Register ShiftReg = 12550 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12551 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12552 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12553 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12554 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12555 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12556 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12557 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12558 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12559 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12560 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12561 Register Ptr1Reg; 12562 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12563 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12564 // thisMBB: 12565 // ... 12566 // fallthrough --> loopMBB 12567 BB->addSuccessor(loop1MBB); 12568 12569 // The 4-byte load must be aligned, while a char or short may be 12570 // anywhere in the word. Hence all this nasty bookkeeping code. 12571 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12572 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12573 // xori shift, shift1, 24 [16] 12574 // rlwinm ptr, ptr1, 0, 0, 29 12575 // slw newval2, newval, shift 12576 // slw oldval2, oldval,shift 12577 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12578 // slw mask, mask2, shift 12579 // and newval3, newval2, mask 12580 // and oldval3, oldval2, mask 12581 // loop1MBB: 12582 // lwarx tmpDest, ptr 12583 // and tmp, tmpDest, mask 12584 // cmpw tmp, oldval3 12585 // bne- midMBB 12586 // loop2MBB: 12587 // andc tmp2, tmpDest, mask 12588 // or tmp4, tmp2, newval3 12589 // stwcx. tmp4, ptr 12590 // bne- loop1MBB 12591 // b exitBB 12592 // midMBB: 12593 // stwcx. tmpDest, ptr 12594 // exitBB: 12595 // srw dest, tmpDest, shift 12596 if (ptrA != ZeroReg) { 12597 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12598 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12599 .addReg(ptrA) 12600 .addReg(ptrB); 12601 } else { 12602 Ptr1Reg = ptrB; 12603 } 12604 12605 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12606 // mode. 12607 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12608 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12609 .addImm(3) 12610 .addImm(27) 12611 .addImm(is8bit ? 28 : 27); 12612 if (!isLittleEndian) 12613 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12614 .addReg(Shift1Reg) 12615 .addImm(is8bit ? 24 : 16); 12616 if (is64bit) 12617 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12618 .addReg(Ptr1Reg) 12619 .addImm(0) 12620 .addImm(61); 12621 else 12622 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12623 .addReg(Ptr1Reg) 12624 .addImm(0) 12625 .addImm(0) 12626 .addImm(29); 12627 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12628 .addReg(newval) 12629 .addReg(ShiftReg); 12630 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12631 .addReg(oldval) 12632 .addReg(ShiftReg); 12633 if (is8bit) 12634 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12635 else { 12636 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12637 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12638 .addReg(Mask3Reg) 12639 .addImm(65535); 12640 } 12641 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12642 .addReg(Mask2Reg) 12643 .addReg(ShiftReg); 12644 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12645 .addReg(NewVal2Reg) 12646 .addReg(MaskReg); 12647 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12648 .addReg(OldVal2Reg) 12649 .addReg(MaskReg); 12650 12651 BB = loop1MBB; 12652 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12653 .addReg(ZeroReg) 12654 .addReg(PtrReg); 12655 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12656 .addReg(TmpDestReg) 12657 .addReg(MaskReg); 12658 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12659 .addReg(TmpReg) 12660 .addReg(OldVal3Reg); 12661 BuildMI(BB, dl, TII->get(PPC::BCC)) 12662 .addImm(PPC::PRED_NE) 12663 .addReg(PPC::CR0) 12664 .addMBB(midMBB); 12665 BB->addSuccessor(loop2MBB); 12666 BB->addSuccessor(midMBB); 12667 12668 BB = loop2MBB; 12669 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12670 .addReg(TmpDestReg) 12671 .addReg(MaskReg); 12672 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12673 .addReg(Tmp2Reg) 12674 .addReg(NewVal3Reg); 12675 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12676 .addReg(Tmp4Reg) 12677 .addReg(ZeroReg) 12678 .addReg(PtrReg); 12679 BuildMI(BB, dl, TII->get(PPC::BCC)) 12680 .addImm(PPC::PRED_NE) 12681 .addReg(PPC::CR0) 12682 .addMBB(loop1MBB); 12683 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12684 BB->addSuccessor(loop1MBB); 12685 BB->addSuccessor(exitMBB); 12686 12687 BB = midMBB; 12688 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12689 .addReg(TmpDestReg) 12690 .addReg(ZeroReg) 12691 .addReg(PtrReg); 12692 BB->addSuccessor(exitMBB); 12693 12694 // exitMBB: 12695 // ... 12696 BB = exitMBB; 12697 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12698 .addReg(TmpReg) 12699 .addReg(ShiftReg); 12700 } else if (MI.getOpcode() == PPC::FADDrtz) { 12701 // This pseudo performs an FADD with rounding mode temporarily forced 12702 // to round-to-zero. We emit this via custom inserter since the FPSCR 12703 // is not modeled at the SelectionDAG level. 12704 Register Dest = MI.getOperand(0).getReg(); 12705 Register Src1 = MI.getOperand(1).getReg(); 12706 Register Src2 = MI.getOperand(2).getReg(); 12707 DebugLoc dl = MI.getDebugLoc(); 12708 12709 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12710 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12711 12712 // Save FPSCR value. 12713 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12714 12715 // Set rounding mode to round-to-zero. 12716 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12717 .addImm(31) 12718 .addReg(PPC::RM, RegState::ImplicitDefine); 12719 12720 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12721 .addImm(30) 12722 .addReg(PPC::RM, RegState::ImplicitDefine); 12723 12724 // Perform addition. 12725 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12726 .addReg(Src1) 12727 .addReg(Src2); 12728 if (MI.getFlag(MachineInstr::NoFPExcept)) 12729 MIB.setMIFlag(MachineInstr::NoFPExcept); 12730 12731 // Restore FPSCR value. 12732 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12733 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12734 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12735 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12736 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12737 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12738 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12739 ? PPC::ANDI8_rec 12740 : PPC::ANDI_rec; 12741 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12742 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12743 12744 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12745 Register Dest = RegInfo.createVirtualRegister( 12746 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12747 12748 DebugLoc Dl = MI.getDebugLoc(); 12749 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12750 .addReg(MI.getOperand(1).getReg()) 12751 .addImm(1); 12752 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12753 MI.getOperand(0).getReg()) 12754 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12755 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12756 DebugLoc Dl = MI.getDebugLoc(); 12757 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12758 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12759 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12760 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12761 MI.getOperand(0).getReg()) 12762 .addReg(CRReg); 12763 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12764 DebugLoc Dl = MI.getDebugLoc(); 12765 unsigned Imm = MI.getOperand(1).getImm(); 12766 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12767 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12768 MI.getOperand(0).getReg()) 12769 .addReg(PPC::CR0EQ); 12770 } else if (MI.getOpcode() == PPC::SETRNDi) { 12771 DebugLoc dl = MI.getDebugLoc(); 12772 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12773 12774 // Save FPSCR value. 12775 if (MRI.use_empty(OldFPSCRReg)) 12776 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 12777 else 12778 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12779 12780 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12781 // the following settings: 12782 // 00 Round to nearest 12783 // 01 Round to 0 12784 // 10 Round to +inf 12785 // 11 Round to -inf 12786 12787 // When the operand is immediate, using the two least significant bits of 12788 // the immediate to set the bits 62:63 of FPSCR. 12789 unsigned Mode = MI.getOperand(1).getImm(); 12790 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12791 .addImm(31) 12792 .addReg(PPC::RM, RegState::ImplicitDefine); 12793 12794 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12795 .addImm(30) 12796 .addReg(PPC::RM, RegState::ImplicitDefine); 12797 } else if (MI.getOpcode() == PPC::SETRND) { 12798 DebugLoc dl = MI.getDebugLoc(); 12799 12800 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12801 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12802 // If the target doesn't have DirectMove, we should use stack to do the 12803 // conversion, because the target doesn't have the instructions like mtvsrd 12804 // or mfvsrd to do this conversion directly. 12805 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12806 if (Subtarget.hasDirectMove()) { 12807 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12808 .addReg(SrcReg); 12809 } else { 12810 // Use stack to do the register copy. 12811 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12812 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12813 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12814 if (RC == &PPC::F8RCRegClass) { 12815 // Copy register from F8RCRegClass to G8RCRegclass. 12816 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12817 "Unsupported RegClass."); 12818 12819 StoreOp = PPC::STFD; 12820 LoadOp = PPC::LD; 12821 } else { 12822 // Copy register from G8RCRegClass to F8RCRegclass. 12823 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12824 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12825 "Unsupported RegClass."); 12826 } 12827 12828 MachineFrameInfo &MFI = F->getFrameInfo(); 12829 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12830 12831 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12832 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12833 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12834 MFI.getObjectAlign(FrameIdx)); 12835 12836 // Store the SrcReg into the stack. 12837 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12838 .addReg(SrcReg) 12839 .addImm(0) 12840 .addFrameIndex(FrameIdx) 12841 .addMemOperand(MMOStore); 12842 12843 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12844 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12845 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12846 MFI.getObjectAlign(FrameIdx)); 12847 12848 // Load from the stack where SrcReg is stored, and save to DestReg, 12849 // so we have done the RegClass conversion from RegClass::SrcReg to 12850 // RegClass::DestReg. 12851 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12852 .addImm(0) 12853 .addFrameIndex(FrameIdx) 12854 .addMemOperand(MMOLoad); 12855 } 12856 }; 12857 12858 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12859 12860 // Save FPSCR value. 12861 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12862 12863 // When the operand is gprc register, use two least significant bits of the 12864 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12865 // 12866 // copy OldFPSCRTmpReg, OldFPSCRReg 12867 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12868 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12869 // copy NewFPSCRReg, NewFPSCRTmpReg 12870 // mtfsf 255, NewFPSCRReg 12871 MachineOperand SrcOp = MI.getOperand(1); 12872 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12873 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12874 12875 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12876 12877 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12878 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12879 12880 // The first operand of INSERT_SUBREG should be a register which has 12881 // subregisters, we only care about its RegClass, so we should use an 12882 // IMPLICIT_DEF register. 12883 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12884 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12885 .addReg(ImDefReg) 12886 .add(SrcOp) 12887 .addImm(1); 12888 12889 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12890 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12891 .addReg(OldFPSCRTmpReg) 12892 .addReg(ExtSrcReg) 12893 .addImm(0) 12894 .addImm(62); 12895 12896 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12897 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12898 12899 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12900 // bits of FPSCR. 12901 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12902 .addImm(255) 12903 .addReg(NewFPSCRReg) 12904 .addImm(0) 12905 .addImm(0); 12906 } else if (MI.getOpcode() == PPC::SETFLM) { 12907 DebugLoc Dl = MI.getDebugLoc(); 12908 12909 // Result of setflm is previous FPSCR content, so we need to save it first. 12910 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12911 if (MRI.use_empty(OldFPSCRReg)) 12912 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 12913 else 12914 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12915 12916 // Put bits in 32:63 to FPSCR. 12917 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12918 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12919 .addImm(255) 12920 .addReg(NewFPSCRReg) 12921 .addImm(0) 12922 .addImm(0); 12923 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12924 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12925 return emitProbedAlloca(MI, BB); 12926 } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) { 12927 DebugLoc DL = MI.getDebugLoc(); 12928 Register Src = MI.getOperand(2).getReg(); 12929 Register Lo = MI.getOperand(0).getReg(); 12930 Register Hi = MI.getOperand(1).getReg(); 12931 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 12932 .addDef(Lo) 12933 .addUse(Src, 0, PPC::sub_gp8_x1); 12934 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 12935 .addDef(Hi) 12936 .addUse(Src, 0, PPC::sub_gp8_x0); 12937 } else if (MI.getOpcode() == PPC::LQX_PSEUDO || 12938 MI.getOpcode() == PPC::STQX_PSEUDO) { 12939 DebugLoc DL = MI.getDebugLoc(); 12940 // Ptr is used as the ptr_rc_no_r0 part 12941 // of LQ/STQ's memory operand and adding result of RA and RB, 12942 // so it has to be g8rc_and_g8rc_nox0. 12943 Register Ptr = 12944 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass); 12945 Register Val = MI.getOperand(0).getReg(); 12946 Register RA = MI.getOperand(1).getReg(); 12947 Register RB = MI.getOperand(2).getReg(); 12948 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB); 12949 BuildMI(*BB, MI, DL, 12950 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ) 12951 : TII->get(PPC::STQ)) 12952 .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0) 12953 .addImm(0) 12954 .addReg(Ptr); 12955 } else { 12956 llvm_unreachable("Unexpected instr type to insert"); 12957 } 12958 12959 MI.eraseFromParent(); // The pseudo instruction is gone now. 12960 return BB; 12961 } 12962 12963 //===----------------------------------------------------------------------===// 12964 // Target Optimization Hooks 12965 //===----------------------------------------------------------------------===// 12966 12967 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12968 // For the estimates, convergence is quadratic, so we essentially double the 12969 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12970 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12971 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12972 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12973 if (VT.getScalarType() == MVT::f64) 12974 RefinementSteps++; 12975 return RefinementSteps; 12976 } 12977 12978 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12979 const DenormalMode &Mode) const { 12980 // We only have VSX Vector Test for software Square Root. 12981 EVT VT = Op.getValueType(); 12982 if (!isTypeLegal(MVT::i1) || 12983 (VT != MVT::f64 && 12984 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12985 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 12986 12987 SDLoc DL(Op); 12988 // The output register of FTSQRT is CR field. 12989 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12990 // ftsqrt BF,FRB 12991 // Let e_b be the unbiased exponent of the double-precision 12992 // floating-point operand in register FRB. 12993 // fe_flag is set to 1 if either of the following conditions occurs. 12994 // - The double-precision floating-point operand in register FRB is a zero, 12995 // a NaN, or an infinity, or a negative value. 12996 // - e_b is less than or equal to -970. 12997 // Otherwise fe_flag is set to 0. 12998 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 12999 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 13000 // exponent is less than -970) 13001 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 13002 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 13003 FTSQRT, SRIdxVal), 13004 0); 13005 } 13006 13007 SDValue 13008 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 13009 SelectionDAG &DAG) const { 13010 // We only have VSX Vector Square Root. 13011 EVT VT = Op.getValueType(); 13012 if (VT != MVT::f64 && 13013 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 13014 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 13015 13016 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 13017 } 13018 13019 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 13020 int Enabled, int &RefinementSteps, 13021 bool &UseOneConstNR, 13022 bool Reciprocal) const { 13023 EVT VT = Operand.getValueType(); 13024 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 13025 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 13026 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13027 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13028 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13029 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13030 13031 // The Newton-Raphson computation with a single constant does not provide 13032 // enough accuracy on some CPUs. 13033 UseOneConstNR = !Subtarget.needsTwoConstNR(); 13034 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 13035 } 13036 return SDValue(); 13037 } 13038 13039 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 13040 int Enabled, 13041 int &RefinementSteps) const { 13042 EVT VT = Operand.getValueType(); 13043 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 13044 (VT == MVT::f64 && Subtarget.hasFRE()) || 13045 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13046 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13047 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13048 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13049 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 13050 } 13051 return SDValue(); 13052 } 13053 13054 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 13055 // Note: This functionality is used only when unsafe-fp-math is enabled, and 13056 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 13057 // enabled for division), this functionality is redundant with the default 13058 // combiner logic (once the division -> reciprocal/multiply transformation 13059 // has taken place). As a result, this matters more for older cores than for 13060 // newer ones. 13061 13062 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13063 // reciprocal if there are two or more FDIVs (for embedded cores with only 13064 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 13065 switch (Subtarget.getCPUDirective()) { 13066 default: 13067 return 3; 13068 case PPC::DIR_440: 13069 case PPC::DIR_A2: 13070 case PPC::DIR_E500: 13071 case PPC::DIR_E500mc: 13072 case PPC::DIR_E5500: 13073 return 2; 13074 } 13075 } 13076 13077 // isConsecutiveLSLoc needs to work even if all adds have not yet been 13078 // collapsed, and so we need to look through chains of them. 13079 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 13080 int64_t& Offset, SelectionDAG &DAG) { 13081 if (DAG.isBaseWithConstantOffset(Loc)) { 13082 Base = Loc.getOperand(0); 13083 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 13084 13085 // The base might itself be a base plus an offset, and if so, accumulate 13086 // that as well. 13087 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 13088 } 13089 } 13090 13091 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 13092 unsigned Bytes, int Dist, 13093 SelectionDAG &DAG) { 13094 if (VT.getSizeInBits() / 8 != Bytes) 13095 return false; 13096 13097 SDValue BaseLoc = Base->getBasePtr(); 13098 if (Loc.getOpcode() == ISD::FrameIndex) { 13099 if (BaseLoc.getOpcode() != ISD::FrameIndex) 13100 return false; 13101 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 13102 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 13103 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 13104 int FS = MFI.getObjectSize(FI); 13105 int BFS = MFI.getObjectSize(BFI); 13106 if (FS != BFS || FS != (int)Bytes) return false; 13107 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 13108 } 13109 13110 SDValue Base1 = Loc, Base2 = BaseLoc; 13111 int64_t Offset1 = 0, Offset2 = 0; 13112 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 13113 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 13114 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 13115 return true; 13116 13117 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13118 const GlobalValue *GV1 = nullptr; 13119 const GlobalValue *GV2 = nullptr; 13120 Offset1 = 0; 13121 Offset2 = 0; 13122 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 13123 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 13124 if (isGA1 && isGA2 && GV1 == GV2) 13125 return Offset1 == (Offset2 + Dist*Bytes); 13126 return false; 13127 } 13128 13129 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 13130 // not enforce equality of the chain operands. 13131 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 13132 unsigned Bytes, int Dist, 13133 SelectionDAG &DAG) { 13134 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 13135 EVT VT = LS->getMemoryVT(); 13136 SDValue Loc = LS->getBasePtr(); 13137 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 13138 } 13139 13140 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 13141 EVT VT; 13142 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13143 default: return false; 13144 case Intrinsic::ppc_altivec_lvx: 13145 case Intrinsic::ppc_altivec_lvxl: 13146 case Intrinsic::ppc_vsx_lxvw4x: 13147 case Intrinsic::ppc_vsx_lxvw4x_be: 13148 VT = MVT::v4i32; 13149 break; 13150 case Intrinsic::ppc_vsx_lxvd2x: 13151 case Intrinsic::ppc_vsx_lxvd2x_be: 13152 VT = MVT::v2f64; 13153 break; 13154 case Intrinsic::ppc_altivec_lvebx: 13155 VT = MVT::i8; 13156 break; 13157 case Intrinsic::ppc_altivec_lvehx: 13158 VT = MVT::i16; 13159 break; 13160 case Intrinsic::ppc_altivec_lvewx: 13161 VT = MVT::i32; 13162 break; 13163 } 13164 13165 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 13166 } 13167 13168 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 13169 EVT VT; 13170 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13171 default: return false; 13172 case Intrinsic::ppc_altivec_stvx: 13173 case Intrinsic::ppc_altivec_stvxl: 13174 case Intrinsic::ppc_vsx_stxvw4x: 13175 VT = MVT::v4i32; 13176 break; 13177 case Intrinsic::ppc_vsx_stxvd2x: 13178 VT = MVT::v2f64; 13179 break; 13180 case Intrinsic::ppc_vsx_stxvw4x_be: 13181 VT = MVT::v4i32; 13182 break; 13183 case Intrinsic::ppc_vsx_stxvd2x_be: 13184 VT = MVT::v2f64; 13185 break; 13186 case Intrinsic::ppc_altivec_stvebx: 13187 VT = MVT::i8; 13188 break; 13189 case Intrinsic::ppc_altivec_stvehx: 13190 VT = MVT::i16; 13191 break; 13192 case Intrinsic::ppc_altivec_stvewx: 13193 VT = MVT::i32; 13194 break; 13195 } 13196 13197 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 13198 } 13199 13200 return false; 13201 } 13202 13203 // Return true is there is a nearyby consecutive load to the one provided 13204 // (regardless of alignment). We search up and down the chain, looking though 13205 // token factors and other loads (but nothing else). As a result, a true result 13206 // indicates that it is safe to create a new consecutive load adjacent to the 13207 // load provided. 13208 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 13209 SDValue Chain = LD->getChain(); 13210 EVT VT = LD->getMemoryVT(); 13211 13212 SmallSet<SDNode *, 16> LoadRoots; 13213 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 13214 SmallSet<SDNode *, 16> Visited; 13215 13216 // First, search up the chain, branching to follow all token-factor operands. 13217 // If we find a consecutive load, then we're done, otherwise, record all 13218 // nodes just above the top-level loads and token factors. 13219 while (!Queue.empty()) { 13220 SDNode *ChainNext = Queue.pop_back_val(); 13221 if (!Visited.insert(ChainNext).second) 13222 continue; 13223 13224 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 13225 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13226 return true; 13227 13228 if (!Visited.count(ChainLD->getChain().getNode())) 13229 Queue.push_back(ChainLD->getChain().getNode()); 13230 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 13231 for (const SDUse &O : ChainNext->ops()) 13232 if (!Visited.count(O.getNode())) 13233 Queue.push_back(O.getNode()); 13234 } else 13235 LoadRoots.insert(ChainNext); 13236 } 13237 13238 // Second, search down the chain, starting from the top-level nodes recorded 13239 // in the first phase. These top-level nodes are the nodes just above all 13240 // loads and token factors. Starting with their uses, recursively look though 13241 // all loads (just the chain uses) and token factors to find a consecutive 13242 // load. 13243 Visited.clear(); 13244 Queue.clear(); 13245 13246 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 13247 IE = LoadRoots.end(); I != IE; ++I) { 13248 Queue.push_back(*I); 13249 13250 while (!Queue.empty()) { 13251 SDNode *LoadRoot = Queue.pop_back_val(); 13252 if (!Visited.insert(LoadRoot).second) 13253 continue; 13254 13255 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 13256 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13257 return true; 13258 13259 for (SDNode *U : LoadRoot->uses()) 13260 if (((isa<MemSDNode>(U) && 13261 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) || 13262 U->getOpcode() == ISD::TokenFactor) && 13263 !Visited.count(U)) 13264 Queue.push_back(U); 13265 } 13266 } 13267 13268 return false; 13269 } 13270 13271 /// This function is called when we have proved that a SETCC node can be replaced 13272 /// by subtraction (and other supporting instructions) so that the result of 13273 /// comparison is kept in a GPR instead of CR. This function is purely for 13274 /// codegen purposes and has some flags to guide the codegen process. 13275 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 13276 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 13277 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13278 13279 // Zero extend the operands to the largest legal integer. Originally, they 13280 // must be of a strictly smaller size. 13281 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 13282 DAG.getConstant(Size, DL, MVT::i32)); 13283 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 13284 DAG.getConstant(Size, DL, MVT::i32)); 13285 13286 // Swap if needed. Depends on the condition code. 13287 if (Swap) 13288 std::swap(Op0, Op1); 13289 13290 // Subtract extended integers. 13291 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 13292 13293 // Move the sign bit to the least significant position and zero out the rest. 13294 // Now the least significant bit carries the result of original comparison. 13295 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 13296 DAG.getConstant(Size - 1, DL, MVT::i32)); 13297 auto Final = Shifted; 13298 13299 // Complement the result if needed. Based on the condition code. 13300 if (Complement) 13301 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 13302 DAG.getConstant(1, DL, MVT::i64)); 13303 13304 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 13305 } 13306 13307 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 13308 DAGCombinerInfo &DCI) const { 13309 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13310 13311 SelectionDAG &DAG = DCI.DAG; 13312 SDLoc DL(N); 13313 13314 // Size of integers being compared has a critical role in the following 13315 // analysis, so we prefer to do this when all types are legal. 13316 if (!DCI.isAfterLegalizeDAG()) 13317 return SDValue(); 13318 13319 // If all users of SETCC extend its value to a legal integer type 13320 // then we replace SETCC with a subtraction 13321 for (const SDNode *U : N->uses()) 13322 if (U->getOpcode() != ISD::ZERO_EXTEND) 13323 return SDValue(); 13324 13325 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13326 auto OpSize = N->getOperand(0).getValueSizeInBits(); 13327 13328 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 13329 13330 if (OpSize < Size) { 13331 switch (CC) { 13332 default: break; 13333 case ISD::SETULT: 13334 return generateEquivalentSub(N, Size, false, false, DL, DAG); 13335 case ISD::SETULE: 13336 return generateEquivalentSub(N, Size, true, true, DL, DAG); 13337 case ISD::SETUGT: 13338 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13339 case ISD::SETUGE: 13340 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13341 } 13342 } 13343 13344 return SDValue(); 13345 } 13346 13347 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13348 DAGCombinerInfo &DCI) const { 13349 SelectionDAG &DAG = DCI.DAG; 13350 SDLoc dl(N); 13351 13352 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13353 // If we're tracking CR bits, we need to be careful that we don't have: 13354 // trunc(binary-ops(zext(x), zext(y))) 13355 // or 13356 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13357 // such that we're unnecessarily moving things into GPRs when it would be 13358 // better to keep them in CR bits. 13359 13360 // Note that trunc here can be an actual i1 trunc, or can be the effective 13361 // truncation that comes from a setcc or select_cc. 13362 if (N->getOpcode() == ISD::TRUNCATE && 13363 N->getValueType(0) != MVT::i1) 13364 return SDValue(); 13365 13366 if (N->getOperand(0).getValueType() != MVT::i32 && 13367 N->getOperand(0).getValueType() != MVT::i64) 13368 return SDValue(); 13369 13370 if (N->getOpcode() == ISD::SETCC || 13371 N->getOpcode() == ISD::SELECT_CC) { 13372 // If we're looking at a comparison, then we need to make sure that the 13373 // high bits (all except for the first) don't matter the result. 13374 ISD::CondCode CC = 13375 cast<CondCodeSDNode>(N->getOperand( 13376 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13377 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13378 13379 if (ISD::isSignedIntSetCC(CC)) { 13380 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13381 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13382 return SDValue(); 13383 } else if (ISD::isUnsignedIntSetCC(CC)) { 13384 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13385 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13386 !DAG.MaskedValueIsZero(N->getOperand(1), 13387 APInt::getHighBitsSet(OpBits, OpBits-1))) 13388 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13389 : SDValue()); 13390 } else { 13391 // This is neither a signed nor an unsigned comparison, just make sure 13392 // that the high bits are equal. 13393 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13394 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13395 13396 // We don't really care about what is known about the first bit (if 13397 // anything), so pretend that it is known zero for both to ensure they can 13398 // be compared as constants. 13399 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13400 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13401 13402 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13403 Op1Known.getConstant() != Op2Known.getConstant()) 13404 return SDValue(); 13405 } 13406 } 13407 13408 // We now know that the higher-order bits are irrelevant, we just need to 13409 // make sure that all of the intermediate operations are bit operations, and 13410 // all inputs are extensions. 13411 if (N->getOperand(0).getOpcode() != ISD::AND && 13412 N->getOperand(0).getOpcode() != ISD::OR && 13413 N->getOperand(0).getOpcode() != ISD::XOR && 13414 N->getOperand(0).getOpcode() != ISD::SELECT && 13415 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13416 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13417 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13418 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13419 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13420 return SDValue(); 13421 13422 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13423 N->getOperand(1).getOpcode() != ISD::AND && 13424 N->getOperand(1).getOpcode() != ISD::OR && 13425 N->getOperand(1).getOpcode() != ISD::XOR && 13426 N->getOperand(1).getOpcode() != ISD::SELECT && 13427 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13428 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13429 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13430 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13431 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13432 return SDValue(); 13433 13434 SmallVector<SDValue, 4> Inputs; 13435 SmallVector<SDValue, 8> BinOps, PromOps; 13436 SmallPtrSet<SDNode *, 16> Visited; 13437 13438 for (unsigned i = 0; i < 2; ++i) { 13439 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13440 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13441 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13442 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13443 isa<ConstantSDNode>(N->getOperand(i))) 13444 Inputs.push_back(N->getOperand(i)); 13445 else 13446 BinOps.push_back(N->getOperand(i)); 13447 13448 if (N->getOpcode() == ISD::TRUNCATE) 13449 break; 13450 } 13451 13452 // Visit all inputs, collect all binary operations (and, or, xor and 13453 // select) that are all fed by extensions. 13454 while (!BinOps.empty()) { 13455 SDValue BinOp = BinOps.pop_back_val(); 13456 13457 if (!Visited.insert(BinOp.getNode()).second) 13458 continue; 13459 13460 PromOps.push_back(BinOp); 13461 13462 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13463 // The condition of the select is not promoted. 13464 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13465 continue; 13466 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13467 continue; 13468 13469 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13470 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13471 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13472 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13473 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13474 Inputs.push_back(BinOp.getOperand(i)); 13475 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13476 BinOp.getOperand(i).getOpcode() == ISD::OR || 13477 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13478 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13479 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13480 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13481 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13482 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13483 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13484 BinOps.push_back(BinOp.getOperand(i)); 13485 } else { 13486 // We have an input that is not an extension or another binary 13487 // operation; we'll abort this transformation. 13488 return SDValue(); 13489 } 13490 } 13491 } 13492 13493 // Make sure that this is a self-contained cluster of operations (which 13494 // is not quite the same thing as saying that everything has only one 13495 // use). 13496 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13497 if (isa<ConstantSDNode>(Inputs[i])) 13498 continue; 13499 13500 for (const SDNode *User : Inputs[i].getNode()->uses()) { 13501 if (User != N && !Visited.count(User)) 13502 return SDValue(); 13503 13504 // Make sure that we're not going to promote the non-output-value 13505 // operand(s) or SELECT or SELECT_CC. 13506 // FIXME: Although we could sometimes handle this, and it does occur in 13507 // practice that one of the condition inputs to the select is also one of 13508 // the outputs, we currently can't deal with this. 13509 if (User->getOpcode() == ISD::SELECT) { 13510 if (User->getOperand(0) == Inputs[i]) 13511 return SDValue(); 13512 } else if (User->getOpcode() == ISD::SELECT_CC) { 13513 if (User->getOperand(0) == Inputs[i] || 13514 User->getOperand(1) == Inputs[i]) 13515 return SDValue(); 13516 } 13517 } 13518 } 13519 13520 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13521 for (const SDNode *User : PromOps[i].getNode()->uses()) { 13522 if (User != N && !Visited.count(User)) 13523 return SDValue(); 13524 13525 // Make sure that we're not going to promote the non-output-value 13526 // operand(s) or SELECT or SELECT_CC. 13527 // FIXME: Although we could sometimes handle this, and it does occur in 13528 // practice that one of the condition inputs to the select is also one of 13529 // the outputs, we currently can't deal with this. 13530 if (User->getOpcode() == ISD::SELECT) { 13531 if (User->getOperand(0) == PromOps[i]) 13532 return SDValue(); 13533 } else if (User->getOpcode() == ISD::SELECT_CC) { 13534 if (User->getOperand(0) == PromOps[i] || 13535 User->getOperand(1) == PromOps[i]) 13536 return SDValue(); 13537 } 13538 } 13539 } 13540 13541 // Replace all inputs with the extension operand. 13542 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13543 // Constants may have users outside the cluster of to-be-promoted nodes, 13544 // and so we need to replace those as we do the promotions. 13545 if (isa<ConstantSDNode>(Inputs[i])) 13546 continue; 13547 else 13548 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13549 } 13550 13551 std::list<HandleSDNode> PromOpHandles; 13552 for (auto &PromOp : PromOps) 13553 PromOpHandles.emplace_back(PromOp); 13554 13555 // Replace all operations (these are all the same, but have a different 13556 // (i1) return type). DAG.getNode will validate that the types of 13557 // a binary operator match, so go through the list in reverse so that 13558 // we've likely promoted both operands first. Any intermediate truncations or 13559 // extensions disappear. 13560 while (!PromOpHandles.empty()) { 13561 SDValue PromOp = PromOpHandles.back().getValue(); 13562 PromOpHandles.pop_back(); 13563 13564 if (PromOp.getOpcode() == ISD::TRUNCATE || 13565 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13566 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13567 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13568 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13569 PromOp.getOperand(0).getValueType() != MVT::i1) { 13570 // The operand is not yet ready (see comment below). 13571 PromOpHandles.emplace_front(PromOp); 13572 continue; 13573 } 13574 13575 SDValue RepValue = PromOp.getOperand(0); 13576 if (isa<ConstantSDNode>(RepValue)) 13577 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13578 13579 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13580 continue; 13581 } 13582 13583 unsigned C; 13584 switch (PromOp.getOpcode()) { 13585 default: C = 0; break; 13586 case ISD::SELECT: C = 1; break; 13587 case ISD::SELECT_CC: C = 2; break; 13588 } 13589 13590 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13591 PromOp.getOperand(C).getValueType() != MVT::i1) || 13592 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13593 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13594 // The to-be-promoted operands of this node have not yet been 13595 // promoted (this should be rare because we're going through the 13596 // list backward, but if one of the operands has several users in 13597 // this cluster of to-be-promoted nodes, it is possible). 13598 PromOpHandles.emplace_front(PromOp); 13599 continue; 13600 } 13601 13602 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13603 PromOp.getNode()->op_end()); 13604 13605 // If there are any constant inputs, make sure they're replaced now. 13606 for (unsigned i = 0; i < 2; ++i) 13607 if (isa<ConstantSDNode>(Ops[C+i])) 13608 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13609 13610 DAG.ReplaceAllUsesOfValueWith(PromOp, 13611 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13612 } 13613 13614 // Now we're left with the initial truncation itself. 13615 if (N->getOpcode() == ISD::TRUNCATE) 13616 return N->getOperand(0); 13617 13618 // Otherwise, this is a comparison. The operands to be compared have just 13619 // changed type (to i1), but everything else is the same. 13620 return SDValue(N, 0); 13621 } 13622 13623 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13624 DAGCombinerInfo &DCI) const { 13625 SelectionDAG &DAG = DCI.DAG; 13626 SDLoc dl(N); 13627 13628 // If we're tracking CR bits, we need to be careful that we don't have: 13629 // zext(binary-ops(trunc(x), trunc(y))) 13630 // or 13631 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13632 // such that we're unnecessarily moving things into CR bits that can more 13633 // efficiently stay in GPRs. Note that if we're not certain that the high 13634 // bits are set as required by the final extension, we still may need to do 13635 // some masking to get the proper behavior. 13636 13637 // This same functionality is important on PPC64 when dealing with 13638 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13639 // the return values of functions. Because it is so similar, it is handled 13640 // here as well. 13641 13642 if (N->getValueType(0) != MVT::i32 && 13643 N->getValueType(0) != MVT::i64) 13644 return SDValue(); 13645 13646 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13647 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13648 return SDValue(); 13649 13650 if (N->getOperand(0).getOpcode() != ISD::AND && 13651 N->getOperand(0).getOpcode() != ISD::OR && 13652 N->getOperand(0).getOpcode() != ISD::XOR && 13653 N->getOperand(0).getOpcode() != ISD::SELECT && 13654 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13655 return SDValue(); 13656 13657 SmallVector<SDValue, 4> Inputs; 13658 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13659 SmallPtrSet<SDNode *, 16> Visited; 13660 13661 // Visit all inputs, collect all binary operations (and, or, xor and 13662 // select) that are all fed by truncations. 13663 while (!BinOps.empty()) { 13664 SDValue BinOp = BinOps.pop_back_val(); 13665 13666 if (!Visited.insert(BinOp.getNode()).second) 13667 continue; 13668 13669 PromOps.push_back(BinOp); 13670 13671 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13672 // The condition of the select is not promoted. 13673 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13674 continue; 13675 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13676 continue; 13677 13678 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13679 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13680 Inputs.push_back(BinOp.getOperand(i)); 13681 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13682 BinOp.getOperand(i).getOpcode() == ISD::OR || 13683 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13684 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13685 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13686 BinOps.push_back(BinOp.getOperand(i)); 13687 } else { 13688 // We have an input that is not a truncation or another binary 13689 // operation; we'll abort this transformation. 13690 return SDValue(); 13691 } 13692 } 13693 } 13694 13695 // The operands of a select that must be truncated when the select is 13696 // promoted because the operand is actually part of the to-be-promoted set. 13697 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13698 13699 // Make sure that this is a self-contained cluster of operations (which 13700 // is not quite the same thing as saying that everything has only one 13701 // use). 13702 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13703 if (isa<ConstantSDNode>(Inputs[i])) 13704 continue; 13705 13706 for (SDNode *User : Inputs[i].getNode()->uses()) { 13707 if (User != N && !Visited.count(User)) 13708 return SDValue(); 13709 13710 // If we're going to promote the non-output-value operand(s) or SELECT or 13711 // SELECT_CC, record them for truncation. 13712 if (User->getOpcode() == ISD::SELECT) { 13713 if (User->getOperand(0) == Inputs[i]) 13714 SelectTruncOp[0].insert(std::make_pair(User, 13715 User->getOperand(0).getValueType())); 13716 } else if (User->getOpcode() == ISD::SELECT_CC) { 13717 if (User->getOperand(0) == Inputs[i]) 13718 SelectTruncOp[0].insert(std::make_pair(User, 13719 User->getOperand(0).getValueType())); 13720 if (User->getOperand(1) == Inputs[i]) 13721 SelectTruncOp[1].insert(std::make_pair(User, 13722 User->getOperand(1).getValueType())); 13723 } 13724 } 13725 } 13726 13727 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13728 for (SDNode *User : PromOps[i].getNode()->uses()) { 13729 if (User != N && !Visited.count(User)) 13730 return SDValue(); 13731 13732 // If we're going to promote the non-output-value operand(s) or SELECT or 13733 // SELECT_CC, record them for truncation. 13734 if (User->getOpcode() == ISD::SELECT) { 13735 if (User->getOperand(0) == PromOps[i]) 13736 SelectTruncOp[0].insert(std::make_pair(User, 13737 User->getOperand(0).getValueType())); 13738 } else if (User->getOpcode() == ISD::SELECT_CC) { 13739 if (User->getOperand(0) == PromOps[i]) 13740 SelectTruncOp[0].insert(std::make_pair(User, 13741 User->getOperand(0).getValueType())); 13742 if (User->getOperand(1) == PromOps[i]) 13743 SelectTruncOp[1].insert(std::make_pair(User, 13744 User->getOperand(1).getValueType())); 13745 } 13746 } 13747 } 13748 13749 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13750 bool ReallyNeedsExt = false; 13751 if (N->getOpcode() != ISD::ANY_EXTEND) { 13752 // If all of the inputs are not already sign/zero extended, then 13753 // we'll still need to do that at the end. 13754 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13755 if (isa<ConstantSDNode>(Inputs[i])) 13756 continue; 13757 13758 unsigned OpBits = 13759 Inputs[i].getOperand(0).getValueSizeInBits(); 13760 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13761 13762 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13763 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13764 APInt::getHighBitsSet(OpBits, 13765 OpBits-PromBits))) || 13766 (N->getOpcode() == ISD::SIGN_EXTEND && 13767 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13768 (OpBits-(PromBits-1)))) { 13769 ReallyNeedsExt = true; 13770 break; 13771 } 13772 } 13773 } 13774 13775 // Replace all inputs, either with the truncation operand, or a 13776 // truncation or extension to the final output type. 13777 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13778 // Constant inputs need to be replaced with the to-be-promoted nodes that 13779 // use them because they might have users outside of the cluster of 13780 // promoted nodes. 13781 if (isa<ConstantSDNode>(Inputs[i])) 13782 continue; 13783 13784 SDValue InSrc = Inputs[i].getOperand(0); 13785 if (Inputs[i].getValueType() == N->getValueType(0)) 13786 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13787 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13788 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13789 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13790 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13791 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13792 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13793 else 13794 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13795 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13796 } 13797 13798 std::list<HandleSDNode> PromOpHandles; 13799 for (auto &PromOp : PromOps) 13800 PromOpHandles.emplace_back(PromOp); 13801 13802 // Replace all operations (these are all the same, but have a different 13803 // (promoted) return type). DAG.getNode will validate that the types of 13804 // a binary operator match, so go through the list in reverse so that 13805 // we've likely promoted both operands first. 13806 while (!PromOpHandles.empty()) { 13807 SDValue PromOp = PromOpHandles.back().getValue(); 13808 PromOpHandles.pop_back(); 13809 13810 unsigned C; 13811 switch (PromOp.getOpcode()) { 13812 default: C = 0; break; 13813 case ISD::SELECT: C = 1; break; 13814 case ISD::SELECT_CC: C = 2; break; 13815 } 13816 13817 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13818 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13819 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13820 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13821 // The to-be-promoted operands of this node have not yet been 13822 // promoted (this should be rare because we're going through the 13823 // list backward, but if one of the operands has several users in 13824 // this cluster of to-be-promoted nodes, it is possible). 13825 PromOpHandles.emplace_front(PromOp); 13826 continue; 13827 } 13828 13829 // For SELECT and SELECT_CC nodes, we do a similar check for any 13830 // to-be-promoted comparison inputs. 13831 if (PromOp.getOpcode() == ISD::SELECT || 13832 PromOp.getOpcode() == ISD::SELECT_CC) { 13833 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13834 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13835 (SelectTruncOp[1].count(PromOp.getNode()) && 13836 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13837 PromOpHandles.emplace_front(PromOp); 13838 continue; 13839 } 13840 } 13841 13842 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13843 PromOp.getNode()->op_end()); 13844 13845 // If this node has constant inputs, then they'll need to be promoted here. 13846 for (unsigned i = 0; i < 2; ++i) { 13847 if (!isa<ConstantSDNode>(Ops[C+i])) 13848 continue; 13849 if (Ops[C+i].getValueType() == N->getValueType(0)) 13850 continue; 13851 13852 if (N->getOpcode() == ISD::SIGN_EXTEND) 13853 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13854 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13855 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13856 else 13857 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13858 } 13859 13860 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13861 // truncate them again to the original value type. 13862 if (PromOp.getOpcode() == ISD::SELECT || 13863 PromOp.getOpcode() == ISD::SELECT_CC) { 13864 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13865 if (SI0 != SelectTruncOp[0].end()) 13866 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13867 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13868 if (SI1 != SelectTruncOp[1].end()) 13869 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13870 } 13871 13872 DAG.ReplaceAllUsesOfValueWith(PromOp, 13873 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13874 } 13875 13876 // Now we're left with the initial extension itself. 13877 if (!ReallyNeedsExt) 13878 return N->getOperand(0); 13879 13880 // To zero extend, just mask off everything except for the first bit (in the 13881 // i1 case). 13882 if (N->getOpcode() == ISD::ZERO_EXTEND) 13883 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13884 DAG.getConstant(APInt::getLowBitsSet( 13885 N->getValueSizeInBits(0), PromBits), 13886 dl, N->getValueType(0))); 13887 13888 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13889 "Invalid extension type"); 13890 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13891 SDValue ShiftCst = 13892 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13893 return DAG.getNode( 13894 ISD::SRA, dl, N->getValueType(0), 13895 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13896 ShiftCst); 13897 } 13898 13899 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13900 DAGCombinerInfo &DCI) const { 13901 assert(N->getOpcode() == ISD::SETCC && 13902 "Should be called with a SETCC node"); 13903 13904 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13905 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13906 SDValue LHS = N->getOperand(0); 13907 SDValue RHS = N->getOperand(1); 13908 13909 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13910 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13911 LHS.hasOneUse()) 13912 std::swap(LHS, RHS); 13913 13914 // x == 0-y --> x+y == 0 13915 // x != 0-y --> x+y != 0 13916 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13917 RHS.hasOneUse()) { 13918 SDLoc DL(N); 13919 SelectionDAG &DAG = DCI.DAG; 13920 EVT VT = N->getValueType(0); 13921 EVT OpVT = LHS.getValueType(); 13922 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13923 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13924 } 13925 } 13926 13927 return DAGCombineTruncBoolExt(N, DCI); 13928 } 13929 13930 // Is this an extending load from an f32 to an f64? 13931 static bool isFPExtLoad(SDValue Op) { 13932 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13933 return LD->getExtensionType() == ISD::EXTLOAD && 13934 Op.getValueType() == MVT::f64; 13935 return false; 13936 } 13937 13938 /// Reduces the number of fp-to-int conversion when building a vector. 13939 /// 13940 /// If this vector is built out of floating to integer conversions, 13941 /// transform it to a vector built out of floating point values followed by a 13942 /// single floating to integer conversion of the vector. 13943 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13944 /// becomes (fptosi (build_vector ($A, $B, ...))) 13945 SDValue PPCTargetLowering:: 13946 combineElementTruncationToVectorTruncation(SDNode *N, 13947 DAGCombinerInfo &DCI) const { 13948 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13949 "Should be called with a BUILD_VECTOR node"); 13950 13951 SelectionDAG &DAG = DCI.DAG; 13952 SDLoc dl(N); 13953 13954 SDValue FirstInput = N->getOperand(0); 13955 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13956 "The input operand must be an fp-to-int conversion."); 13957 13958 // This combine happens after legalization so the fp_to_[su]i nodes are 13959 // already converted to PPCSISD nodes. 13960 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13961 if (FirstConversion == PPCISD::FCTIDZ || 13962 FirstConversion == PPCISD::FCTIDUZ || 13963 FirstConversion == PPCISD::FCTIWZ || 13964 FirstConversion == PPCISD::FCTIWUZ) { 13965 bool IsSplat = true; 13966 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13967 FirstConversion == PPCISD::FCTIWUZ; 13968 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13969 SmallVector<SDValue, 4> Ops; 13970 EVT TargetVT = N->getValueType(0); 13971 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13972 SDValue NextOp = N->getOperand(i); 13973 if (NextOp.getOpcode() != PPCISD::MFVSR) 13974 return SDValue(); 13975 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13976 if (NextConversion != FirstConversion) 13977 return SDValue(); 13978 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13979 // This is not valid if the input was originally double precision. It is 13980 // also not profitable to do unless this is an extending load in which 13981 // case doing this combine will allow us to combine consecutive loads. 13982 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13983 return SDValue(); 13984 if (N->getOperand(i) != FirstInput) 13985 IsSplat = false; 13986 } 13987 13988 // If this is a splat, we leave it as-is since there will be only a single 13989 // fp-to-int conversion followed by a splat of the integer. This is better 13990 // for 32-bit and smaller ints and neutral for 64-bit ints. 13991 if (IsSplat) 13992 return SDValue(); 13993 13994 // Now that we know we have the right type of node, get its operands 13995 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13996 SDValue In = N->getOperand(i).getOperand(0); 13997 if (Is32Bit) { 13998 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13999 // here, we know that all inputs are extending loads so this is safe). 14000 if (In.isUndef()) 14001 Ops.push_back(DAG.getUNDEF(SrcVT)); 14002 else { 14003 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 14004 MVT::f32, In.getOperand(0), 14005 DAG.getIntPtrConstant(1, dl)); 14006 Ops.push_back(Trunc); 14007 } 14008 } else 14009 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 14010 } 14011 14012 unsigned Opcode; 14013 if (FirstConversion == PPCISD::FCTIDZ || 14014 FirstConversion == PPCISD::FCTIWZ) 14015 Opcode = ISD::FP_TO_SINT; 14016 else 14017 Opcode = ISD::FP_TO_UINT; 14018 14019 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 14020 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 14021 return DAG.getNode(Opcode, dl, TargetVT, BV); 14022 } 14023 return SDValue(); 14024 } 14025 14026 /// Reduce the number of loads when building a vector. 14027 /// 14028 /// Building a vector out of multiple loads can be converted to a load 14029 /// of the vector type if the loads are consecutive. If the loads are 14030 /// consecutive but in descending order, a shuffle is added at the end 14031 /// to reorder the vector. 14032 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 14033 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14034 "Should be called with a BUILD_VECTOR node"); 14035 14036 SDLoc dl(N); 14037 14038 // Return early for non byte-sized type, as they can't be consecutive. 14039 if (!N->getValueType(0).getVectorElementType().isByteSized()) 14040 return SDValue(); 14041 14042 bool InputsAreConsecutiveLoads = true; 14043 bool InputsAreReverseConsecutive = true; 14044 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 14045 SDValue FirstInput = N->getOperand(0); 14046 bool IsRoundOfExtLoad = false; 14047 14048 if (FirstInput.getOpcode() == ISD::FP_ROUND && 14049 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 14050 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 14051 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 14052 } 14053 // Not a build vector of (possibly fp_rounded) loads. 14054 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 14055 N->getNumOperands() == 1) 14056 return SDValue(); 14057 14058 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 14059 // If any inputs are fp_round(extload), they all must be. 14060 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 14061 return SDValue(); 14062 14063 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 14064 N->getOperand(i); 14065 if (NextInput.getOpcode() != ISD::LOAD) 14066 return SDValue(); 14067 14068 SDValue PreviousInput = 14069 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 14070 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 14071 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 14072 14073 // If any inputs are fp_round(extload), they all must be. 14074 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 14075 return SDValue(); 14076 14077 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 14078 InputsAreConsecutiveLoads = false; 14079 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 14080 InputsAreReverseConsecutive = false; 14081 14082 // Exit early if the loads are neither consecutive nor reverse consecutive. 14083 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 14084 return SDValue(); 14085 } 14086 14087 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 14088 "The loads cannot be both consecutive and reverse consecutive."); 14089 14090 SDValue FirstLoadOp = 14091 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 14092 SDValue LastLoadOp = 14093 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 14094 N->getOperand(N->getNumOperands()-1); 14095 14096 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 14097 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 14098 if (InputsAreConsecutiveLoads) { 14099 assert(LD1 && "Input needs to be a LoadSDNode."); 14100 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 14101 LD1->getBasePtr(), LD1->getPointerInfo(), 14102 LD1->getAlignment()); 14103 } 14104 if (InputsAreReverseConsecutive) { 14105 assert(LDL && "Input needs to be a LoadSDNode."); 14106 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 14107 LDL->getBasePtr(), LDL->getPointerInfo(), 14108 LDL->getAlignment()); 14109 SmallVector<int, 16> Ops; 14110 for (int i = N->getNumOperands() - 1; i >= 0; i--) 14111 Ops.push_back(i); 14112 14113 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 14114 DAG.getUNDEF(N->getValueType(0)), Ops); 14115 } 14116 return SDValue(); 14117 } 14118 14119 // This function adds the required vector_shuffle needed to get 14120 // the elements of the vector extract in the correct position 14121 // as specified by the CorrectElems encoding. 14122 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 14123 SDValue Input, uint64_t Elems, 14124 uint64_t CorrectElems) { 14125 SDLoc dl(N); 14126 14127 unsigned NumElems = Input.getValueType().getVectorNumElements(); 14128 SmallVector<int, 16> ShuffleMask(NumElems, -1); 14129 14130 // Knowing the element indices being extracted from the original 14131 // vector and the order in which they're being inserted, just put 14132 // them at element indices required for the instruction. 14133 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14134 if (DAG.getDataLayout().isLittleEndian()) 14135 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 14136 else 14137 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 14138 CorrectElems = CorrectElems >> 8; 14139 Elems = Elems >> 8; 14140 } 14141 14142 SDValue Shuffle = 14143 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 14144 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 14145 14146 EVT VT = N->getValueType(0); 14147 SDValue Conv = DAG.getBitcast(VT, Shuffle); 14148 14149 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 14150 Input.getValueType().getVectorElementType(), 14151 VT.getVectorNumElements()); 14152 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 14153 DAG.getValueType(ExtVT)); 14154 } 14155 14156 // Look for build vector patterns where input operands come from sign 14157 // extended vector_extract elements of specific indices. If the correct indices 14158 // aren't used, add a vector shuffle to fix up the indices and create 14159 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 14160 // during instruction selection. 14161 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 14162 // This array encodes the indices that the vector sign extend instructions 14163 // extract from when extending from one type to another for both BE and LE. 14164 // The right nibble of each byte corresponds to the LE incides. 14165 // and the left nibble of each byte corresponds to the BE incides. 14166 // For example: 0x3074B8FC byte->word 14167 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 14168 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 14169 // For example: 0x000070F8 byte->double word 14170 // For LE: the allowed indices are: 0x0,0x8 14171 // For BE: the allowed indices are: 0x7,0xF 14172 uint64_t TargetElems[] = { 14173 0x3074B8FC, // b->w 14174 0x000070F8, // b->d 14175 0x10325476, // h->w 14176 0x00003074, // h->d 14177 0x00001032, // w->d 14178 }; 14179 14180 uint64_t Elems = 0; 14181 int Index; 14182 SDValue Input; 14183 14184 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 14185 if (!Op) 14186 return false; 14187 if (Op.getOpcode() != ISD::SIGN_EXTEND && 14188 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 14189 return false; 14190 14191 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 14192 // of the right width. 14193 SDValue Extract = Op.getOperand(0); 14194 if (Extract.getOpcode() == ISD::ANY_EXTEND) 14195 Extract = Extract.getOperand(0); 14196 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14197 return false; 14198 14199 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 14200 if (!ExtOp) 14201 return false; 14202 14203 Index = ExtOp->getZExtValue(); 14204 if (Input && Input != Extract.getOperand(0)) 14205 return false; 14206 14207 if (!Input) 14208 Input = Extract.getOperand(0); 14209 14210 Elems = Elems << 8; 14211 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 14212 Elems |= Index; 14213 14214 return true; 14215 }; 14216 14217 // If the build vector operands aren't sign extended vector extracts, 14218 // of the same input vector, then return. 14219 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14220 if (!isSExtOfVecExtract(N->getOperand(i))) { 14221 return SDValue(); 14222 } 14223 } 14224 14225 // If the vector extract indicies are not correct, add the appropriate 14226 // vector_shuffle. 14227 int TgtElemArrayIdx; 14228 int InputSize = Input.getValueType().getScalarSizeInBits(); 14229 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 14230 if (InputSize + OutputSize == 40) 14231 TgtElemArrayIdx = 0; 14232 else if (InputSize + OutputSize == 72) 14233 TgtElemArrayIdx = 1; 14234 else if (InputSize + OutputSize == 48) 14235 TgtElemArrayIdx = 2; 14236 else if (InputSize + OutputSize == 80) 14237 TgtElemArrayIdx = 3; 14238 else if (InputSize + OutputSize == 96) 14239 TgtElemArrayIdx = 4; 14240 else 14241 return SDValue(); 14242 14243 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 14244 CorrectElems = DAG.getDataLayout().isLittleEndian() 14245 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 14246 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 14247 if (Elems != CorrectElems) { 14248 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 14249 } 14250 14251 // Regular lowering will catch cases where a shuffle is not needed. 14252 return SDValue(); 14253 } 14254 14255 // Look for the pattern of a load from a narrow width to i128, feeding 14256 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 14257 // (LXVRZX). This node represents a zero extending load that will be matched 14258 // to the Load VSX Vector Rightmost instructions. 14259 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 14260 SDLoc DL(N); 14261 14262 // This combine is only eligible for a BUILD_VECTOR of v1i128. 14263 if (N->getValueType(0) != MVT::v1i128) 14264 return SDValue(); 14265 14266 SDValue Operand = N->getOperand(0); 14267 // Proceed with the transformation if the operand to the BUILD_VECTOR 14268 // is a load instruction. 14269 if (Operand.getOpcode() != ISD::LOAD) 14270 return SDValue(); 14271 14272 auto *LD = cast<LoadSDNode>(Operand); 14273 EVT MemoryType = LD->getMemoryVT(); 14274 14275 // This transformation is only valid if the we are loading either a byte, 14276 // halfword, word, or doubleword. 14277 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 14278 MemoryType == MVT::i32 || MemoryType == MVT::i64; 14279 14280 // Ensure that the load from the narrow width is being zero extended to i128. 14281 if (!ValidLDType || 14282 (LD->getExtensionType() != ISD::ZEXTLOAD && 14283 LD->getExtensionType() != ISD::EXTLOAD)) 14284 return SDValue(); 14285 14286 SDValue LoadOps[] = { 14287 LD->getChain(), LD->getBasePtr(), 14288 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 14289 14290 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 14291 DAG.getVTList(MVT::v1i128, MVT::Other), 14292 LoadOps, MemoryType, LD->getMemOperand()); 14293 } 14294 14295 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 14296 DAGCombinerInfo &DCI) const { 14297 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14298 "Should be called with a BUILD_VECTOR node"); 14299 14300 SelectionDAG &DAG = DCI.DAG; 14301 SDLoc dl(N); 14302 14303 if (!Subtarget.hasVSX()) 14304 return SDValue(); 14305 14306 // The target independent DAG combiner will leave a build_vector of 14307 // float-to-int conversions intact. We can generate MUCH better code for 14308 // a float-to-int conversion of a vector of floats. 14309 SDValue FirstInput = N->getOperand(0); 14310 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 14311 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 14312 if (Reduced) 14313 return Reduced; 14314 } 14315 14316 // If we're building a vector out of consecutive loads, just load that 14317 // vector type. 14318 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 14319 if (Reduced) 14320 return Reduced; 14321 14322 // If we're building a vector out of extended elements from another vector 14323 // we have P9 vector integer extend instructions. The code assumes legal 14324 // input types (i.e. it can't handle things like v4i16) so do not run before 14325 // legalization. 14326 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14327 Reduced = combineBVOfVecSExt(N, DAG); 14328 if (Reduced) 14329 return Reduced; 14330 } 14331 14332 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14333 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14334 // is a load from <valid narrow width> to i128. 14335 if (Subtarget.isISA3_1()) { 14336 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14337 if (BVOfZLoad) 14338 return BVOfZLoad; 14339 } 14340 14341 if (N->getValueType(0) != MVT::v2f64) 14342 return SDValue(); 14343 14344 // Looking for: 14345 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14346 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14347 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14348 return SDValue(); 14349 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14350 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14351 return SDValue(); 14352 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14353 return SDValue(); 14354 14355 SDValue Ext1 = FirstInput.getOperand(0); 14356 SDValue Ext2 = N->getOperand(1).getOperand(0); 14357 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14358 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14359 return SDValue(); 14360 14361 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14362 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14363 if (!Ext1Op || !Ext2Op) 14364 return SDValue(); 14365 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14366 Ext1.getOperand(0) != Ext2.getOperand(0)) 14367 return SDValue(); 14368 14369 int FirstElem = Ext1Op->getZExtValue(); 14370 int SecondElem = Ext2Op->getZExtValue(); 14371 int SubvecIdx; 14372 if (FirstElem == 0 && SecondElem == 1) 14373 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14374 else if (FirstElem == 2 && SecondElem == 3) 14375 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14376 else 14377 return SDValue(); 14378 14379 SDValue SrcVec = Ext1.getOperand(0); 14380 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14381 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14382 return DAG.getNode(NodeType, dl, MVT::v2f64, 14383 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14384 } 14385 14386 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14387 DAGCombinerInfo &DCI) const { 14388 assert((N->getOpcode() == ISD::SINT_TO_FP || 14389 N->getOpcode() == ISD::UINT_TO_FP) && 14390 "Need an int -> FP conversion node here"); 14391 14392 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14393 return SDValue(); 14394 14395 SelectionDAG &DAG = DCI.DAG; 14396 SDLoc dl(N); 14397 SDValue Op(N, 0); 14398 14399 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14400 // from the hardware. 14401 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14402 return SDValue(); 14403 if (!Op.getOperand(0).getValueType().isSimple()) 14404 return SDValue(); 14405 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14406 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14407 return SDValue(); 14408 14409 SDValue FirstOperand(Op.getOperand(0)); 14410 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14411 (FirstOperand.getValueType() == MVT::i8 || 14412 FirstOperand.getValueType() == MVT::i16); 14413 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14414 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14415 bool DstDouble = Op.getValueType() == MVT::f64; 14416 unsigned ConvOp = Signed ? 14417 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14418 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14419 SDValue WidthConst = 14420 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14421 dl, false); 14422 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14423 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14424 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14425 DAG.getVTList(MVT::f64, MVT::Other), 14426 Ops, MVT::i8, LDN->getMemOperand()); 14427 14428 // For signed conversion, we need to sign-extend the value in the VSR 14429 if (Signed) { 14430 SDValue ExtOps[] = { Ld, WidthConst }; 14431 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14432 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14433 } else 14434 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14435 } 14436 14437 14438 // For i32 intermediate values, unfortunately, the conversion functions 14439 // leave the upper 32 bits of the value are undefined. Within the set of 14440 // scalar instructions, we have no method for zero- or sign-extending the 14441 // value. Thus, we cannot handle i32 intermediate values here. 14442 if (Op.getOperand(0).getValueType() == MVT::i32) 14443 return SDValue(); 14444 14445 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14446 "UINT_TO_FP is supported only with FPCVT"); 14447 14448 // If we have FCFIDS, then use it when converting to single-precision. 14449 // Otherwise, convert to double-precision and then round. 14450 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14451 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14452 : PPCISD::FCFIDS) 14453 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14454 : PPCISD::FCFID); 14455 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14456 ? MVT::f32 14457 : MVT::f64; 14458 14459 // If we're converting from a float, to an int, and back to a float again, 14460 // then we don't need the store/load pair at all. 14461 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14462 Subtarget.hasFPCVT()) || 14463 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14464 SDValue Src = Op.getOperand(0).getOperand(0); 14465 if (Src.getValueType() == MVT::f32) { 14466 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14467 DCI.AddToWorklist(Src.getNode()); 14468 } else if (Src.getValueType() != MVT::f64) { 14469 // Make sure that we don't pick up a ppc_fp128 source value. 14470 return SDValue(); 14471 } 14472 14473 unsigned FCTOp = 14474 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14475 PPCISD::FCTIDUZ; 14476 14477 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14478 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14479 14480 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14481 FP = DAG.getNode(ISD::FP_ROUND, dl, 14482 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14483 DCI.AddToWorklist(FP.getNode()); 14484 } 14485 14486 return FP; 14487 } 14488 14489 return SDValue(); 14490 } 14491 14492 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14493 // builtins) into loads with swaps. 14494 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14495 DAGCombinerInfo &DCI) const { 14496 SelectionDAG &DAG = DCI.DAG; 14497 SDLoc dl(N); 14498 SDValue Chain; 14499 SDValue Base; 14500 MachineMemOperand *MMO; 14501 14502 switch (N->getOpcode()) { 14503 default: 14504 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14505 case ISD::LOAD: { 14506 LoadSDNode *LD = cast<LoadSDNode>(N); 14507 Chain = LD->getChain(); 14508 Base = LD->getBasePtr(); 14509 MMO = LD->getMemOperand(); 14510 // If the MMO suggests this isn't a load of a full vector, leave 14511 // things alone. For a built-in, we have to make the change for 14512 // correctness, so if there is a size problem that will be a bug. 14513 if (MMO->getSize() < 16) 14514 return SDValue(); 14515 break; 14516 } 14517 case ISD::INTRINSIC_W_CHAIN: { 14518 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14519 Chain = Intrin->getChain(); 14520 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14521 // us what we want. Get operand 2 instead. 14522 Base = Intrin->getOperand(2); 14523 MMO = Intrin->getMemOperand(); 14524 break; 14525 } 14526 } 14527 14528 MVT VecTy = N->getValueType(0).getSimpleVT(); 14529 14530 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14531 // aligned and the type is a vector with elements up to 4 bytes 14532 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14533 VecTy.getScalarSizeInBits() <= 32) { 14534 return SDValue(); 14535 } 14536 14537 SDValue LoadOps[] = { Chain, Base }; 14538 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14539 DAG.getVTList(MVT::v2f64, MVT::Other), 14540 LoadOps, MVT::v2f64, MMO); 14541 14542 DCI.AddToWorklist(Load.getNode()); 14543 Chain = Load.getValue(1); 14544 SDValue Swap = DAG.getNode( 14545 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14546 DCI.AddToWorklist(Swap.getNode()); 14547 14548 // Add a bitcast if the resulting load type doesn't match v2f64. 14549 if (VecTy != MVT::v2f64) { 14550 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14551 DCI.AddToWorklist(N.getNode()); 14552 // Package {bitcast value, swap's chain} to match Load's shape. 14553 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14554 N, Swap.getValue(1)); 14555 } 14556 14557 return Swap; 14558 } 14559 14560 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14561 // builtins) into stores with swaps. 14562 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14563 DAGCombinerInfo &DCI) const { 14564 SelectionDAG &DAG = DCI.DAG; 14565 SDLoc dl(N); 14566 SDValue Chain; 14567 SDValue Base; 14568 unsigned SrcOpnd; 14569 MachineMemOperand *MMO; 14570 14571 switch (N->getOpcode()) { 14572 default: 14573 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14574 case ISD::STORE: { 14575 StoreSDNode *ST = cast<StoreSDNode>(N); 14576 Chain = ST->getChain(); 14577 Base = ST->getBasePtr(); 14578 MMO = ST->getMemOperand(); 14579 SrcOpnd = 1; 14580 // If the MMO suggests this isn't a store of a full vector, leave 14581 // things alone. For a built-in, we have to make the change for 14582 // correctness, so if there is a size problem that will be a bug. 14583 if (MMO->getSize() < 16) 14584 return SDValue(); 14585 break; 14586 } 14587 case ISD::INTRINSIC_VOID: { 14588 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14589 Chain = Intrin->getChain(); 14590 // Intrin->getBasePtr() oddly does not get what we want. 14591 Base = Intrin->getOperand(3); 14592 MMO = Intrin->getMemOperand(); 14593 SrcOpnd = 2; 14594 break; 14595 } 14596 } 14597 14598 SDValue Src = N->getOperand(SrcOpnd); 14599 MVT VecTy = Src.getValueType().getSimpleVT(); 14600 14601 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14602 // aligned and the type is a vector with elements up to 4 bytes 14603 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14604 VecTy.getScalarSizeInBits() <= 32) { 14605 return SDValue(); 14606 } 14607 14608 // All stores are done as v2f64 and possible bit cast. 14609 if (VecTy != MVT::v2f64) { 14610 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14611 DCI.AddToWorklist(Src.getNode()); 14612 } 14613 14614 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14615 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14616 DCI.AddToWorklist(Swap.getNode()); 14617 Chain = Swap.getValue(1); 14618 SDValue StoreOps[] = { Chain, Swap, Base }; 14619 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14620 DAG.getVTList(MVT::Other), 14621 StoreOps, VecTy, MMO); 14622 DCI.AddToWorklist(Store.getNode()); 14623 return Store; 14624 } 14625 14626 // Handle DAG combine for STORE (FP_TO_INT F). 14627 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14628 DAGCombinerInfo &DCI) const { 14629 14630 SelectionDAG &DAG = DCI.DAG; 14631 SDLoc dl(N); 14632 unsigned Opcode = N->getOperand(1).getOpcode(); 14633 14634 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14635 && "Not a FP_TO_INT Instruction!"); 14636 14637 SDValue Val = N->getOperand(1).getOperand(0); 14638 EVT Op1VT = N->getOperand(1).getValueType(); 14639 EVT ResVT = Val.getValueType(); 14640 14641 if (!isTypeLegal(ResVT)) 14642 return SDValue(); 14643 14644 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14645 bool ValidTypeForStoreFltAsInt = 14646 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14647 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14648 14649 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14650 return SDValue(); 14651 14652 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14653 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14654 return SDValue(); 14655 14656 // Extend f32 values to f64 14657 if (ResVT.getScalarSizeInBits() == 32) { 14658 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14659 DCI.AddToWorklist(Val.getNode()); 14660 } 14661 14662 // Set signed or unsigned conversion opcode. 14663 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14664 PPCISD::FP_TO_SINT_IN_VSR : 14665 PPCISD::FP_TO_UINT_IN_VSR; 14666 14667 Val = DAG.getNode(ConvOpcode, 14668 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14669 DCI.AddToWorklist(Val.getNode()); 14670 14671 // Set number of bytes being converted. 14672 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14673 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14674 DAG.getIntPtrConstant(ByteSize, dl, false), 14675 DAG.getValueType(Op1VT) }; 14676 14677 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14678 DAG.getVTList(MVT::Other), Ops, 14679 cast<StoreSDNode>(N)->getMemoryVT(), 14680 cast<StoreSDNode>(N)->getMemOperand()); 14681 14682 DCI.AddToWorklist(Val.getNode()); 14683 return Val; 14684 } 14685 14686 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14687 // Check that the source of the element keeps flipping 14688 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14689 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14690 for (int i = 1, e = Mask.size(); i < e; i++) { 14691 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14692 return false; 14693 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14694 return false; 14695 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14696 } 14697 return true; 14698 } 14699 14700 static bool isSplatBV(SDValue Op) { 14701 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14702 return false; 14703 SDValue FirstOp; 14704 14705 // Find first non-undef input. 14706 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14707 FirstOp = Op.getOperand(i); 14708 if (!FirstOp.isUndef()) 14709 break; 14710 } 14711 14712 // All inputs are undef or the same as the first non-undef input. 14713 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14714 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14715 return false; 14716 return true; 14717 } 14718 14719 static SDValue isScalarToVec(SDValue Op) { 14720 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14721 return Op; 14722 if (Op.getOpcode() != ISD::BITCAST) 14723 return SDValue(); 14724 Op = Op.getOperand(0); 14725 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14726 return Op; 14727 return SDValue(); 14728 } 14729 14730 // Fix up the shuffle mask to account for the fact that the result of 14731 // scalar_to_vector is not in lane zero. This just takes all values in 14732 // the ranges specified by the min/max indices and adds the number of 14733 // elements required to ensure each element comes from the respective 14734 // position in the valid lane. 14735 // On little endian, that's just the corresponding element in the other 14736 // half of the vector. On big endian, it is in the same half but right 14737 // justified rather than left justified in that half. 14738 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14739 int LHSMaxIdx, int RHSMinIdx, 14740 int RHSMaxIdx, int HalfVec, 14741 unsigned ValidLaneWidth, 14742 const PPCSubtarget &Subtarget) { 14743 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14744 int Idx = ShuffV[i]; 14745 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14746 ShuffV[i] += 14747 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14748 } 14749 } 14750 14751 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14752 // the original is: 14753 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14754 // In such a case, just change the shuffle mask to extract the element 14755 // from the permuted index. 14756 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14757 const PPCSubtarget &Subtarget) { 14758 SDLoc dl(OrigSToV); 14759 EVT VT = OrigSToV.getValueType(); 14760 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14761 "Expecting a SCALAR_TO_VECTOR here"); 14762 SDValue Input = OrigSToV.getOperand(0); 14763 14764 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14765 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14766 SDValue OrigVector = Input.getOperand(0); 14767 14768 // Can't handle non-const element indices or different vector types 14769 // for the input to the extract and the output of the scalar_to_vector. 14770 if (Idx && VT == OrigVector.getValueType()) { 14771 unsigned NumElts = VT.getVectorNumElements(); 14772 assert( 14773 NumElts > 1 && 14774 "Cannot produce a permuted scalar_to_vector for one element vector"); 14775 SmallVector<int, 16> NewMask(NumElts, -1); 14776 unsigned ResultInElt = NumElts / 2; 14777 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14778 NewMask[ResultInElt] = Idx->getZExtValue(); 14779 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14780 } 14781 } 14782 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14783 OrigSToV.getOperand(0)); 14784 } 14785 14786 // On little endian subtargets, combine shuffles such as: 14787 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14788 // into: 14789 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14790 // because the latter can be matched to a single instruction merge. 14791 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14792 // to put the value into element zero. Adjust the shuffle mask so that the 14793 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14794 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 14795 // nodes with elements smaller than doubleword because all the ways 14796 // of getting scalar data into a vector register put the value in the 14797 // rightmost element of the left half of the vector. 14798 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14799 SelectionDAG &DAG) const { 14800 SDValue LHS = SVN->getOperand(0); 14801 SDValue RHS = SVN->getOperand(1); 14802 auto Mask = SVN->getMask(); 14803 int NumElts = LHS.getValueType().getVectorNumElements(); 14804 SDValue Res(SVN, 0); 14805 SDLoc dl(SVN); 14806 bool IsLittleEndian = Subtarget.isLittleEndian(); 14807 14808 // On big endian targets this is only useful for subtargets with direct moves. 14809 // On little endian targets it would be useful for all subtargets with VSX. 14810 // However adding special handling for LE subtargets without direct moves 14811 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8) 14812 // which includes direct moves. 14813 if (!Subtarget.hasDirectMove()) 14814 return Res; 14815 14816 // If this is not a shuffle of a shuffle and the first element comes from 14817 // the second vector, canonicalize to the commuted form. This will make it 14818 // more likely to match one of the single instruction patterns. 14819 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14820 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14821 std::swap(LHS, RHS); 14822 Res = DAG.getCommutedVectorShuffle(*SVN); 14823 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14824 } 14825 14826 // Adjust the shuffle mask if either input vector comes from a 14827 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14828 // form (to prevent the need for a swap). 14829 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14830 SDValue SToVLHS = isScalarToVec(LHS); 14831 SDValue SToVRHS = isScalarToVec(RHS); 14832 if (SToVLHS || SToVRHS) { 14833 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14834 : SToVRHS.getValueType().getVectorNumElements(); 14835 int NumEltsOut = ShuffV.size(); 14836 // The width of the "valid lane" (i.e. the lane that contains the value that 14837 // is vectorized) needs to be expressed in terms of the number of elements 14838 // of the shuffle. It is thereby the ratio of the values before and after 14839 // any bitcast. 14840 unsigned ValidLaneWidth = 14841 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() / 14842 LHS.getValueType().getScalarSizeInBits() 14843 : SToVRHS.getValueType().getScalarSizeInBits() / 14844 RHS.getValueType().getScalarSizeInBits(); 14845 14846 // Initially assume that neither input is permuted. These will be adjusted 14847 // accordingly if either input is. 14848 int LHSMaxIdx = -1; 14849 int RHSMinIdx = -1; 14850 int RHSMaxIdx = -1; 14851 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14852 14853 // Get the permuted scalar to vector nodes for the source(s) that come from 14854 // ISD::SCALAR_TO_VECTOR. 14855 // On big endian systems, this only makes sense for element sizes smaller 14856 // than 64 bits since for 64-bit elements, all instructions already put 14857 // the value into element zero. Since scalar size of LHS and RHS may differ 14858 // after isScalarToVec, this should be checked using their own sizes. 14859 if (SToVLHS) { 14860 if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64) 14861 return Res; 14862 // Set up the values for the shuffle vector fixup. 14863 LHSMaxIdx = NumEltsOut / NumEltsIn; 14864 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 14865 if (SToVLHS.getValueType() != LHS.getValueType()) 14866 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14867 LHS = SToVLHS; 14868 } 14869 if (SToVRHS) { 14870 if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64) 14871 return Res; 14872 RHSMinIdx = NumEltsOut; 14873 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14874 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 14875 if (SToVRHS.getValueType() != RHS.getValueType()) 14876 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14877 RHS = SToVRHS; 14878 } 14879 14880 // Fix up the shuffle mask to reflect where the desired element actually is. 14881 // The minimum and maximum indices that correspond to element zero for both 14882 // the LHS and RHS are computed and will control which shuffle mask entries 14883 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14884 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 14885 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14886 HalfVec, ValidLaneWidth, Subtarget); 14887 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14888 14889 // We may have simplified away the shuffle. We won't be able to do anything 14890 // further with it here. 14891 if (!isa<ShuffleVectorSDNode>(Res)) 14892 return Res; 14893 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14894 } 14895 14896 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 14897 // The common case after we commuted the shuffle is that the RHS is a splat 14898 // and we have elements coming in from the splat at indices that are not 14899 // conducive to using a merge. 14900 // Example: 14901 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14902 if (!isSplatBV(TheSplat)) 14903 return Res; 14904 14905 // We are looking for a mask such that all even elements are from 14906 // one vector and all odd elements from the other. 14907 if (!isAlternatingShuffMask(Mask, NumElts)) 14908 return Res; 14909 14910 // Adjust the mask so we are pulling in the same index from the splat 14911 // as the index from the interesting vector in consecutive elements. 14912 if (IsLittleEndian) { 14913 // Example (even elements from first vector): 14914 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14915 if (Mask[0] < NumElts) 14916 for (int i = 1, e = Mask.size(); i < e; i += 2) 14917 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14918 // Example (odd elements from first vector): 14919 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14920 else 14921 for (int i = 0, e = Mask.size(); i < e; i += 2) 14922 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14923 } else { 14924 // Example (even elements from first vector): 14925 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 14926 if (Mask[0] < NumElts) 14927 for (int i = 0, e = Mask.size(); i < e; i += 2) 14928 ShuffV[i] = ShuffV[i + 1] - NumElts; 14929 // Example (odd elements from first vector): 14930 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 14931 else 14932 for (int i = 1, e = Mask.size(); i < e; i += 2) 14933 ShuffV[i] = ShuffV[i - 1] - NumElts; 14934 } 14935 14936 // If the RHS has undefs, we need to remove them since we may have created 14937 // a shuffle that adds those instead of the splat value. 14938 SDValue SplatVal = 14939 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 14940 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 14941 14942 if (IsLittleEndian) 14943 RHS = TheSplat; 14944 else 14945 LHS = TheSplat; 14946 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14947 } 14948 14949 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14950 LSBaseSDNode *LSBase, 14951 DAGCombinerInfo &DCI) const { 14952 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14953 "Not a reverse memop pattern!"); 14954 14955 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14956 auto Mask = SVN->getMask(); 14957 int i = 0; 14958 auto I = Mask.rbegin(); 14959 auto E = Mask.rend(); 14960 14961 for (; I != E; ++I) { 14962 if (*I != i) 14963 return false; 14964 i++; 14965 } 14966 return true; 14967 }; 14968 14969 SelectionDAG &DAG = DCI.DAG; 14970 EVT VT = SVN->getValueType(0); 14971 14972 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14973 return SDValue(); 14974 14975 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14976 // See comment in PPCVSXSwapRemoval.cpp. 14977 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14978 if (!Subtarget.hasP9Vector()) 14979 return SDValue(); 14980 14981 if(!IsElementReverse(SVN)) 14982 return SDValue(); 14983 14984 if (LSBase->getOpcode() == ISD::LOAD) { 14985 // If the load return value 0 has more than one user except the 14986 // shufflevector instruction, it is not profitable to replace the 14987 // shufflevector with a reverse load. 14988 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end(); 14989 UI != UE; ++UI) 14990 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE) 14991 return SDValue(); 14992 14993 SDLoc dl(LSBase); 14994 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14995 return DAG.getMemIntrinsicNode( 14996 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14997 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14998 } 14999 15000 if (LSBase->getOpcode() == ISD::STORE) { 15001 // If there are other uses of the shuffle, the swap cannot be avoided. 15002 // Forcing the use of an X-Form (since swapped stores only have 15003 // X-Forms) without removing the swap is unprofitable. 15004 if (!SVN->hasOneUse()) 15005 return SDValue(); 15006 15007 SDLoc dl(LSBase); 15008 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 15009 LSBase->getBasePtr()}; 15010 return DAG.getMemIntrinsicNode( 15011 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 15012 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15013 } 15014 15015 llvm_unreachable("Expected a load or store node here"); 15016 } 15017 15018 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 15019 DAGCombinerInfo &DCI) const { 15020 SelectionDAG &DAG = DCI.DAG; 15021 SDLoc dl(N); 15022 switch (N->getOpcode()) { 15023 default: break; 15024 case ISD::ADD: 15025 return combineADD(N, DCI); 15026 case ISD::SHL: 15027 return combineSHL(N, DCI); 15028 case ISD::SRA: 15029 return combineSRA(N, DCI); 15030 case ISD::SRL: 15031 return combineSRL(N, DCI); 15032 case ISD::MUL: 15033 return combineMUL(N, DCI); 15034 case ISD::FMA: 15035 case PPCISD::FNMSUB: 15036 return combineFMALike(N, DCI); 15037 case PPCISD::SHL: 15038 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 15039 return N->getOperand(0); 15040 break; 15041 case PPCISD::SRL: 15042 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 15043 return N->getOperand(0); 15044 break; 15045 case PPCISD::SRA: 15046 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 15047 if (C->isZero() || // 0 >>s V -> 0. 15048 C->isAllOnes()) // -1 >>s V -> -1. 15049 return N->getOperand(0); 15050 } 15051 break; 15052 case ISD::SIGN_EXTEND: 15053 case ISD::ZERO_EXTEND: 15054 case ISD::ANY_EXTEND: 15055 return DAGCombineExtBoolTrunc(N, DCI); 15056 case ISD::TRUNCATE: 15057 return combineTRUNCATE(N, DCI); 15058 case ISD::SETCC: 15059 if (SDValue CSCC = combineSetCC(N, DCI)) 15060 return CSCC; 15061 LLVM_FALLTHROUGH; 15062 case ISD::SELECT_CC: 15063 return DAGCombineTruncBoolExt(N, DCI); 15064 case ISD::SINT_TO_FP: 15065 case ISD::UINT_TO_FP: 15066 return combineFPToIntToFP(N, DCI); 15067 case ISD::VECTOR_SHUFFLE: 15068 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 15069 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 15070 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 15071 } 15072 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 15073 case ISD::STORE: { 15074 15075 EVT Op1VT = N->getOperand(1).getValueType(); 15076 unsigned Opcode = N->getOperand(1).getOpcode(); 15077 15078 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 15079 SDValue Val= combineStoreFPToInt(N, DCI); 15080 if (Val) 15081 return Val; 15082 } 15083 15084 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 15085 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 15086 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 15087 if (Val) 15088 return Val; 15089 } 15090 15091 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 15092 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 15093 N->getOperand(1).getNode()->hasOneUse() && 15094 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 15095 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 15096 15097 // STBRX can only handle simple types and it makes no sense to store less 15098 // two bytes in byte-reversed order. 15099 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 15100 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 15101 break; 15102 15103 SDValue BSwapOp = N->getOperand(1).getOperand(0); 15104 // Do an any-extend to 32-bits if this is a half-word input. 15105 if (BSwapOp.getValueType() == MVT::i16) 15106 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 15107 15108 // If the type of BSWAP operand is wider than stored memory width 15109 // it need to be shifted to the right side before STBRX. 15110 if (Op1VT.bitsGT(mVT)) { 15111 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 15112 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 15113 DAG.getConstant(Shift, dl, MVT::i32)); 15114 // Need to truncate if this is a bswap of i64 stored as i32/i16. 15115 if (Op1VT == MVT::i64) 15116 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 15117 } 15118 15119 SDValue Ops[] = { 15120 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 15121 }; 15122 return 15123 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 15124 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 15125 cast<StoreSDNode>(N)->getMemOperand()); 15126 } 15127 15128 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 15129 // So it can increase the chance of CSE constant construction. 15130 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 15131 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 15132 // Need to sign-extended to 64-bits to handle negative values. 15133 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 15134 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 15135 MemVT.getSizeInBits()); 15136 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 15137 15138 // DAG.getTruncStore() can't be used here because it doesn't accept 15139 // the general (base + offset) addressing mode. 15140 // So we use UpdateNodeOperands and setTruncatingStore instead. 15141 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 15142 N->getOperand(3)); 15143 cast<StoreSDNode>(N)->setTruncatingStore(true); 15144 return SDValue(N, 0); 15145 } 15146 15147 // For little endian, VSX stores require generating xxswapd/lxvd2x. 15148 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15149 if (Op1VT.isSimple()) { 15150 MVT StoreVT = Op1VT.getSimpleVT(); 15151 if (Subtarget.needsSwapsForVSXMemOps() && 15152 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 15153 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 15154 return expandVSXStoreForLE(N, DCI); 15155 } 15156 break; 15157 } 15158 case ISD::LOAD: { 15159 LoadSDNode *LD = cast<LoadSDNode>(N); 15160 EVT VT = LD->getValueType(0); 15161 15162 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15163 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15164 if (VT.isSimple()) { 15165 MVT LoadVT = VT.getSimpleVT(); 15166 if (Subtarget.needsSwapsForVSXMemOps() && 15167 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 15168 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 15169 return expandVSXLoadForLE(N, DCI); 15170 } 15171 15172 // We sometimes end up with a 64-bit integer load, from which we extract 15173 // two single-precision floating-point numbers. This happens with 15174 // std::complex<float>, and other similar structures, because of the way we 15175 // canonicalize structure copies. However, if we lack direct moves, 15176 // then the final bitcasts from the extracted integer values to the 15177 // floating-point numbers turn into store/load pairs. Even with direct moves, 15178 // just loading the two floating-point numbers is likely better. 15179 auto ReplaceTwoFloatLoad = [&]() { 15180 if (VT != MVT::i64) 15181 return false; 15182 15183 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 15184 LD->isVolatile()) 15185 return false; 15186 15187 // We're looking for a sequence like this: 15188 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 15189 // t16: i64 = srl t13, Constant:i32<32> 15190 // t17: i32 = truncate t16 15191 // t18: f32 = bitcast t17 15192 // t19: i32 = truncate t13 15193 // t20: f32 = bitcast t19 15194 15195 if (!LD->hasNUsesOfValue(2, 0)) 15196 return false; 15197 15198 auto UI = LD->use_begin(); 15199 while (UI.getUse().getResNo() != 0) ++UI; 15200 SDNode *Trunc = *UI++; 15201 while (UI.getUse().getResNo() != 0) ++UI; 15202 SDNode *RightShift = *UI; 15203 if (Trunc->getOpcode() != ISD::TRUNCATE) 15204 std::swap(Trunc, RightShift); 15205 15206 if (Trunc->getOpcode() != ISD::TRUNCATE || 15207 Trunc->getValueType(0) != MVT::i32 || 15208 !Trunc->hasOneUse()) 15209 return false; 15210 if (RightShift->getOpcode() != ISD::SRL || 15211 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 15212 RightShift->getConstantOperandVal(1) != 32 || 15213 !RightShift->hasOneUse()) 15214 return false; 15215 15216 SDNode *Trunc2 = *RightShift->use_begin(); 15217 if (Trunc2->getOpcode() != ISD::TRUNCATE || 15218 Trunc2->getValueType(0) != MVT::i32 || 15219 !Trunc2->hasOneUse()) 15220 return false; 15221 15222 SDNode *Bitcast = *Trunc->use_begin(); 15223 SDNode *Bitcast2 = *Trunc2->use_begin(); 15224 15225 if (Bitcast->getOpcode() != ISD::BITCAST || 15226 Bitcast->getValueType(0) != MVT::f32) 15227 return false; 15228 if (Bitcast2->getOpcode() != ISD::BITCAST || 15229 Bitcast2->getValueType(0) != MVT::f32) 15230 return false; 15231 15232 if (Subtarget.isLittleEndian()) 15233 std::swap(Bitcast, Bitcast2); 15234 15235 // Bitcast has the second float (in memory-layout order) and Bitcast2 15236 // has the first one. 15237 15238 SDValue BasePtr = LD->getBasePtr(); 15239 if (LD->isIndexed()) { 15240 assert(LD->getAddressingMode() == ISD::PRE_INC && 15241 "Non-pre-inc AM on PPC?"); 15242 BasePtr = 15243 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15244 LD->getOffset()); 15245 } 15246 15247 auto MMOFlags = 15248 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 15249 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 15250 LD->getPointerInfo(), LD->getAlignment(), 15251 MMOFlags, LD->getAAInfo()); 15252 SDValue AddPtr = 15253 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 15254 BasePtr, DAG.getIntPtrConstant(4, dl)); 15255 SDValue FloatLoad2 = DAG.getLoad( 15256 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 15257 LD->getPointerInfo().getWithOffset(4), 15258 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 15259 15260 if (LD->isIndexed()) { 15261 // Note that DAGCombine should re-form any pre-increment load(s) from 15262 // what is produced here if that makes sense. 15263 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 15264 } 15265 15266 DCI.CombineTo(Bitcast2, FloatLoad); 15267 DCI.CombineTo(Bitcast, FloatLoad2); 15268 15269 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 15270 SDValue(FloatLoad2.getNode(), 1)); 15271 return true; 15272 }; 15273 15274 if (ReplaceTwoFloatLoad()) 15275 return SDValue(N, 0); 15276 15277 EVT MemVT = LD->getMemoryVT(); 15278 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 15279 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 15280 if (LD->isUnindexed() && VT.isVector() && 15281 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 15282 // P8 and later hardware should just use LOAD. 15283 !Subtarget.hasP8Vector() && 15284 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 15285 VT == MVT::v4f32))) && 15286 LD->getAlign() < ABIAlignment) { 15287 // This is a type-legal unaligned Altivec load. 15288 SDValue Chain = LD->getChain(); 15289 SDValue Ptr = LD->getBasePtr(); 15290 bool isLittleEndian = Subtarget.isLittleEndian(); 15291 15292 // This implements the loading of unaligned vectors as described in 15293 // the venerable Apple Velocity Engine overview. Specifically: 15294 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 15295 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 15296 // 15297 // The general idea is to expand a sequence of one or more unaligned 15298 // loads into an alignment-based permutation-control instruction (lvsl 15299 // or lvsr), a series of regular vector loads (which always truncate 15300 // their input address to an aligned address), and a series of 15301 // permutations. The results of these permutations are the requested 15302 // loaded values. The trick is that the last "extra" load is not taken 15303 // from the address you might suspect (sizeof(vector) bytes after the 15304 // last requested load), but rather sizeof(vector) - 1 bytes after the 15305 // last requested vector. The point of this is to avoid a page fault if 15306 // the base address happened to be aligned. This works because if the 15307 // base address is aligned, then adding less than a full vector length 15308 // will cause the last vector in the sequence to be (re)loaded. 15309 // Otherwise, the next vector will be fetched as you might suspect was 15310 // necessary. 15311 15312 // We might be able to reuse the permutation generation from 15313 // a different base address offset from this one by an aligned amount. 15314 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 15315 // optimization later. 15316 Intrinsic::ID Intr, IntrLD, IntrPerm; 15317 MVT PermCntlTy, PermTy, LDTy; 15318 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15319 : Intrinsic::ppc_altivec_lvsl; 15320 IntrLD = Intrinsic::ppc_altivec_lvx; 15321 IntrPerm = Intrinsic::ppc_altivec_vperm; 15322 PermCntlTy = MVT::v16i8; 15323 PermTy = MVT::v4i32; 15324 LDTy = MVT::v4i32; 15325 15326 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 15327 15328 // Create the new MMO for the new base load. It is like the original MMO, 15329 // but represents an area in memory almost twice the vector size centered 15330 // on the original address. If the address is unaligned, we might start 15331 // reading up to (sizeof(vector)-1) bytes below the address of the 15332 // original unaligned load. 15333 MachineFunction &MF = DAG.getMachineFunction(); 15334 MachineMemOperand *BaseMMO = 15335 MF.getMachineMemOperand(LD->getMemOperand(), 15336 -(long)MemVT.getStoreSize()+1, 15337 2*MemVT.getStoreSize()-1); 15338 15339 // Create the new base load. 15340 SDValue LDXIntID = 15341 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 15342 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 15343 SDValue BaseLoad = 15344 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15345 DAG.getVTList(PermTy, MVT::Other), 15346 BaseLoadOps, LDTy, BaseMMO); 15347 15348 // Note that the value of IncOffset (which is provided to the next 15349 // load's pointer info offset value, and thus used to calculate the 15350 // alignment), and the value of IncValue (which is actually used to 15351 // increment the pointer value) are different! This is because we 15352 // require the next load to appear to be aligned, even though it 15353 // is actually offset from the base pointer by a lesser amount. 15354 int IncOffset = VT.getSizeInBits() / 8; 15355 int IncValue = IncOffset; 15356 15357 // Walk (both up and down) the chain looking for another load at the real 15358 // (aligned) offset (the alignment of the other load does not matter in 15359 // this case). If found, then do not use the offset reduction trick, as 15360 // that will prevent the loads from being later combined (as they would 15361 // otherwise be duplicates). 15362 if (!findConsecutiveLoad(LD, DAG)) 15363 --IncValue; 15364 15365 SDValue Increment = 15366 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15367 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15368 15369 MachineMemOperand *ExtraMMO = 15370 MF.getMachineMemOperand(LD->getMemOperand(), 15371 1, 2*MemVT.getStoreSize()-1); 15372 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15373 SDValue ExtraLoad = 15374 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15375 DAG.getVTList(PermTy, MVT::Other), 15376 ExtraLoadOps, LDTy, ExtraMMO); 15377 15378 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15379 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15380 15381 // Because vperm has a big-endian bias, we must reverse the order 15382 // of the input vectors and complement the permute control vector 15383 // when generating little endian code. We have already handled the 15384 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15385 // and ExtraLoad here. 15386 SDValue Perm; 15387 if (isLittleEndian) 15388 Perm = BuildIntrinsicOp(IntrPerm, 15389 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15390 else 15391 Perm = BuildIntrinsicOp(IntrPerm, 15392 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15393 15394 if (VT != PermTy) 15395 Perm = Subtarget.hasAltivec() 15396 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15397 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15398 DAG.getTargetConstant(1, dl, MVT::i64)); 15399 // second argument is 1 because this rounding 15400 // is always exact. 15401 15402 // The output of the permutation is our loaded result, the TokenFactor is 15403 // our new chain. 15404 DCI.CombineTo(N, Perm, TF); 15405 return SDValue(N, 0); 15406 } 15407 } 15408 break; 15409 case ISD::INTRINSIC_WO_CHAIN: { 15410 bool isLittleEndian = Subtarget.isLittleEndian(); 15411 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15412 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15413 : Intrinsic::ppc_altivec_lvsl); 15414 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15415 SDValue Add = N->getOperand(1); 15416 15417 int Bits = 4 /* 16 byte alignment */; 15418 15419 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15420 APInt::getAllOnes(Bits /* alignment */) 15421 .zext(Add.getScalarValueSizeInBits()))) { 15422 SDNode *BasePtr = Add->getOperand(0).getNode(); 15423 for (SDNode *U : BasePtr->uses()) { 15424 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15425 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) { 15426 // We've found another LVSL/LVSR, and this address is an aligned 15427 // multiple of that one. The results will be the same, so use the 15428 // one we've just found instead. 15429 15430 return SDValue(U, 0); 15431 } 15432 } 15433 } 15434 15435 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15436 SDNode *BasePtr = Add->getOperand(0).getNode(); 15437 for (SDNode *U : BasePtr->uses()) { 15438 if (U->getOpcode() == ISD::ADD && 15439 isa<ConstantSDNode>(U->getOperand(1)) && 15440 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15441 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) % 15442 (1ULL << Bits) == 15443 0) { 15444 SDNode *OtherAdd = U; 15445 for (SDNode *V : OtherAdd->uses()) { 15446 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15447 cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() == 15448 IID) { 15449 return SDValue(V, 0); 15450 } 15451 } 15452 } 15453 } 15454 } 15455 } 15456 15457 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15458 // Expose the vabsduw/h/b opportunity for down stream 15459 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15460 (IID == Intrinsic::ppc_altivec_vmaxsw || 15461 IID == Intrinsic::ppc_altivec_vmaxsh || 15462 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15463 SDValue V1 = N->getOperand(1); 15464 SDValue V2 = N->getOperand(2); 15465 if ((V1.getSimpleValueType() == MVT::v4i32 || 15466 V1.getSimpleValueType() == MVT::v8i16 || 15467 V1.getSimpleValueType() == MVT::v16i8) && 15468 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15469 // (0-a, a) 15470 if (V1.getOpcode() == ISD::SUB && 15471 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15472 V1.getOperand(1) == V2) { 15473 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15474 } 15475 // (a, 0-a) 15476 if (V2.getOpcode() == ISD::SUB && 15477 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15478 V2.getOperand(1) == V1) { 15479 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15480 } 15481 // (x-y, y-x) 15482 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15483 V1.getOperand(0) == V2.getOperand(1) && 15484 V1.getOperand(1) == V2.getOperand(0)) { 15485 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15486 } 15487 } 15488 } 15489 } 15490 15491 break; 15492 case ISD::INTRINSIC_W_CHAIN: 15493 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15494 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15495 if (Subtarget.needsSwapsForVSXMemOps()) { 15496 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15497 default: 15498 break; 15499 case Intrinsic::ppc_vsx_lxvw4x: 15500 case Intrinsic::ppc_vsx_lxvd2x: 15501 return expandVSXLoadForLE(N, DCI); 15502 } 15503 } 15504 break; 15505 case ISD::INTRINSIC_VOID: 15506 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15507 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15508 if (Subtarget.needsSwapsForVSXMemOps()) { 15509 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15510 default: 15511 break; 15512 case Intrinsic::ppc_vsx_stxvw4x: 15513 case Intrinsic::ppc_vsx_stxvd2x: 15514 return expandVSXStoreForLE(N, DCI); 15515 } 15516 } 15517 break; 15518 case ISD::BSWAP: { 15519 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15520 // For subtargets without LDBRX, we can still do better than the default 15521 // expansion even for 64-bit BSWAP (LOAD). 15522 bool Is64BitBswapOn64BitTgt = 15523 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64; 15524 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) && 15525 N->getOperand(0).hasOneUse(); 15526 if (IsSingleUseNormalLd && 15527 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15528 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) { 15529 SDValue Load = N->getOperand(0); 15530 LoadSDNode *LD = cast<LoadSDNode>(Load); 15531 // Create the byte-swapping load. 15532 SDValue Ops[] = { 15533 LD->getChain(), // Chain 15534 LD->getBasePtr(), // Ptr 15535 DAG.getValueType(N->getValueType(0)) // VT 15536 }; 15537 SDValue BSLoad = 15538 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15539 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15540 MVT::i64 : MVT::i32, MVT::Other), 15541 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15542 15543 // If this is an i16 load, insert the truncate. 15544 SDValue ResVal = BSLoad; 15545 if (N->getValueType(0) == MVT::i16) 15546 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15547 15548 // First, combine the bswap away. This makes the value produced by the 15549 // load dead. 15550 DCI.CombineTo(N, ResVal); 15551 15552 // Next, combine the load away, we give it a bogus result value but a real 15553 // chain result. The result value is dead because the bswap is dead. 15554 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15555 15556 // Return N so it doesn't get rechecked! 15557 return SDValue(N, 0); 15558 } 15559 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only 15560 // before legalization so that the BUILD_PAIR is handled correctly. 15561 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt || 15562 !IsSingleUseNormalLd) 15563 return SDValue(); 15564 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0)); 15565 15566 // Can't split volatile or atomic loads. 15567 if (!LD->isSimple()) 15568 return SDValue(); 15569 SDValue BasePtr = LD->getBasePtr(); 15570 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, 15571 LD->getPointerInfo(), LD->getAlignment()); 15572 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo); 15573 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15574 DAG.getIntPtrConstant(4, dl)); 15575 MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand( 15576 LD->getMemOperand(), 4, 4); 15577 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO); 15578 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi); 15579 SDValue Res; 15580 if (Subtarget.isLittleEndian()) 15581 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo); 15582 else 15583 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 15584 SDValue TF = 15585 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15586 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1)); 15587 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF); 15588 return Res; 15589 } 15590 case PPCISD::VCMP: 15591 // If a VCMP_rec node already exists with exactly the same operands as this 15592 // node, use its result instead of this node (VCMP_rec computes both a CR6 15593 // and a normal output). 15594 // 15595 if (!N->getOperand(0).hasOneUse() && 15596 !N->getOperand(1).hasOneUse() && 15597 !N->getOperand(2).hasOneUse()) { 15598 15599 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15600 SDNode *VCMPrecNode = nullptr; 15601 15602 SDNode *LHSN = N->getOperand(0).getNode(); 15603 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15604 UI != E; ++UI) 15605 if (UI->getOpcode() == PPCISD::VCMP_rec && 15606 UI->getOperand(1) == N->getOperand(1) && 15607 UI->getOperand(2) == N->getOperand(2) && 15608 UI->getOperand(0) == N->getOperand(0)) { 15609 VCMPrecNode = *UI; 15610 break; 15611 } 15612 15613 // If there is no VCMP_rec node, or if the flag value has a single use, 15614 // don't transform this. 15615 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15616 break; 15617 15618 // Look at the (necessarily single) use of the flag value. If it has a 15619 // chain, this transformation is more complex. Note that multiple things 15620 // could use the value result, which we should ignore. 15621 SDNode *FlagUser = nullptr; 15622 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15623 FlagUser == nullptr; ++UI) { 15624 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15625 SDNode *User = *UI; 15626 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15627 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15628 FlagUser = User; 15629 break; 15630 } 15631 } 15632 } 15633 15634 // If the user is a MFOCRF instruction, we know this is safe. 15635 // Otherwise we give up for right now. 15636 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15637 return SDValue(VCMPrecNode, 0); 15638 } 15639 break; 15640 case ISD::BRCOND: { 15641 SDValue Cond = N->getOperand(1); 15642 SDValue Target = N->getOperand(2); 15643 15644 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15645 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15646 Intrinsic::loop_decrement) { 15647 15648 // We now need to make the intrinsic dead (it cannot be instruction 15649 // selected). 15650 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15651 assert(Cond.getNode()->hasOneUse() && 15652 "Counter decrement has more than one use"); 15653 15654 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15655 N->getOperand(0), Target); 15656 } 15657 } 15658 break; 15659 case ISD::BR_CC: { 15660 // If this is a branch on an altivec predicate comparison, lower this so 15661 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15662 // lowering is done pre-legalize, because the legalizer lowers the predicate 15663 // compare down to code that is difficult to reassemble. 15664 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15665 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15666 15667 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15668 // value. If so, pass-through the AND to get to the intrinsic. 15669 if (LHS.getOpcode() == ISD::AND && 15670 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15671 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15672 Intrinsic::loop_decrement && 15673 isa<ConstantSDNode>(LHS.getOperand(1)) && 15674 !isNullConstant(LHS.getOperand(1))) 15675 LHS = LHS.getOperand(0); 15676 15677 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15678 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15679 Intrinsic::loop_decrement && 15680 isa<ConstantSDNode>(RHS)) { 15681 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15682 "Counter decrement comparison is not EQ or NE"); 15683 15684 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15685 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15686 (CC == ISD::SETNE && !Val); 15687 15688 // We now need to make the intrinsic dead (it cannot be instruction 15689 // selected). 15690 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15691 assert(LHS.getNode()->hasOneUse() && 15692 "Counter decrement has more than one use"); 15693 15694 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15695 N->getOperand(0), N->getOperand(4)); 15696 } 15697 15698 int CompareOpc; 15699 bool isDot; 15700 15701 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15702 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15703 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15704 assert(isDot && "Can't compare against a vector result!"); 15705 15706 // If this is a comparison against something other than 0/1, then we know 15707 // that the condition is never/always true. 15708 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15709 if (Val != 0 && Val != 1) { 15710 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15711 return N->getOperand(0); 15712 // Always !=, turn it into an unconditional branch. 15713 return DAG.getNode(ISD::BR, dl, MVT::Other, 15714 N->getOperand(0), N->getOperand(4)); 15715 } 15716 15717 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15718 15719 // Create the PPCISD altivec 'dot' comparison node. 15720 SDValue Ops[] = { 15721 LHS.getOperand(2), // LHS of compare 15722 LHS.getOperand(3), // RHS of compare 15723 DAG.getConstant(CompareOpc, dl, MVT::i32) 15724 }; 15725 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15726 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15727 15728 // Unpack the result based on how the target uses it. 15729 PPC::Predicate CompOpc; 15730 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15731 default: // Can't happen, don't crash on invalid number though. 15732 case 0: // Branch on the value of the EQ bit of CR6. 15733 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15734 break; 15735 case 1: // Branch on the inverted value of the EQ bit of CR6. 15736 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15737 break; 15738 case 2: // Branch on the value of the LT bit of CR6. 15739 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15740 break; 15741 case 3: // Branch on the inverted value of the LT bit of CR6. 15742 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15743 break; 15744 } 15745 15746 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15747 DAG.getConstant(CompOpc, dl, MVT::i32), 15748 DAG.getRegister(PPC::CR6, MVT::i32), 15749 N->getOperand(4), CompNode.getValue(1)); 15750 } 15751 break; 15752 } 15753 case ISD::BUILD_VECTOR: 15754 return DAGCombineBuildVector(N, DCI); 15755 case ISD::ABS: 15756 return combineABS(N, DCI); 15757 case ISD::VSELECT: 15758 return combineVSelect(N, DCI); 15759 } 15760 15761 return SDValue(); 15762 } 15763 15764 SDValue 15765 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15766 SelectionDAG &DAG, 15767 SmallVectorImpl<SDNode *> &Created) const { 15768 // fold (sdiv X, pow2) 15769 EVT VT = N->getValueType(0); 15770 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15771 return SDValue(); 15772 if ((VT != MVT::i32 && VT != MVT::i64) || 15773 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2())) 15774 return SDValue(); 15775 15776 SDLoc DL(N); 15777 SDValue N0 = N->getOperand(0); 15778 15779 bool IsNegPow2 = Divisor.isNegatedPowerOf2(); 15780 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15781 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15782 15783 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15784 Created.push_back(Op.getNode()); 15785 15786 if (IsNegPow2) { 15787 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15788 Created.push_back(Op.getNode()); 15789 } 15790 15791 return Op; 15792 } 15793 15794 //===----------------------------------------------------------------------===// 15795 // Inline Assembly Support 15796 //===----------------------------------------------------------------------===// 15797 15798 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15799 KnownBits &Known, 15800 const APInt &DemandedElts, 15801 const SelectionDAG &DAG, 15802 unsigned Depth) const { 15803 Known.resetAll(); 15804 switch (Op.getOpcode()) { 15805 default: break; 15806 case PPCISD::LBRX: { 15807 // lhbrx is known to have the top bits cleared out. 15808 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15809 Known.Zero = 0xFFFF0000; 15810 break; 15811 } 15812 case ISD::INTRINSIC_WO_CHAIN: { 15813 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15814 default: break; 15815 case Intrinsic::ppc_altivec_vcmpbfp_p: 15816 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15817 case Intrinsic::ppc_altivec_vcmpequb_p: 15818 case Intrinsic::ppc_altivec_vcmpequh_p: 15819 case Intrinsic::ppc_altivec_vcmpequw_p: 15820 case Intrinsic::ppc_altivec_vcmpequd_p: 15821 case Intrinsic::ppc_altivec_vcmpequq_p: 15822 case Intrinsic::ppc_altivec_vcmpgefp_p: 15823 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15824 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15825 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15826 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15827 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15828 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15829 case Intrinsic::ppc_altivec_vcmpgtub_p: 15830 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15831 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15832 case Intrinsic::ppc_altivec_vcmpgtud_p: 15833 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15834 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15835 break; 15836 } 15837 break; 15838 } 15839 case ISD::INTRINSIC_W_CHAIN: { 15840 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 15841 default: 15842 break; 15843 case Intrinsic::ppc_load2r: 15844 // Top bits are cleared for load2r (which is the same as lhbrx). 15845 Known.Zero = 0xFFFF0000; 15846 break; 15847 } 15848 break; 15849 } 15850 } 15851 } 15852 15853 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15854 switch (Subtarget.getCPUDirective()) { 15855 default: break; 15856 case PPC::DIR_970: 15857 case PPC::DIR_PWR4: 15858 case PPC::DIR_PWR5: 15859 case PPC::DIR_PWR5X: 15860 case PPC::DIR_PWR6: 15861 case PPC::DIR_PWR6X: 15862 case PPC::DIR_PWR7: 15863 case PPC::DIR_PWR8: 15864 case PPC::DIR_PWR9: 15865 case PPC::DIR_PWR10: 15866 case PPC::DIR_PWR_FUTURE: { 15867 if (!ML) 15868 break; 15869 15870 if (!DisableInnermostLoopAlign32) { 15871 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15872 // so that we can decrease cache misses and branch-prediction misses. 15873 // Actual alignment of the loop will depend on the hotness check and other 15874 // logic in alignBlocks. 15875 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15876 return Align(32); 15877 } 15878 15879 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15880 15881 // For small loops (between 5 and 8 instructions), align to a 32-byte 15882 // boundary so that the entire loop fits in one instruction-cache line. 15883 uint64_t LoopSize = 0; 15884 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15885 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15886 LoopSize += TII->getInstSizeInBytes(*J); 15887 if (LoopSize > 32) 15888 break; 15889 } 15890 15891 if (LoopSize > 16 && LoopSize <= 32) 15892 return Align(32); 15893 15894 break; 15895 } 15896 } 15897 15898 return TargetLowering::getPrefLoopAlignment(ML); 15899 } 15900 15901 /// getConstraintType - Given a constraint, return the type of 15902 /// constraint it is for this target. 15903 PPCTargetLowering::ConstraintType 15904 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15905 if (Constraint.size() == 1) { 15906 switch (Constraint[0]) { 15907 default: break; 15908 case 'b': 15909 case 'r': 15910 case 'f': 15911 case 'd': 15912 case 'v': 15913 case 'y': 15914 return C_RegisterClass; 15915 case 'Z': 15916 // FIXME: While Z does indicate a memory constraint, it specifically 15917 // indicates an r+r address (used in conjunction with the 'y' modifier 15918 // in the replacement string). Currently, we're forcing the base 15919 // register to be r0 in the asm printer (which is interpreted as zero) 15920 // and forming the complete address in the second register. This is 15921 // suboptimal. 15922 return C_Memory; 15923 } 15924 } else if (Constraint == "wc") { // individual CR bits. 15925 return C_RegisterClass; 15926 } else if (Constraint == "wa" || Constraint == "wd" || 15927 Constraint == "wf" || Constraint == "ws" || 15928 Constraint == "wi" || Constraint == "ww") { 15929 return C_RegisterClass; // VSX registers. 15930 } 15931 return TargetLowering::getConstraintType(Constraint); 15932 } 15933 15934 /// Examine constraint type and operand type and determine a weight value. 15935 /// This object must already have been set up with the operand type 15936 /// and the current alternative constraint selected. 15937 TargetLowering::ConstraintWeight 15938 PPCTargetLowering::getSingleConstraintMatchWeight( 15939 AsmOperandInfo &info, const char *constraint) const { 15940 ConstraintWeight weight = CW_Invalid; 15941 Value *CallOperandVal = info.CallOperandVal; 15942 // If we don't have a value, we can't do a match, 15943 // but allow it at the lowest weight. 15944 if (!CallOperandVal) 15945 return CW_Default; 15946 Type *type = CallOperandVal->getType(); 15947 15948 // Look at the constraint type. 15949 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15950 return CW_Register; // an individual CR bit. 15951 else if ((StringRef(constraint) == "wa" || 15952 StringRef(constraint) == "wd" || 15953 StringRef(constraint) == "wf") && 15954 type->isVectorTy()) 15955 return CW_Register; 15956 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15957 return CW_Register; // just hold 64-bit integers data. 15958 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15959 return CW_Register; 15960 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15961 return CW_Register; 15962 15963 switch (*constraint) { 15964 default: 15965 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15966 break; 15967 case 'b': 15968 if (type->isIntegerTy()) 15969 weight = CW_Register; 15970 break; 15971 case 'f': 15972 if (type->isFloatTy()) 15973 weight = CW_Register; 15974 break; 15975 case 'd': 15976 if (type->isDoubleTy()) 15977 weight = CW_Register; 15978 break; 15979 case 'v': 15980 if (type->isVectorTy()) 15981 weight = CW_Register; 15982 break; 15983 case 'y': 15984 weight = CW_Register; 15985 break; 15986 case 'Z': 15987 weight = CW_Memory; 15988 break; 15989 } 15990 return weight; 15991 } 15992 15993 std::pair<unsigned, const TargetRegisterClass *> 15994 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15995 StringRef Constraint, 15996 MVT VT) const { 15997 if (Constraint.size() == 1) { 15998 // GCC RS6000 Constraint Letters 15999 switch (Constraint[0]) { 16000 case 'b': // R1-R31 16001 if (VT == MVT::i64 && Subtarget.isPPC64()) 16002 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 16003 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 16004 case 'r': // R0-R31 16005 if (VT == MVT::i64 && Subtarget.isPPC64()) 16006 return std::make_pair(0U, &PPC::G8RCRegClass); 16007 return std::make_pair(0U, &PPC::GPRCRegClass); 16008 // 'd' and 'f' constraints are both defined to be "the floating point 16009 // registers", where one is for 32-bit and the other for 64-bit. We don't 16010 // really care overly much here so just give them all the same reg classes. 16011 case 'd': 16012 case 'f': 16013 if (Subtarget.hasSPE()) { 16014 if (VT == MVT::f32 || VT == MVT::i32) 16015 return std::make_pair(0U, &PPC::GPRCRegClass); 16016 if (VT == MVT::f64 || VT == MVT::i64) 16017 return std::make_pair(0U, &PPC::SPERCRegClass); 16018 } else { 16019 if (VT == MVT::f32 || VT == MVT::i32) 16020 return std::make_pair(0U, &PPC::F4RCRegClass); 16021 if (VT == MVT::f64 || VT == MVT::i64) 16022 return std::make_pair(0U, &PPC::F8RCRegClass); 16023 } 16024 break; 16025 case 'v': 16026 if (Subtarget.hasAltivec() && VT.isVector()) 16027 return std::make_pair(0U, &PPC::VRRCRegClass); 16028 else if (Subtarget.hasVSX()) 16029 // Scalars in Altivec registers only make sense with VSX. 16030 return std::make_pair(0U, &PPC::VFRCRegClass); 16031 break; 16032 case 'y': // crrc 16033 return std::make_pair(0U, &PPC::CRRCRegClass); 16034 } 16035 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 16036 // An individual CR bit. 16037 return std::make_pair(0U, &PPC::CRBITRCRegClass); 16038 } else if ((Constraint == "wa" || Constraint == "wd" || 16039 Constraint == "wf" || Constraint == "wi") && 16040 Subtarget.hasVSX()) { 16041 // A VSX register for either a scalar (FP) or vector. There is no 16042 // support for single precision scalars on subtargets prior to Power8. 16043 if (VT.isVector()) 16044 return std::make_pair(0U, &PPC::VSRCRegClass); 16045 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16046 return std::make_pair(0U, &PPC::VSSRCRegClass); 16047 return std::make_pair(0U, &PPC::VSFRCRegClass); 16048 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 16049 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16050 return std::make_pair(0U, &PPC::VSSRCRegClass); 16051 else 16052 return std::make_pair(0U, &PPC::VSFRCRegClass); 16053 } else if (Constraint == "lr") { 16054 if (VT == MVT::i64) 16055 return std::make_pair(0U, &PPC::LR8RCRegClass); 16056 else 16057 return std::make_pair(0U, &PPC::LRRCRegClass); 16058 } 16059 16060 // Handle special cases of physical registers that are not properly handled 16061 // by the base class. 16062 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 16063 // If we name a VSX register, we can't defer to the base class because it 16064 // will not recognize the correct register (their names will be VSL{0-31} 16065 // and V{0-31} so they won't match). So we match them here. 16066 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 16067 int VSNum = atoi(Constraint.data() + 3); 16068 assert(VSNum >= 0 && VSNum <= 63 && 16069 "Attempted to access a vsr out of range"); 16070 if (VSNum < 32) 16071 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 16072 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 16073 } 16074 16075 // For float registers, we can't defer to the base class as it will match 16076 // the SPILLTOVSRRC class. 16077 if (Constraint.size() > 3 && Constraint[1] == 'f') { 16078 int RegNum = atoi(Constraint.data() + 2); 16079 if (RegNum > 31 || RegNum < 0) 16080 report_fatal_error("Invalid floating point register number"); 16081 if (VT == MVT::f32 || VT == MVT::i32) 16082 return Subtarget.hasSPE() 16083 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 16084 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 16085 if (VT == MVT::f64 || VT == MVT::i64) 16086 return Subtarget.hasSPE() 16087 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 16088 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 16089 } 16090 } 16091 16092 std::pair<unsigned, const TargetRegisterClass *> R = 16093 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 16094 16095 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 16096 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 16097 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 16098 // register. 16099 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 16100 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 16101 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 16102 PPC::GPRCRegClass.contains(R.first)) 16103 return std::make_pair(TRI->getMatchingSuperReg(R.first, 16104 PPC::sub_32, &PPC::G8RCRegClass), 16105 &PPC::G8RCRegClass); 16106 16107 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 16108 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) { 16109 R.first = PPC::CR0; 16110 R.second = &PPC::CRRCRegClass; 16111 } 16112 // FIXME: This warning should ideally be emitted in the front end. 16113 const auto &TM = getTargetMachine(); 16114 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 16115 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 16116 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 16117 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 16118 errs() << "warning: vector registers 20 to 32 are reserved in the " 16119 "default AIX AltiVec ABI and cannot be used\n"; 16120 } 16121 16122 return R; 16123 } 16124 16125 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16126 /// vector. If it is invalid, don't add anything to Ops. 16127 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16128 std::string &Constraint, 16129 std::vector<SDValue>&Ops, 16130 SelectionDAG &DAG) const { 16131 SDValue Result; 16132 16133 // Only support length 1 constraints. 16134 if (Constraint.length() > 1) return; 16135 16136 char Letter = Constraint[0]; 16137 switch (Letter) { 16138 default: break; 16139 case 'I': 16140 case 'J': 16141 case 'K': 16142 case 'L': 16143 case 'M': 16144 case 'N': 16145 case 'O': 16146 case 'P': { 16147 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 16148 if (!CST) return; // Must be an immediate to match. 16149 SDLoc dl(Op); 16150 int64_t Value = CST->getSExtValue(); 16151 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 16152 // numbers are printed as such. 16153 switch (Letter) { 16154 default: llvm_unreachable("Unknown constraint letter!"); 16155 case 'I': // "I" is a signed 16-bit constant. 16156 if (isInt<16>(Value)) 16157 Result = DAG.getTargetConstant(Value, dl, TCVT); 16158 break; 16159 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 16160 if (isShiftedUInt<16, 16>(Value)) 16161 Result = DAG.getTargetConstant(Value, dl, TCVT); 16162 break; 16163 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 16164 if (isShiftedInt<16, 16>(Value)) 16165 Result = DAG.getTargetConstant(Value, dl, TCVT); 16166 break; 16167 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 16168 if (isUInt<16>(Value)) 16169 Result = DAG.getTargetConstant(Value, dl, TCVT); 16170 break; 16171 case 'M': // "M" is a constant that is greater than 31. 16172 if (Value > 31) 16173 Result = DAG.getTargetConstant(Value, dl, TCVT); 16174 break; 16175 case 'N': // "N" is a positive constant that is an exact power of two. 16176 if (Value > 0 && isPowerOf2_64(Value)) 16177 Result = DAG.getTargetConstant(Value, dl, TCVT); 16178 break; 16179 case 'O': // "O" is the constant zero. 16180 if (Value == 0) 16181 Result = DAG.getTargetConstant(Value, dl, TCVT); 16182 break; 16183 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 16184 if (isInt<16>(-Value)) 16185 Result = DAG.getTargetConstant(Value, dl, TCVT); 16186 break; 16187 } 16188 break; 16189 } 16190 } 16191 16192 if (Result.getNode()) { 16193 Ops.push_back(Result); 16194 return; 16195 } 16196 16197 // Handle standard constraint letters. 16198 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16199 } 16200 16201 // isLegalAddressingMode - Return true if the addressing mode represented 16202 // by AM is legal for this target, for a load/store of the specified type. 16203 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16204 const AddrMode &AM, Type *Ty, 16205 unsigned AS, 16206 Instruction *I) const { 16207 // Vector type r+i form is supported since power9 as DQ form. We don't check 16208 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 16209 // imm form is preferred and the offset can be adjusted to use imm form later 16210 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 16211 // max offset to check legal addressing mode, we should be a little aggressive 16212 // to contain other offsets for that LSRUse. 16213 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 16214 return false; 16215 16216 // PPC allows a sign-extended 16-bit immediate field. 16217 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 16218 return false; 16219 16220 // No global is ever allowed as a base. 16221 if (AM.BaseGV) 16222 return false; 16223 16224 // PPC only support r+r, 16225 switch (AM.Scale) { 16226 case 0: // "r+i" or just "i", depending on HasBaseReg. 16227 break; 16228 case 1: 16229 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 16230 return false; 16231 // Otherwise we have r+r or r+i. 16232 break; 16233 case 2: 16234 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 16235 return false; 16236 // Allow 2*r as r+r. 16237 break; 16238 default: 16239 // No other scales are supported. 16240 return false; 16241 } 16242 16243 return true; 16244 } 16245 16246 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 16247 SelectionDAG &DAG) const { 16248 MachineFunction &MF = DAG.getMachineFunction(); 16249 MachineFrameInfo &MFI = MF.getFrameInfo(); 16250 MFI.setReturnAddressIsTaken(true); 16251 16252 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 16253 return SDValue(); 16254 16255 SDLoc dl(Op); 16256 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16257 16258 // Make sure the function does not optimize away the store of the RA to 16259 // the stack. 16260 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 16261 FuncInfo->setLRStoreRequired(); 16262 bool isPPC64 = Subtarget.isPPC64(); 16263 auto PtrVT = getPointerTy(MF.getDataLayout()); 16264 16265 if (Depth > 0) { 16266 // The link register (return address) is saved in the caller's frame 16267 // not the callee's stack frame. So we must get the caller's frame 16268 // address and load the return address at the LR offset from there. 16269 SDValue FrameAddr = 16270 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16271 LowerFRAMEADDR(Op, DAG), MachinePointerInfo()); 16272 SDValue Offset = 16273 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 16274 isPPC64 ? MVT::i64 : MVT::i32); 16275 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 16276 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 16277 MachinePointerInfo()); 16278 } 16279 16280 // Just load the return address off the stack. 16281 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 16282 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 16283 MachinePointerInfo()); 16284 } 16285 16286 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 16287 SelectionDAG &DAG) const { 16288 SDLoc dl(Op); 16289 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16290 16291 MachineFunction &MF = DAG.getMachineFunction(); 16292 MachineFrameInfo &MFI = MF.getFrameInfo(); 16293 MFI.setFrameAddressIsTaken(true); 16294 16295 EVT PtrVT = getPointerTy(MF.getDataLayout()); 16296 bool isPPC64 = PtrVT == MVT::i64; 16297 16298 // Naked functions never have a frame pointer, and so we use r1. For all 16299 // other functions, this decision must be delayed until during PEI. 16300 unsigned FrameReg; 16301 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 16302 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 16303 else 16304 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 16305 16306 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 16307 PtrVT); 16308 while (Depth--) 16309 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16310 FrameAddr, MachinePointerInfo()); 16311 return FrameAddr; 16312 } 16313 16314 // FIXME? Maybe this could be a TableGen attribute on some registers and 16315 // this table could be generated automatically from RegInfo. 16316 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 16317 const MachineFunction &MF) const { 16318 bool isPPC64 = Subtarget.isPPC64(); 16319 16320 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 16321 if (!is64Bit && VT != LLT::scalar(32)) 16322 report_fatal_error("Invalid register global variable type"); 16323 16324 Register Reg = StringSwitch<Register>(RegName) 16325 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 16326 .Case("r2", isPPC64 ? Register() : PPC::R2) 16327 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 16328 .Default(Register()); 16329 16330 if (Reg) 16331 return Reg; 16332 report_fatal_error("Invalid register name global variable"); 16333 } 16334 16335 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 16336 // 32-bit SVR4 ABI access everything as got-indirect. 16337 if (Subtarget.is32BitELFABI()) 16338 return true; 16339 16340 // AIX accesses everything indirectly through the TOC, which is similar to 16341 // the GOT. 16342 if (Subtarget.isAIXABI()) 16343 return true; 16344 16345 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 16346 // If it is small or large code model, module locals are accessed 16347 // indirectly by loading their address from .toc/.got. 16348 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 16349 return true; 16350 16351 // JumpTable and BlockAddress are accessed as got-indirect. 16352 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 16353 return true; 16354 16355 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 16356 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 16357 16358 return false; 16359 } 16360 16361 bool 16362 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16363 // The PowerPC target isn't yet aware of offsets. 16364 return false; 16365 } 16366 16367 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16368 const CallInst &I, 16369 MachineFunction &MF, 16370 unsigned Intrinsic) const { 16371 switch (Intrinsic) { 16372 case Intrinsic::ppc_atomicrmw_xchg_i128: 16373 case Intrinsic::ppc_atomicrmw_add_i128: 16374 case Intrinsic::ppc_atomicrmw_sub_i128: 16375 case Intrinsic::ppc_atomicrmw_nand_i128: 16376 case Intrinsic::ppc_atomicrmw_and_i128: 16377 case Intrinsic::ppc_atomicrmw_or_i128: 16378 case Intrinsic::ppc_atomicrmw_xor_i128: 16379 case Intrinsic::ppc_cmpxchg_i128: 16380 Info.opc = ISD::INTRINSIC_W_CHAIN; 16381 Info.memVT = MVT::i128; 16382 Info.ptrVal = I.getArgOperand(0); 16383 Info.offset = 0; 16384 Info.align = Align(16); 16385 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 16386 MachineMemOperand::MOVolatile; 16387 return true; 16388 case Intrinsic::ppc_atomic_load_i128: 16389 Info.opc = ISD::INTRINSIC_W_CHAIN; 16390 Info.memVT = MVT::i128; 16391 Info.ptrVal = I.getArgOperand(0); 16392 Info.offset = 0; 16393 Info.align = Align(16); 16394 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16395 return true; 16396 case Intrinsic::ppc_atomic_store_i128: 16397 Info.opc = ISD::INTRINSIC_VOID; 16398 Info.memVT = MVT::i128; 16399 Info.ptrVal = I.getArgOperand(2); 16400 Info.offset = 0; 16401 Info.align = Align(16); 16402 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16403 return true; 16404 case Intrinsic::ppc_altivec_lvx: 16405 case Intrinsic::ppc_altivec_lvxl: 16406 case Intrinsic::ppc_altivec_lvebx: 16407 case Intrinsic::ppc_altivec_lvehx: 16408 case Intrinsic::ppc_altivec_lvewx: 16409 case Intrinsic::ppc_vsx_lxvd2x: 16410 case Intrinsic::ppc_vsx_lxvw4x: 16411 case Intrinsic::ppc_vsx_lxvd2x_be: 16412 case Intrinsic::ppc_vsx_lxvw4x_be: 16413 case Intrinsic::ppc_vsx_lxvl: 16414 case Intrinsic::ppc_vsx_lxvll: { 16415 EVT VT; 16416 switch (Intrinsic) { 16417 case Intrinsic::ppc_altivec_lvebx: 16418 VT = MVT::i8; 16419 break; 16420 case Intrinsic::ppc_altivec_lvehx: 16421 VT = MVT::i16; 16422 break; 16423 case Intrinsic::ppc_altivec_lvewx: 16424 VT = MVT::i32; 16425 break; 16426 case Intrinsic::ppc_vsx_lxvd2x: 16427 case Intrinsic::ppc_vsx_lxvd2x_be: 16428 VT = MVT::v2f64; 16429 break; 16430 default: 16431 VT = MVT::v4i32; 16432 break; 16433 } 16434 16435 Info.opc = ISD::INTRINSIC_W_CHAIN; 16436 Info.memVT = VT; 16437 Info.ptrVal = I.getArgOperand(0); 16438 Info.offset = -VT.getStoreSize()+1; 16439 Info.size = 2*VT.getStoreSize()-1; 16440 Info.align = Align(1); 16441 Info.flags = MachineMemOperand::MOLoad; 16442 return true; 16443 } 16444 case Intrinsic::ppc_altivec_stvx: 16445 case Intrinsic::ppc_altivec_stvxl: 16446 case Intrinsic::ppc_altivec_stvebx: 16447 case Intrinsic::ppc_altivec_stvehx: 16448 case Intrinsic::ppc_altivec_stvewx: 16449 case Intrinsic::ppc_vsx_stxvd2x: 16450 case Intrinsic::ppc_vsx_stxvw4x: 16451 case Intrinsic::ppc_vsx_stxvd2x_be: 16452 case Intrinsic::ppc_vsx_stxvw4x_be: 16453 case Intrinsic::ppc_vsx_stxvl: 16454 case Intrinsic::ppc_vsx_stxvll: { 16455 EVT VT; 16456 switch (Intrinsic) { 16457 case Intrinsic::ppc_altivec_stvebx: 16458 VT = MVT::i8; 16459 break; 16460 case Intrinsic::ppc_altivec_stvehx: 16461 VT = MVT::i16; 16462 break; 16463 case Intrinsic::ppc_altivec_stvewx: 16464 VT = MVT::i32; 16465 break; 16466 case Intrinsic::ppc_vsx_stxvd2x: 16467 case Intrinsic::ppc_vsx_stxvd2x_be: 16468 VT = MVT::v2f64; 16469 break; 16470 default: 16471 VT = MVT::v4i32; 16472 break; 16473 } 16474 16475 Info.opc = ISD::INTRINSIC_VOID; 16476 Info.memVT = VT; 16477 Info.ptrVal = I.getArgOperand(1); 16478 Info.offset = -VT.getStoreSize()+1; 16479 Info.size = 2*VT.getStoreSize()-1; 16480 Info.align = Align(1); 16481 Info.flags = MachineMemOperand::MOStore; 16482 return true; 16483 } 16484 default: 16485 break; 16486 } 16487 16488 return false; 16489 } 16490 16491 /// It returns EVT::Other if the type should be determined using generic 16492 /// target-independent logic. 16493 EVT PPCTargetLowering::getOptimalMemOpType( 16494 const MemOp &Op, const AttributeList &FuncAttributes) const { 16495 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16496 // We should use Altivec/VSX loads and stores when available. For unaligned 16497 // addresses, unaligned VSX loads are only fast starting with the P8. 16498 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16499 (Op.isAligned(Align(16)) || 16500 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16501 return MVT::v4i32; 16502 } 16503 16504 if (Subtarget.isPPC64()) { 16505 return MVT::i64; 16506 } 16507 16508 return MVT::i32; 16509 } 16510 16511 /// Returns true if it is beneficial to convert a load of a constant 16512 /// to just the constant itself. 16513 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16514 Type *Ty) const { 16515 assert(Ty->isIntegerTy()); 16516 16517 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16518 return !(BitSize == 0 || BitSize > 64); 16519 } 16520 16521 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16522 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16523 return false; 16524 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16525 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16526 return NumBits1 == 64 && NumBits2 == 32; 16527 } 16528 16529 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16530 if (!VT1.isInteger() || !VT2.isInteger()) 16531 return false; 16532 unsigned NumBits1 = VT1.getSizeInBits(); 16533 unsigned NumBits2 = VT2.getSizeInBits(); 16534 return NumBits1 == 64 && NumBits2 == 32; 16535 } 16536 16537 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16538 // Generally speaking, zexts are not free, but they are free when they can be 16539 // folded with other operations. 16540 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16541 EVT MemVT = LD->getMemoryVT(); 16542 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16543 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16544 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16545 LD->getExtensionType() == ISD::ZEXTLOAD)) 16546 return true; 16547 } 16548 16549 // FIXME: Add other cases... 16550 // - 32-bit shifts with a zext to i64 16551 // - zext after ctlz, bswap, etc. 16552 // - zext after and by a constant mask 16553 16554 return TargetLowering::isZExtFree(Val, VT2); 16555 } 16556 16557 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16558 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16559 "invalid fpext types"); 16560 // Extending to float128 is not free. 16561 if (DestVT == MVT::f128) 16562 return false; 16563 return true; 16564 } 16565 16566 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16567 return isInt<16>(Imm) || isUInt<16>(Imm); 16568 } 16569 16570 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16571 return isInt<16>(Imm) || isUInt<16>(Imm); 16572 } 16573 16574 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 16575 MachineMemOperand::Flags, 16576 bool *Fast) const { 16577 if (DisablePPCUnaligned) 16578 return false; 16579 16580 // PowerPC supports unaligned memory access for simple non-vector types. 16581 // Although accessing unaligned addresses is not as efficient as accessing 16582 // aligned addresses, it is generally more efficient than manual expansion, 16583 // and generally only traps for software emulation when crossing page 16584 // boundaries. 16585 16586 if (!VT.isSimple()) 16587 return false; 16588 16589 if (VT.isFloatingPoint() && !VT.isVector() && 16590 !Subtarget.allowsUnalignedFPAccess()) 16591 return false; 16592 16593 if (VT.getSimpleVT().isVector()) { 16594 if (Subtarget.hasVSX()) { 16595 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16596 VT != MVT::v4f32 && VT != MVT::v4i32) 16597 return false; 16598 } else { 16599 return false; 16600 } 16601 } 16602 16603 if (VT == MVT::ppcf128) 16604 return false; 16605 16606 if (Fast) 16607 *Fast = true; 16608 16609 return true; 16610 } 16611 16612 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16613 SDValue C) const { 16614 // Check integral scalar types. 16615 if (!VT.isScalarInteger()) 16616 return false; 16617 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16618 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16619 return false; 16620 // This transformation will generate >= 2 operations. But the following 16621 // cases will generate <= 2 instructions during ISEL. So exclude them. 16622 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16623 // HW instruction, ie. MULLI 16624 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16625 // instruction is needed than case 1, ie. MULLI and RLDICR 16626 int64_t Imm = ConstNode->getSExtValue(); 16627 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16628 Imm >>= Shift; 16629 if (isInt<16>(Imm)) 16630 return false; 16631 uint64_t UImm = static_cast<uint64_t>(Imm); 16632 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16633 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16634 return true; 16635 } 16636 return false; 16637 } 16638 16639 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16640 EVT VT) const { 16641 return isFMAFasterThanFMulAndFAdd( 16642 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16643 } 16644 16645 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16646 Type *Ty) const { 16647 switch (Ty->getScalarType()->getTypeID()) { 16648 case Type::FloatTyID: 16649 case Type::DoubleTyID: 16650 return true; 16651 case Type::FP128TyID: 16652 return Subtarget.hasP9Vector(); 16653 default: 16654 return false; 16655 } 16656 } 16657 16658 // FIXME: add more patterns which are not profitable to hoist. 16659 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16660 if (!I->hasOneUse()) 16661 return true; 16662 16663 Instruction *User = I->user_back(); 16664 assert(User && "A single use instruction with no uses."); 16665 16666 switch (I->getOpcode()) { 16667 case Instruction::FMul: { 16668 // Don't break FMA, PowerPC prefers FMA. 16669 if (User->getOpcode() != Instruction::FSub && 16670 User->getOpcode() != Instruction::FAdd) 16671 return true; 16672 16673 const TargetOptions &Options = getTargetMachine().Options; 16674 const Function *F = I->getFunction(); 16675 const DataLayout &DL = F->getParent()->getDataLayout(); 16676 Type *Ty = User->getOperand(0)->getType(); 16677 16678 return !( 16679 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16680 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16681 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16682 } 16683 case Instruction::Load: { 16684 // Don't break "store (load float*)" pattern, this pattern will be combined 16685 // to "store (load int32)" in later InstCombine pass. See function 16686 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16687 // cycles than loading a 32 bit integer. 16688 LoadInst *LI = cast<LoadInst>(I); 16689 // For the loads that combineLoadToOperationType does nothing, like 16690 // ordered load, it should be profitable to hoist them. 16691 // For swifterror load, it can only be used for pointer to pointer type, so 16692 // later type check should get rid of this case. 16693 if (!LI->isUnordered()) 16694 return true; 16695 16696 if (User->getOpcode() != Instruction::Store) 16697 return true; 16698 16699 if (I->getType()->getTypeID() != Type::FloatTyID) 16700 return true; 16701 16702 return false; 16703 } 16704 default: 16705 return true; 16706 } 16707 return true; 16708 } 16709 16710 const MCPhysReg * 16711 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16712 // LR is a callee-save register, but we must treat it as clobbered by any call 16713 // site. Hence we include LR in the scratch registers, which are in turn added 16714 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16715 // to CTR, which is used by any indirect call. 16716 static const MCPhysReg ScratchRegs[] = { 16717 PPC::X12, PPC::LR8, PPC::CTR8, 0 16718 }; 16719 16720 return ScratchRegs; 16721 } 16722 16723 Register PPCTargetLowering::getExceptionPointerRegister( 16724 const Constant *PersonalityFn) const { 16725 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16726 } 16727 16728 Register PPCTargetLowering::getExceptionSelectorRegister( 16729 const Constant *PersonalityFn) const { 16730 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16731 } 16732 16733 bool 16734 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16735 EVT VT , unsigned DefinedValues) const { 16736 if (VT == MVT::v2i64) 16737 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16738 16739 if (Subtarget.hasVSX()) 16740 return true; 16741 16742 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16743 } 16744 16745 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16746 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16747 return TargetLowering::getSchedulingPreference(N); 16748 16749 return Sched::ILP; 16750 } 16751 16752 // Create a fast isel object. 16753 FastISel * 16754 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16755 const TargetLibraryInfo *LibInfo) const { 16756 return PPC::createFastISel(FuncInfo, LibInfo); 16757 } 16758 16759 // 'Inverted' means the FMA opcode after negating one multiplicand. 16760 // For example, (fma -a b c) = (fnmsub a b c) 16761 static unsigned invertFMAOpcode(unsigned Opc) { 16762 switch (Opc) { 16763 default: 16764 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16765 case ISD::FMA: 16766 return PPCISD::FNMSUB; 16767 case PPCISD::FNMSUB: 16768 return ISD::FMA; 16769 } 16770 } 16771 16772 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16773 bool LegalOps, bool OptForSize, 16774 NegatibleCost &Cost, 16775 unsigned Depth) const { 16776 if (Depth > SelectionDAG::MaxRecursionDepth) 16777 return SDValue(); 16778 16779 unsigned Opc = Op.getOpcode(); 16780 EVT VT = Op.getValueType(); 16781 SDNodeFlags Flags = Op.getNode()->getFlags(); 16782 16783 switch (Opc) { 16784 case PPCISD::FNMSUB: 16785 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16786 break; 16787 16788 const TargetOptions &Options = getTargetMachine().Options; 16789 SDValue N0 = Op.getOperand(0); 16790 SDValue N1 = Op.getOperand(1); 16791 SDValue N2 = Op.getOperand(2); 16792 SDLoc Loc(Op); 16793 16794 NegatibleCost N2Cost = NegatibleCost::Expensive; 16795 SDValue NegN2 = 16796 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16797 16798 if (!NegN2) 16799 return SDValue(); 16800 16801 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16802 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16803 // These transformations may change sign of zeroes. For example, 16804 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16805 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16806 // Try and choose the cheaper one to negate. 16807 NegatibleCost N0Cost = NegatibleCost::Expensive; 16808 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16809 N0Cost, Depth + 1); 16810 16811 NegatibleCost N1Cost = NegatibleCost::Expensive; 16812 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16813 N1Cost, Depth + 1); 16814 16815 if (NegN0 && N0Cost <= N1Cost) { 16816 Cost = std::min(N0Cost, N2Cost); 16817 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16818 } else if (NegN1) { 16819 Cost = std::min(N1Cost, N2Cost); 16820 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16821 } 16822 } 16823 16824 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16825 if (isOperationLegal(ISD::FMA, VT)) { 16826 Cost = N2Cost; 16827 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16828 } 16829 16830 break; 16831 } 16832 16833 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16834 Cost, Depth); 16835 } 16836 16837 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16838 bool PPCTargetLowering::useLoadStackGuardNode() const { 16839 if (!Subtarget.isTargetLinux()) 16840 return TargetLowering::useLoadStackGuardNode(); 16841 return true; 16842 } 16843 16844 // Override to disable global variable loading on Linux and insert AIX canary 16845 // word declaration. 16846 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16847 if (Subtarget.isAIXABI()) { 16848 M.getOrInsertGlobal(AIXSSPCanaryWordName, 16849 Type::getInt8PtrTy(M.getContext())); 16850 return; 16851 } 16852 if (!Subtarget.isTargetLinux()) 16853 return TargetLowering::insertSSPDeclarations(M); 16854 } 16855 16856 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const { 16857 if (Subtarget.isAIXABI()) 16858 return M.getGlobalVariable(AIXSSPCanaryWordName); 16859 return TargetLowering::getSDagStackGuard(M); 16860 } 16861 16862 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16863 bool ForCodeSize) const { 16864 if (!VT.isSimple() || !Subtarget.hasVSX()) 16865 return false; 16866 16867 switch(VT.getSimpleVT().SimpleTy) { 16868 default: 16869 // For FP types that are currently not supported by PPC backend, return 16870 // false. Examples: f16, f80. 16871 return false; 16872 case MVT::f32: 16873 case MVT::f64: 16874 if (Subtarget.hasPrefixInstrs()) { 16875 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 16876 return true; 16877 } 16878 LLVM_FALLTHROUGH; 16879 case MVT::ppcf128: 16880 return Imm.isPosZero(); 16881 } 16882 } 16883 16884 // For vector shift operation op, fold 16885 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16886 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16887 SelectionDAG &DAG) { 16888 SDValue N0 = N->getOperand(0); 16889 SDValue N1 = N->getOperand(1); 16890 EVT VT = N0.getValueType(); 16891 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16892 unsigned Opcode = N->getOpcode(); 16893 unsigned TargetOpcode; 16894 16895 switch (Opcode) { 16896 default: 16897 llvm_unreachable("Unexpected shift operation"); 16898 case ISD::SHL: 16899 TargetOpcode = PPCISD::SHL; 16900 break; 16901 case ISD::SRL: 16902 TargetOpcode = PPCISD::SRL; 16903 break; 16904 case ISD::SRA: 16905 TargetOpcode = PPCISD::SRA; 16906 break; 16907 } 16908 16909 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16910 N1->getOpcode() == ISD::AND) 16911 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16912 if (Mask->getZExtValue() == OpSizeInBits - 1) 16913 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16914 16915 return SDValue(); 16916 } 16917 16918 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16919 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16920 return Value; 16921 16922 SDValue N0 = N->getOperand(0); 16923 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16924 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16925 N0.getOpcode() != ISD::SIGN_EXTEND || 16926 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16927 N->getValueType(0) != MVT::i64) 16928 return SDValue(); 16929 16930 // We can't save an operation here if the value is already extended, and 16931 // the existing shift is easier to combine. 16932 SDValue ExtsSrc = N0.getOperand(0); 16933 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16934 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16935 return SDValue(); 16936 16937 SDLoc DL(N0); 16938 SDValue ShiftBy = SDValue(CN1, 0); 16939 // We want the shift amount to be i32 on the extswli, but the shift could 16940 // have an i64. 16941 if (ShiftBy.getValueType() == MVT::i64) 16942 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16943 16944 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16945 ShiftBy); 16946 } 16947 16948 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16949 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16950 return Value; 16951 16952 return SDValue(); 16953 } 16954 16955 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16956 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16957 return Value; 16958 16959 return SDValue(); 16960 } 16961 16962 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16963 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16964 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16965 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16966 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16967 const PPCSubtarget &Subtarget) { 16968 if (!Subtarget.isPPC64()) 16969 return SDValue(); 16970 16971 SDValue LHS = N->getOperand(0); 16972 SDValue RHS = N->getOperand(1); 16973 16974 auto isZextOfCompareWithConstant = [](SDValue Op) { 16975 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16976 Op.getValueType() != MVT::i64) 16977 return false; 16978 16979 SDValue Cmp = Op.getOperand(0); 16980 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16981 Cmp.getOperand(0).getValueType() != MVT::i64) 16982 return false; 16983 16984 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16985 int64_t NegConstant = 0 - Constant->getSExtValue(); 16986 // Due to the limitations of the addi instruction, 16987 // -C is required to be [-32768, 32767]. 16988 return isInt<16>(NegConstant); 16989 } 16990 16991 return false; 16992 }; 16993 16994 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16995 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16996 16997 // If there is a pattern, canonicalize a zext operand to the RHS. 16998 if (LHSHasPattern && !RHSHasPattern) 16999 std::swap(LHS, RHS); 17000 else if (!LHSHasPattern && !RHSHasPattern) 17001 return SDValue(); 17002 17003 SDLoc DL(N); 17004 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 17005 SDValue Cmp = RHS.getOperand(0); 17006 SDValue Z = Cmp.getOperand(0); 17007 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1)); 17008 int64_t NegConstant = 0 - Constant->getSExtValue(); 17009 17010 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 17011 default: break; 17012 case ISD::SETNE: { 17013 // when C == 0 17014 // --> addze X, (addic Z, -1).carry 17015 // / 17016 // add X, (zext(setne Z, C))-- 17017 // \ when -32768 <= -C <= 32767 && C != 0 17018 // --> addze X, (addic (addi Z, -C), -1).carry 17019 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17020 DAG.getConstant(NegConstant, DL, MVT::i64)); 17021 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17022 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17023 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 17024 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17025 SDValue(Addc.getNode(), 1)); 17026 } 17027 case ISD::SETEQ: { 17028 // when C == 0 17029 // --> addze X, (subfic Z, 0).carry 17030 // / 17031 // add X, (zext(sete Z, C))-- 17032 // \ when -32768 <= -C <= 32767 && C != 0 17033 // --> addze X, (subfic (addi Z, -C), 0).carry 17034 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17035 DAG.getConstant(NegConstant, DL, MVT::i64)); 17036 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17037 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17038 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 17039 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17040 SDValue(Subc.getNode(), 1)); 17041 } 17042 } 17043 17044 return SDValue(); 17045 } 17046 17047 // Transform 17048 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 17049 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 17050 // In this case both C1 and C2 must be known constants. 17051 // C1+C2 must fit into a 34 bit signed integer. 17052 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 17053 const PPCSubtarget &Subtarget) { 17054 if (!Subtarget.isUsingPCRelativeCalls()) 17055 return SDValue(); 17056 17057 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 17058 // If we find that node try to cast the Global Address and the Constant. 17059 SDValue LHS = N->getOperand(0); 17060 SDValue RHS = N->getOperand(1); 17061 17062 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17063 std::swap(LHS, RHS); 17064 17065 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17066 return SDValue(); 17067 17068 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 17069 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 17070 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 17071 17072 // Check that both casts succeeded. 17073 if (!GSDN || !ConstNode) 17074 return SDValue(); 17075 17076 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 17077 SDLoc DL(GSDN); 17078 17079 // The signed int offset needs to fit in 34 bits. 17080 if (!isInt<34>(NewOffset)) 17081 return SDValue(); 17082 17083 // The new global address is a copy of the old global address except 17084 // that it has the updated Offset. 17085 SDValue GA = 17086 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 17087 NewOffset, GSDN->getTargetFlags()); 17088 SDValue MatPCRel = 17089 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 17090 return MatPCRel; 17091 } 17092 17093 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 17094 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 17095 return Value; 17096 17097 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 17098 return Value; 17099 17100 return SDValue(); 17101 } 17102 17103 // Detect TRUNCATE operations on bitcasts of float128 values. 17104 // What we are looking for here is the situtation where we extract a subset 17105 // of bits from a 128 bit float. 17106 // This can be of two forms: 17107 // 1) BITCAST of f128 feeding TRUNCATE 17108 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 17109 // The reason this is required is because we do not have a legal i128 type 17110 // and so we want to prevent having to store the f128 and then reload part 17111 // of it. 17112 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 17113 DAGCombinerInfo &DCI) const { 17114 // If we are using CRBits then try that first. 17115 if (Subtarget.useCRBits()) { 17116 // Check if CRBits did anything and return that if it did. 17117 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 17118 return CRTruncValue; 17119 } 17120 17121 SDLoc dl(N); 17122 SDValue Op0 = N->getOperand(0); 17123 17124 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 17125 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 17126 EVT VT = N->getValueType(0); 17127 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17128 return SDValue(); 17129 SDValue Sub = Op0.getOperand(0); 17130 if (Sub.getOpcode() == ISD::SUB) { 17131 SDValue SubOp0 = Sub.getOperand(0); 17132 SDValue SubOp1 = Sub.getOperand(1); 17133 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 17134 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 17135 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 17136 SubOp1.getOperand(0), 17137 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 17138 } 17139 } 17140 } 17141 17142 // Looking for a truncate of i128 to i64. 17143 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 17144 return SDValue(); 17145 17146 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 17147 17148 // SRL feeding TRUNCATE. 17149 if (Op0.getOpcode() == ISD::SRL) { 17150 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 17151 // The right shift has to be by 64 bits. 17152 if (!ConstNode || ConstNode->getZExtValue() != 64) 17153 return SDValue(); 17154 17155 // Switch the element number to extract. 17156 EltToExtract = EltToExtract ? 0 : 1; 17157 // Update Op0 past the SRL. 17158 Op0 = Op0.getOperand(0); 17159 } 17160 17161 // BITCAST feeding a TRUNCATE possibly via SRL. 17162 if (Op0.getOpcode() == ISD::BITCAST && 17163 Op0.getValueType() == MVT::i128 && 17164 Op0.getOperand(0).getValueType() == MVT::f128) { 17165 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 17166 return DCI.DAG.getNode( 17167 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 17168 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 17169 } 17170 return SDValue(); 17171 } 17172 17173 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 17174 SelectionDAG &DAG = DCI.DAG; 17175 17176 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 17177 if (!ConstOpOrElement) 17178 return SDValue(); 17179 17180 // An imul is usually smaller than the alternative sequence for legal type. 17181 if (DAG.getMachineFunction().getFunction().hasMinSize() && 17182 isOperationLegal(ISD::MUL, N->getValueType(0))) 17183 return SDValue(); 17184 17185 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 17186 switch (this->Subtarget.getCPUDirective()) { 17187 default: 17188 // TODO: enhance the condition for subtarget before pwr8 17189 return false; 17190 case PPC::DIR_PWR8: 17191 // type mul add shl 17192 // scalar 4 1 1 17193 // vector 7 2 2 17194 return true; 17195 case PPC::DIR_PWR9: 17196 case PPC::DIR_PWR10: 17197 case PPC::DIR_PWR_FUTURE: 17198 // type mul add shl 17199 // scalar 5 2 2 17200 // vector 7 2 2 17201 17202 // The cycle RATIO of related operations are showed as a table above. 17203 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 17204 // scalar and vector type. For 2 instrs patterns, add/sub + shl 17205 // are 4, it is always profitable; but for 3 instrs patterns 17206 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 17207 // So we should only do it for vector type. 17208 return IsAddOne && IsNeg ? VT.isVector() : true; 17209 } 17210 }; 17211 17212 EVT VT = N->getValueType(0); 17213 SDLoc DL(N); 17214 17215 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 17216 bool IsNeg = MulAmt.isNegative(); 17217 APInt MulAmtAbs = MulAmt.abs(); 17218 17219 if ((MulAmtAbs - 1).isPowerOf2()) { 17220 // (mul x, 2^N + 1) => (add (shl x, N), x) 17221 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 17222 17223 if (!IsProfitable(IsNeg, true, VT)) 17224 return SDValue(); 17225 17226 SDValue Op0 = N->getOperand(0); 17227 SDValue Op1 = 17228 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17229 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 17230 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 17231 17232 if (!IsNeg) 17233 return Res; 17234 17235 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 17236 } else if ((MulAmtAbs + 1).isPowerOf2()) { 17237 // (mul x, 2^N - 1) => (sub (shl x, N), x) 17238 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 17239 17240 if (!IsProfitable(IsNeg, false, VT)) 17241 return SDValue(); 17242 17243 SDValue Op0 = N->getOperand(0); 17244 SDValue Op1 = 17245 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17246 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 17247 17248 if (!IsNeg) 17249 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 17250 else 17251 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 17252 17253 } else { 17254 return SDValue(); 17255 } 17256 } 17257 17258 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 17259 // in combiner since we need to check SD flags and other subtarget features. 17260 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 17261 DAGCombinerInfo &DCI) const { 17262 SDValue N0 = N->getOperand(0); 17263 SDValue N1 = N->getOperand(1); 17264 SDValue N2 = N->getOperand(2); 17265 SDNodeFlags Flags = N->getFlags(); 17266 EVT VT = N->getValueType(0); 17267 SelectionDAG &DAG = DCI.DAG; 17268 const TargetOptions &Options = getTargetMachine().Options; 17269 unsigned Opc = N->getOpcode(); 17270 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 17271 bool LegalOps = !DCI.isBeforeLegalizeOps(); 17272 SDLoc Loc(N); 17273 17274 if (!isOperationLegal(ISD::FMA, VT)) 17275 return SDValue(); 17276 17277 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 17278 // since (fnmsub a b c)=-0 while c-ab=+0. 17279 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 17280 return SDValue(); 17281 17282 // (fma (fneg a) b c) => (fnmsub a b c) 17283 // (fnmsub (fneg a) b c) => (fma a b c) 17284 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 17285 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 17286 17287 // (fma a (fneg b) c) => (fnmsub a b c) 17288 // (fnmsub a (fneg b) c) => (fma a b c) 17289 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 17290 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 17291 17292 return SDValue(); 17293 } 17294 17295 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 17296 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 17297 if (!Subtarget.is64BitELFABI()) 17298 return false; 17299 17300 // If not a tail call then no need to proceed. 17301 if (!CI->isTailCall()) 17302 return false; 17303 17304 // If sibling calls have been disabled and tail-calls aren't guaranteed 17305 // there is no reason to duplicate. 17306 auto &TM = getTargetMachine(); 17307 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 17308 return false; 17309 17310 // Can't tail call a function called indirectly, or if it has variadic args. 17311 const Function *Callee = CI->getCalledFunction(); 17312 if (!Callee || Callee->isVarArg()) 17313 return false; 17314 17315 // Make sure the callee and caller calling conventions are eligible for tco. 17316 const Function *Caller = CI->getParent()->getParent(); 17317 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 17318 CI->getCallingConv())) 17319 return false; 17320 17321 // If the function is local then we have a good chance at tail-calling it 17322 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 17323 } 17324 17325 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 17326 if (!Subtarget.hasVSX()) 17327 return false; 17328 if (Subtarget.hasP9Vector() && VT == MVT::f128) 17329 return true; 17330 return VT == MVT::f32 || VT == MVT::f64 || 17331 VT == MVT::v4f32 || VT == MVT::v2f64; 17332 } 17333 17334 bool PPCTargetLowering:: 17335 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 17336 const Value *Mask = AndI.getOperand(1); 17337 // If the mask is suitable for andi. or andis. we should sink the and. 17338 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 17339 // Can't handle constants wider than 64-bits. 17340 if (CI->getBitWidth() > 64) 17341 return false; 17342 int64_t ConstVal = CI->getZExtValue(); 17343 return isUInt<16>(ConstVal) || 17344 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 17345 } 17346 17347 // For non-constant masks, we can always use the record-form and. 17348 return true; 17349 } 17350 17351 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 17352 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 17353 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 17354 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 17355 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 17356 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 17357 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 17358 assert(Subtarget.hasP9Altivec() && 17359 "Only combine this when P9 altivec supported!"); 17360 EVT VT = N->getValueType(0); 17361 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17362 return SDValue(); 17363 17364 SelectionDAG &DAG = DCI.DAG; 17365 SDLoc dl(N); 17366 if (N->getOperand(0).getOpcode() == ISD::SUB) { 17367 // Even for signed integers, if it's known to be positive (as signed 17368 // integer) due to zero-extended inputs. 17369 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 17370 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 17371 if ((SubOpcd0 == ISD::ZERO_EXTEND || 17372 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 17373 (SubOpcd1 == ISD::ZERO_EXTEND || 17374 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 17375 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17376 N->getOperand(0)->getOperand(0), 17377 N->getOperand(0)->getOperand(1), 17378 DAG.getTargetConstant(0, dl, MVT::i32)); 17379 } 17380 17381 // For type v4i32, it can be optimized with xvnegsp + vabsduw 17382 if (N->getOperand(0).getValueType() == MVT::v4i32 && 17383 N->getOperand(0).hasOneUse()) { 17384 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 17385 N->getOperand(0)->getOperand(0), 17386 N->getOperand(0)->getOperand(1), 17387 DAG.getTargetConstant(1, dl, MVT::i32)); 17388 } 17389 } 17390 17391 return SDValue(); 17392 } 17393 17394 // For type v4i32/v8ii16/v16i8, transform 17395 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 17396 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 17397 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 17398 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 17399 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 17400 DAGCombinerInfo &DCI) const { 17401 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 17402 assert(Subtarget.hasP9Altivec() && 17403 "Only combine this when P9 altivec supported!"); 17404 17405 SelectionDAG &DAG = DCI.DAG; 17406 SDLoc dl(N); 17407 SDValue Cond = N->getOperand(0); 17408 SDValue TrueOpnd = N->getOperand(1); 17409 SDValue FalseOpnd = N->getOperand(2); 17410 EVT VT = N->getOperand(1).getValueType(); 17411 17412 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 17413 FalseOpnd.getOpcode() != ISD::SUB) 17414 return SDValue(); 17415 17416 // ABSD only available for type v4i32/v8i16/v16i8 17417 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17418 return SDValue(); 17419 17420 // At least to save one more dependent computation 17421 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 17422 return SDValue(); 17423 17424 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 17425 17426 // Can only handle unsigned comparison here 17427 switch (CC) { 17428 default: 17429 return SDValue(); 17430 case ISD::SETUGT: 17431 case ISD::SETUGE: 17432 break; 17433 case ISD::SETULT: 17434 case ISD::SETULE: 17435 std::swap(TrueOpnd, FalseOpnd); 17436 break; 17437 } 17438 17439 SDValue CmpOpnd1 = Cond.getOperand(0); 17440 SDValue CmpOpnd2 = Cond.getOperand(1); 17441 17442 // SETCC CmpOpnd1 CmpOpnd2 cond 17443 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17444 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17445 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17446 TrueOpnd.getOperand(1) == CmpOpnd2 && 17447 FalseOpnd.getOperand(0) == CmpOpnd2 && 17448 FalseOpnd.getOperand(1) == CmpOpnd1) { 17449 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 17450 CmpOpnd1, CmpOpnd2, 17451 DAG.getTargetConstant(0, dl, MVT::i32)); 17452 } 17453 17454 return SDValue(); 17455 } 17456 17457 /// getAddrModeForFlags - Based on the set of address flags, select the most 17458 /// optimal instruction format to match by. 17459 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const { 17460 // This is not a node we should be handling here. 17461 if (Flags == PPC::MOF_None) 17462 return PPC::AM_None; 17463 // Unaligned D-Forms are tried first, followed by the aligned D-Forms. 17464 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm)) 17465 if ((Flags & FlagSet) == FlagSet) 17466 return PPC::AM_DForm; 17467 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm)) 17468 if ((Flags & FlagSet) == FlagSet) 17469 return PPC::AM_DSForm; 17470 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm)) 17471 if ((Flags & FlagSet) == FlagSet) 17472 return PPC::AM_DQForm; 17473 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm)) 17474 if ((Flags & FlagSet) == FlagSet) 17475 return PPC::AM_PrefixDForm; 17476 // If no other forms are selected, return an X-Form as it is the most 17477 // general addressing mode. 17478 return PPC::AM_XForm; 17479 } 17480 17481 /// Set alignment flags based on whether or not the Frame Index is aligned. 17482 /// Utilized when computing flags for address computation when selecting 17483 /// load and store instructions. 17484 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, 17485 SelectionDAG &DAG) { 17486 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR)); 17487 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N); 17488 if (!FI) 17489 return; 17490 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17491 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value(); 17492 // If this is (add $FI, $S16Imm), the alignment flags are already set 17493 // based on the immediate. We just need to clear the alignment flags 17494 // if the FI alignment is weaker. 17495 if ((FrameIndexAlign % 4) != 0) 17496 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4; 17497 if ((FrameIndexAlign % 16) != 0) 17498 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16; 17499 // If the address is a plain FrameIndex, set alignment flags based on 17500 // FI alignment. 17501 if (!IsAdd) { 17502 if ((FrameIndexAlign % 4) == 0) 17503 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17504 if ((FrameIndexAlign % 16) == 0) 17505 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17506 } 17507 } 17508 17509 /// Given a node, compute flags that are used for address computation when 17510 /// selecting load and store instructions. The flags computed are stored in 17511 /// FlagSet. This function takes into account whether the node is a constant, 17512 /// an ADD, OR, or a constant, and computes the address flags accordingly. 17513 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, 17514 SelectionDAG &DAG) { 17515 // Set the alignment flags for the node depending on if the node is 17516 // 4-byte or 16-byte aligned. 17517 auto SetAlignFlagsForImm = [&](uint64_t Imm) { 17518 if ((Imm & 0x3) == 0) 17519 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17520 if ((Imm & 0xf) == 0) 17521 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17522 }; 17523 17524 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 17525 // All 32-bit constants can be computed as LIS + Disp. 17526 const APInt &ConstImm = CN->getAPIntValue(); 17527 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants. 17528 FlagSet |= PPC::MOF_AddrIsSImm32; 17529 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17530 setAlignFlagsForFI(N, FlagSet, DAG); 17531 } 17532 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants. 17533 FlagSet |= PPC::MOF_RPlusSImm34; 17534 else // Let constant materialization handle large constants. 17535 FlagSet |= PPC::MOF_NotAddNorCst; 17536 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) { 17537 // This address can be represented as an addition of: 17538 // - Register + Imm16 (possibly a multiple of 4/16) 17539 // - Register + Imm34 17540 // - Register + PPCISD::Lo 17541 // - Register + Register 17542 // In any case, we won't have to match this as Base + Zero. 17543 SDValue RHS = N.getOperand(1); 17544 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) { 17545 const APInt &ConstImm = CN->getAPIntValue(); 17546 if (ConstImm.isSignedIntN(16)) { 17547 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates. 17548 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17549 setAlignFlagsForFI(N, FlagSet, DAG); 17550 } 17551 if (ConstImm.isSignedIntN(34)) 17552 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates. 17553 else 17554 FlagSet |= PPC::MOF_RPlusR; // Register. 17555 } else if (RHS.getOpcode() == PPCISD::Lo && 17556 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue()) 17557 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo. 17558 else 17559 FlagSet |= PPC::MOF_RPlusR; 17560 } else { // The address computation is not a constant or an addition. 17561 setAlignFlagsForFI(N, FlagSet, DAG); 17562 FlagSet |= PPC::MOF_NotAddNorCst; 17563 } 17564 } 17565 17566 static bool isPCRelNode(SDValue N) { 17567 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR || 17568 isValidPCRelNode<ConstantPoolSDNode>(N) || 17569 isValidPCRelNode<GlobalAddressSDNode>(N) || 17570 isValidPCRelNode<JumpTableSDNode>(N) || 17571 isValidPCRelNode<BlockAddressSDNode>(N)); 17572 } 17573 17574 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute 17575 /// the address flags of the load/store instruction that is to be matched. 17576 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N, 17577 SelectionDAG &DAG) const { 17578 unsigned FlagSet = PPC::MOF_None; 17579 17580 // Compute subtarget flags. 17581 if (!Subtarget.hasP9Vector()) 17582 FlagSet |= PPC::MOF_SubtargetBeforeP9; 17583 else { 17584 FlagSet |= PPC::MOF_SubtargetP9; 17585 if (Subtarget.hasPrefixInstrs()) 17586 FlagSet |= PPC::MOF_SubtargetP10; 17587 } 17588 if (Subtarget.hasSPE()) 17589 FlagSet |= PPC::MOF_SubtargetSPE; 17590 17591 // Check if we have a PCRel node and return early. 17592 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N)) 17593 return FlagSet; 17594 17595 // If the node is the paired load/store intrinsics, compute flags for 17596 // address computation and return early. 17597 unsigned ParentOp = Parent->getOpcode(); 17598 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) || 17599 (ParentOp == ISD::INTRINSIC_VOID))) { 17600 unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue(); 17601 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) { 17602 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) 17603 ? Parent->getOperand(2) 17604 : Parent->getOperand(3); 17605 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG); 17606 FlagSet |= PPC::MOF_Vector; 17607 return FlagSet; 17608 } 17609 } 17610 17611 // Mark this as something we don't want to handle here if it is atomic 17612 // or pre-increment instruction. 17613 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent)) 17614 if (LSB->isIndexed()) 17615 return PPC::MOF_None; 17616 17617 // Compute in-memory type flags. This is based on if there are scalars, 17618 // floats or vectors. 17619 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent); 17620 assert(MN && "Parent should be a MemSDNode!"); 17621 EVT MemVT = MN->getMemoryVT(); 17622 unsigned Size = MemVT.getSizeInBits(); 17623 if (MemVT.isScalarInteger()) { 17624 assert(Size <= 128 && 17625 "Not expecting scalar integers larger than 16 bytes!"); 17626 if (Size < 32) 17627 FlagSet |= PPC::MOF_SubWordInt; 17628 else if (Size == 32) 17629 FlagSet |= PPC::MOF_WordInt; 17630 else 17631 FlagSet |= PPC::MOF_DoubleWordInt; 17632 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors. 17633 if (Size == 128) 17634 FlagSet |= PPC::MOF_Vector; 17635 else if (Size == 256) { 17636 assert(Subtarget.pairedVectorMemops() && 17637 "256-bit vectors are only available when paired vector memops is " 17638 "enabled!"); 17639 FlagSet |= PPC::MOF_Vector; 17640 } else 17641 llvm_unreachable("Not expecting illegal vectors!"); 17642 } else { // Floating point type: can be scalar, f128 or vector types. 17643 if (Size == 32 || Size == 64) 17644 FlagSet |= PPC::MOF_ScalarFloat; 17645 else if (MemVT == MVT::f128 || MemVT.isVector()) 17646 FlagSet |= PPC::MOF_Vector; 17647 else 17648 llvm_unreachable("Not expecting illegal scalar floats!"); 17649 } 17650 17651 // Compute flags for address computation. 17652 computeFlagsForAddressComputation(N, FlagSet, DAG); 17653 17654 // Compute type extension flags. 17655 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) { 17656 switch (LN->getExtensionType()) { 17657 case ISD::SEXTLOAD: 17658 FlagSet |= PPC::MOF_SExt; 17659 break; 17660 case ISD::EXTLOAD: 17661 case ISD::ZEXTLOAD: 17662 FlagSet |= PPC::MOF_ZExt; 17663 break; 17664 case ISD::NON_EXTLOAD: 17665 FlagSet |= PPC::MOF_NoExt; 17666 break; 17667 } 17668 } else 17669 FlagSet |= PPC::MOF_NoExt; 17670 17671 // For integers, no extension is the same as zero extension. 17672 // We set the extension mode to zero extension so we don't have 17673 // to add separate entries in AddrModesMap for loads and stores. 17674 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) { 17675 FlagSet |= PPC::MOF_ZExt; 17676 FlagSet &= ~PPC::MOF_NoExt; 17677 } 17678 17679 // If we don't have prefixed instructions, 34-bit constants should be 17680 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms. 17681 bool IsNonP1034BitConst = 17682 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) & 17683 FlagSet) == PPC::MOF_RPlusSImm34; 17684 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR && 17685 IsNonP1034BitConst) 17686 FlagSet |= PPC::MOF_NotAddNorCst; 17687 17688 return FlagSet; 17689 } 17690 17691 /// SelectForceXFormMode - Given the specified address, force it to be 17692 /// represented as an indexed [r+r] operation (an XForm instruction). 17693 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp, 17694 SDValue &Base, 17695 SelectionDAG &DAG) const { 17696 17697 PPC::AddrMode Mode = PPC::AM_XForm; 17698 int16_t ForceXFormImm = 0; 17699 if (provablyDisjointOr(DAG, N) && 17700 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) { 17701 Disp = N.getOperand(0); 17702 Base = N.getOperand(1); 17703 return Mode; 17704 } 17705 17706 // If the address is the result of an add, we will utilize the fact that the 17707 // address calculation includes an implicit add. However, we can reduce 17708 // register pressure if we do not materialize a constant just for use as the 17709 // index register. We only get rid of the add if it is not an add of a 17710 // value and a 16-bit signed constant and both have a single use. 17711 if (N.getOpcode() == ISD::ADD && 17712 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) || 17713 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 17714 Disp = N.getOperand(0); 17715 Base = N.getOperand(1); 17716 return Mode; 17717 } 17718 17719 // Otherwise, use R0 as the base register. 17720 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17721 N.getValueType()); 17722 Base = N; 17723 17724 return Mode; 17725 } 17726 17727 bool PPCTargetLowering::splitValueIntoRegisterParts( 17728 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 17729 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 17730 EVT ValVT = Val.getValueType(); 17731 // If we are splitting a scalar integer into f64 parts (i.e. so they 17732 // can be placed into VFRC registers), we need to zero extend and 17733 // bitcast the values. This will ensure the value is placed into a 17734 // VSR using direct moves or stack operations as needed. 17735 if (PartVT == MVT::f64 && 17736 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) { 17737 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 17738 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val); 17739 Parts[0] = Val; 17740 return true; 17741 } 17742 return false; 17743 } 17744 17745 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op, 17746 SelectionDAG &DAG) const { 17747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17748 TargetLowering::CallLoweringInfo CLI(DAG); 17749 EVT RetVT = Op.getValueType(); 17750 SDValue Callee = 17751 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout())); 17752 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false); 17753 TargetLowering::ArgListTy Args; 17754 TargetLowering::ArgListEntry Entry; 17755 for (const SDValue &N : Op->op_values()) { 17756 EVT ArgVT = N.getValueType(); 17757 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 17758 Entry.Node = N; 17759 Entry.Ty = ArgTy; 17760 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend); 17761 Entry.IsZExt = !Entry.IsSExt; 17762 Args.push_back(Entry); 17763 } 17764 CLI.setDebugLoc(SDLoc(Op)) 17765 .setChain(DAG.getEntryNode()) 17766 .setLibCallee(CallingConv::C, RetVT.getTypeForEVT(*DAG.getContext()), 17767 Callee, std::move(Args)) 17768 .setTailCall(true) 17769 .setSExtResult(SignExtend) 17770 .setZExtResult(!SignExtend) 17771 .setIsPostTypeLegalization(true); 17772 return TLI.LowerCallTo(CLI).first; 17773 } 17774 17775 SDValue PPCTargetLowering::lowerLibCallBasedOnType( 17776 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op, 17777 SelectionDAG &DAG) const { 17778 if (Op.getValueType() == MVT::f32) 17779 return lowerToLibCall(LibCallFloatName, Op, DAG); 17780 17781 if (Op.getValueType() == MVT::f64) 17782 return lowerToLibCall(LibCallDoubleName, Op, DAG); 17783 17784 return SDValue(); 17785 } 17786 17787 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const { 17788 SDNodeFlags Flags = Op.getNode()->getFlags(); 17789 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() && 17790 Flags.hasNoNaNs() && Flags.hasNoInfs(); 17791 } 17792 17793 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const { 17794 return Op.getNode()->getFlags().hasApproximateFuncs(); 17795 } 17796 17797 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName, 17798 const char *LibCallFloatName, 17799 const char *LibCallDoubleNameFinite, 17800 const char *LibCallFloatNameFinite, 17801 SDValue Op, 17802 SelectionDAG &DAG) const { 17803 if (!isLowringToMASSSafe(Op)) 17804 return SDValue(); 17805 17806 if (!isLowringToMASSFiniteSafe(Op)) 17807 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op, 17808 DAG); 17809 17810 return lowerLibCallBasedOnType(LibCallFloatNameFinite, 17811 LibCallDoubleNameFinite, Op, DAG); 17812 } 17813 17814 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const { 17815 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite", 17816 "__xl_powf_finite", Op, DAG); 17817 } 17818 17819 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const { 17820 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite", 17821 "__xl_sinf_finite", Op, DAG); 17822 } 17823 17824 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const { 17825 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite", 17826 "__xl_cosf_finite", Op, DAG); 17827 } 17828 17829 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const { 17830 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite", 17831 "__xl_logf_finite", Op, DAG); 17832 } 17833 17834 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const { 17835 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite", 17836 "__xl_log10f_finite", Op, DAG); 17837 } 17838 17839 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const { 17840 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite", 17841 "__xl_expf_finite", Op, DAG); 17842 } 17843 17844 // If we happen to match to an aligned D-Form, check if the Frame Index is 17845 // adequately aligned. If it is not, reset the mode to match to X-Form. 17846 static void setXFormForUnalignedFI(SDValue N, unsigned Flags, 17847 PPC::AddrMode &Mode) { 17848 if (!isa<FrameIndexSDNode>(N)) 17849 return; 17850 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) || 17851 (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16))) 17852 Mode = PPC::AM_XForm; 17853 } 17854 17855 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), 17856 /// compute the address flags of the node, get the optimal address mode based 17857 /// on the flags, and set the Base and Disp based on the address mode. 17858 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent, 17859 SDValue N, SDValue &Disp, 17860 SDValue &Base, 17861 SelectionDAG &DAG, 17862 MaybeAlign Align) const { 17863 SDLoc DL(Parent); 17864 17865 // Compute the address flags. 17866 unsigned Flags = computeMOFlags(Parent, N, DAG); 17867 17868 // Get the optimal address mode based on the Flags. 17869 PPC::AddrMode Mode = getAddrModeForFlags(Flags); 17870 17871 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned. 17872 // Select an X-Form load if it is not. 17873 setXFormForUnalignedFI(N, Flags, Mode); 17874 17875 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node. 17876 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) { 17877 assert(Subtarget.isUsingPCRelativeCalls() && 17878 "Must be using PC-Relative calls when a valid PC-Relative node is " 17879 "present!"); 17880 Mode = PPC::AM_PCRel; 17881 } 17882 17883 // Set Base and Disp accordingly depending on the address mode. 17884 switch (Mode) { 17885 case PPC::AM_DForm: 17886 case PPC::AM_DSForm: 17887 case PPC::AM_DQForm: { 17888 // This is a register plus a 16-bit immediate. The base will be the 17889 // register and the displacement will be the immediate unless it 17890 // isn't sufficiently aligned. 17891 if (Flags & PPC::MOF_RPlusSImm16) { 17892 SDValue Op0 = N.getOperand(0); 17893 SDValue Op1 = N.getOperand(1); 17894 int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue(); 17895 if (!Align || isAligned(*Align, Imm)) { 17896 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType()); 17897 Base = Op0; 17898 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) { 17899 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17900 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17901 } 17902 break; 17903 } 17904 } 17905 // This is a register plus the @lo relocation. The base is the register 17906 // and the displacement is the global address. 17907 else if (Flags & PPC::MOF_RPlusLo) { 17908 Disp = N.getOperand(1).getOperand(0); // The global address. 17909 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 17910 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 17911 Disp.getOpcode() == ISD::TargetConstantPool || 17912 Disp.getOpcode() == ISD::TargetJumpTable); 17913 Base = N.getOperand(0); 17914 break; 17915 } 17916 // This is a constant address at most 32 bits. The base will be 17917 // zero or load-immediate-shifted and the displacement will be 17918 // the low 16 bits of the address. 17919 else if (Flags & PPC::MOF_AddrIsSImm32) { 17920 auto *CN = cast<ConstantSDNode>(N); 17921 EVT CNType = CN->getValueType(0); 17922 uint64_t CNImm = CN->getZExtValue(); 17923 // If this address fits entirely in a 16-bit sext immediate field, codegen 17924 // this as "d, 0". 17925 int16_t Imm; 17926 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) { 17927 Disp = DAG.getTargetConstant(Imm, DL, CNType); 17928 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17929 CNType); 17930 break; 17931 } 17932 // Handle 32-bit sext immediate with LIS + Addr mode. 17933 if ((CNType == MVT::i32 || isInt<32>(CNImm)) && 17934 (!Align || isAligned(*Align, CNImm))) { 17935 int32_t Addr = (int32_t)CNImm; 17936 // Otherwise, break this down into LIS + Disp. 17937 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32); 17938 Base = 17939 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32); 17940 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8; 17941 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0); 17942 break; 17943 } 17944 } 17945 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable. 17946 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout())); 17947 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 17948 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17949 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17950 } else 17951 Base = N; 17952 break; 17953 } 17954 case PPC::AM_PrefixDForm: { 17955 int64_t Imm34 = 0; 17956 unsigned Opcode = N.getOpcode(); 17957 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) && 17958 (isIntS34Immediate(N.getOperand(1), Imm34))) { 17959 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate. 17960 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 17961 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 17962 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17963 else 17964 Base = N.getOperand(0); 17965 } else if (isIntS34Immediate(N, Imm34)) { 17966 // The address is a 34-bit signed immediate. 17967 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 17968 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 17969 } 17970 break; 17971 } 17972 case PPC::AM_PCRel: { 17973 // When selecting PC-Relative instructions, "Base" is not utilized as 17974 // we select the address as [PC+imm]. 17975 Disp = N; 17976 break; 17977 } 17978 case PPC::AM_None: 17979 break; 17980 default: { // By default, X-Form is always available to be selected. 17981 // When a frame index is not aligned, we also match by XForm. 17982 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N); 17983 Base = FI ? N : N.getOperand(1); 17984 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17985 N.getValueType()) 17986 : N.getOperand(0); 17987 break; 17988 } 17989 } 17990 return Mode; 17991 } 17992 17993 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC, 17994 bool Return, 17995 bool IsVarArg) const { 17996 switch (CC) { 17997 case CallingConv::Cold: 17998 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS); 17999 default: 18000 return CC_PPC64_ELF_FIS; 18001 } 18002 } 18003 18004 TargetLowering::AtomicExpansionKind 18005 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18006 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18007 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128) 18008 return AtomicExpansionKind::MaskedIntrinsic; 18009 return TargetLowering::shouldExpandAtomicRMWInIR(AI); 18010 } 18011 18012 TargetLowering::AtomicExpansionKind 18013 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18014 unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits(); 18015 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128) 18016 return AtomicExpansionKind::MaskedIntrinsic; 18017 return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI); 18018 } 18019 18020 static Intrinsic::ID 18021 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) { 18022 switch (BinOp) { 18023 default: 18024 llvm_unreachable("Unexpected AtomicRMW BinOp"); 18025 case AtomicRMWInst::Xchg: 18026 return Intrinsic::ppc_atomicrmw_xchg_i128; 18027 case AtomicRMWInst::Add: 18028 return Intrinsic::ppc_atomicrmw_add_i128; 18029 case AtomicRMWInst::Sub: 18030 return Intrinsic::ppc_atomicrmw_sub_i128; 18031 case AtomicRMWInst::And: 18032 return Intrinsic::ppc_atomicrmw_and_i128; 18033 case AtomicRMWInst::Or: 18034 return Intrinsic::ppc_atomicrmw_or_i128; 18035 case AtomicRMWInst::Xor: 18036 return Intrinsic::ppc_atomicrmw_xor_i128; 18037 case AtomicRMWInst::Nand: 18038 return Intrinsic::ppc_atomicrmw_nand_i128; 18039 } 18040 } 18041 18042 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic( 18043 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 18044 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 18045 assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && 18046 "Only support quadword now"); 18047 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18048 Type *ValTy = AlignedAddr->getType()->getPointerElementType(); 18049 assert(ValTy->getPrimitiveSizeInBits() == 128); 18050 Function *RMW = Intrinsic::getDeclaration( 18051 M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation())); 18052 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18053 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo"); 18054 Value *IncrHi = 18055 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi"); 18056 Value *Addr = 18057 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18058 Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi}); 18059 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18060 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18061 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18062 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18063 return Builder.CreateOr( 18064 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18065 } 18066 18067 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 18068 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 18069 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 18070 assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && 18071 "Only support quadword now"); 18072 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18073 Type *ValTy = AlignedAddr->getType()->getPointerElementType(); 18074 assert(ValTy->getPrimitiveSizeInBits() == 128); 18075 Function *IntCmpXchg = 18076 Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128); 18077 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18078 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo"); 18079 Value *CmpHi = 18080 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi"); 18081 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo"); 18082 Value *NewHi = 18083 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi"); 18084 Value *Addr = 18085 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18086 emitLeadingFence(Builder, CI, Ord); 18087 Value *LoHi = 18088 Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi}); 18089 emitTrailingFence(Builder, CI, Ord); 18090 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18091 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18092 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18093 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18094 return Builder.CreateOr( 18095 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18096 } 18097