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 STATISTIC(NumTailCalls, "Number of tail calls"); 125 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 126 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 127 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 128 129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 130 131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 132 133 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word"; 134 135 // FIXME: Remove this once the bug has been fixed! 136 extern cl::opt<bool> ANDIGlueBug; 137 138 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 139 const PPCSubtarget &STI) 140 : TargetLowering(TM), Subtarget(STI) { 141 // Initialize map that relates the PPC addressing modes to the computed flags 142 // of a load/store instruction. The map is used to determine the optimal 143 // addressing mode when selecting load and stores. 144 initializeAddrModeMap(); 145 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 146 // arguments are at least 4/8 bytes aligned. 147 bool isPPC64 = Subtarget.isPPC64(); 148 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 149 150 // Set up the register classes. 151 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 152 if (!useSoftFloat()) { 153 if (hasSPE()) { 154 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 155 // EFPU2 APU only supports f32 156 if (!Subtarget.hasEFPU2()) 157 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 158 } else { 159 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 160 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 161 } 162 } 163 164 // Match BITREVERSE to customized fast code sequence in the td file. 165 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 166 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 167 168 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 169 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 170 171 // Custom lower inline assembly to check for special registers. 172 setOperationAction(ISD::INLINEASM, MVT::Other, Custom); 173 setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom); 174 175 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 176 for (MVT VT : MVT::integer_valuetypes()) { 177 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 178 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 179 } 180 181 if (Subtarget.isISA3_0()) { 182 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 183 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 184 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 185 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 186 } else { 187 // No extending loads from f16 or HW conversions back and forth. 188 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 189 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 190 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 191 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 192 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 193 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 194 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 195 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 196 } 197 198 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 199 200 // PowerPC has pre-inc load and store's. 201 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 202 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 203 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 204 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 205 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 206 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 207 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 208 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 209 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 210 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 211 if (!Subtarget.hasSPE()) { 212 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 213 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 214 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 215 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 216 } 217 218 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 219 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 220 for (MVT VT : ScalarIntVTs) { 221 setOperationAction(ISD::ADDC, VT, Legal); 222 setOperationAction(ISD::ADDE, VT, Legal); 223 setOperationAction(ISD::SUBC, VT, Legal); 224 setOperationAction(ISD::SUBE, VT, Legal); 225 } 226 227 if (Subtarget.useCRBits()) { 228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 229 230 if (isPPC64 || Subtarget.hasFPCVT()) { 231 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 232 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 233 isPPC64 ? MVT::i64 : MVT::i32); 234 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 235 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 236 isPPC64 ? MVT::i64 : MVT::i32); 237 238 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 239 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 240 isPPC64 ? MVT::i64 : MVT::i32); 241 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 242 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 243 isPPC64 ? MVT::i64 : MVT::i32); 244 245 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 246 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 247 isPPC64 ? MVT::i64 : MVT::i32); 248 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 249 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 250 isPPC64 ? MVT::i64 : MVT::i32); 251 252 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 253 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 254 isPPC64 ? MVT::i64 : MVT::i32); 255 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 256 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 257 isPPC64 ? MVT::i64 : MVT::i32); 258 } else { 259 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 260 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 261 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 262 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 263 } 264 265 // PowerPC does not support direct load/store of condition registers. 266 setOperationAction(ISD::LOAD, MVT::i1, Custom); 267 setOperationAction(ISD::STORE, MVT::i1, Custom); 268 269 // FIXME: Remove this once the ANDI glue bug is fixed: 270 if (ANDIGlueBug) 271 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 272 273 for (MVT VT : MVT::integer_valuetypes()) { 274 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 275 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 276 setTruncStoreAction(VT, MVT::i1, Expand); 277 } 278 279 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 280 } 281 282 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 283 // PPC (the libcall is not available). 284 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 285 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 286 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 287 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 288 289 // We do not currently implement these libm ops for PowerPC. 290 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 291 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 292 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 293 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 294 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 295 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 296 297 // PowerPC has no SREM/UREM instructions unless we are on P9 298 // On P9 we may use a hardware instruction to compute the remainder. 299 // When the result of both the remainder and the division is required it is 300 // more efficient to compute the remainder from the result of the division 301 // rather than use the remainder instruction. The instructions are legalized 302 // directly because the DivRemPairsPass performs the transformation at the IR 303 // level. 304 if (Subtarget.isISA3_0()) { 305 setOperationAction(ISD::SREM, MVT::i32, Legal); 306 setOperationAction(ISD::UREM, MVT::i32, Legal); 307 setOperationAction(ISD::SREM, MVT::i64, Legal); 308 setOperationAction(ISD::UREM, MVT::i64, Legal); 309 } else { 310 setOperationAction(ISD::SREM, MVT::i32, Expand); 311 setOperationAction(ISD::UREM, MVT::i32, Expand); 312 setOperationAction(ISD::SREM, MVT::i64, Expand); 313 setOperationAction(ISD::UREM, MVT::i64, Expand); 314 } 315 316 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 317 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 318 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 319 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 320 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 321 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 322 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 323 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 324 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 325 326 // Handle constrained floating-point operations of scalar. 327 // TODO: Handle SPE specific operation. 328 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 329 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 330 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 331 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 332 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 333 334 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 335 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 336 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 337 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 338 339 if (!Subtarget.hasSPE()) { 340 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 341 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 342 } 343 344 if (Subtarget.hasVSX()) { 345 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 346 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 347 } 348 349 if (Subtarget.hasFSQRT()) { 350 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 351 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 352 } 353 354 if (Subtarget.hasFPRND()) { 355 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 356 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 357 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 358 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 359 360 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 361 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 362 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 363 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 364 } 365 366 // We don't support sin/cos/sqrt/fmod/pow 367 setOperationAction(ISD::FSIN , MVT::f64, Expand); 368 setOperationAction(ISD::FCOS , MVT::f64, Expand); 369 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 370 setOperationAction(ISD::FREM , MVT::f64, Expand); 371 setOperationAction(ISD::FPOW , MVT::f64, Expand); 372 setOperationAction(ISD::FSIN , MVT::f32, Expand); 373 setOperationAction(ISD::FCOS , MVT::f32, Expand); 374 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 375 setOperationAction(ISD::FREM , MVT::f32, Expand); 376 setOperationAction(ISD::FPOW , MVT::f32, Expand); 377 if (Subtarget.hasSPE()) { 378 setOperationAction(ISD::FMA , MVT::f64, Expand); 379 setOperationAction(ISD::FMA , MVT::f32, Expand); 380 } else { 381 setOperationAction(ISD::FMA , MVT::f64, Legal); 382 setOperationAction(ISD::FMA , MVT::f32, Legal); 383 } 384 385 if (Subtarget.hasSPE()) 386 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 387 388 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 389 390 // If we're enabling GP optimizations, use hardware square root 391 if (!Subtarget.hasFSQRT() && 392 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 393 Subtarget.hasFRE())) 394 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 395 396 if (!Subtarget.hasFSQRT() && 397 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 398 Subtarget.hasFRES())) 399 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 400 401 if (Subtarget.hasFCPSGN()) { 402 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 403 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 404 } else { 405 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 406 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 407 } 408 409 if (Subtarget.hasFPRND()) { 410 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 411 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 412 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 413 setOperationAction(ISD::FROUND, MVT::f64, Legal); 414 415 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 416 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 417 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 418 setOperationAction(ISD::FROUND, MVT::f32, Legal); 419 } 420 421 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 422 // to speed up scalar BSWAP64. 423 // CTPOP or CTTZ were introduced in P8/P9 respectively 424 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 425 if (Subtarget.hasP9Vector() && Subtarget.isPPC64()) 426 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 427 else 428 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 429 if (Subtarget.isISA3_0()) { 430 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 431 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 432 } else { 433 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 434 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 435 } 436 437 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 438 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 439 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 440 } else { 441 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 442 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 443 } 444 445 // PowerPC does not have ROTR 446 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 447 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 448 449 if (!Subtarget.useCRBits()) { 450 // PowerPC does not have Select 451 setOperationAction(ISD::SELECT, MVT::i32, Expand); 452 setOperationAction(ISD::SELECT, MVT::i64, Expand); 453 setOperationAction(ISD::SELECT, MVT::f32, Expand); 454 setOperationAction(ISD::SELECT, MVT::f64, Expand); 455 } 456 457 // PowerPC wants to turn select_cc of FP into fsel when possible. 458 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 459 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 460 461 // PowerPC wants to optimize integer setcc a bit 462 if (!Subtarget.useCRBits()) 463 setOperationAction(ISD::SETCC, MVT::i32, Custom); 464 465 if (Subtarget.hasFPU()) { 466 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 467 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 468 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 469 470 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 471 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 472 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 473 } 474 475 // PowerPC does not have BRCOND which requires SetCC 476 if (!Subtarget.useCRBits()) 477 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 478 479 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 480 481 if (Subtarget.hasSPE()) { 482 // SPE has built-in conversions 483 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 484 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 485 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 486 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 487 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 488 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 489 490 // SPE supports signaling compare of f32/f64. 491 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 492 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 493 } else { 494 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 495 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 496 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 497 498 // PowerPC does not have [U|S]INT_TO_FP 499 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 500 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 501 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 502 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 503 } 504 505 if (Subtarget.hasDirectMove() && isPPC64) { 506 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 507 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 508 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 509 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 510 if (TM.Options.UnsafeFPMath) { 511 setOperationAction(ISD::LRINT, MVT::f64, Legal); 512 setOperationAction(ISD::LRINT, MVT::f32, Legal); 513 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 514 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 515 setOperationAction(ISD::LROUND, MVT::f64, Legal); 516 setOperationAction(ISD::LROUND, MVT::f32, Legal); 517 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 518 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 519 } 520 } else { 521 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 522 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 523 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 524 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 525 } 526 527 // We cannot sextinreg(i1). Expand to shifts. 528 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 529 530 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 531 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 532 // support continuation, user-level threading, and etc.. As a result, no 533 // other SjLj exception interfaces are implemented and please don't build 534 // your own exception handling based on them. 535 // LLVM/Clang supports zero-cost DWARF exception handling. 536 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 537 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 538 539 // We want to legalize GlobalAddress and ConstantPool nodes into the 540 // appropriate instructions to materialize the address. 541 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 542 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 543 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 544 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 545 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 546 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 547 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 548 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 549 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 550 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 551 552 // TRAP is legal. 553 setOperationAction(ISD::TRAP, MVT::Other, Legal); 554 555 // TRAMPOLINE is custom lowered. 556 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 557 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 558 559 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 560 setOperationAction(ISD::VASTART , MVT::Other, Custom); 561 562 if (Subtarget.is64BitELFABI()) { 563 // VAARG always uses double-word chunks, so promote anything smaller. 564 setOperationAction(ISD::VAARG, MVT::i1, Promote); 565 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 566 setOperationAction(ISD::VAARG, MVT::i8, Promote); 567 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 568 setOperationAction(ISD::VAARG, MVT::i16, Promote); 569 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 570 setOperationAction(ISD::VAARG, MVT::i32, Promote); 571 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 572 setOperationAction(ISD::VAARG, MVT::Other, Expand); 573 } else if (Subtarget.is32BitELFABI()) { 574 // VAARG is custom lowered with the 32-bit SVR4 ABI. 575 setOperationAction(ISD::VAARG, MVT::Other, Custom); 576 setOperationAction(ISD::VAARG, MVT::i64, Custom); 577 } else 578 setOperationAction(ISD::VAARG, MVT::Other, Expand); 579 580 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 581 if (Subtarget.is32BitELFABI()) 582 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 583 else 584 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 585 586 // Use the default implementation. 587 setOperationAction(ISD::VAEND , MVT::Other, Expand); 588 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 589 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 590 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 591 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 592 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 593 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 594 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 595 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 596 597 // We want to custom lower some of our intrinsics. 598 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 599 600 // To handle counter-based loop conditions. 601 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 602 603 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 604 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 605 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 606 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 607 608 // Comparisons that require checking two conditions. 609 if (Subtarget.hasSPE()) { 610 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 611 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 612 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 613 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 614 } 615 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 616 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 617 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 618 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 619 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 620 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 621 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 622 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 623 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 624 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 625 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 626 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 627 628 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 629 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 630 631 if (Subtarget.has64BitSupport()) { 632 // They also have instructions for converting between i64 and fp. 633 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 634 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 635 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 636 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 637 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 638 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 639 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 640 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 641 // This is just the low 32 bits of a (signed) fp->i64 conversion. 642 // We cannot do this with Promote because i64 is not a legal type. 643 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 644 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 645 646 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 647 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 648 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 649 } 650 } else { 651 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 652 if (Subtarget.hasSPE()) { 653 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 654 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 655 } else { 656 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 657 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 658 } 659 } 660 661 // With the instructions enabled under FPCVT, we can do everything. 662 if (Subtarget.hasFPCVT()) { 663 if (Subtarget.has64BitSupport()) { 664 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 665 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 666 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 667 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 668 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 669 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 670 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 671 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 672 } 673 674 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 675 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 676 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 677 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 678 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 679 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 680 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 681 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 682 } 683 684 if (Subtarget.use64BitRegs()) { 685 // 64-bit PowerPC implementations can support i64 types directly 686 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 687 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 688 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 689 // 64-bit PowerPC wants to expand i128 shifts itself. 690 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 691 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 692 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 693 } else { 694 // 32-bit PowerPC wants to expand i64 shifts itself. 695 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 696 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 697 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 698 } 699 700 // PowerPC has better expansions for funnel shifts than the generic 701 // TargetLowering::expandFunnelShift. 702 if (Subtarget.has64BitSupport()) { 703 setOperationAction(ISD::FSHL, MVT::i64, Custom); 704 setOperationAction(ISD::FSHR, MVT::i64, Custom); 705 } 706 setOperationAction(ISD::FSHL, MVT::i32, Custom); 707 setOperationAction(ISD::FSHR, MVT::i32, Custom); 708 709 if (Subtarget.hasVSX()) { 710 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 711 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 712 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 713 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 714 } 715 716 if (Subtarget.hasAltivec()) { 717 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 718 setOperationAction(ISD::SADDSAT, VT, Legal); 719 setOperationAction(ISD::SSUBSAT, VT, Legal); 720 setOperationAction(ISD::UADDSAT, VT, Legal); 721 setOperationAction(ISD::USUBSAT, VT, Legal); 722 } 723 // First set operation action for all vector types to expand. Then we 724 // will selectively turn on ones that can be effectively codegen'd. 725 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 726 // add/sub are legal for all supported vector VT's. 727 setOperationAction(ISD::ADD, VT, Legal); 728 setOperationAction(ISD::SUB, VT, Legal); 729 730 // For v2i64, these are only valid with P8Vector. This is corrected after 731 // the loop. 732 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 733 setOperationAction(ISD::SMAX, VT, Legal); 734 setOperationAction(ISD::SMIN, VT, Legal); 735 setOperationAction(ISD::UMAX, VT, Legal); 736 setOperationAction(ISD::UMIN, VT, Legal); 737 } 738 else { 739 setOperationAction(ISD::SMAX, VT, Expand); 740 setOperationAction(ISD::SMIN, VT, Expand); 741 setOperationAction(ISD::UMAX, VT, Expand); 742 setOperationAction(ISD::UMIN, VT, Expand); 743 } 744 745 if (Subtarget.hasVSX()) { 746 setOperationAction(ISD::FMAXNUM, VT, Legal); 747 setOperationAction(ISD::FMINNUM, VT, Legal); 748 } 749 750 // Vector instructions introduced in P8 751 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 752 setOperationAction(ISD::CTPOP, VT, Legal); 753 setOperationAction(ISD::CTLZ, VT, Legal); 754 } 755 else { 756 setOperationAction(ISD::CTPOP, VT, Expand); 757 setOperationAction(ISD::CTLZ, VT, Expand); 758 } 759 760 // Vector instructions introduced in P9 761 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 762 setOperationAction(ISD::CTTZ, VT, Legal); 763 else 764 setOperationAction(ISD::CTTZ, VT, Expand); 765 766 // We promote all shuffles to v16i8. 767 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 768 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 769 770 // We promote all non-typed operations to v4i32. 771 setOperationAction(ISD::AND , VT, Promote); 772 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 773 setOperationAction(ISD::OR , VT, Promote); 774 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 775 setOperationAction(ISD::XOR , VT, Promote); 776 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 777 setOperationAction(ISD::LOAD , VT, Promote); 778 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 779 setOperationAction(ISD::SELECT, VT, Promote); 780 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 781 setOperationAction(ISD::VSELECT, VT, Legal); 782 setOperationAction(ISD::SELECT_CC, VT, Promote); 783 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 784 setOperationAction(ISD::STORE, VT, Promote); 785 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 786 787 // No other operations are legal. 788 setOperationAction(ISD::MUL , VT, Expand); 789 setOperationAction(ISD::SDIV, VT, Expand); 790 setOperationAction(ISD::SREM, VT, Expand); 791 setOperationAction(ISD::UDIV, VT, Expand); 792 setOperationAction(ISD::UREM, VT, Expand); 793 setOperationAction(ISD::FDIV, VT, Expand); 794 setOperationAction(ISD::FREM, VT, Expand); 795 setOperationAction(ISD::FNEG, VT, Expand); 796 setOperationAction(ISD::FSQRT, VT, Expand); 797 setOperationAction(ISD::FLOG, VT, Expand); 798 setOperationAction(ISD::FLOG10, VT, Expand); 799 setOperationAction(ISD::FLOG2, VT, Expand); 800 setOperationAction(ISD::FEXP, VT, Expand); 801 setOperationAction(ISD::FEXP2, VT, Expand); 802 setOperationAction(ISD::FSIN, VT, Expand); 803 setOperationAction(ISD::FCOS, VT, Expand); 804 setOperationAction(ISD::FABS, VT, Expand); 805 setOperationAction(ISD::FFLOOR, VT, Expand); 806 setOperationAction(ISD::FCEIL, VT, Expand); 807 setOperationAction(ISD::FTRUNC, VT, Expand); 808 setOperationAction(ISD::FRINT, VT, Expand); 809 setOperationAction(ISD::FNEARBYINT, VT, Expand); 810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 811 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 812 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 813 setOperationAction(ISD::MULHU, VT, Expand); 814 setOperationAction(ISD::MULHS, VT, Expand); 815 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 816 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 817 setOperationAction(ISD::UDIVREM, VT, Expand); 818 setOperationAction(ISD::SDIVREM, VT, Expand); 819 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 820 setOperationAction(ISD::FPOW, VT, Expand); 821 setOperationAction(ISD::BSWAP, VT, Expand); 822 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 823 setOperationAction(ISD::ROTL, VT, Expand); 824 setOperationAction(ISD::ROTR, VT, Expand); 825 826 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 827 setTruncStoreAction(VT, InnerVT, Expand); 828 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 829 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 830 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 831 } 832 } 833 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 834 if (!Subtarget.hasP8Vector()) { 835 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 836 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 837 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 838 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 839 } 840 841 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 842 // with merges, splats, etc. 843 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 844 845 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 846 // are cheap, so handle them before they get expanded to scalar. 847 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 848 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 849 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 850 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 851 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 852 853 setOperationAction(ISD::AND , MVT::v4i32, Legal); 854 setOperationAction(ISD::OR , MVT::v4i32, Legal); 855 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 856 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 857 setOperationAction(ISD::SELECT, MVT::v4i32, 858 Subtarget.useCRBits() ? Legal : Expand); 859 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 860 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 861 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 862 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 863 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 864 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 865 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 866 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 867 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 868 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 869 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 870 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 871 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 872 873 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 874 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 875 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 876 if (Subtarget.hasAltivec()) 877 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 878 setOperationAction(ISD::ROTL, VT, Legal); 879 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 880 if (Subtarget.hasP8Altivec()) 881 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 882 883 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 884 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 885 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 886 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 887 888 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 889 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 890 891 if (Subtarget.hasVSX()) { 892 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 893 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 895 } 896 897 if (Subtarget.hasP8Altivec()) 898 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 899 else 900 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 901 902 if (Subtarget.isISA3_1()) { 903 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 904 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 905 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 906 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 907 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 908 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 909 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 910 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 911 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 912 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 913 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 914 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 915 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 916 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 917 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 918 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 919 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 920 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 921 } 922 923 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 924 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 925 926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 928 929 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 930 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 931 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 932 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 933 934 // Altivec does not contain unordered floating-point compare instructions 935 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 936 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 937 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 938 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 939 940 if (Subtarget.hasVSX()) { 941 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 943 if (Subtarget.hasP8Vector()) { 944 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 945 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 946 } 947 if (Subtarget.hasDirectMove() && isPPC64) { 948 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 949 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 950 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 951 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 953 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 954 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 955 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 956 } 957 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 958 959 // The nearbyint variants are not allowed to raise the inexact exception 960 // so we can only code-gen them with unsafe math. 961 if (TM.Options.UnsafeFPMath) { 962 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 963 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 964 } 965 966 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 967 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 968 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 969 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 970 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 971 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 972 setOperationAction(ISD::FROUND, MVT::f64, Legal); 973 setOperationAction(ISD::FRINT, MVT::f64, Legal); 974 975 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 976 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 977 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 978 setOperationAction(ISD::FROUND, MVT::f32, Legal); 979 setOperationAction(ISD::FRINT, MVT::f32, Legal); 980 981 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 982 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 983 984 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 985 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 986 987 // Share the Altivec comparison restrictions. 988 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 989 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 990 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 991 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 992 993 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 994 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 995 996 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 997 998 if (Subtarget.hasP8Vector()) 999 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 1000 1001 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 1002 1003 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 1004 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 1005 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 1006 1007 if (Subtarget.hasP8Altivec()) { 1008 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 1009 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 1010 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 1011 1012 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1013 // SRL, but not for SRA because of the instructions available: 1014 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1015 // doing 1016 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1017 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1018 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1019 1020 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1021 } 1022 else { 1023 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1024 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1025 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1026 1027 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1028 1029 // VSX v2i64 only supports non-arithmetic operations. 1030 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1031 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1032 } 1033 1034 if (Subtarget.isISA3_1()) 1035 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1036 else 1037 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1038 1039 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1040 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1041 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1042 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1043 1044 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1045 1046 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1047 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1048 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1049 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1050 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1051 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1052 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1053 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1054 1055 // Custom handling for partial vectors of integers converted to 1056 // floating point. We already have optimal handling for v2i32 through 1057 // the DAG combine, so those aren't necessary. 1058 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1059 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1060 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1061 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1062 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1063 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1064 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1065 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1066 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1067 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1068 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1069 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1070 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1071 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1072 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1073 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1074 1075 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1076 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1077 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1078 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1079 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1080 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1081 1082 if (Subtarget.hasDirectMove()) 1083 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1084 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1085 1086 // Handle constrained floating-point operations of vector. 1087 // The predictor is `hasVSX` because altivec instruction has 1088 // no exception but VSX vector instruction has. 1089 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1090 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1091 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1092 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1093 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1094 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1095 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1096 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1097 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1098 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1099 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1100 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1101 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1102 1103 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1104 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1105 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1106 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1107 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1108 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1109 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1110 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1111 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1112 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1113 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1114 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1115 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1116 1117 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1118 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1119 1120 for (MVT FPT : MVT::fp_valuetypes()) 1121 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1122 1123 // Expand the SELECT to SELECT_CC 1124 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1125 1126 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1127 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1128 1129 // No implementation for these ops for PowerPC. 1130 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1131 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1132 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1133 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1134 setOperationAction(ISD::FREM, MVT::f128, Expand); 1135 } 1136 1137 if (Subtarget.hasP8Altivec()) { 1138 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1139 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1140 } 1141 1142 if (Subtarget.hasP9Vector()) { 1143 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1144 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1145 1146 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1147 // SRL, but not for SRA because of the instructions available: 1148 // VS{RL} and VS{RL}O. 1149 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1150 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1151 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1152 1153 setOperationAction(ISD::FADD, MVT::f128, Legal); 1154 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1155 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1156 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1157 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1158 1159 setOperationAction(ISD::FMA, MVT::f128, Legal); 1160 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1161 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1162 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1163 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1164 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1165 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1166 1167 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1168 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1169 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1170 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1171 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1172 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1173 1174 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1175 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1176 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1177 1178 // Handle constrained floating-point operations of fp128 1179 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1180 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1181 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1182 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1183 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1184 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1185 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1186 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1187 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1188 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1189 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1190 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1191 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1192 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1193 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1194 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1195 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1196 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1197 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1198 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1199 } else if (Subtarget.hasVSX()) { 1200 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1201 setOperationAction(ISD::STORE, MVT::f128, Promote); 1202 1203 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1204 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1205 1206 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1207 // fp_to_uint and int_to_fp. 1208 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1209 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1210 1211 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1212 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1213 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1214 setOperationAction(ISD::FABS, MVT::f128, Expand); 1215 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1216 setOperationAction(ISD::FMA, MVT::f128, Expand); 1217 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1218 1219 // Expand the fp_extend if the target type is fp128. 1220 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1221 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1222 1223 // Expand the fp_round if the source type is fp128. 1224 for (MVT VT : {MVT::f32, MVT::f64}) { 1225 setOperationAction(ISD::FP_ROUND, VT, Custom); 1226 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1227 } 1228 1229 setOperationAction(ISD::SETCC, MVT::f128, Custom); 1230 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 1231 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 1232 setOperationAction(ISD::BR_CC, MVT::f128, Expand); 1233 1234 // Lower following f128 select_cc pattern: 1235 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE 1236 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1237 1238 // We need to handle f128 SELECT_CC with integer result type. 1239 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1240 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand); 1241 } 1242 1243 if (Subtarget.hasP9Altivec()) { 1244 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1245 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1246 1247 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1248 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1249 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1250 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1251 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1252 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1253 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1254 } 1255 1256 if (Subtarget.isISA3_1()) 1257 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 1258 } 1259 1260 if (Subtarget.pairedVectorMemops()) { 1261 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1262 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1263 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1264 } 1265 if (Subtarget.hasMMA()) { 1266 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1267 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1268 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1269 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1270 } 1271 1272 if (Subtarget.has64BitSupport()) 1273 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1274 1275 if (Subtarget.isISA3_1()) 1276 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1277 1278 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1279 1280 if (!isPPC64) { 1281 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1282 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1283 } 1284 1285 setBooleanContents(ZeroOrOneBooleanContent); 1286 1287 if (Subtarget.hasAltivec()) { 1288 // Altivec instructions set fields to all zeros or all ones. 1289 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1290 } 1291 1292 if (!isPPC64) { 1293 // These libcalls are not available in 32-bit. 1294 setLibcallName(RTLIB::SHL_I128, nullptr); 1295 setLibcallName(RTLIB::SRL_I128, nullptr); 1296 setLibcallName(RTLIB::SRA_I128, nullptr); 1297 } 1298 1299 if (!isPPC64) 1300 setMaxAtomicSizeInBitsSupported(32); 1301 1302 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1303 1304 // We have target-specific dag combine patterns for the following nodes: 1305 setTargetDAGCombine(ISD::ADD); 1306 setTargetDAGCombine(ISD::SHL); 1307 setTargetDAGCombine(ISD::SRA); 1308 setTargetDAGCombine(ISD::SRL); 1309 setTargetDAGCombine(ISD::MUL); 1310 setTargetDAGCombine(ISD::FMA); 1311 setTargetDAGCombine(ISD::SINT_TO_FP); 1312 setTargetDAGCombine(ISD::BUILD_VECTOR); 1313 if (Subtarget.hasFPCVT()) 1314 setTargetDAGCombine(ISD::UINT_TO_FP); 1315 setTargetDAGCombine(ISD::LOAD); 1316 setTargetDAGCombine(ISD::STORE); 1317 setTargetDAGCombine(ISD::BR_CC); 1318 if (Subtarget.useCRBits()) 1319 setTargetDAGCombine(ISD::BRCOND); 1320 setTargetDAGCombine(ISD::BSWAP); 1321 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1322 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1323 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1324 1325 setTargetDAGCombine(ISD::SIGN_EXTEND); 1326 setTargetDAGCombine(ISD::ZERO_EXTEND); 1327 setTargetDAGCombine(ISD::ANY_EXTEND); 1328 1329 setTargetDAGCombine(ISD::TRUNCATE); 1330 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1331 1332 1333 if (Subtarget.useCRBits()) { 1334 setTargetDAGCombine(ISD::TRUNCATE); 1335 setTargetDAGCombine(ISD::SETCC); 1336 setTargetDAGCombine(ISD::SELECT_CC); 1337 } 1338 1339 if (Subtarget.hasP9Altivec()) { 1340 setTargetDAGCombine(ISD::ABS); 1341 setTargetDAGCombine(ISD::VSELECT); 1342 } 1343 1344 setLibcallName(RTLIB::LOG_F128, "logf128"); 1345 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1346 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1347 setLibcallName(RTLIB::EXP_F128, "expf128"); 1348 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1349 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1350 setLibcallName(RTLIB::COS_F128, "cosf128"); 1351 setLibcallName(RTLIB::POW_F128, "powf128"); 1352 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1353 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1354 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1355 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1356 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1357 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1358 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1359 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1360 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1361 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1362 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1363 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1364 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1365 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1366 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1367 1368 // With 32 condition bits, we don't need to sink (and duplicate) compares 1369 // aggressively in CodeGenPrep. 1370 if (Subtarget.useCRBits()) { 1371 setHasMultipleConditionRegisters(); 1372 setJumpIsExpensive(); 1373 } 1374 1375 setMinFunctionAlignment(Align(4)); 1376 1377 switch (Subtarget.getCPUDirective()) { 1378 default: break; 1379 case PPC::DIR_970: 1380 case PPC::DIR_A2: 1381 case PPC::DIR_E500: 1382 case PPC::DIR_E500mc: 1383 case PPC::DIR_E5500: 1384 case PPC::DIR_PWR4: 1385 case PPC::DIR_PWR5: 1386 case PPC::DIR_PWR5X: 1387 case PPC::DIR_PWR6: 1388 case PPC::DIR_PWR6X: 1389 case PPC::DIR_PWR7: 1390 case PPC::DIR_PWR8: 1391 case PPC::DIR_PWR9: 1392 case PPC::DIR_PWR10: 1393 case PPC::DIR_PWR_FUTURE: 1394 setPrefLoopAlignment(Align(16)); 1395 setPrefFunctionAlignment(Align(16)); 1396 break; 1397 } 1398 1399 if (Subtarget.enableMachineScheduler()) 1400 setSchedulingPreference(Sched::Source); 1401 else 1402 setSchedulingPreference(Sched::Hybrid); 1403 1404 computeRegisterProperties(STI.getRegisterInfo()); 1405 1406 // The Freescale cores do better with aggressive inlining of memcpy and 1407 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1408 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1409 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1410 MaxStoresPerMemset = 32; 1411 MaxStoresPerMemsetOptSize = 16; 1412 MaxStoresPerMemcpy = 32; 1413 MaxStoresPerMemcpyOptSize = 8; 1414 MaxStoresPerMemmove = 32; 1415 MaxStoresPerMemmoveOptSize = 8; 1416 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1417 // The A2 also benefits from (very) aggressive inlining of memcpy and 1418 // friends. The overhead of a the function call, even when warm, can be 1419 // over one hundred cycles. 1420 MaxStoresPerMemset = 128; 1421 MaxStoresPerMemcpy = 128; 1422 MaxStoresPerMemmove = 128; 1423 MaxLoadsPerMemcmp = 128; 1424 } else { 1425 MaxLoadsPerMemcmp = 8; 1426 MaxLoadsPerMemcmpOptSize = 4; 1427 } 1428 1429 IsStrictFPEnabled = true; 1430 1431 // Let the subtarget (CPU) decide if a predictable select is more expensive 1432 // than the corresponding branch. This information is used in CGP to decide 1433 // when to convert selects into branches. 1434 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1435 } 1436 1437 // *********************************** NOTE ************************************ 1438 // For selecting load and store instructions, the addressing modes are defined 1439 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD 1440 // patterns to match the load the store instructions. 1441 // 1442 // The TD definitions for the addressing modes correspond to their respective 1443 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely 1444 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the 1445 // address mode flags of a particular node. Afterwards, the computed address 1446 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal 1447 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement 1448 // accordingly, based on the preferred addressing mode. 1449 // 1450 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode. 1451 // MemOpFlags contains all the possible flags that can be used to compute the 1452 // optimal addressing mode for load and store instructions. 1453 // AddrMode contains all the possible load and store addressing modes available 1454 // on Power (such as DForm, DSForm, DQForm, XForm, etc.) 1455 // 1456 // When adding new load and store instructions, it is possible that new address 1457 // flags may need to be added into MemOpFlags, and a new addressing mode will 1458 // need to be added to AddrMode. An entry of the new addressing mode (consisting 1459 // of the minimal and main distinguishing address flags for the new load/store 1460 // instructions) will need to be added into initializeAddrModeMap() below. 1461 // Finally, when adding new addressing modes, the getAddrModeForFlags() will 1462 // need to be updated to account for selecting the optimal addressing mode. 1463 // ***************************************************************************** 1464 /// Initialize the map that relates the different addressing modes of the load 1465 /// and store instructions to a set of flags. This ensures the load/store 1466 /// instruction is correctly matched during instruction selection. 1467 void PPCTargetLowering::initializeAddrModeMap() { 1468 AddrModesMap[PPC::AM_DForm] = { 1469 // LWZ, STW 1470 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt, 1471 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt, 1472 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1473 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1474 // LBZ, LHZ, STB, STH 1475 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1476 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1477 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1478 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1479 // LHA 1480 PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1481 PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1482 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1483 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1484 // LFS, LFD, STFS, STFD 1485 PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1486 PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1487 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1488 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1489 }; 1490 AddrModesMap[PPC::AM_DSForm] = { 1491 // LWA 1492 PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt, 1493 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1494 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1495 // LD, STD 1496 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt, 1497 PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt, 1498 PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt, 1499 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64 1500 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1501 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1502 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1503 }; 1504 AddrModesMap[PPC::AM_DQForm] = { 1505 // LXV, STXV 1506 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1507 PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1508 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1509 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10, 1510 PPC::MOF_NotAddNorCst | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10, 1511 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10, 1512 }; 1513 } 1514 1515 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1516 /// the desired ByVal argument alignment. 1517 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1518 if (MaxAlign == MaxMaxAlign) 1519 return; 1520 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1521 if (MaxMaxAlign >= 32 && 1522 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1523 MaxAlign = Align(32); 1524 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1525 MaxAlign < 16) 1526 MaxAlign = Align(16); 1527 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1528 Align EltAlign; 1529 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1530 if (EltAlign > MaxAlign) 1531 MaxAlign = EltAlign; 1532 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1533 for (auto *EltTy : STy->elements()) { 1534 Align EltAlign; 1535 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1536 if (EltAlign > MaxAlign) 1537 MaxAlign = EltAlign; 1538 if (MaxAlign == MaxMaxAlign) 1539 break; 1540 } 1541 } 1542 } 1543 1544 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1545 /// function arguments in the caller parameter area. 1546 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1547 const DataLayout &DL) const { 1548 // 16byte and wider vectors are passed on 16byte boundary. 1549 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1550 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1551 if (Subtarget.hasAltivec()) 1552 getMaxByValAlign(Ty, Alignment, Align(16)); 1553 return Alignment.value(); 1554 } 1555 1556 bool PPCTargetLowering::useSoftFloat() const { 1557 return Subtarget.useSoftFloat(); 1558 } 1559 1560 bool PPCTargetLowering::hasSPE() const { 1561 return Subtarget.hasSPE(); 1562 } 1563 1564 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1565 return VT.isScalarInteger(); 1566 } 1567 1568 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1569 switch ((PPCISD::NodeType)Opcode) { 1570 case PPCISD::FIRST_NUMBER: break; 1571 case PPCISD::FSEL: return "PPCISD::FSEL"; 1572 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1573 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1574 case PPCISD::FCFID: return "PPCISD::FCFID"; 1575 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1576 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1577 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1578 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1579 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1580 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1581 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1582 case PPCISD::FP_TO_UINT_IN_VSR: 1583 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1584 case PPCISD::FP_TO_SINT_IN_VSR: 1585 return "PPCISD::FP_TO_SINT_IN_VSR"; 1586 case PPCISD::FRE: return "PPCISD::FRE"; 1587 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1588 case PPCISD::FTSQRT: 1589 return "PPCISD::FTSQRT"; 1590 case PPCISD::FSQRT: 1591 return "PPCISD::FSQRT"; 1592 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1593 case PPCISD::VPERM: return "PPCISD::VPERM"; 1594 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1595 case PPCISD::XXSPLTI_SP_TO_DP: 1596 return "PPCISD::XXSPLTI_SP_TO_DP"; 1597 case PPCISD::XXSPLTI32DX: 1598 return "PPCISD::XXSPLTI32DX"; 1599 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1600 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1601 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1602 case PPCISD::CMPB: return "PPCISD::CMPB"; 1603 case PPCISD::Hi: return "PPCISD::Hi"; 1604 case PPCISD::Lo: return "PPCISD::Lo"; 1605 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1606 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1607 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1608 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1609 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1610 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1611 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1612 case PPCISD::SRL: return "PPCISD::SRL"; 1613 case PPCISD::SRA: return "PPCISD::SRA"; 1614 case PPCISD::SHL: return "PPCISD::SHL"; 1615 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1616 case PPCISD::CALL: return "PPCISD::CALL"; 1617 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1618 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1619 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1620 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1621 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1622 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1623 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1624 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1625 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1626 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1627 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1628 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1629 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1630 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1631 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1632 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1633 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1634 case PPCISD::ANDI_rec_1_EQ_BIT: 1635 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1636 case PPCISD::ANDI_rec_1_GT_BIT: 1637 return "PPCISD::ANDI_rec_1_GT_BIT"; 1638 case PPCISD::VCMP: return "PPCISD::VCMP"; 1639 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1640 case PPCISD::LBRX: return "PPCISD::LBRX"; 1641 case PPCISD::STBRX: return "PPCISD::STBRX"; 1642 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1643 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1644 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1645 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1646 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1647 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1648 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1649 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1650 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1651 case PPCISD::ST_VSR_SCAL_INT: 1652 return "PPCISD::ST_VSR_SCAL_INT"; 1653 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1654 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1655 case PPCISD::BDZ: return "PPCISD::BDZ"; 1656 case PPCISD::MFFS: return "PPCISD::MFFS"; 1657 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1658 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1659 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1660 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1661 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1662 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1663 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1664 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1665 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1666 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1667 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1668 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1669 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1670 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX"; 1671 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1672 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1673 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1674 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1675 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1676 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1677 case PPCISD::PADDI_DTPREL: 1678 return "PPCISD::PADDI_DTPREL"; 1679 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1680 case PPCISD::SC: return "PPCISD::SC"; 1681 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1682 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1683 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1684 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1685 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1686 case PPCISD::VABSD: return "PPCISD::VABSD"; 1687 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1688 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1689 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1690 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1691 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1692 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1693 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1694 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1695 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1696 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1697 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1698 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1699 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1700 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1701 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1702 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1703 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1704 case PPCISD::STRICT_FADDRTZ: 1705 return "PPCISD::STRICT_FADDRTZ"; 1706 case PPCISD::STRICT_FCTIDZ: 1707 return "PPCISD::STRICT_FCTIDZ"; 1708 case PPCISD::STRICT_FCTIWZ: 1709 return "PPCISD::STRICT_FCTIWZ"; 1710 case PPCISD::STRICT_FCTIDUZ: 1711 return "PPCISD::STRICT_FCTIDUZ"; 1712 case PPCISD::STRICT_FCTIWUZ: 1713 return "PPCISD::STRICT_FCTIWUZ"; 1714 case PPCISD::STRICT_FCFID: 1715 return "PPCISD::STRICT_FCFID"; 1716 case PPCISD::STRICT_FCFIDU: 1717 return "PPCISD::STRICT_FCFIDU"; 1718 case PPCISD::STRICT_FCFIDS: 1719 return "PPCISD::STRICT_FCFIDS"; 1720 case PPCISD::STRICT_FCFIDUS: 1721 return "PPCISD::STRICT_FCFIDUS"; 1722 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1723 } 1724 return nullptr; 1725 } 1726 1727 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1728 EVT VT) const { 1729 if (!VT.isVector()) 1730 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1731 1732 return VT.changeVectorElementTypeToInteger(); 1733 } 1734 1735 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1736 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1737 return true; 1738 } 1739 1740 //===----------------------------------------------------------------------===// 1741 // Node matching predicates, for use by the tblgen matching code. 1742 //===----------------------------------------------------------------------===// 1743 1744 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1745 static bool isFloatingPointZero(SDValue Op) { 1746 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1747 return CFP->getValueAPF().isZero(); 1748 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1749 // Maybe this has already been legalized into the constant pool? 1750 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1751 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1752 return CFP->getValueAPF().isZero(); 1753 } 1754 return false; 1755 } 1756 1757 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1758 /// true if Op is undef or if it matches the specified value. 1759 static bool isConstantOrUndef(int Op, int Val) { 1760 return Op < 0 || Op == Val; 1761 } 1762 1763 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1764 /// VPKUHUM instruction. 1765 /// The ShuffleKind distinguishes between big-endian operations with 1766 /// two different inputs (0), either-endian operations with two identical 1767 /// inputs (1), and little-endian operations with two different inputs (2). 1768 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1769 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1770 SelectionDAG &DAG) { 1771 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1772 if (ShuffleKind == 0) { 1773 if (IsLE) 1774 return false; 1775 for (unsigned i = 0; i != 16; ++i) 1776 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1777 return false; 1778 } else if (ShuffleKind == 2) { 1779 if (!IsLE) 1780 return false; 1781 for (unsigned i = 0; i != 16; ++i) 1782 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1783 return false; 1784 } else if (ShuffleKind == 1) { 1785 unsigned j = IsLE ? 0 : 1; 1786 for (unsigned i = 0; i != 8; ++i) 1787 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1788 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1789 return false; 1790 } 1791 return true; 1792 } 1793 1794 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1795 /// VPKUWUM instruction. 1796 /// The ShuffleKind distinguishes between big-endian operations with 1797 /// two different inputs (0), either-endian operations with two identical 1798 /// inputs (1), and little-endian operations with two different inputs (2). 1799 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1800 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1801 SelectionDAG &DAG) { 1802 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1803 if (ShuffleKind == 0) { 1804 if (IsLE) 1805 return false; 1806 for (unsigned i = 0; i != 16; i += 2) 1807 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1808 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1809 return false; 1810 } else if (ShuffleKind == 2) { 1811 if (!IsLE) 1812 return false; 1813 for (unsigned i = 0; i != 16; i += 2) 1814 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1815 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1816 return false; 1817 } else if (ShuffleKind == 1) { 1818 unsigned j = IsLE ? 0 : 2; 1819 for (unsigned i = 0; i != 8; i += 2) 1820 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1821 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1822 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1823 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1824 return false; 1825 } 1826 return true; 1827 } 1828 1829 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1830 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1831 /// current subtarget. 1832 /// 1833 /// The ShuffleKind distinguishes between big-endian operations with 1834 /// two different inputs (0), either-endian operations with two identical 1835 /// inputs (1), and little-endian operations with two different inputs (2). 1836 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1837 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1838 SelectionDAG &DAG) { 1839 const PPCSubtarget& Subtarget = 1840 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1841 if (!Subtarget.hasP8Vector()) 1842 return false; 1843 1844 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1845 if (ShuffleKind == 0) { 1846 if (IsLE) 1847 return false; 1848 for (unsigned i = 0; i != 16; i += 4) 1849 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1850 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1851 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1852 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1853 return false; 1854 } else if (ShuffleKind == 2) { 1855 if (!IsLE) 1856 return false; 1857 for (unsigned i = 0; i != 16; i += 4) 1858 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1859 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1860 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1861 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1862 return false; 1863 } else if (ShuffleKind == 1) { 1864 unsigned j = IsLE ? 0 : 4; 1865 for (unsigned i = 0; i != 8; i += 4) 1866 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1867 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1868 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1869 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1870 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1871 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1872 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1873 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1874 return false; 1875 } 1876 return true; 1877 } 1878 1879 /// isVMerge - Common function, used to match vmrg* shuffles. 1880 /// 1881 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1882 unsigned LHSStart, unsigned RHSStart) { 1883 if (N->getValueType(0) != MVT::v16i8) 1884 return false; 1885 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1886 "Unsupported merge size!"); 1887 1888 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1889 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1890 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1891 LHSStart+j+i*UnitSize) || 1892 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1893 RHSStart+j+i*UnitSize)) 1894 return false; 1895 } 1896 return true; 1897 } 1898 1899 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1900 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1901 /// The ShuffleKind distinguishes between big-endian merges with two 1902 /// different inputs (0), either-endian merges with two identical inputs (1), 1903 /// and little-endian merges with two different inputs (2). For the latter, 1904 /// the input operands are swapped (see PPCInstrAltivec.td). 1905 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1906 unsigned ShuffleKind, SelectionDAG &DAG) { 1907 if (DAG.getDataLayout().isLittleEndian()) { 1908 if (ShuffleKind == 1) // unary 1909 return isVMerge(N, UnitSize, 0, 0); 1910 else if (ShuffleKind == 2) // swapped 1911 return isVMerge(N, UnitSize, 0, 16); 1912 else 1913 return false; 1914 } else { 1915 if (ShuffleKind == 1) // unary 1916 return isVMerge(N, UnitSize, 8, 8); 1917 else if (ShuffleKind == 0) // normal 1918 return isVMerge(N, UnitSize, 8, 24); 1919 else 1920 return false; 1921 } 1922 } 1923 1924 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1925 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1926 /// The ShuffleKind distinguishes between big-endian merges with two 1927 /// different inputs (0), either-endian merges with two identical inputs (1), 1928 /// and little-endian merges with two different inputs (2). For the latter, 1929 /// the input operands are swapped (see PPCInstrAltivec.td). 1930 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1931 unsigned ShuffleKind, SelectionDAG &DAG) { 1932 if (DAG.getDataLayout().isLittleEndian()) { 1933 if (ShuffleKind == 1) // unary 1934 return isVMerge(N, UnitSize, 8, 8); 1935 else if (ShuffleKind == 2) // swapped 1936 return isVMerge(N, UnitSize, 8, 24); 1937 else 1938 return false; 1939 } else { 1940 if (ShuffleKind == 1) // unary 1941 return isVMerge(N, UnitSize, 0, 0); 1942 else if (ShuffleKind == 0) // normal 1943 return isVMerge(N, UnitSize, 0, 16); 1944 else 1945 return false; 1946 } 1947 } 1948 1949 /** 1950 * Common function used to match vmrgew and vmrgow shuffles 1951 * 1952 * The indexOffset determines whether to look for even or odd words in 1953 * the shuffle mask. This is based on the of the endianness of the target 1954 * machine. 1955 * - Little Endian: 1956 * - Use offset of 0 to check for odd elements 1957 * - Use offset of 4 to check for even elements 1958 * - Big Endian: 1959 * - Use offset of 0 to check for even elements 1960 * - Use offset of 4 to check for odd elements 1961 * A detailed description of the vector element ordering for little endian and 1962 * big endian can be found at 1963 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1964 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1965 * compiler differences mean to you 1966 * 1967 * The mask to the shuffle vector instruction specifies the indices of the 1968 * elements from the two input vectors to place in the result. The elements are 1969 * numbered in array-access order, starting with the first vector. These vectors 1970 * are always of type v16i8, thus each vector will contain 16 elements of size 1971 * 8. More info on the shuffle vector can be found in the 1972 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1973 * Language Reference. 1974 * 1975 * The RHSStartValue indicates whether the same input vectors are used (unary) 1976 * or two different input vectors are used, based on the following: 1977 * - If the instruction uses the same vector for both inputs, the range of the 1978 * indices will be 0 to 15. In this case, the RHSStart value passed should 1979 * be 0. 1980 * - If the instruction has two different vectors then the range of the 1981 * indices will be 0 to 31. In this case, the RHSStart value passed should 1982 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1983 * to 31 specify elements in the second vector). 1984 * 1985 * \param[in] N The shuffle vector SD Node to analyze 1986 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1987 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1988 * vector to the shuffle_vector instruction 1989 * \return true iff this shuffle vector represents an even or odd word merge 1990 */ 1991 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1992 unsigned RHSStartValue) { 1993 if (N->getValueType(0) != MVT::v16i8) 1994 return false; 1995 1996 for (unsigned i = 0; i < 2; ++i) 1997 for (unsigned j = 0; j < 4; ++j) 1998 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1999 i*RHSStartValue+j+IndexOffset) || 2000 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 2001 i*RHSStartValue+j+IndexOffset+8)) 2002 return false; 2003 return true; 2004 } 2005 2006 /** 2007 * Determine if the specified shuffle mask is suitable for the vmrgew or 2008 * vmrgow instructions. 2009 * 2010 * \param[in] N The shuffle vector SD Node to analyze 2011 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 2012 * \param[in] ShuffleKind Identify the type of merge: 2013 * - 0 = big-endian merge with two different inputs; 2014 * - 1 = either-endian merge with two identical inputs; 2015 * - 2 = little-endian merge with two different inputs (inputs are swapped for 2016 * little-endian merges). 2017 * \param[in] DAG The current SelectionDAG 2018 * \return true iff this shuffle mask 2019 */ 2020 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 2021 unsigned ShuffleKind, SelectionDAG &DAG) { 2022 if (DAG.getDataLayout().isLittleEndian()) { 2023 unsigned indexOffset = CheckEven ? 4 : 0; 2024 if (ShuffleKind == 1) // Unary 2025 return isVMerge(N, indexOffset, 0); 2026 else if (ShuffleKind == 2) // swapped 2027 return isVMerge(N, indexOffset, 16); 2028 else 2029 return false; 2030 } 2031 else { 2032 unsigned indexOffset = CheckEven ? 0 : 4; 2033 if (ShuffleKind == 1) // Unary 2034 return isVMerge(N, indexOffset, 0); 2035 else if (ShuffleKind == 0) // Normal 2036 return isVMerge(N, indexOffset, 16); 2037 else 2038 return false; 2039 } 2040 return false; 2041 } 2042 2043 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 2044 /// amount, otherwise return -1. 2045 /// The ShuffleKind distinguishes between big-endian operations with two 2046 /// different inputs (0), either-endian operations with two identical inputs 2047 /// (1), and little-endian operations with two different inputs (2). For the 2048 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 2049 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 2050 SelectionDAG &DAG) { 2051 if (N->getValueType(0) != MVT::v16i8) 2052 return -1; 2053 2054 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2055 2056 // Find the first non-undef value in the shuffle mask. 2057 unsigned i; 2058 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 2059 /*search*/; 2060 2061 if (i == 16) return -1; // all undef. 2062 2063 // Otherwise, check to see if the rest of the elements are consecutively 2064 // numbered from this value. 2065 unsigned ShiftAmt = SVOp->getMaskElt(i); 2066 if (ShiftAmt < i) return -1; 2067 2068 ShiftAmt -= i; 2069 bool isLE = DAG.getDataLayout().isLittleEndian(); 2070 2071 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 2072 // Check the rest of the elements to see if they are consecutive. 2073 for (++i; i != 16; ++i) 2074 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2075 return -1; 2076 } else if (ShuffleKind == 1) { 2077 // Check the rest of the elements to see if they are consecutive. 2078 for (++i; i != 16; ++i) 2079 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 2080 return -1; 2081 } else 2082 return -1; 2083 2084 if (isLE) 2085 ShiftAmt = 16 - ShiftAmt; 2086 2087 return ShiftAmt; 2088 } 2089 2090 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 2091 /// specifies a splat of a single element that is suitable for input to 2092 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 2093 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 2094 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 2095 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2096 2097 // The consecutive indices need to specify an element, not part of two 2098 // different elements. So abandon ship early if this isn't the case. 2099 if (N->getMaskElt(0) % EltSize != 0) 2100 return false; 2101 2102 // This is a splat operation if each element of the permute is the same, and 2103 // if the value doesn't reference the second vector. 2104 unsigned ElementBase = N->getMaskElt(0); 2105 2106 // FIXME: Handle UNDEF elements too! 2107 if (ElementBase >= 16) 2108 return false; 2109 2110 // Check that the indices are consecutive, in the case of a multi-byte element 2111 // splatted with a v16i8 mask. 2112 for (unsigned i = 1; i != EltSize; ++i) 2113 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2114 return false; 2115 2116 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2117 if (N->getMaskElt(i) < 0) continue; 2118 for (unsigned j = 0; j != EltSize; ++j) 2119 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2120 return false; 2121 } 2122 return true; 2123 } 2124 2125 /// Check that the mask is shuffling N byte elements. Within each N byte 2126 /// element of the mask, the indices could be either in increasing or 2127 /// decreasing order as long as they are consecutive. 2128 /// \param[in] N the shuffle vector SD Node to analyze 2129 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2130 /// Word/DoubleWord/QuadWord). 2131 /// \param[in] StepLen the delta indices number among the N byte element, if 2132 /// the mask is in increasing/decreasing order then it is 1/-1. 2133 /// \return true iff the mask is shuffling N byte elements. 2134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2135 int StepLen) { 2136 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2137 "Unexpected element width."); 2138 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2139 2140 unsigned NumOfElem = 16 / Width; 2141 unsigned MaskVal[16]; // Width is never greater than 16 2142 for (unsigned i = 0; i < NumOfElem; ++i) { 2143 MaskVal[0] = N->getMaskElt(i * Width); 2144 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2145 return false; 2146 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2147 return false; 2148 } 2149 2150 for (unsigned int j = 1; j < Width; ++j) { 2151 MaskVal[j] = N->getMaskElt(i * Width + j); 2152 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2153 return false; 2154 } 2155 } 2156 } 2157 2158 return true; 2159 } 2160 2161 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2162 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2163 if (!isNByteElemShuffleMask(N, 4, 1)) 2164 return false; 2165 2166 // Now we look at mask elements 0,4,8,12 2167 unsigned M0 = N->getMaskElt(0) / 4; 2168 unsigned M1 = N->getMaskElt(4) / 4; 2169 unsigned M2 = N->getMaskElt(8) / 4; 2170 unsigned M3 = N->getMaskElt(12) / 4; 2171 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2172 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2173 2174 // Below, let H and L be arbitrary elements of the shuffle mask 2175 // where H is in the range [4,7] and L is in the range [0,3]. 2176 // H, 1, 2, 3 or L, 5, 6, 7 2177 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2178 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2179 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2180 InsertAtByte = IsLE ? 12 : 0; 2181 Swap = M0 < 4; 2182 return true; 2183 } 2184 // 0, H, 2, 3 or 4, L, 6, 7 2185 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2186 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2187 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2188 InsertAtByte = IsLE ? 8 : 4; 2189 Swap = M1 < 4; 2190 return true; 2191 } 2192 // 0, 1, H, 3 or 4, 5, L, 7 2193 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2194 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2195 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2196 InsertAtByte = IsLE ? 4 : 8; 2197 Swap = M2 < 4; 2198 return true; 2199 } 2200 // 0, 1, 2, H or 4, 5, 6, L 2201 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2202 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2203 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2204 InsertAtByte = IsLE ? 0 : 12; 2205 Swap = M3 < 4; 2206 return true; 2207 } 2208 2209 // If both vector operands for the shuffle are the same vector, the mask will 2210 // contain only elements from the first one and the second one will be undef. 2211 if (N->getOperand(1).isUndef()) { 2212 ShiftElts = 0; 2213 Swap = true; 2214 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2215 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2216 InsertAtByte = IsLE ? 12 : 0; 2217 return true; 2218 } 2219 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2220 InsertAtByte = IsLE ? 8 : 4; 2221 return true; 2222 } 2223 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2224 InsertAtByte = IsLE ? 4 : 8; 2225 return true; 2226 } 2227 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2228 InsertAtByte = IsLE ? 0 : 12; 2229 return true; 2230 } 2231 } 2232 2233 return false; 2234 } 2235 2236 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2237 bool &Swap, bool IsLE) { 2238 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2239 // Ensure each byte index of the word is consecutive. 2240 if (!isNByteElemShuffleMask(N, 4, 1)) 2241 return false; 2242 2243 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2244 unsigned M0 = N->getMaskElt(0) / 4; 2245 unsigned M1 = N->getMaskElt(4) / 4; 2246 unsigned M2 = N->getMaskElt(8) / 4; 2247 unsigned M3 = N->getMaskElt(12) / 4; 2248 2249 // If both vector operands for the shuffle are the same vector, the mask will 2250 // contain only elements from the first one and the second one will be undef. 2251 if (N->getOperand(1).isUndef()) { 2252 assert(M0 < 4 && "Indexing into an undef vector?"); 2253 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2254 return false; 2255 2256 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2257 Swap = false; 2258 return true; 2259 } 2260 2261 // Ensure each word index of the ShuffleVector Mask is consecutive. 2262 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2263 return false; 2264 2265 if (IsLE) { 2266 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2267 // Input vectors don't need to be swapped if the leading element 2268 // of the result is one of the 3 left elements of the second vector 2269 // (or if there is no shift to be done at all). 2270 Swap = false; 2271 ShiftElts = (8 - M0) % 8; 2272 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2273 // Input vectors need to be swapped if the leading element 2274 // of the result is one of the 3 left elements of the first vector 2275 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2276 Swap = true; 2277 ShiftElts = (4 - M0) % 4; 2278 } 2279 2280 return true; 2281 } else { // BE 2282 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2283 // Input vectors don't need to be swapped if the leading element 2284 // of the result is one of the 4 elements of the first vector. 2285 Swap = false; 2286 ShiftElts = M0; 2287 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2288 // Input vectors need to be swapped if the leading element 2289 // of the result is one of the 4 elements of the right vector. 2290 Swap = true; 2291 ShiftElts = M0 - 4; 2292 } 2293 2294 return true; 2295 } 2296 } 2297 2298 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2299 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2300 2301 if (!isNByteElemShuffleMask(N, Width, -1)) 2302 return false; 2303 2304 for (int i = 0; i < 16; i += Width) 2305 if (N->getMaskElt(i) != i + Width - 1) 2306 return false; 2307 2308 return true; 2309 } 2310 2311 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2312 return isXXBRShuffleMaskHelper(N, 2); 2313 } 2314 2315 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2316 return isXXBRShuffleMaskHelper(N, 4); 2317 } 2318 2319 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2320 return isXXBRShuffleMaskHelper(N, 8); 2321 } 2322 2323 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2324 return isXXBRShuffleMaskHelper(N, 16); 2325 } 2326 2327 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2328 /// if the inputs to the instruction should be swapped and set \p DM to the 2329 /// value for the immediate. 2330 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2331 /// AND element 0 of the result comes from the first input (LE) or second input 2332 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2333 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2334 /// mask. 2335 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2336 bool &Swap, bool IsLE) { 2337 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2338 2339 // Ensure each byte index of the double word is consecutive. 2340 if (!isNByteElemShuffleMask(N, 8, 1)) 2341 return false; 2342 2343 unsigned M0 = N->getMaskElt(0) / 8; 2344 unsigned M1 = N->getMaskElt(8) / 8; 2345 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2346 2347 // If both vector operands for the shuffle are the same vector, the mask will 2348 // contain only elements from the first one and the second one will be undef. 2349 if (N->getOperand(1).isUndef()) { 2350 if ((M0 | M1) < 2) { 2351 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2352 Swap = false; 2353 return true; 2354 } else 2355 return false; 2356 } 2357 2358 if (IsLE) { 2359 if (M0 > 1 && M1 < 2) { 2360 Swap = false; 2361 } else if (M0 < 2 && M1 > 1) { 2362 M0 = (M0 + 2) % 4; 2363 M1 = (M1 + 2) % 4; 2364 Swap = true; 2365 } else 2366 return false; 2367 2368 // Note: if control flow comes here that means Swap is already set above 2369 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2370 return true; 2371 } else { // BE 2372 if (M0 < 2 && M1 > 1) { 2373 Swap = false; 2374 } else if (M0 > 1 && M1 < 2) { 2375 M0 = (M0 + 2) % 4; 2376 M1 = (M1 + 2) % 4; 2377 Swap = true; 2378 } else 2379 return false; 2380 2381 // Note: if control flow comes here that means Swap is already set above 2382 DM = (M0 << 1) + (M1 & 1); 2383 return true; 2384 } 2385 } 2386 2387 2388 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2389 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2390 /// elements are counted from the left of the vector register). 2391 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2392 SelectionDAG &DAG) { 2393 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2394 assert(isSplatShuffleMask(SVOp, EltSize)); 2395 if (DAG.getDataLayout().isLittleEndian()) 2396 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2397 else 2398 return SVOp->getMaskElt(0) / EltSize; 2399 } 2400 2401 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2402 /// by using a vspltis[bhw] instruction of the specified element size, return 2403 /// the constant being splatted. The ByteSize field indicates the number of 2404 /// bytes of each element [124] -> [bhw]. 2405 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2406 SDValue OpVal(nullptr, 0); 2407 2408 // If ByteSize of the splat is bigger than the element size of the 2409 // build_vector, then we have a case where we are checking for a splat where 2410 // multiple elements of the buildvector are folded together into a single 2411 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2412 unsigned EltSize = 16/N->getNumOperands(); 2413 if (EltSize < ByteSize) { 2414 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2415 SDValue UniquedVals[4]; 2416 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2417 2418 // See if all of the elements in the buildvector agree across. 2419 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2420 if (N->getOperand(i).isUndef()) continue; 2421 // If the element isn't a constant, bail fully out. 2422 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2423 2424 if (!UniquedVals[i&(Multiple-1)].getNode()) 2425 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2426 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2427 return SDValue(); // no match. 2428 } 2429 2430 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2431 // either constant or undef values that are identical for each chunk. See 2432 // if these chunks can form into a larger vspltis*. 2433 2434 // Check to see if all of the leading entries are either 0 or -1. If 2435 // neither, then this won't fit into the immediate field. 2436 bool LeadingZero = true; 2437 bool LeadingOnes = true; 2438 for (unsigned i = 0; i != Multiple-1; ++i) { 2439 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2440 2441 LeadingZero &= isNullConstant(UniquedVals[i]); 2442 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2443 } 2444 // Finally, check the least significant entry. 2445 if (LeadingZero) { 2446 if (!UniquedVals[Multiple-1].getNode()) 2447 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2448 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2449 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2450 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2451 } 2452 if (LeadingOnes) { 2453 if (!UniquedVals[Multiple-1].getNode()) 2454 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2455 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2456 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2457 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2458 } 2459 2460 return SDValue(); 2461 } 2462 2463 // Check to see if this buildvec has a single non-undef value in its elements. 2464 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2465 if (N->getOperand(i).isUndef()) continue; 2466 if (!OpVal.getNode()) 2467 OpVal = N->getOperand(i); 2468 else if (OpVal != N->getOperand(i)) 2469 return SDValue(); 2470 } 2471 2472 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2473 2474 unsigned ValSizeInBytes = EltSize; 2475 uint64_t Value = 0; 2476 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2477 Value = CN->getZExtValue(); 2478 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2479 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2480 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2481 } 2482 2483 // If the splat value is larger than the element value, then we can never do 2484 // this splat. The only case that we could fit the replicated bits into our 2485 // immediate field for would be zero, and we prefer to use vxor for it. 2486 if (ValSizeInBytes < ByteSize) return SDValue(); 2487 2488 // If the element value is larger than the splat value, check if it consists 2489 // of a repeated bit pattern of size ByteSize. 2490 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2491 return SDValue(); 2492 2493 // Properly sign extend the value. 2494 int MaskVal = SignExtend32(Value, ByteSize * 8); 2495 2496 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2497 if (MaskVal == 0) return SDValue(); 2498 2499 // Finally, if this value fits in a 5 bit sext field, return it 2500 if (SignExtend32<5>(MaskVal) == MaskVal) 2501 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2502 return SDValue(); 2503 } 2504 2505 //===----------------------------------------------------------------------===// 2506 // Addressing Mode Selection 2507 //===----------------------------------------------------------------------===// 2508 2509 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2510 /// or 64-bit immediate, and if the value can be accurately represented as a 2511 /// sign extension from a 16-bit value. If so, this returns true and the 2512 /// immediate. 2513 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2514 if (!isa<ConstantSDNode>(N)) 2515 return false; 2516 2517 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2518 if (N->getValueType(0) == MVT::i32) 2519 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2520 else 2521 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2522 } 2523 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2524 return isIntS16Immediate(Op.getNode(), Imm); 2525 } 2526 2527 /// Used when computing address flags for selecting loads and stores. 2528 /// If we have an OR, check if the LHS and RHS are provably disjoint. 2529 /// An OR of two provably disjoint values is equivalent to an ADD. 2530 /// Most PPC load/store instructions compute the effective address as a sum, 2531 /// so doing this conversion is useful. 2532 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) { 2533 if (N.getOpcode() != ISD::OR) 2534 return false; 2535 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2536 if (!LHSKnown.Zero.getBoolValue()) 2537 return false; 2538 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2539 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0); 2540 } 2541 2542 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2543 /// be represented as an indexed [r+r] operation. 2544 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2545 SDValue &Index, 2546 SelectionDAG &DAG) const { 2547 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2548 UI != E; ++UI) { 2549 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2550 if (Memop->getMemoryVT() == MVT::f64) { 2551 Base = N.getOperand(0); 2552 Index = N.getOperand(1); 2553 return true; 2554 } 2555 } 2556 } 2557 return false; 2558 } 2559 2560 /// isIntS34Immediate - This method tests if value of node given can be 2561 /// accurately represented as a sign extension from a 34-bit value. If so, 2562 /// this returns true and the immediate. 2563 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2564 if (!isa<ConstantSDNode>(N)) 2565 return false; 2566 2567 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2568 return isInt<34>(Imm); 2569 } 2570 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2571 return isIntS34Immediate(Op.getNode(), Imm); 2572 } 2573 2574 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2575 /// can be represented as an indexed [r+r] operation. Returns false if it 2576 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2577 /// non-zero and N can be represented by a base register plus a signed 16-bit 2578 /// displacement, make a more precise judgement by checking (displacement % \p 2579 /// EncodingAlignment). 2580 bool PPCTargetLowering::SelectAddressRegReg( 2581 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2582 MaybeAlign EncodingAlignment) const { 2583 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2584 // a [pc+imm]. 2585 if (SelectAddressPCRel(N, Base)) 2586 return false; 2587 2588 int16_t Imm = 0; 2589 if (N.getOpcode() == ISD::ADD) { 2590 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2591 // SPE load/store can only handle 8-bit offsets. 2592 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2593 return true; 2594 if (isIntS16Immediate(N.getOperand(1), Imm) && 2595 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2596 return false; // r+i 2597 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2598 return false; // r+i 2599 2600 Base = N.getOperand(0); 2601 Index = N.getOperand(1); 2602 return true; 2603 } else if (N.getOpcode() == ISD::OR) { 2604 if (isIntS16Immediate(N.getOperand(1), Imm) && 2605 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2606 return false; // r+i can fold it if we can. 2607 2608 // If this is an or of disjoint bitfields, we can codegen this as an add 2609 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2610 // disjoint. 2611 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2612 2613 if (LHSKnown.Zero.getBoolValue()) { 2614 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2615 // If all of the bits are known zero on the LHS or RHS, the add won't 2616 // carry. 2617 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2618 Base = N.getOperand(0); 2619 Index = N.getOperand(1); 2620 return true; 2621 } 2622 } 2623 } 2624 2625 return false; 2626 } 2627 2628 // If we happen to be doing an i64 load or store into a stack slot that has 2629 // less than a 4-byte alignment, then the frame-index elimination may need to 2630 // use an indexed load or store instruction (because the offset may not be a 2631 // multiple of 4). The extra register needed to hold the offset comes from the 2632 // register scavenger, and it is possible that the scavenger will need to use 2633 // an emergency spill slot. As a result, we need to make sure that a spill slot 2634 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2635 // stack slot. 2636 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2637 // FIXME: This does not handle the LWA case. 2638 if (VT != MVT::i64) 2639 return; 2640 2641 // NOTE: We'll exclude negative FIs here, which come from argument 2642 // lowering, because there are no known test cases triggering this problem 2643 // using packed structures (or similar). We can remove this exclusion if 2644 // we find such a test case. The reason why this is so test-case driven is 2645 // because this entire 'fixup' is only to prevent crashes (from the 2646 // register scavenger) on not-really-valid inputs. For example, if we have: 2647 // %a = alloca i1 2648 // %b = bitcast i1* %a to i64* 2649 // store i64* a, i64 b 2650 // then the store should really be marked as 'align 1', but is not. If it 2651 // were marked as 'align 1' then the indexed form would have been 2652 // instruction-selected initially, and the problem this 'fixup' is preventing 2653 // won't happen regardless. 2654 if (FrameIdx < 0) 2655 return; 2656 2657 MachineFunction &MF = DAG.getMachineFunction(); 2658 MachineFrameInfo &MFI = MF.getFrameInfo(); 2659 2660 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2661 return; 2662 2663 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2664 FuncInfo->setHasNonRISpills(); 2665 } 2666 2667 /// Returns true if the address N can be represented by a base register plus 2668 /// a signed 16-bit displacement [r+imm], and if it is not better 2669 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2670 /// displacements that are multiples of that value. 2671 bool PPCTargetLowering::SelectAddressRegImm( 2672 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2673 MaybeAlign EncodingAlignment) const { 2674 // FIXME dl should come from parent load or store, not from address 2675 SDLoc dl(N); 2676 2677 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2678 // a [pc+imm]. 2679 if (SelectAddressPCRel(N, Base)) 2680 return false; 2681 2682 // If this can be more profitably realized as r+r, fail. 2683 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2684 return false; 2685 2686 if (N.getOpcode() == ISD::ADD) { 2687 int16_t imm = 0; 2688 if (isIntS16Immediate(N.getOperand(1), imm) && 2689 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2690 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2691 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2692 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2693 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2694 } else { 2695 Base = N.getOperand(0); 2696 } 2697 return true; // [r+i] 2698 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2699 // Match LOAD (ADD (X, Lo(G))). 2700 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2701 && "Cannot handle constant offsets yet!"); 2702 Disp = N.getOperand(1).getOperand(0); // The global address. 2703 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2704 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2705 Disp.getOpcode() == ISD::TargetConstantPool || 2706 Disp.getOpcode() == ISD::TargetJumpTable); 2707 Base = N.getOperand(0); 2708 return true; // [&g+r] 2709 } 2710 } else if (N.getOpcode() == ISD::OR) { 2711 int16_t imm = 0; 2712 if (isIntS16Immediate(N.getOperand(1), imm) && 2713 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2714 // If this is an or of disjoint bitfields, we can codegen this as an add 2715 // (for better address arithmetic) if the LHS and RHS of the OR are 2716 // provably disjoint. 2717 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2718 2719 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2720 // If all of the bits are known zero on the LHS or RHS, the add won't 2721 // carry. 2722 if (FrameIndexSDNode *FI = 2723 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2724 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2725 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2726 } else { 2727 Base = N.getOperand(0); 2728 } 2729 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2730 return true; 2731 } 2732 } 2733 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2734 // Loading from a constant address. 2735 2736 // If this address fits entirely in a 16-bit sext immediate field, codegen 2737 // this as "d, 0" 2738 int16_t Imm; 2739 if (isIntS16Immediate(CN, Imm) && 2740 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2741 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2742 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2743 CN->getValueType(0)); 2744 return true; 2745 } 2746 2747 // Handle 32-bit sext immediates with LIS + addr mode. 2748 if ((CN->getValueType(0) == MVT::i32 || 2749 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2750 (!EncodingAlignment || 2751 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2752 int Addr = (int)CN->getZExtValue(); 2753 2754 // Otherwise, break this down into an LIS + disp. 2755 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2756 2757 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2758 MVT::i32); 2759 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2760 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2761 return true; 2762 } 2763 } 2764 2765 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2766 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2767 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2768 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2769 } else 2770 Base = N; 2771 return true; // [r+0] 2772 } 2773 2774 /// Similar to the 16-bit case but for instructions that take a 34-bit 2775 /// displacement field (prefixed loads/stores). 2776 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2777 SDValue &Base, 2778 SelectionDAG &DAG) const { 2779 // Only on 64-bit targets. 2780 if (N.getValueType() != MVT::i64) 2781 return false; 2782 2783 SDLoc dl(N); 2784 int64_t Imm = 0; 2785 2786 if (N.getOpcode() == ISD::ADD) { 2787 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2788 return false; 2789 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2790 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2791 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2792 else 2793 Base = N.getOperand(0); 2794 return true; 2795 } 2796 2797 if (N.getOpcode() == ISD::OR) { 2798 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2799 return false; 2800 // If this is an or of disjoint bitfields, we can codegen this as an add 2801 // (for better address arithmetic) if the LHS and RHS of the OR are 2802 // provably disjoint. 2803 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2804 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2805 return false; 2806 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2807 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2808 else 2809 Base = N.getOperand(0); 2810 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2811 return true; 2812 } 2813 2814 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2815 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2816 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2817 return true; 2818 } 2819 2820 return false; 2821 } 2822 2823 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2824 /// represented as an indexed [r+r] operation. 2825 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2826 SDValue &Index, 2827 SelectionDAG &DAG) const { 2828 // Check to see if we can easily represent this as an [r+r] address. This 2829 // will fail if it thinks that the address is more profitably represented as 2830 // reg+imm, e.g. where imm = 0. 2831 if (SelectAddressRegReg(N, Base, Index, DAG)) 2832 return true; 2833 2834 // If the address is the result of an add, we will utilize the fact that the 2835 // address calculation includes an implicit add. However, we can reduce 2836 // register pressure if we do not materialize a constant just for use as the 2837 // index register. We only get rid of the add if it is not an add of a 2838 // value and a 16-bit signed constant and both have a single use. 2839 int16_t imm = 0; 2840 if (N.getOpcode() == ISD::ADD && 2841 (!isIntS16Immediate(N.getOperand(1), imm) || 2842 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2843 Base = N.getOperand(0); 2844 Index = N.getOperand(1); 2845 return true; 2846 } 2847 2848 // Otherwise, do it the hard way, using R0 as the base register. 2849 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2850 N.getValueType()); 2851 Index = N; 2852 return true; 2853 } 2854 2855 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2856 Ty *PCRelCand = dyn_cast<Ty>(N); 2857 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2858 } 2859 2860 /// Returns true if this address is a PC Relative address. 2861 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2862 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2863 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2864 // This is a materialize PC Relative node. Always select this as PC Relative. 2865 Base = N; 2866 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2867 return true; 2868 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2869 isValidPCRelNode<GlobalAddressSDNode>(N) || 2870 isValidPCRelNode<JumpTableSDNode>(N) || 2871 isValidPCRelNode<BlockAddressSDNode>(N)) 2872 return true; 2873 return false; 2874 } 2875 2876 /// Returns true if we should use a direct load into vector instruction 2877 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2878 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2879 2880 // If there are any other uses other than scalar to vector, then we should 2881 // keep it as a scalar load -> direct move pattern to prevent multiple 2882 // loads. 2883 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2884 if (!LD) 2885 return false; 2886 2887 EVT MemVT = LD->getMemoryVT(); 2888 if (!MemVT.isSimple()) 2889 return false; 2890 switch(MemVT.getSimpleVT().SimpleTy) { 2891 case MVT::i64: 2892 break; 2893 case MVT::i32: 2894 if (!ST.hasP8Vector()) 2895 return false; 2896 break; 2897 case MVT::i16: 2898 case MVT::i8: 2899 if (!ST.hasP9Vector()) 2900 return false; 2901 break; 2902 default: 2903 return false; 2904 } 2905 2906 SDValue LoadedVal(N, 0); 2907 if (!LoadedVal.hasOneUse()) 2908 return false; 2909 2910 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2911 UI != UE; ++UI) 2912 if (UI.getUse().get().getResNo() == 0 && 2913 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2914 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2915 return false; 2916 2917 return true; 2918 } 2919 2920 /// getPreIndexedAddressParts - returns true by value, base pointer and 2921 /// offset pointer and addressing mode by reference if the node's address 2922 /// can be legally represented as pre-indexed load / store address. 2923 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2924 SDValue &Offset, 2925 ISD::MemIndexedMode &AM, 2926 SelectionDAG &DAG) const { 2927 if (DisablePPCPreinc) return false; 2928 2929 bool isLoad = true; 2930 SDValue Ptr; 2931 EVT VT; 2932 unsigned Alignment; 2933 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2934 Ptr = LD->getBasePtr(); 2935 VT = LD->getMemoryVT(); 2936 Alignment = LD->getAlignment(); 2937 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2938 Ptr = ST->getBasePtr(); 2939 VT = ST->getMemoryVT(); 2940 Alignment = ST->getAlignment(); 2941 isLoad = false; 2942 } else 2943 return false; 2944 2945 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2946 // instructions because we can fold these into a more efficient instruction 2947 // instead, (such as LXSD). 2948 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2949 return false; 2950 } 2951 2952 // PowerPC doesn't have preinc load/store instructions for vectors 2953 if (VT.isVector()) 2954 return false; 2955 2956 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2957 // Common code will reject creating a pre-inc form if the base pointer 2958 // is a frame index, or if N is a store and the base pointer is either 2959 // the same as or a predecessor of the value being stored. Check for 2960 // those situations here, and try with swapped Base/Offset instead. 2961 bool Swap = false; 2962 2963 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2964 Swap = true; 2965 else if (!isLoad) { 2966 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2967 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2968 Swap = true; 2969 } 2970 2971 if (Swap) 2972 std::swap(Base, Offset); 2973 2974 AM = ISD::PRE_INC; 2975 return true; 2976 } 2977 2978 // LDU/STU can only handle immediates that are a multiple of 4. 2979 if (VT != MVT::i64) { 2980 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2981 return false; 2982 } else { 2983 // LDU/STU need an address with at least 4-byte alignment. 2984 if (Alignment < 4) 2985 return false; 2986 2987 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2988 return false; 2989 } 2990 2991 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2992 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2993 // sext i32 to i64 when addr mode is r+i. 2994 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2995 LD->getExtensionType() == ISD::SEXTLOAD && 2996 isa<ConstantSDNode>(Offset)) 2997 return false; 2998 } 2999 3000 AM = ISD::PRE_INC; 3001 return true; 3002 } 3003 3004 //===----------------------------------------------------------------------===// 3005 // LowerOperation implementation 3006 //===----------------------------------------------------------------------===// 3007 3008 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 3009 /// and LoOpFlags to the target MO flags. 3010 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 3011 unsigned &HiOpFlags, unsigned &LoOpFlags, 3012 const GlobalValue *GV = nullptr) { 3013 HiOpFlags = PPCII::MO_HA; 3014 LoOpFlags = PPCII::MO_LO; 3015 3016 // Don't use the pic base if not in PIC relocation model. 3017 if (IsPIC) { 3018 HiOpFlags |= PPCII::MO_PIC_FLAG; 3019 LoOpFlags |= PPCII::MO_PIC_FLAG; 3020 } 3021 } 3022 3023 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 3024 SelectionDAG &DAG) { 3025 SDLoc DL(HiPart); 3026 EVT PtrVT = HiPart.getValueType(); 3027 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 3028 3029 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 3030 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 3031 3032 // With PIC, the first instruction is actually "GR+hi(&G)". 3033 if (isPIC) 3034 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 3035 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 3036 3037 // Generate non-pic code that has direct accesses to the constant pool. 3038 // The address of the global is just (hi(&g)+lo(&g)). 3039 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 3040 } 3041 3042 static void setUsesTOCBasePtr(MachineFunction &MF) { 3043 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3044 FuncInfo->setUsesTOCBasePtr(); 3045 } 3046 3047 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 3048 setUsesTOCBasePtr(DAG.getMachineFunction()); 3049 } 3050 3051 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 3052 SDValue GA) const { 3053 const bool Is64Bit = Subtarget.isPPC64(); 3054 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 3055 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 3056 : Subtarget.isAIXABI() 3057 ? DAG.getRegister(PPC::R2, VT) 3058 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 3059 SDValue Ops[] = { GA, Reg }; 3060 return DAG.getMemIntrinsicNode( 3061 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 3062 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 3063 MachineMemOperand::MOLoad); 3064 } 3065 3066 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 3067 SelectionDAG &DAG) const { 3068 EVT PtrVT = Op.getValueType(); 3069 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3070 const Constant *C = CP->getConstVal(); 3071 3072 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3073 // The actual address of the GlobalValue is stored in the TOC. 3074 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3075 if (Subtarget.isUsingPCRelativeCalls()) { 3076 SDLoc DL(CP); 3077 EVT Ty = getPointerTy(DAG.getDataLayout()); 3078 SDValue ConstPool = DAG.getTargetConstantPool( 3079 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 3080 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 3081 } 3082 setUsesTOCBasePtr(DAG); 3083 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 3084 return getTOCEntry(DAG, SDLoc(CP), GA); 3085 } 3086 3087 unsigned MOHiFlag, MOLoFlag; 3088 bool IsPIC = isPositionIndependent(); 3089 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3090 3091 if (IsPIC && Subtarget.isSVR4ABI()) { 3092 SDValue GA = 3093 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 3094 return getTOCEntry(DAG, SDLoc(CP), GA); 3095 } 3096 3097 SDValue CPIHi = 3098 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 3099 SDValue CPILo = 3100 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 3101 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 3102 } 3103 3104 // For 64-bit PowerPC, prefer the more compact relative encodings. 3105 // This trades 32 bits per jump table entry for one or two instructions 3106 // on the jump site. 3107 unsigned PPCTargetLowering::getJumpTableEncoding() const { 3108 if (isJumpTableRelative()) 3109 return MachineJumpTableInfo::EK_LabelDifference32; 3110 3111 return TargetLowering::getJumpTableEncoding(); 3112 } 3113 3114 bool PPCTargetLowering::isJumpTableRelative() const { 3115 if (UseAbsoluteJumpTables) 3116 return false; 3117 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3118 return true; 3119 return TargetLowering::isJumpTableRelative(); 3120 } 3121 3122 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3123 SelectionDAG &DAG) const { 3124 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3125 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3126 3127 switch (getTargetMachine().getCodeModel()) { 3128 case CodeModel::Small: 3129 case CodeModel::Medium: 3130 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3131 default: 3132 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3133 getPointerTy(DAG.getDataLayout())); 3134 } 3135 } 3136 3137 const MCExpr * 3138 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3139 unsigned JTI, 3140 MCContext &Ctx) const { 3141 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3142 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3143 3144 switch (getTargetMachine().getCodeModel()) { 3145 case CodeModel::Small: 3146 case CodeModel::Medium: 3147 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3148 default: 3149 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3150 } 3151 } 3152 3153 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3154 EVT PtrVT = Op.getValueType(); 3155 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3156 3157 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3158 if (Subtarget.isUsingPCRelativeCalls()) { 3159 SDLoc DL(JT); 3160 EVT Ty = getPointerTy(DAG.getDataLayout()); 3161 SDValue GA = 3162 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3163 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3164 return MatAddr; 3165 } 3166 3167 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3168 // The actual address of the GlobalValue is stored in the TOC. 3169 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3170 setUsesTOCBasePtr(DAG); 3171 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3172 return getTOCEntry(DAG, SDLoc(JT), GA); 3173 } 3174 3175 unsigned MOHiFlag, MOLoFlag; 3176 bool IsPIC = isPositionIndependent(); 3177 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3178 3179 if (IsPIC && Subtarget.isSVR4ABI()) { 3180 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3181 PPCII::MO_PIC_FLAG); 3182 return getTOCEntry(DAG, SDLoc(GA), GA); 3183 } 3184 3185 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3186 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3187 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3188 } 3189 3190 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3191 SelectionDAG &DAG) const { 3192 EVT PtrVT = Op.getValueType(); 3193 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3194 const BlockAddress *BA = BASDN->getBlockAddress(); 3195 3196 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3197 if (Subtarget.isUsingPCRelativeCalls()) { 3198 SDLoc DL(BASDN); 3199 EVT Ty = getPointerTy(DAG.getDataLayout()); 3200 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3201 PPCII::MO_PCREL_FLAG); 3202 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3203 return MatAddr; 3204 } 3205 3206 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3207 // The actual BlockAddress is stored in the TOC. 3208 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3209 setUsesTOCBasePtr(DAG); 3210 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3211 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3212 } 3213 3214 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3215 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3216 return getTOCEntry( 3217 DAG, SDLoc(BASDN), 3218 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3219 3220 unsigned MOHiFlag, MOLoFlag; 3221 bool IsPIC = isPositionIndependent(); 3222 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3223 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3224 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3225 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3226 } 3227 3228 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3229 SelectionDAG &DAG) const { 3230 if (Subtarget.isAIXABI()) 3231 return LowerGlobalTLSAddressAIX(Op, DAG); 3232 3233 return LowerGlobalTLSAddressLinux(Op, DAG); 3234 } 3235 3236 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3237 SelectionDAG &DAG) const { 3238 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3239 3240 if (DAG.getTarget().useEmulatedTLS()) 3241 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3242 3243 SDLoc dl(GA); 3244 const GlobalValue *GV = GA->getGlobal(); 3245 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3246 3247 // The general-dynamic model is the only access model supported for now, so 3248 // all the GlobalTLSAddress nodes are lowered with this model. 3249 // We need to generate two TOC entries, one for the variable offset, one for 3250 // the region handle. The global address for the TOC entry of the region 3251 // handle is created with the MO_TLSGDM_FLAG flag and the global address 3252 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG. 3253 SDValue VariableOffsetTGA = 3254 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3255 SDValue RegionHandleTGA = 3256 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG); 3257 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3258 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3259 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3260 RegionHandle); 3261 } 3262 3263 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3264 SelectionDAG &DAG) const { 3265 // FIXME: TLS addresses currently use medium model code sequences, 3266 // which is the most useful form. Eventually support for small and 3267 // large models could be added if users need it, at the cost of 3268 // additional complexity. 3269 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3270 if (DAG.getTarget().useEmulatedTLS()) 3271 return LowerToTLSEmulatedModel(GA, DAG); 3272 3273 SDLoc dl(GA); 3274 const GlobalValue *GV = GA->getGlobal(); 3275 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3276 bool is64bit = Subtarget.isPPC64(); 3277 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3278 PICLevel::Level picLevel = M->getPICLevel(); 3279 3280 const TargetMachine &TM = getTargetMachine(); 3281 TLSModel::Model Model = TM.getTLSModel(GV); 3282 3283 if (Model == TLSModel::LocalExec) { 3284 if (Subtarget.isUsingPCRelativeCalls()) { 3285 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3286 SDValue TGA = DAG.getTargetGlobalAddress( 3287 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3288 SDValue MatAddr = 3289 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3290 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3291 } 3292 3293 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3294 PPCII::MO_TPREL_HA); 3295 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3296 PPCII::MO_TPREL_LO); 3297 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3298 : DAG.getRegister(PPC::R2, MVT::i32); 3299 3300 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3301 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3302 } 3303 3304 if (Model == TLSModel::InitialExec) { 3305 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3306 SDValue TGA = DAG.getTargetGlobalAddress( 3307 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3308 SDValue TGATLS = DAG.getTargetGlobalAddress( 3309 GV, dl, PtrVT, 0, 3310 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3311 SDValue TPOffset; 3312 if (IsPCRel) { 3313 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3314 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3315 MachinePointerInfo()); 3316 } else { 3317 SDValue GOTPtr; 3318 if (is64bit) { 3319 setUsesTOCBasePtr(DAG); 3320 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3321 GOTPtr = 3322 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3323 } else { 3324 if (!TM.isPositionIndependent()) 3325 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3326 else if (picLevel == PICLevel::SmallPIC) 3327 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3328 else 3329 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3330 } 3331 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3332 } 3333 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3334 } 3335 3336 if (Model == TLSModel::GeneralDynamic) { 3337 if (Subtarget.isUsingPCRelativeCalls()) { 3338 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3339 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3340 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3341 } 3342 3343 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3344 SDValue GOTPtr; 3345 if (is64bit) { 3346 setUsesTOCBasePtr(DAG); 3347 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3348 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3349 GOTReg, TGA); 3350 } else { 3351 if (picLevel == PICLevel::SmallPIC) 3352 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3353 else 3354 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3355 } 3356 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3357 GOTPtr, TGA, TGA); 3358 } 3359 3360 if (Model == TLSModel::LocalDynamic) { 3361 if (Subtarget.isUsingPCRelativeCalls()) { 3362 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3363 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3364 SDValue MatPCRel = 3365 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3366 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3367 } 3368 3369 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3370 SDValue GOTPtr; 3371 if (is64bit) { 3372 setUsesTOCBasePtr(DAG); 3373 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3374 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3375 GOTReg, TGA); 3376 } else { 3377 if (picLevel == PICLevel::SmallPIC) 3378 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3379 else 3380 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3381 } 3382 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3383 PtrVT, GOTPtr, TGA, TGA); 3384 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3385 PtrVT, TLSAddr, TGA); 3386 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3387 } 3388 3389 llvm_unreachable("Unknown TLS model!"); 3390 } 3391 3392 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3393 SelectionDAG &DAG) const { 3394 EVT PtrVT = Op.getValueType(); 3395 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3396 SDLoc DL(GSDN); 3397 const GlobalValue *GV = GSDN->getGlobal(); 3398 3399 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3400 // The actual address of the GlobalValue is stored in the TOC. 3401 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3402 if (Subtarget.isUsingPCRelativeCalls()) { 3403 EVT Ty = getPointerTy(DAG.getDataLayout()); 3404 if (isAccessedAsGotIndirect(Op)) { 3405 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3406 PPCII::MO_PCREL_FLAG | 3407 PPCII::MO_GOT_FLAG); 3408 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3409 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3410 MachinePointerInfo()); 3411 return Load; 3412 } else { 3413 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3414 PPCII::MO_PCREL_FLAG); 3415 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3416 } 3417 } 3418 setUsesTOCBasePtr(DAG); 3419 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3420 return getTOCEntry(DAG, DL, GA); 3421 } 3422 3423 unsigned MOHiFlag, MOLoFlag; 3424 bool IsPIC = isPositionIndependent(); 3425 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3426 3427 if (IsPIC && Subtarget.isSVR4ABI()) { 3428 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3429 GSDN->getOffset(), 3430 PPCII::MO_PIC_FLAG); 3431 return getTOCEntry(DAG, DL, GA); 3432 } 3433 3434 SDValue GAHi = 3435 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3436 SDValue GALo = 3437 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3438 3439 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3440 } 3441 3442 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3443 bool IsStrict = Op->isStrictFPOpcode(); 3444 ISD::CondCode CC = 3445 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get(); 3446 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0); 3447 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1); 3448 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 3449 EVT LHSVT = LHS.getValueType(); 3450 SDLoc dl(Op); 3451 3452 // Soften the setcc with libcall if it is fp128. 3453 if (LHSVT == MVT::f128) { 3454 assert(!Subtarget.hasP9Vector() && 3455 "SETCC for f128 is already legal under Power9!"); 3456 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain, 3457 Op->getOpcode() == ISD::STRICT_FSETCCS); 3458 if (RHS.getNode()) 3459 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS, 3460 DAG.getCondCode(CC)); 3461 if (IsStrict) 3462 return DAG.getMergeValues({LHS, Chain}, dl); 3463 return LHS; 3464 } 3465 3466 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!"); 3467 3468 if (Op.getValueType() == MVT::v2i64) { 3469 // When the operands themselves are v2i64 values, we need to do something 3470 // special because VSX has no underlying comparison operations for these. 3471 if (LHS.getValueType() == MVT::v2i64) { 3472 // Equality can be handled by casting to the legal type for Altivec 3473 // comparisons, everything else needs to be expanded. 3474 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3475 return DAG.getNode( 3476 ISD::BITCAST, dl, MVT::v2i64, 3477 DAG.getSetCC(dl, MVT::v4i32, 3478 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS), 3479 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC)); 3480 } 3481 3482 return SDValue(); 3483 } 3484 3485 // We handle most of these in the usual way. 3486 return Op; 3487 } 3488 3489 // If we're comparing for equality to zero, expose the fact that this is 3490 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3491 // fold the new nodes. 3492 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3493 return V; 3494 3495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 3496 // Leave comparisons against 0 and -1 alone for now, since they're usually 3497 // optimized. FIXME: revisit this when we can custom lower all setcc 3498 // optimizations. 3499 if (C->isAllOnesValue() || C->isNullValue()) 3500 return SDValue(); 3501 } 3502 3503 // If we have an integer seteq/setne, turn it into a compare against zero 3504 // by xor'ing the rhs with the lhs, which is faster than setting a 3505 // condition register, reading it back out, and masking the correct bit. The 3506 // normal approach here uses sub to do this instead of xor. Using xor exposes 3507 // the result to other bit-twiddling opportunities. 3508 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3509 EVT VT = Op.getValueType(); 3510 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS); 3511 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3512 } 3513 return SDValue(); 3514 } 3515 3516 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3517 SDNode *Node = Op.getNode(); 3518 EVT VT = Node->getValueType(0); 3519 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3520 SDValue InChain = Node->getOperand(0); 3521 SDValue VAListPtr = Node->getOperand(1); 3522 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3523 SDLoc dl(Node); 3524 3525 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3526 3527 // gpr_index 3528 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3529 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3530 InChain = GprIndex.getValue(1); 3531 3532 if (VT == MVT::i64) { 3533 // Check if GprIndex is even 3534 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3535 DAG.getConstant(1, dl, MVT::i32)); 3536 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3537 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3538 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3539 DAG.getConstant(1, dl, MVT::i32)); 3540 // Align GprIndex to be even if it isn't 3541 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3542 GprIndex); 3543 } 3544 3545 // fpr index is 1 byte after gpr 3546 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3547 DAG.getConstant(1, dl, MVT::i32)); 3548 3549 // fpr 3550 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3551 FprPtr, MachinePointerInfo(SV), MVT::i8); 3552 InChain = FprIndex.getValue(1); 3553 3554 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3555 DAG.getConstant(8, dl, MVT::i32)); 3556 3557 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3558 DAG.getConstant(4, dl, MVT::i32)); 3559 3560 // areas 3561 SDValue OverflowArea = 3562 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3563 InChain = OverflowArea.getValue(1); 3564 3565 SDValue RegSaveArea = 3566 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3567 InChain = RegSaveArea.getValue(1); 3568 3569 // select overflow_area if index > 8 3570 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3571 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3572 3573 // adjustment constant gpr_index * 4/8 3574 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3575 VT.isInteger() ? GprIndex : FprIndex, 3576 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3577 MVT::i32)); 3578 3579 // OurReg = RegSaveArea + RegConstant 3580 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3581 RegConstant); 3582 3583 // Floating types are 32 bytes into RegSaveArea 3584 if (VT.isFloatingPoint()) 3585 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3586 DAG.getConstant(32, dl, MVT::i32)); 3587 3588 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3589 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3590 VT.isInteger() ? GprIndex : FprIndex, 3591 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3592 MVT::i32)); 3593 3594 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3595 VT.isInteger() ? VAListPtr : FprPtr, 3596 MachinePointerInfo(SV), MVT::i8); 3597 3598 // determine if we should load from reg_save_area or overflow_area 3599 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3600 3601 // increase overflow_area by 4/8 if gpr/fpr > 8 3602 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3603 DAG.getConstant(VT.isInteger() ? 4 : 8, 3604 dl, MVT::i32)); 3605 3606 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3607 OverflowAreaPlusN); 3608 3609 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3610 MachinePointerInfo(), MVT::i32); 3611 3612 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3613 } 3614 3615 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3616 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3617 3618 // We have to copy the entire va_list struct: 3619 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3620 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3621 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3622 false, true, false, MachinePointerInfo(), 3623 MachinePointerInfo()); 3624 } 3625 3626 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3627 SelectionDAG &DAG) const { 3628 if (Subtarget.isAIXABI()) 3629 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3630 3631 return Op.getOperand(0); 3632 } 3633 3634 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const { 3635 MachineFunction &MF = DAG.getMachineFunction(); 3636 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>(); 3637 3638 assert((Op.getOpcode() == ISD::INLINEASM || 3639 Op.getOpcode() == ISD::INLINEASM_BR) && 3640 "Expecting Inline ASM node."); 3641 3642 // If an LR store is already known to be required then there is not point in 3643 // checking this ASM as well. 3644 if (MFI.isLRStoreRequired()) 3645 return Op; 3646 3647 // Inline ASM nodes have an optional last operand that is an incoming Flag of 3648 // type MVT::Glue. We want to ignore this last operand if that is the case. 3649 unsigned NumOps = Op.getNumOperands(); 3650 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue) 3651 --NumOps; 3652 3653 // Check all operands that may contain the LR. 3654 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 3655 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue(); 3656 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 3657 ++i; // Skip the ID value. 3658 3659 switch (InlineAsm::getKind(Flags)) { 3660 default: 3661 llvm_unreachable("Bad flags!"); 3662 case InlineAsm::Kind_RegUse: 3663 case InlineAsm::Kind_Imm: 3664 case InlineAsm::Kind_Mem: 3665 i += NumVals; 3666 break; 3667 case InlineAsm::Kind_Clobber: 3668 case InlineAsm::Kind_RegDef: 3669 case InlineAsm::Kind_RegDefEarlyClobber: { 3670 for (; NumVals; --NumVals, ++i) { 3671 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg(); 3672 if (Reg != PPC::LR && Reg != PPC::LR8) 3673 continue; 3674 MFI.setLRStoreRequired(); 3675 return Op; 3676 } 3677 break; 3678 } 3679 } 3680 } 3681 3682 return Op; 3683 } 3684 3685 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3686 SelectionDAG &DAG) const { 3687 if (Subtarget.isAIXABI()) 3688 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3689 3690 SDValue Chain = Op.getOperand(0); 3691 SDValue Trmp = Op.getOperand(1); // trampoline 3692 SDValue FPtr = Op.getOperand(2); // nested function 3693 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3694 SDLoc dl(Op); 3695 3696 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3697 bool isPPC64 = (PtrVT == MVT::i64); 3698 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3699 3700 TargetLowering::ArgListTy Args; 3701 TargetLowering::ArgListEntry Entry; 3702 3703 Entry.Ty = IntPtrTy; 3704 Entry.Node = Trmp; Args.push_back(Entry); 3705 3706 // TrampSize == (isPPC64 ? 48 : 40); 3707 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3708 isPPC64 ? MVT::i64 : MVT::i32); 3709 Args.push_back(Entry); 3710 3711 Entry.Node = FPtr; Args.push_back(Entry); 3712 Entry.Node = Nest; Args.push_back(Entry); 3713 3714 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3715 TargetLowering::CallLoweringInfo CLI(DAG); 3716 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3717 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3718 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3719 3720 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3721 return CallResult.second; 3722 } 3723 3724 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3725 MachineFunction &MF = DAG.getMachineFunction(); 3726 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3727 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3728 3729 SDLoc dl(Op); 3730 3731 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3732 // vastart just stores the address of the VarArgsFrameIndex slot into the 3733 // memory location argument. 3734 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3735 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3736 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3737 MachinePointerInfo(SV)); 3738 } 3739 3740 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3741 // We suppose the given va_list is already allocated. 3742 // 3743 // typedef struct { 3744 // char gpr; /* index into the array of 8 GPRs 3745 // * stored in the register save area 3746 // * gpr=0 corresponds to r3, 3747 // * gpr=1 to r4, etc. 3748 // */ 3749 // char fpr; /* index into the array of 8 FPRs 3750 // * stored in the register save area 3751 // * fpr=0 corresponds to f1, 3752 // * fpr=1 to f2, etc. 3753 // */ 3754 // char *overflow_arg_area; 3755 // /* location on stack that holds 3756 // * the next overflow argument 3757 // */ 3758 // char *reg_save_area; 3759 // /* where r3:r10 and f1:f8 (if saved) 3760 // * are stored 3761 // */ 3762 // } va_list[1]; 3763 3764 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3765 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3766 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3767 PtrVT); 3768 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3769 PtrVT); 3770 3771 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3772 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3773 3774 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3775 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3776 3777 uint64_t FPROffset = 1; 3778 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3779 3780 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3781 3782 // Store first byte : number of int regs 3783 SDValue firstStore = 3784 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3785 MachinePointerInfo(SV), MVT::i8); 3786 uint64_t nextOffset = FPROffset; 3787 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3788 ConstFPROffset); 3789 3790 // Store second byte : number of float regs 3791 SDValue secondStore = 3792 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3793 MachinePointerInfo(SV, nextOffset), MVT::i8); 3794 nextOffset += StackOffset; 3795 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3796 3797 // Store second word : arguments given on stack 3798 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3799 MachinePointerInfo(SV, nextOffset)); 3800 nextOffset += FrameOffset; 3801 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3802 3803 // Store third word : arguments given in registers 3804 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3805 MachinePointerInfo(SV, nextOffset)); 3806 } 3807 3808 /// FPR - The set of FP registers that should be allocated for arguments 3809 /// on Darwin and AIX. 3810 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3811 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3812 PPC::F11, PPC::F12, PPC::F13}; 3813 3814 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3815 /// the stack. 3816 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3817 unsigned PtrByteSize) { 3818 unsigned ArgSize = ArgVT.getStoreSize(); 3819 if (Flags.isByVal()) 3820 ArgSize = Flags.getByValSize(); 3821 3822 // Round up to multiples of the pointer size, except for array members, 3823 // which are always packed. 3824 if (!Flags.isInConsecutiveRegs()) 3825 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3826 3827 return ArgSize; 3828 } 3829 3830 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3831 /// on the stack. 3832 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3833 ISD::ArgFlagsTy Flags, 3834 unsigned PtrByteSize) { 3835 Align Alignment(PtrByteSize); 3836 3837 // Altivec parameters are padded to a 16 byte boundary. 3838 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3839 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3840 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3841 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3842 Alignment = Align(16); 3843 3844 // ByVal parameters are aligned as requested. 3845 if (Flags.isByVal()) { 3846 auto BVAlign = Flags.getNonZeroByValAlign(); 3847 if (BVAlign > PtrByteSize) { 3848 if (BVAlign.value() % PtrByteSize != 0) 3849 llvm_unreachable( 3850 "ByVal alignment is not a multiple of the pointer size"); 3851 3852 Alignment = BVAlign; 3853 } 3854 } 3855 3856 // Array members are always packed to their original alignment. 3857 if (Flags.isInConsecutiveRegs()) { 3858 // If the array member was split into multiple registers, the first 3859 // needs to be aligned to the size of the full type. (Except for 3860 // ppcf128, which is only aligned as its f64 components.) 3861 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3862 Alignment = Align(OrigVT.getStoreSize()); 3863 else 3864 Alignment = Align(ArgVT.getStoreSize()); 3865 } 3866 3867 return Alignment; 3868 } 3869 3870 /// CalculateStackSlotUsed - Return whether this argument will use its 3871 /// stack slot (instead of being passed in registers). ArgOffset, 3872 /// AvailableFPRs, and AvailableVRs must hold the current argument 3873 /// position, and will be updated to account for this argument. 3874 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3875 unsigned PtrByteSize, unsigned LinkageSize, 3876 unsigned ParamAreaSize, unsigned &ArgOffset, 3877 unsigned &AvailableFPRs, 3878 unsigned &AvailableVRs) { 3879 bool UseMemory = false; 3880 3881 // Respect alignment of argument on the stack. 3882 Align Alignment = 3883 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3884 ArgOffset = alignTo(ArgOffset, Alignment); 3885 // If there's no space left in the argument save area, we must 3886 // use memory (this check also catches zero-sized arguments). 3887 if (ArgOffset >= LinkageSize + ParamAreaSize) 3888 UseMemory = true; 3889 3890 // Allocate argument on the stack. 3891 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3892 if (Flags.isInConsecutiveRegsLast()) 3893 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3894 // If we overran the argument save area, we must use memory 3895 // (this check catches arguments passed partially in memory) 3896 if (ArgOffset > LinkageSize + ParamAreaSize) 3897 UseMemory = true; 3898 3899 // However, if the argument is actually passed in an FPR or a VR, 3900 // we don't use memory after all. 3901 if (!Flags.isByVal()) { 3902 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3903 if (AvailableFPRs > 0) { 3904 --AvailableFPRs; 3905 return false; 3906 } 3907 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3908 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3909 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3910 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3911 if (AvailableVRs > 0) { 3912 --AvailableVRs; 3913 return false; 3914 } 3915 } 3916 3917 return UseMemory; 3918 } 3919 3920 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3921 /// ensure minimum alignment required for target. 3922 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3923 unsigned NumBytes) { 3924 return alignTo(NumBytes, Lowering->getStackAlign()); 3925 } 3926 3927 SDValue PPCTargetLowering::LowerFormalArguments( 3928 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3929 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3930 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3931 if (Subtarget.isAIXABI()) 3932 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3933 InVals); 3934 if (Subtarget.is64BitELFABI()) 3935 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3936 InVals); 3937 assert(Subtarget.is32BitELFABI()); 3938 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3939 InVals); 3940 } 3941 3942 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3943 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3944 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3945 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3946 3947 // 32-bit SVR4 ABI Stack Frame Layout: 3948 // +-----------------------------------+ 3949 // +--> | Back chain | 3950 // | +-----------------------------------+ 3951 // | | Floating-point register save area | 3952 // | +-----------------------------------+ 3953 // | | General register save area | 3954 // | +-----------------------------------+ 3955 // | | CR save word | 3956 // | +-----------------------------------+ 3957 // | | VRSAVE save word | 3958 // | +-----------------------------------+ 3959 // | | Alignment padding | 3960 // | +-----------------------------------+ 3961 // | | Vector register save area | 3962 // | +-----------------------------------+ 3963 // | | Local variable space | 3964 // | +-----------------------------------+ 3965 // | | Parameter list area | 3966 // | +-----------------------------------+ 3967 // | | LR save word | 3968 // | +-----------------------------------+ 3969 // SP--> +--- | Back chain | 3970 // +-----------------------------------+ 3971 // 3972 // Specifications: 3973 // System V Application Binary Interface PowerPC Processor Supplement 3974 // AltiVec Technology Programming Interface Manual 3975 3976 MachineFunction &MF = DAG.getMachineFunction(); 3977 MachineFrameInfo &MFI = MF.getFrameInfo(); 3978 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3979 3980 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3981 // Potential tail calls could cause overwriting of argument stack slots. 3982 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3983 (CallConv == CallingConv::Fast)); 3984 const Align PtrAlign(4); 3985 3986 // Assign locations to all of the incoming arguments. 3987 SmallVector<CCValAssign, 16> ArgLocs; 3988 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3989 *DAG.getContext()); 3990 3991 // Reserve space for the linkage area on the stack. 3992 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3993 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3994 if (useSoftFloat()) 3995 CCInfo.PreAnalyzeFormalArguments(Ins); 3996 3997 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3998 CCInfo.clearWasPPCF128(); 3999 4000 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4001 CCValAssign &VA = ArgLocs[i]; 4002 4003 // Arguments stored in registers. 4004 if (VA.isRegLoc()) { 4005 const TargetRegisterClass *RC; 4006 EVT ValVT = VA.getValVT(); 4007 4008 switch (ValVT.getSimpleVT().SimpleTy) { 4009 default: 4010 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 4011 case MVT::i1: 4012 case MVT::i32: 4013 RC = &PPC::GPRCRegClass; 4014 break; 4015 case MVT::f32: 4016 if (Subtarget.hasP8Vector()) 4017 RC = &PPC::VSSRCRegClass; 4018 else if (Subtarget.hasSPE()) 4019 RC = &PPC::GPRCRegClass; 4020 else 4021 RC = &PPC::F4RCRegClass; 4022 break; 4023 case MVT::f64: 4024 if (Subtarget.hasVSX()) 4025 RC = &PPC::VSFRCRegClass; 4026 else if (Subtarget.hasSPE()) 4027 // SPE passes doubles in GPR pairs. 4028 RC = &PPC::GPRCRegClass; 4029 else 4030 RC = &PPC::F8RCRegClass; 4031 break; 4032 case MVT::v16i8: 4033 case MVT::v8i16: 4034 case MVT::v4i32: 4035 RC = &PPC::VRRCRegClass; 4036 break; 4037 case MVT::v4f32: 4038 RC = &PPC::VRRCRegClass; 4039 break; 4040 case MVT::v2f64: 4041 case MVT::v2i64: 4042 RC = &PPC::VRRCRegClass; 4043 break; 4044 } 4045 4046 SDValue ArgValue; 4047 // Transform the arguments stored in physical registers into 4048 // virtual ones. 4049 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 4050 assert(i + 1 < e && "No second half of double precision argument"); 4051 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 4052 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 4053 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 4054 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 4055 if (!Subtarget.isLittleEndian()) 4056 std::swap (ArgValueLo, ArgValueHi); 4057 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 4058 ArgValueHi); 4059 } else { 4060 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4061 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 4062 ValVT == MVT::i1 ? MVT::i32 : ValVT); 4063 if (ValVT == MVT::i1) 4064 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 4065 } 4066 4067 InVals.push_back(ArgValue); 4068 } else { 4069 // Argument stored in memory. 4070 assert(VA.isMemLoc()); 4071 4072 // Get the extended size of the argument type in stack 4073 unsigned ArgSize = VA.getLocVT().getStoreSize(); 4074 // Get the actual size of the argument type 4075 unsigned ObjSize = VA.getValVT().getStoreSize(); 4076 unsigned ArgOffset = VA.getLocMemOffset(); 4077 // Stack objects in PPC32 are right justified. 4078 ArgOffset += ArgSize - ObjSize; 4079 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 4080 4081 // Create load nodes to retrieve arguments from the stack. 4082 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4083 InVals.push_back( 4084 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 4085 } 4086 } 4087 4088 // Assign locations to all of the incoming aggregate by value arguments. 4089 // Aggregates passed by value are stored in the local variable space of the 4090 // caller's stack frame, right above the parameter list area. 4091 SmallVector<CCValAssign, 16> ByValArgLocs; 4092 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4093 ByValArgLocs, *DAG.getContext()); 4094 4095 // Reserve stack space for the allocations in CCInfo. 4096 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 4097 4098 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 4099 4100 // Area that is at least reserved in the caller of this function. 4101 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 4102 MinReservedArea = std::max(MinReservedArea, LinkageSize); 4103 4104 // Set the size that is at least reserved in caller of this function. Tail 4105 // call optimized function's reserved stack space needs to be aligned so that 4106 // taking the difference between two stack areas will result in an aligned 4107 // stack. 4108 MinReservedArea = 4109 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4110 FuncInfo->setMinReservedArea(MinReservedArea); 4111 4112 SmallVector<SDValue, 8> MemOps; 4113 4114 // If the function takes variable number of arguments, make a frame index for 4115 // the start of the first vararg value... for expansion of llvm.va_start. 4116 if (isVarArg) { 4117 static const MCPhysReg GPArgRegs[] = { 4118 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4119 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4120 }; 4121 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 4122 4123 static const MCPhysReg FPArgRegs[] = { 4124 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 4125 PPC::F8 4126 }; 4127 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 4128 4129 if (useSoftFloat() || hasSPE()) 4130 NumFPArgRegs = 0; 4131 4132 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 4133 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 4134 4135 // Make room for NumGPArgRegs and NumFPArgRegs. 4136 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 4137 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 4138 4139 FuncInfo->setVarArgsStackOffset( 4140 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4141 CCInfo.getNextStackOffset(), true)); 4142 4143 FuncInfo->setVarArgsFrameIndex( 4144 MFI.CreateStackObject(Depth, Align(8), false)); 4145 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4146 4147 // The fixed integer arguments of a variadic function are stored to the 4148 // VarArgsFrameIndex on the stack so that they may be loaded by 4149 // dereferencing the result of va_next. 4150 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 4151 // Get an existing live-in vreg, or add a new one. 4152 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 4153 if (!VReg) 4154 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 4155 4156 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4157 SDValue Store = 4158 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4159 MemOps.push_back(Store); 4160 // Increment the address by four for the next argument to store 4161 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4162 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4163 } 4164 4165 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 4166 // is set. 4167 // The double arguments are stored to the VarArgsFrameIndex 4168 // on the stack. 4169 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 4170 // Get an existing live-in vreg, or add a new one. 4171 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 4172 if (!VReg) 4173 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 4174 4175 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 4176 SDValue Store = 4177 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4178 MemOps.push_back(Store); 4179 // Increment the address by eight for the next argument to store 4180 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4181 PtrVT); 4182 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4183 } 4184 } 4185 4186 if (!MemOps.empty()) 4187 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4188 4189 return Chain; 4190 } 4191 4192 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4193 // value to MVT::i64 and then truncate to the correct register size. 4194 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4195 EVT ObjectVT, SelectionDAG &DAG, 4196 SDValue ArgVal, 4197 const SDLoc &dl) const { 4198 if (Flags.isSExt()) 4199 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4200 DAG.getValueType(ObjectVT)); 4201 else if (Flags.isZExt()) 4202 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4203 DAG.getValueType(ObjectVT)); 4204 4205 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4206 } 4207 4208 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4209 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4210 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4211 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4212 // TODO: add description of PPC stack frame format, or at least some docs. 4213 // 4214 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4215 bool isLittleEndian = Subtarget.isLittleEndian(); 4216 MachineFunction &MF = DAG.getMachineFunction(); 4217 MachineFrameInfo &MFI = MF.getFrameInfo(); 4218 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4219 4220 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4221 "fastcc not supported on varargs functions"); 4222 4223 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4224 // Potential tail calls could cause overwriting of argument stack slots. 4225 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4226 (CallConv == CallingConv::Fast)); 4227 unsigned PtrByteSize = 8; 4228 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4229 4230 static const MCPhysReg GPR[] = { 4231 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4232 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4233 }; 4234 static const MCPhysReg VR[] = { 4235 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4236 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4237 }; 4238 4239 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4240 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4241 const unsigned Num_VR_Regs = array_lengthof(VR); 4242 4243 // Do a first pass over the arguments to determine whether the ABI 4244 // guarantees that our caller has allocated the parameter save area 4245 // on its stack frame. In the ELFv1 ABI, this is always the case; 4246 // in the ELFv2 ABI, it is true if this is a vararg function or if 4247 // any parameter is located in a stack slot. 4248 4249 bool HasParameterArea = !isELFv2ABI || isVarArg; 4250 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4251 unsigned NumBytes = LinkageSize; 4252 unsigned AvailableFPRs = Num_FPR_Regs; 4253 unsigned AvailableVRs = Num_VR_Regs; 4254 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4255 if (Ins[i].Flags.isNest()) 4256 continue; 4257 4258 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4259 PtrByteSize, LinkageSize, ParamAreaSize, 4260 NumBytes, AvailableFPRs, AvailableVRs)) 4261 HasParameterArea = true; 4262 } 4263 4264 // Add DAG nodes to load the arguments or copy them out of registers. On 4265 // entry to a function on PPC, the arguments start after the linkage area, 4266 // although the first ones are often in registers. 4267 4268 unsigned ArgOffset = LinkageSize; 4269 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4270 SmallVector<SDValue, 8> MemOps; 4271 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4272 unsigned CurArgIdx = 0; 4273 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4274 SDValue ArgVal; 4275 bool needsLoad = false; 4276 EVT ObjectVT = Ins[ArgNo].VT; 4277 EVT OrigVT = Ins[ArgNo].ArgVT; 4278 unsigned ObjSize = ObjectVT.getStoreSize(); 4279 unsigned ArgSize = ObjSize; 4280 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4281 if (Ins[ArgNo].isOrigArg()) { 4282 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4283 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4284 } 4285 // We re-align the argument offset for each argument, except when using the 4286 // fast calling convention, when we need to make sure we do that only when 4287 // we'll actually use a stack slot. 4288 unsigned CurArgOffset; 4289 Align Alignment; 4290 auto ComputeArgOffset = [&]() { 4291 /* Respect alignment of argument on the stack. */ 4292 Alignment = 4293 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4294 ArgOffset = alignTo(ArgOffset, Alignment); 4295 CurArgOffset = ArgOffset; 4296 }; 4297 4298 if (CallConv != CallingConv::Fast) { 4299 ComputeArgOffset(); 4300 4301 /* Compute GPR index associated with argument offset. */ 4302 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4303 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4304 } 4305 4306 // FIXME the codegen can be much improved in some cases. 4307 // We do not have to keep everything in memory. 4308 if (Flags.isByVal()) { 4309 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4310 4311 if (CallConv == CallingConv::Fast) 4312 ComputeArgOffset(); 4313 4314 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4315 ObjSize = Flags.getByValSize(); 4316 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4317 // Empty aggregate parameters do not take up registers. Examples: 4318 // struct { } a; 4319 // union { } b; 4320 // int c[0]; 4321 // etc. However, we have to provide a place-holder in InVals, so 4322 // pretend we have an 8-byte item at the current address for that 4323 // purpose. 4324 if (!ObjSize) { 4325 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4326 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4327 InVals.push_back(FIN); 4328 continue; 4329 } 4330 4331 // Create a stack object covering all stack doublewords occupied 4332 // by the argument. If the argument is (fully or partially) on 4333 // the stack, or if the argument is fully in registers but the 4334 // caller has allocated the parameter save anyway, we can refer 4335 // directly to the caller's stack frame. Otherwise, create a 4336 // local copy in our own frame. 4337 int FI; 4338 if (HasParameterArea || 4339 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4340 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4341 else 4342 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4343 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4344 4345 // Handle aggregates smaller than 8 bytes. 4346 if (ObjSize < PtrByteSize) { 4347 // The value of the object is its address, which differs from the 4348 // address of the enclosing doubleword on big-endian systems. 4349 SDValue Arg = FIN; 4350 if (!isLittleEndian) { 4351 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4352 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4353 } 4354 InVals.push_back(Arg); 4355 4356 if (GPR_idx != Num_GPR_Regs) { 4357 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4358 FuncInfo->addLiveInAttr(VReg, Flags); 4359 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4360 SDValue Store; 4361 4362 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4363 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4364 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4365 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4366 MachinePointerInfo(&*FuncArg), ObjType); 4367 } else { 4368 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4369 // store the whole register as-is to the parameter save area 4370 // slot. 4371 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4372 MachinePointerInfo(&*FuncArg)); 4373 } 4374 4375 MemOps.push_back(Store); 4376 } 4377 // Whether we copied from a register or not, advance the offset 4378 // into the parameter save area by a full doubleword. 4379 ArgOffset += PtrByteSize; 4380 continue; 4381 } 4382 4383 // The value of the object is its address, which is the address of 4384 // its first stack doubleword. 4385 InVals.push_back(FIN); 4386 4387 // Store whatever pieces of the object are in registers to memory. 4388 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4389 if (GPR_idx == Num_GPR_Regs) 4390 break; 4391 4392 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4393 FuncInfo->addLiveInAttr(VReg, Flags); 4394 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4395 SDValue Addr = FIN; 4396 if (j) { 4397 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4398 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4399 } 4400 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4401 MachinePointerInfo(&*FuncArg, j)); 4402 MemOps.push_back(Store); 4403 ++GPR_idx; 4404 } 4405 ArgOffset += ArgSize; 4406 continue; 4407 } 4408 4409 switch (ObjectVT.getSimpleVT().SimpleTy) { 4410 default: llvm_unreachable("Unhandled argument type!"); 4411 case MVT::i1: 4412 case MVT::i32: 4413 case MVT::i64: 4414 if (Flags.isNest()) { 4415 // The 'nest' parameter, if any, is passed in R11. 4416 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4417 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4418 4419 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4420 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4421 4422 break; 4423 } 4424 4425 // These can be scalar arguments or elements of an integer array type 4426 // passed directly. Clang may use those instead of "byval" aggregate 4427 // types to avoid forcing arguments to memory unnecessarily. 4428 if (GPR_idx != Num_GPR_Regs) { 4429 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4430 FuncInfo->addLiveInAttr(VReg, Flags); 4431 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4432 4433 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4434 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4435 // value to MVT::i64 and then truncate to the correct register size. 4436 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4437 } else { 4438 if (CallConv == CallingConv::Fast) 4439 ComputeArgOffset(); 4440 4441 needsLoad = true; 4442 ArgSize = PtrByteSize; 4443 } 4444 if (CallConv != CallingConv::Fast || needsLoad) 4445 ArgOffset += 8; 4446 break; 4447 4448 case MVT::f32: 4449 case MVT::f64: 4450 // These can be scalar arguments or elements of a float array type 4451 // passed directly. The latter are used to implement ELFv2 homogenous 4452 // float aggregates. 4453 if (FPR_idx != Num_FPR_Regs) { 4454 unsigned VReg; 4455 4456 if (ObjectVT == MVT::f32) 4457 VReg = MF.addLiveIn(FPR[FPR_idx], 4458 Subtarget.hasP8Vector() 4459 ? &PPC::VSSRCRegClass 4460 : &PPC::F4RCRegClass); 4461 else 4462 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4463 ? &PPC::VSFRCRegClass 4464 : &PPC::F8RCRegClass); 4465 4466 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4467 ++FPR_idx; 4468 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4469 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4470 // once we support fp <-> gpr moves. 4471 4472 // This can only ever happen in the presence of f32 array types, 4473 // since otherwise we never run out of FPRs before running out 4474 // of GPRs. 4475 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4476 FuncInfo->addLiveInAttr(VReg, Flags); 4477 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4478 4479 if (ObjectVT == MVT::f32) { 4480 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4481 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4482 DAG.getConstant(32, dl, MVT::i32)); 4483 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4484 } 4485 4486 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4487 } else { 4488 if (CallConv == CallingConv::Fast) 4489 ComputeArgOffset(); 4490 4491 needsLoad = true; 4492 } 4493 4494 // When passing an array of floats, the array occupies consecutive 4495 // space in the argument area; only round up to the next doubleword 4496 // at the end of the array. Otherwise, each float takes 8 bytes. 4497 if (CallConv != CallingConv::Fast || needsLoad) { 4498 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4499 ArgOffset += ArgSize; 4500 if (Flags.isInConsecutiveRegsLast()) 4501 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4502 } 4503 break; 4504 case MVT::v4f32: 4505 case MVT::v4i32: 4506 case MVT::v8i16: 4507 case MVT::v16i8: 4508 case MVT::v2f64: 4509 case MVT::v2i64: 4510 case MVT::v1i128: 4511 case MVT::f128: 4512 // These can be scalar arguments or elements of a vector array type 4513 // passed directly. The latter are used to implement ELFv2 homogenous 4514 // vector aggregates. 4515 if (VR_idx != Num_VR_Regs) { 4516 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4517 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4518 ++VR_idx; 4519 } else { 4520 if (CallConv == CallingConv::Fast) 4521 ComputeArgOffset(); 4522 needsLoad = true; 4523 } 4524 if (CallConv != CallingConv::Fast || needsLoad) 4525 ArgOffset += 16; 4526 break; 4527 } 4528 4529 // We need to load the argument to a virtual register if we determined 4530 // above that we ran out of physical registers of the appropriate type. 4531 if (needsLoad) { 4532 if (ObjSize < ArgSize && !isLittleEndian) 4533 CurArgOffset += ArgSize - ObjSize; 4534 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4535 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4536 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4537 } 4538 4539 InVals.push_back(ArgVal); 4540 } 4541 4542 // Area that is at least reserved in the caller of this function. 4543 unsigned MinReservedArea; 4544 if (HasParameterArea) 4545 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4546 else 4547 MinReservedArea = LinkageSize; 4548 4549 // Set the size that is at least reserved in caller of this function. Tail 4550 // call optimized functions' reserved stack space needs to be aligned so that 4551 // taking the difference between two stack areas will result in an aligned 4552 // stack. 4553 MinReservedArea = 4554 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4555 FuncInfo->setMinReservedArea(MinReservedArea); 4556 4557 // If the function takes variable number of arguments, make a frame index for 4558 // the start of the first vararg value... for expansion of llvm.va_start. 4559 // On ELFv2ABI spec, it writes: 4560 // C programs that are intended to be *portable* across different compilers 4561 // and architectures must use the header file <stdarg.h> to deal with variable 4562 // argument lists. 4563 if (isVarArg && MFI.hasVAStart()) { 4564 int Depth = ArgOffset; 4565 4566 FuncInfo->setVarArgsFrameIndex( 4567 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4568 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4569 4570 // If this function is vararg, store any remaining integer argument regs 4571 // to their spots on the stack so that they may be loaded by dereferencing 4572 // the result of va_next. 4573 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4574 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4575 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4576 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4577 SDValue Store = 4578 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4579 MemOps.push_back(Store); 4580 // Increment the address by four for the next argument to store 4581 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4582 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4583 } 4584 } 4585 4586 if (!MemOps.empty()) 4587 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4588 4589 return Chain; 4590 } 4591 4592 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4593 /// adjusted to accommodate the arguments for the tailcall. 4594 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4595 unsigned ParamSize) { 4596 4597 if (!isTailCall) return 0; 4598 4599 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4600 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4601 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4602 // Remember only if the new adjustment is bigger. 4603 if (SPDiff < FI->getTailCallSPDelta()) 4604 FI->setTailCallSPDelta(SPDiff); 4605 4606 return SPDiff; 4607 } 4608 4609 static bool isFunctionGlobalAddress(SDValue Callee); 4610 4611 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4612 const TargetMachine &TM) { 4613 // It does not make sense to call callsShareTOCBase() with a caller that 4614 // is PC Relative since PC Relative callers do not have a TOC. 4615 #ifndef NDEBUG 4616 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4617 assert(!STICaller->isUsingPCRelativeCalls() && 4618 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4619 #endif 4620 4621 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4622 // don't have enough information to determine if the caller and callee share 4623 // the same TOC base, so we have to pessimistically assume they don't for 4624 // correctness. 4625 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4626 if (!G) 4627 return false; 4628 4629 const GlobalValue *GV = G->getGlobal(); 4630 4631 // If the callee is preemptable, then the static linker will use a plt-stub 4632 // which saves the toc to the stack, and needs a nop after the call 4633 // instruction to convert to a toc-restore. 4634 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4635 return false; 4636 4637 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4638 // We may need a TOC restore in the situation where the caller requires a 4639 // valid TOC but the callee is PC Relative and does not. 4640 const Function *F = dyn_cast<Function>(GV); 4641 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4642 4643 // If we have an Alias we can try to get the function from there. 4644 if (Alias) { 4645 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4646 F = dyn_cast<Function>(GlobalObj); 4647 } 4648 4649 // If we still have no valid function pointer we do not have enough 4650 // information to determine if the callee uses PC Relative calls so we must 4651 // assume that it does. 4652 if (!F) 4653 return false; 4654 4655 // If the callee uses PC Relative we cannot guarantee that the callee won't 4656 // clobber the TOC of the caller and so we must assume that the two 4657 // functions do not share a TOC base. 4658 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4659 if (STICallee->isUsingPCRelativeCalls()) 4660 return false; 4661 4662 // If the GV is not a strong definition then we need to assume it can be 4663 // replaced by another function at link time. The function that replaces 4664 // it may not share the same TOC as the caller since the callee may be 4665 // replaced by a PC Relative version of the same function. 4666 if (!GV->isStrongDefinitionForLinker()) 4667 return false; 4668 4669 // The medium and large code models are expected to provide a sufficiently 4670 // large TOC to provide all data addressing needs of a module with a 4671 // single TOC. 4672 if (CodeModel::Medium == TM.getCodeModel() || 4673 CodeModel::Large == TM.getCodeModel()) 4674 return true; 4675 4676 // Any explicitly-specified sections and section prefixes must also match. 4677 // Also, if we're using -ffunction-sections, then each function is always in 4678 // a different section (the same is true for COMDAT functions). 4679 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4680 GV->getSection() != Caller->getSection()) 4681 return false; 4682 if (const auto *F = dyn_cast<Function>(GV)) { 4683 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4684 return false; 4685 } 4686 4687 return true; 4688 } 4689 4690 static bool 4691 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4692 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4693 assert(Subtarget.is64BitELFABI()); 4694 4695 const unsigned PtrByteSize = 8; 4696 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4697 4698 static const MCPhysReg GPR[] = { 4699 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4700 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4701 }; 4702 static const MCPhysReg VR[] = { 4703 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4704 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4705 }; 4706 4707 const unsigned NumGPRs = array_lengthof(GPR); 4708 const unsigned NumFPRs = 13; 4709 const unsigned NumVRs = array_lengthof(VR); 4710 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4711 4712 unsigned NumBytes = LinkageSize; 4713 unsigned AvailableFPRs = NumFPRs; 4714 unsigned AvailableVRs = NumVRs; 4715 4716 for (const ISD::OutputArg& Param : Outs) { 4717 if (Param.Flags.isNest()) continue; 4718 4719 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4720 LinkageSize, ParamAreaSize, NumBytes, 4721 AvailableFPRs, AvailableVRs)) 4722 return true; 4723 } 4724 return false; 4725 } 4726 4727 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4728 if (CB.arg_size() != CallerFn->arg_size()) 4729 return false; 4730 4731 auto CalleeArgIter = CB.arg_begin(); 4732 auto CalleeArgEnd = CB.arg_end(); 4733 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4734 4735 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4736 const Value* CalleeArg = *CalleeArgIter; 4737 const Value* CallerArg = &(*CallerArgIter); 4738 if (CalleeArg == CallerArg) 4739 continue; 4740 4741 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4742 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4743 // } 4744 // 1st argument of callee is undef and has the same type as caller. 4745 if (CalleeArg->getType() == CallerArg->getType() && 4746 isa<UndefValue>(CalleeArg)) 4747 continue; 4748 4749 return false; 4750 } 4751 4752 return true; 4753 } 4754 4755 // Returns true if TCO is possible between the callers and callees 4756 // calling conventions. 4757 static bool 4758 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4759 CallingConv::ID CalleeCC) { 4760 // Tail calls are possible with fastcc and ccc. 4761 auto isTailCallableCC = [] (CallingConv::ID CC){ 4762 return CC == CallingConv::C || CC == CallingConv::Fast; 4763 }; 4764 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4765 return false; 4766 4767 // We can safely tail call both fastcc and ccc callees from a c calling 4768 // convention caller. If the caller is fastcc, we may have less stack space 4769 // than a non-fastcc caller with the same signature so disable tail-calls in 4770 // that case. 4771 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4772 } 4773 4774 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4775 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4776 const SmallVectorImpl<ISD::OutputArg> &Outs, 4777 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4778 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4779 4780 if (DisableSCO && !TailCallOpt) return false; 4781 4782 // Variadic argument functions are not supported. 4783 if (isVarArg) return false; 4784 4785 auto &Caller = DAG.getMachineFunction().getFunction(); 4786 // Check that the calling conventions are compatible for tco. 4787 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4788 return false; 4789 4790 // Caller contains any byval parameter is not supported. 4791 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4792 return false; 4793 4794 // Callee contains any byval parameter is not supported, too. 4795 // Note: This is a quick work around, because in some cases, e.g. 4796 // caller's stack size > callee's stack size, we are still able to apply 4797 // sibling call optimization. For example, gcc is able to do SCO for caller1 4798 // in the following example, but not for caller2. 4799 // struct test { 4800 // long int a; 4801 // char ary[56]; 4802 // } gTest; 4803 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4804 // b->a = v.a; 4805 // return 0; 4806 // } 4807 // void caller1(struct test a, struct test c, struct test *b) { 4808 // callee(gTest, b); } 4809 // void caller2(struct test *b) { callee(gTest, b); } 4810 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4811 return false; 4812 4813 // If callee and caller use different calling conventions, we cannot pass 4814 // parameters on stack since offsets for the parameter area may be different. 4815 if (Caller.getCallingConv() != CalleeCC && 4816 needStackSlotPassParameters(Subtarget, Outs)) 4817 return false; 4818 4819 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4820 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4821 // callee potentially have different TOC bases then we cannot tail call since 4822 // we need to restore the TOC pointer after the call. 4823 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4824 // We cannot guarantee this for indirect calls or calls to external functions. 4825 // When PC-Relative addressing is used, the concept of the TOC is no longer 4826 // applicable so this check is not required. 4827 // Check first for indirect calls. 4828 if (!Subtarget.isUsingPCRelativeCalls() && 4829 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4830 return false; 4831 4832 // Check if we share the TOC base. 4833 if (!Subtarget.isUsingPCRelativeCalls() && 4834 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4835 return false; 4836 4837 // TCO allows altering callee ABI, so we don't have to check further. 4838 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4839 return true; 4840 4841 if (DisableSCO) return false; 4842 4843 // If callee use the same argument list that caller is using, then we can 4844 // apply SCO on this case. If it is not, then we need to check if callee needs 4845 // stack for passing arguments. 4846 // PC Relative tail calls may not have a CallBase. 4847 // If there is no CallBase we cannot verify if we have the same argument 4848 // list so assume that we don't have the same argument list. 4849 if (CB && !hasSameArgumentList(&Caller, *CB) && 4850 needStackSlotPassParameters(Subtarget, Outs)) 4851 return false; 4852 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4853 return false; 4854 4855 return true; 4856 } 4857 4858 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4859 /// for tail call optimization. Targets which want to do tail call 4860 /// optimization should implement this function. 4861 bool 4862 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4863 CallingConv::ID CalleeCC, 4864 bool isVarArg, 4865 const SmallVectorImpl<ISD::InputArg> &Ins, 4866 SelectionDAG& DAG) const { 4867 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4868 return false; 4869 4870 // Variable argument functions are not supported. 4871 if (isVarArg) 4872 return false; 4873 4874 MachineFunction &MF = DAG.getMachineFunction(); 4875 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4876 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4877 // Functions containing by val parameters are not supported. 4878 for (unsigned i = 0; i != Ins.size(); i++) { 4879 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4880 if (Flags.isByVal()) return false; 4881 } 4882 4883 // Non-PIC/GOT tail calls are supported. 4884 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4885 return true; 4886 4887 // At the moment we can only do local tail calls (in same module, hidden 4888 // or protected) if we are generating PIC. 4889 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4890 return G->getGlobal()->hasHiddenVisibility() 4891 || G->getGlobal()->hasProtectedVisibility(); 4892 } 4893 4894 return false; 4895 } 4896 4897 /// isCallCompatibleAddress - Return the immediate to use if the specified 4898 /// 32-bit value is representable in the immediate field of a BxA instruction. 4899 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4900 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4901 if (!C) return nullptr; 4902 4903 int Addr = C->getZExtValue(); 4904 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4905 SignExtend32<26>(Addr) != Addr) 4906 return nullptr; // Top 6 bits have to be sext of immediate. 4907 4908 return DAG 4909 .getConstant( 4910 (int)C->getZExtValue() >> 2, SDLoc(Op), 4911 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4912 .getNode(); 4913 } 4914 4915 namespace { 4916 4917 struct TailCallArgumentInfo { 4918 SDValue Arg; 4919 SDValue FrameIdxOp; 4920 int FrameIdx = 0; 4921 4922 TailCallArgumentInfo() = default; 4923 }; 4924 4925 } // end anonymous namespace 4926 4927 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4928 static void StoreTailCallArgumentsToStackSlot( 4929 SelectionDAG &DAG, SDValue Chain, 4930 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4931 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4932 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4933 SDValue Arg = TailCallArgs[i].Arg; 4934 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4935 int FI = TailCallArgs[i].FrameIdx; 4936 // Store relative to framepointer. 4937 MemOpChains.push_back(DAG.getStore( 4938 Chain, dl, Arg, FIN, 4939 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4940 } 4941 } 4942 4943 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4944 /// the appropriate stack slot for the tail call optimized function call. 4945 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4946 SDValue OldRetAddr, SDValue OldFP, 4947 int SPDiff, const SDLoc &dl) { 4948 if (SPDiff) { 4949 // Calculate the new stack slot for the return address. 4950 MachineFunction &MF = DAG.getMachineFunction(); 4951 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4952 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4953 bool isPPC64 = Subtarget.isPPC64(); 4954 int SlotSize = isPPC64 ? 8 : 4; 4955 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4956 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4957 NewRetAddrLoc, true); 4958 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4959 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4960 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4961 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4962 } 4963 return Chain; 4964 } 4965 4966 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4967 /// the position of the argument. 4968 static void 4969 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4970 SDValue Arg, int SPDiff, unsigned ArgOffset, 4971 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4972 int Offset = ArgOffset + SPDiff; 4973 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4974 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4975 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4976 SDValue FIN = DAG.getFrameIndex(FI, VT); 4977 TailCallArgumentInfo Info; 4978 Info.Arg = Arg; 4979 Info.FrameIdxOp = FIN; 4980 Info.FrameIdx = FI; 4981 TailCallArguments.push_back(Info); 4982 } 4983 4984 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4985 /// stack slot. Returns the chain as result and the loaded frame pointers in 4986 /// LROpOut/FPOpout. Used when tail calling. 4987 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4988 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4989 SDValue &FPOpOut, const SDLoc &dl) const { 4990 if (SPDiff) { 4991 // Load the LR and FP stack slot for later adjusting. 4992 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4993 LROpOut = getReturnAddrFrameIndex(DAG); 4994 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4995 Chain = SDValue(LROpOut.getNode(), 1); 4996 } 4997 return Chain; 4998 } 4999 5000 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5001 /// by "Src" to address "Dst" of size "Size". Alignment information is 5002 /// specified by the specific parameter attribute. The copy will be passed as 5003 /// a byval function parameter. 5004 /// Sometimes what we are copying is the end of a larger object, the part that 5005 /// does not fit in registers. 5006 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5007 SDValue Chain, ISD::ArgFlagsTy Flags, 5008 SelectionDAG &DAG, const SDLoc &dl) { 5009 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5010 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5011 Flags.getNonZeroByValAlign(), false, false, false, 5012 MachinePointerInfo(), MachinePointerInfo()); 5013 } 5014 5015 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5016 /// tail calls. 5017 static void LowerMemOpCallTo( 5018 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5019 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5020 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5021 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5022 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5023 if (!isTailCall) { 5024 if (isVector) { 5025 SDValue StackPtr; 5026 if (isPPC64) 5027 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5028 else 5029 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5030 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5031 DAG.getConstant(ArgOffset, dl, PtrVT)); 5032 } 5033 MemOpChains.push_back( 5034 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5035 // Calculate and remember argument location. 5036 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5037 TailCallArguments); 5038 } 5039 5040 static void 5041 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5042 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5043 SDValue FPOp, 5044 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5045 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5046 // might overwrite each other in case of tail call optimization. 5047 SmallVector<SDValue, 8> MemOpChains2; 5048 // Do not flag preceding copytoreg stuff together with the following stuff. 5049 InFlag = SDValue(); 5050 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5051 MemOpChains2, dl); 5052 if (!MemOpChains2.empty()) 5053 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5054 5055 // Store the return address to the appropriate stack slot. 5056 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5057 5058 // Emit callseq_end just before tailcall node. 5059 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5060 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5061 InFlag = Chain.getValue(1); 5062 } 5063 5064 // Is this global address that of a function that can be called by name? (as 5065 // opposed to something that must hold a descriptor for an indirect call). 5066 static bool isFunctionGlobalAddress(SDValue Callee) { 5067 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5068 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5069 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5070 return false; 5071 5072 return G->getGlobal()->getValueType()->isFunctionTy(); 5073 } 5074 5075 return false; 5076 } 5077 5078 SDValue PPCTargetLowering::LowerCallResult( 5079 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5080 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5081 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5082 SmallVector<CCValAssign, 16> RVLocs; 5083 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5084 *DAG.getContext()); 5085 5086 CCRetInfo.AnalyzeCallResult( 5087 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5088 ? RetCC_PPC_Cold 5089 : RetCC_PPC); 5090 5091 // Copy all of the result registers out of their specified physreg. 5092 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5093 CCValAssign &VA = RVLocs[i]; 5094 assert(VA.isRegLoc() && "Can only return in registers!"); 5095 5096 SDValue Val; 5097 5098 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5099 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5100 InFlag); 5101 Chain = Lo.getValue(1); 5102 InFlag = Lo.getValue(2); 5103 VA = RVLocs[++i]; // skip ahead to next loc 5104 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5105 InFlag); 5106 Chain = Hi.getValue(1); 5107 InFlag = Hi.getValue(2); 5108 if (!Subtarget.isLittleEndian()) 5109 std::swap (Lo, Hi); 5110 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5111 } else { 5112 Val = DAG.getCopyFromReg(Chain, dl, 5113 VA.getLocReg(), VA.getLocVT(), InFlag); 5114 Chain = Val.getValue(1); 5115 InFlag = Val.getValue(2); 5116 } 5117 5118 switch (VA.getLocInfo()) { 5119 default: llvm_unreachable("Unknown loc info!"); 5120 case CCValAssign::Full: break; 5121 case CCValAssign::AExt: 5122 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5123 break; 5124 case CCValAssign::ZExt: 5125 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5126 DAG.getValueType(VA.getValVT())); 5127 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5128 break; 5129 case CCValAssign::SExt: 5130 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5131 DAG.getValueType(VA.getValVT())); 5132 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5133 break; 5134 } 5135 5136 InVals.push_back(Val); 5137 } 5138 5139 return Chain; 5140 } 5141 5142 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5143 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5144 // PatchPoint calls are not indirect. 5145 if (isPatchPoint) 5146 return false; 5147 5148 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 5149 return false; 5150 5151 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5152 // becuase the immediate function pointer points to a descriptor instead of 5153 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5154 // pointer immediate points to the global entry point, while the BLA would 5155 // need to jump to the local entry point (see rL211174). 5156 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5157 isBLACompatibleAddress(Callee, DAG)) 5158 return false; 5159 5160 return true; 5161 } 5162 5163 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5164 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5165 return Subtarget.isAIXABI() || 5166 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5167 } 5168 5169 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5170 const Function &Caller, 5171 const SDValue &Callee, 5172 const PPCSubtarget &Subtarget, 5173 const TargetMachine &TM) { 5174 if (CFlags.IsTailCall) 5175 return PPCISD::TC_RETURN; 5176 5177 // This is a call through a function pointer. 5178 if (CFlags.IsIndirect) { 5179 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5180 // indirect calls. The save of the caller's TOC pointer to the stack will be 5181 // inserted into the DAG as part of call lowering. The restore of the TOC 5182 // pointer is modeled by using a pseudo instruction for the call opcode that 5183 // represents the 2 instruction sequence of an indirect branch and link, 5184 // immediately followed by a load of the TOC pointer from the the stack save 5185 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5186 // as it is not saved or used. 5187 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5188 : PPCISD::BCTRL; 5189 } 5190 5191 if (Subtarget.isUsingPCRelativeCalls()) { 5192 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5193 return PPCISD::CALL_NOTOC; 5194 } 5195 5196 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5197 // immediately following the call instruction if the caller and callee may 5198 // have different TOC bases. At link time if the linker determines the calls 5199 // may not share a TOC base, the call is redirected to a trampoline inserted 5200 // by the linker. The trampoline will (among other things) save the callers 5201 // TOC pointer at an ABI designated offset in the linkage area and the linker 5202 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5203 // into gpr2. 5204 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5205 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5206 : PPCISD::CALL_NOP; 5207 5208 return PPCISD::CALL; 5209 } 5210 5211 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5212 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5213 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5214 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5215 return SDValue(Dest, 0); 5216 5217 // Returns true if the callee is local, and false otherwise. 5218 auto isLocalCallee = [&]() { 5219 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5220 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5221 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5222 5223 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5224 !dyn_cast_or_null<GlobalIFunc>(GV); 5225 }; 5226 5227 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5228 // a static relocation model causes some versions of GNU LD (2.17.50, at 5229 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5230 // built with secure-PLT. 5231 bool UsePlt = 5232 Subtarget.is32BitELFABI() && !isLocalCallee() && 5233 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5234 5235 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5236 const TargetMachine &TM = Subtarget.getTargetMachine(); 5237 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5238 MCSymbolXCOFF *S = 5239 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5240 5241 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5242 return DAG.getMCSymbol(S, PtrVT); 5243 }; 5244 5245 if (isFunctionGlobalAddress(Callee)) { 5246 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5247 5248 if (Subtarget.isAIXABI()) { 5249 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5250 return getAIXFuncEntryPointSymbolSDNode(GV); 5251 } 5252 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5253 UsePlt ? PPCII::MO_PLT : 0); 5254 } 5255 5256 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5257 const char *SymName = S->getSymbol(); 5258 if (Subtarget.isAIXABI()) { 5259 // If there exists a user-declared function whose name is the same as the 5260 // ExternalSymbol's, then we pick up the user-declared version. 5261 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5262 if (const Function *F = 5263 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5264 return getAIXFuncEntryPointSymbolSDNode(F); 5265 5266 // On AIX, direct function calls reference the symbol for the function's 5267 // entry point, which is named by prepending a "." before the function's 5268 // C-linkage name. A Qualname is returned here because an external 5269 // function entry point is a csect with XTY_ER property. 5270 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5271 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5272 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5273 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5274 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5275 return Sec->getQualNameSymbol(); 5276 }; 5277 5278 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5279 } 5280 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5281 UsePlt ? PPCII::MO_PLT : 0); 5282 } 5283 5284 // No transformation needed. 5285 assert(Callee.getNode() && "What no callee?"); 5286 return Callee; 5287 } 5288 5289 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5290 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5291 "Expected a CALLSEQ_STARTSDNode."); 5292 5293 // The last operand is the chain, except when the node has glue. If the node 5294 // has glue, then the last operand is the glue, and the chain is the second 5295 // last operand. 5296 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5297 if (LastValue.getValueType() != MVT::Glue) 5298 return LastValue; 5299 5300 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5301 } 5302 5303 // Creates the node that moves a functions address into the count register 5304 // to prepare for an indirect call instruction. 5305 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5306 SDValue &Glue, SDValue &Chain, 5307 const SDLoc &dl) { 5308 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5309 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5310 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5311 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5312 // The glue is the second value produced. 5313 Glue = Chain.getValue(1); 5314 } 5315 5316 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5317 SDValue &Glue, SDValue &Chain, 5318 SDValue CallSeqStart, 5319 const CallBase *CB, const SDLoc &dl, 5320 bool hasNest, 5321 const PPCSubtarget &Subtarget) { 5322 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5323 // entry point, but to the function descriptor (the function entry point 5324 // address is part of the function descriptor though). 5325 // The function descriptor is a three doubleword structure with the 5326 // following fields: function entry point, TOC base address and 5327 // environment pointer. 5328 // Thus for a call through a function pointer, the following actions need 5329 // to be performed: 5330 // 1. Save the TOC of the caller in the TOC save area of its stack 5331 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5332 // 2. Load the address of the function entry point from the function 5333 // descriptor. 5334 // 3. Load the TOC of the callee from the function descriptor into r2. 5335 // 4. Load the environment pointer from the function descriptor into 5336 // r11. 5337 // 5. Branch to the function entry point address. 5338 // 6. On return of the callee, the TOC of the caller needs to be 5339 // restored (this is done in FinishCall()). 5340 // 5341 // The loads are scheduled at the beginning of the call sequence, and the 5342 // register copies are flagged together to ensure that no other 5343 // operations can be scheduled in between. E.g. without flagging the 5344 // copies together, a TOC access in the caller could be scheduled between 5345 // the assignment of the callee TOC and the branch to the callee, which leads 5346 // to incorrect code. 5347 5348 // Start by loading the function address from the descriptor. 5349 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5350 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5351 ? (MachineMemOperand::MODereferenceable | 5352 MachineMemOperand::MOInvariant) 5353 : MachineMemOperand::MONone; 5354 5355 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5356 5357 // Registers used in building the DAG. 5358 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5359 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5360 5361 // Offsets of descriptor members. 5362 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5363 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5364 5365 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5366 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5367 5368 // One load for the functions entry point address. 5369 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5370 Alignment, MMOFlags); 5371 5372 // One for loading the TOC anchor for the module that contains the called 5373 // function. 5374 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5375 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5376 SDValue TOCPtr = 5377 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5378 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5379 5380 // One for loading the environment pointer. 5381 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5382 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5383 SDValue LoadEnvPtr = 5384 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5385 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5386 5387 5388 // Then copy the newly loaded TOC anchor to the TOC pointer. 5389 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5390 Chain = TOCVal.getValue(0); 5391 Glue = TOCVal.getValue(1); 5392 5393 // If the function call has an explicit 'nest' parameter, it takes the 5394 // place of the environment pointer. 5395 assert((!hasNest || !Subtarget.isAIXABI()) && 5396 "Nest parameter is not supported on AIX."); 5397 if (!hasNest) { 5398 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5399 Chain = EnvVal.getValue(0); 5400 Glue = EnvVal.getValue(1); 5401 } 5402 5403 // The rest of the indirect call sequence is the same as the non-descriptor 5404 // DAG. 5405 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5406 } 5407 5408 static void 5409 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5410 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5411 SelectionDAG &DAG, 5412 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5413 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5414 const PPCSubtarget &Subtarget) { 5415 const bool IsPPC64 = Subtarget.isPPC64(); 5416 // MVT for a general purpose register. 5417 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5418 5419 // First operand is always the chain. 5420 Ops.push_back(Chain); 5421 5422 // If it's a direct call pass the callee as the second operand. 5423 if (!CFlags.IsIndirect) 5424 Ops.push_back(Callee); 5425 else { 5426 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5427 5428 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5429 // on the stack (this would have been done in `LowerCall_64SVR4` or 5430 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5431 // represents both the indirect branch and a load that restores the TOC 5432 // pointer from the linkage area. The operand for the TOC restore is an add 5433 // of the TOC save offset to the stack pointer. This must be the second 5434 // operand: after the chain input but before any other variadic arguments. 5435 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5436 // saved or used. 5437 if (isTOCSaveRestoreRequired(Subtarget)) { 5438 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5439 5440 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5441 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5442 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5443 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5444 Ops.push_back(AddTOC); 5445 } 5446 5447 // Add the register used for the environment pointer. 5448 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5449 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5450 RegVT)); 5451 5452 5453 // Add CTR register as callee so a bctr can be emitted later. 5454 if (CFlags.IsTailCall) 5455 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5456 } 5457 5458 // If this is a tail call add stack pointer delta. 5459 if (CFlags.IsTailCall) 5460 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5461 5462 // Add argument registers to the end of the list so that they are known live 5463 // into the call. 5464 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5465 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5466 RegsToPass[i].second.getValueType())); 5467 5468 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5469 // no way to mark dependencies as implicit here. 5470 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5471 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5472 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5473 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5474 5475 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5476 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5477 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5478 5479 // Add a register mask operand representing the call-preserved registers. 5480 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5481 const uint32_t *Mask = 5482 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5483 assert(Mask && "Missing call preserved mask for calling convention"); 5484 Ops.push_back(DAG.getRegisterMask(Mask)); 5485 5486 // If the glue is valid, it is the last operand. 5487 if (Glue.getNode()) 5488 Ops.push_back(Glue); 5489 } 5490 5491 SDValue PPCTargetLowering::FinishCall( 5492 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5493 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5494 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5495 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5496 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5497 5498 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5499 Subtarget.isAIXABI()) 5500 setUsesTOCBasePtr(DAG); 5501 5502 unsigned CallOpc = 5503 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5504 Subtarget, DAG.getTarget()); 5505 5506 if (!CFlags.IsIndirect) 5507 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5508 else if (Subtarget.usesFunctionDescriptors()) 5509 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5510 dl, CFlags.HasNest, Subtarget); 5511 else 5512 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5513 5514 // Build the operand list for the call instruction. 5515 SmallVector<SDValue, 8> Ops; 5516 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5517 SPDiff, Subtarget); 5518 5519 // Emit tail call. 5520 if (CFlags.IsTailCall) { 5521 // Indirect tail call when using PC Relative calls do not have the same 5522 // constraints. 5523 assert(((Callee.getOpcode() == ISD::Register && 5524 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5525 Callee.getOpcode() == ISD::TargetExternalSymbol || 5526 Callee.getOpcode() == ISD::TargetGlobalAddress || 5527 isa<ConstantSDNode>(Callee) || 5528 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5529 "Expecting a global address, external symbol, absolute value, " 5530 "register or an indirect tail call when PC Relative calls are " 5531 "used."); 5532 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5533 assert(CallOpc == PPCISD::TC_RETURN && 5534 "Unexpected call opcode for a tail call."); 5535 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5536 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5537 } 5538 5539 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5540 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5541 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5542 Glue = Chain.getValue(1); 5543 5544 // When performing tail call optimization the callee pops its arguments off 5545 // the stack. Account for this here so these bytes can be pushed back on in 5546 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5547 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5548 getTargetMachine().Options.GuaranteedTailCallOpt) 5549 ? NumBytes 5550 : 0; 5551 5552 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5553 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5554 Glue, dl); 5555 Glue = Chain.getValue(1); 5556 5557 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5558 DAG, InVals); 5559 } 5560 5561 SDValue 5562 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5563 SmallVectorImpl<SDValue> &InVals) const { 5564 SelectionDAG &DAG = CLI.DAG; 5565 SDLoc &dl = CLI.DL; 5566 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5567 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5568 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5569 SDValue Chain = CLI.Chain; 5570 SDValue Callee = CLI.Callee; 5571 bool &isTailCall = CLI.IsTailCall; 5572 CallingConv::ID CallConv = CLI.CallConv; 5573 bool isVarArg = CLI.IsVarArg; 5574 bool isPatchPoint = CLI.IsPatchPoint; 5575 const CallBase *CB = CLI.CB; 5576 5577 if (isTailCall) { 5578 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5579 isTailCall = false; 5580 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5581 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5582 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5583 else 5584 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5585 Ins, DAG); 5586 if (isTailCall) { 5587 ++NumTailCalls; 5588 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5589 ++NumSiblingCalls; 5590 5591 // PC Relative calls no longer guarantee that the callee is a Global 5592 // Address Node. The callee could be an indirect tail call in which 5593 // case the SDValue for the callee could be a load (to load the address 5594 // of a function pointer) or it may be a register copy (to move the 5595 // address of the callee from a function parameter into a virtual 5596 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5597 assert((Subtarget.isUsingPCRelativeCalls() || 5598 isa<GlobalAddressSDNode>(Callee)) && 5599 "Callee should be an llvm::Function object."); 5600 5601 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5602 << "\nTCO callee: "); 5603 LLVM_DEBUG(Callee.dump()); 5604 } 5605 } 5606 5607 if (!isTailCall && CB && CB->isMustTailCall()) 5608 report_fatal_error("failed to perform tail call elimination on a call " 5609 "site marked musttail"); 5610 5611 // When long calls (i.e. indirect calls) are always used, calls are always 5612 // made via function pointer. If we have a function name, first translate it 5613 // into a pointer. 5614 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5615 !isTailCall) 5616 Callee = LowerGlobalAddress(Callee, DAG); 5617 5618 CallFlags CFlags( 5619 CallConv, isTailCall, isVarArg, isPatchPoint, 5620 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5621 // hasNest 5622 Subtarget.is64BitELFABI() && 5623 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5624 CLI.NoMerge); 5625 5626 if (Subtarget.isAIXABI()) 5627 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5628 InVals, CB); 5629 5630 assert(Subtarget.isSVR4ABI()); 5631 if (Subtarget.isPPC64()) 5632 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5633 InVals, CB); 5634 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5635 InVals, CB); 5636 } 5637 5638 SDValue PPCTargetLowering::LowerCall_32SVR4( 5639 SDValue Chain, SDValue Callee, CallFlags CFlags, 5640 const SmallVectorImpl<ISD::OutputArg> &Outs, 5641 const SmallVectorImpl<SDValue> &OutVals, 5642 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5643 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5644 const CallBase *CB) const { 5645 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5646 // of the 32-bit SVR4 ABI stack frame layout. 5647 5648 const CallingConv::ID CallConv = CFlags.CallConv; 5649 const bool IsVarArg = CFlags.IsVarArg; 5650 const bool IsTailCall = CFlags.IsTailCall; 5651 5652 assert((CallConv == CallingConv::C || 5653 CallConv == CallingConv::Cold || 5654 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5655 5656 const Align PtrAlign(4); 5657 5658 MachineFunction &MF = DAG.getMachineFunction(); 5659 5660 // Mark this function as potentially containing a function that contains a 5661 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5662 // and restoring the callers stack pointer in this functions epilog. This is 5663 // done because by tail calling the called function might overwrite the value 5664 // in this function's (MF) stack pointer stack slot 0(SP). 5665 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5666 CallConv == CallingConv::Fast) 5667 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5668 5669 // Count how many bytes are to be pushed on the stack, including the linkage 5670 // area, parameter list area and the part of the local variable space which 5671 // contains copies of aggregates which are passed by value. 5672 5673 // Assign locations to all of the outgoing arguments. 5674 SmallVector<CCValAssign, 16> ArgLocs; 5675 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5676 5677 // Reserve space for the linkage area on the stack. 5678 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5679 PtrAlign); 5680 if (useSoftFloat()) 5681 CCInfo.PreAnalyzeCallOperands(Outs); 5682 5683 if (IsVarArg) { 5684 // Handle fixed and variable vector arguments differently. 5685 // Fixed vector arguments go into registers as long as registers are 5686 // available. Variable vector arguments always go into memory. 5687 unsigned NumArgs = Outs.size(); 5688 5689 for (unsigned i = 0; i != NumArgs; ++i) { 5690 MVT ArgVT = Outs[i].VT; 5691 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5692 bool Result; 5693 5694 if (Outs[i].IsFixed) { 5695 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5696 CCInfo); 5697 } else { 5698 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5699 ArgFlags, CCInfo); 5700 } 5701 5702 if (Result) { 5703 #ifndef NDEBUG 5704 errs() << "Call operand #" << i << " has unhandled type " 5705 << EVT(ArgVT).getEVTString() << "\n"; 5706 #endif 5707 llvm_unreachable(nullptr); 5708 } 5709 } 5710 } else { 5711 // All arguments are treated the same. 5712 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5713 } 5714 CCInfo.clearWasPPCF128(); 5715 5716 // Assign locations to all of the outgoing aggregate by value arguments. 5717 SmallVector<CCValAssign, 16> ByValArgLocs; 5718 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5719 5720 // Reserve stack space for the allocations in CCInfo. 5721 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5722 5723 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5724 5725 // Size of the linkage area, parameter list area and the part of the local 5726 // space variable where copies of aggregates which are passed by value are 5727 // stored. 5728 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5729 5730 // Calculate by how many bytes the stack has to be adjusted in case of tail 5731 // call optimization. 5732 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5733 5734 // Adjust the stack pointer for the new arguments... 5735 // These operations are automatically eliminated by the prolog/epilog pass 5736 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5737 SDValue CallSeqStart = Chain; 5738 5739 // Load the return address and frame pointer so it can be moved somewhere else 5740 // later. 5741 SDValue LROp, FPOp; 5742 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5743 5744 // Set up a copy of the stack pointer for use loading and storing any 5745 // arguments that may not fit in the registers available for argument 5746 // passing. 5747 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5748 5749 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5750 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5751 SmallVector<SDValue, 8> MemOpChains; 5752 5753 bool seenFloatArg = false; 5754 // Walk the register/memloc assignments, inserting copies/loads. 5755 // i - Tracks the index into the list of registers allocated for the call 5756 // RealArgIdx - Tracks the index into the list of actual function arguments 5757 // j - Tracks the index into the list of byval arguments 5758 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5759 i != e; 5760 ++i, ++RealArgIdx) { 5761 CCValAssign &VA = ArgLocs[i]; 5762 SDValue Arg = OutVals[RealArgIdx]; 5763 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5764 5765 if (Flags.isByVal()) { 5766 // Argument is an aggregate which is passed by value, thus we need to 5767 // create a copy of it in the local variable space of the current stack 5768 // frame (which is the stack frame of the caller) and pass the address of 5769 // this copy to the callee. 5770 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5771 CCValAssign &ByValVA = ByValArgLocs[j++]; 5772 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5773 5774 // Memory reserved in the local variable space of the callers stack frame. 5775 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5776 5777 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5778 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5779 StackPtr, PtrOff); 5780 5781 // Create a copy of the argument in the local area of the current 5782 // stack frame. 5783 SDValue MemcpyCall = 5784 CreateCopyOfByValArgument(Arg, PtrOff, 5785 CallSeqStart.getNode()->getOperand(0), 5786 Flags, DAG, dl); 5787 5788 // This must go outside the CALLSEQ_START..END. 5789 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5790 SDLoc(MemcpyCall)); 5791 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5792 NewCallSeqStart.getNode()); 5793 Chain = CallSeqStart = NewCallSeqStart; 5794 5795 // Pass the address of the aggregate copy on the stack either in a 5796 // physical register or in the parameter list area of the current stack 5797 // frame to the callee. 5798 Arg = PtrOff; 5799 } 5800 5801 // When useCRBits() is true, there can be i1 arguments. 5802 // It is because getRegisterType(MVT::i1) => MVT::i1, 5803 // and for other integer types getRegisterType() => MVT::i32. 5804 // Extend i1 and ensure callee will get i32. 5805 if (Arg.getValueType() == MVT::i1) 5806 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5807 dl, MVT::i32, Arg); 5808 5809 if (VA.isRegLoc()) { 5810 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5811 // Put argument in a physical register. 5812 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5813 bool IsLE = Subtarget.isLittleEndian(); 5814 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5815 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5816 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5817 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5818 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5819 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5820 SVal.getValue(0))); 5821 } else 5822 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5823 } else { 5824 // Put argument in the parameter list area of the current stack frame. 5825 assert(VA.isMemLoc()); 5826 unsigned LocMemOffset = VA.getLocMemOffset(); 5827 5828 if (!IsTailCall) { 5829 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5830 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5831 StackPtr, PtrOff); 5832 5833 MemOpChains.push_back( 5834 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5835 } else { 5836 // Calculate and remember argument location. 5837 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5838 TailCallArguments); 5839 } 5840 } 5841 } 5842 5843 if (!MemOpChains.empty()) 5844 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5845 5846 // Build a sequence of copy-to-reg nodes chained together with token chain 5847 // and flag operands which copy the outgoing args into the appropriate regs. 5848 SDValue InFlag; 5849 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5850 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5851 RegsToPass[i].second, InFlag); 5852 InFlag = Chain.getValue(1); 5853 } 5854 5855 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5856 // registers. 5857 if (IsVarArg) { 5858 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5859 SDValue Ops[] = { Chain, InFlag }; 5860 5861 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5862 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5863 5864 InFlag = Chain.getValue(1); 5865 } 5866 5867 if (IsTailCall) 5868 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5869 TailCallArguments); 5870 5871 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5872 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5873 } 5874 5875 // Copy an argument into memory, being careful to do this outside the 5876 // call sequence for the call to which the argument belongs. 5877 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5878 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5879 SelectionDAG &DAG, const SDLoc &dl) const { 5880 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5881 CallSeqStart.getNode()->getOperand(0), 5882 Flags, DAG, dl); 5883 // The MEMCPY must go outside the CALLSEQ_START..END. 5884 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5885 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5886 SDLoc(MemcpyCall)); 5887 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5888 NewCallSeqStart.getNode()); 5889 return NewCallSeqStart; 5890 } 5891 5892 SDValue PPCTargetLowering::LowerCall_64SVR4( 5893 SDValue Chain, SDValue Callee, CallFlags CFlags, 5894 const SmallVectorImpl<ISD::OutputArg> &Outs, 5895 const SmallVectorImpl<SDValue> &OutVals, 5896 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5897 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5898 const CallBase *CB) const { 5899 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5900 bool isLittleEndian = Subtarget.isLittleEndian(); 5901 unsigned NumOps = Outs.size(); 5902 bool IsSibCall = false; 5903 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5904 5905 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5906 unsigned PtrByteSize = 8; 5907 5908 MachineFunction &MF = DAG.getMachineFunction(); 5909 5910 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5911 IsSibCall = true; 5912 5913 // Mark this function as potentially containing a function that contains a 5914 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5915 // and restoring the callers stack pointer in this functions epilog. This is 5916 // done because by tail calling the called function might overwrite the value 5917 // in this function's (MF) stack pointer stack slot 0(SP). 5918 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5919 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5920 5921 assert(!(IsFastCall && CFlags.IsVarArg) && 5922 "fastcc not supported on varargs functions"); 5923 5924 // Count how many bytes are to be pushed on the stack, including the linkage 5925 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5926 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5927 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5928 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5929 unsigned NumBytes = LinkageSize; 5930 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5931 5932 static const MCPhysReg GPR[] = { 5933 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5934 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5935 }; 5936 static const MCPhysReg VR[] = { 5937 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5938 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5939 }; 5940 5941 const unsigned NumGPRs = array_lengthof(GPR); 5942 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5943 const unsigned NumVRs = array_lengthof(VR); 5944 5945 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5946 // can be passed to the callee in registers. 5947 // For the fast calling convention, there is another check below. 5948 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5949 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5950 if (!HasParameterArea) { 5951 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5952 unsigned AvailableFPRs = NumFPRs; 5953 unsigned AvailableVRs = NumVRs; 5954 unsigned NumBytesTmp = NumBytes; 5955 for (unsigned i = 0; i != NumOps; ++i) { 5956 if (Outs[i].Flags.isNest()) continue; 5957 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5958 PtrByteSize, LinkageSize, ParamAreaSize, 5959 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5960 HasParameterArea = true; 5961 } 5962 } 5963 5964 // When using the fast calling convention, we don't provide backing for 5965 // arguments that will be in registers. 5966 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5967 5968 // Avoid allocating parameter area for fastcc functions if all the arguments 5969 // can be passed in the registers. 5970 if (IsFastCall) 5971 HasParameterArea = false; 5972 5973 // Add up all the space actually used. 5974 for (unsigned i = 0; i != NumOps; ++i) { 5975 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5976 EVT ArgVT = Outs[i].VT; 5977 EVT OrigVT = Outs[i].ArgVT; 5978 5979 if (Flags.isNest()) 5980 continue; 5981 5982 if (IsFastCall) { 5983 if (Flags.isByVal()) { 5984 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5985 if (NumGPRsUsed > NumGPRs) 5986 HasParameterArea = true; 5987 } else { 5988 switch (ArgVT.getSimpleVT().SimpleTy) { 5989 default: llvm_unreachable("Unexpected ValueType for argument!"); 5990 case MVT::i1: 5991 case MVT::i32: 5992 case MVT::i64: 5993 if (++NumGPRsUsed <= NumGPRs) 5994 continue; 5995 break; 5996 case MVT::v4i32: 5997 case MVT::v8i16: 5998 case MVT::v16i8: 5999 case MVT::v2f64: 6000 case MVT::v2i64: 6001 case MVT::v1i128: 6002 case MVT::f128: 6003 if (++NumVRsUsed <= NumVRs) 6004 continue; 6005 break; 6006 case MVT::v4f32: 6007 if (++NumVRsUsed <= NumVRs) 6008 continue; 6009 break; 6010 case MVT::f32: 6011 case MVT::f64: 6012 if (++NumFPRsUsed <= NumFPRs) 6013 continue; 6014 break; 6015 } 6016 HasParameterArea = true; 6017 } 6018 } 6019 6020 /* Respect alignment of argument on the stack. */ 6021 auto Alignement = 6022 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6023 NumBytes = alignTo(NumBytes, Alignement); 6024 6025 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6026 if (Flags.isInConsecutiveRegsLast()) 6027 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6028 } 6029 6030 unsigned NumBytesActuallyUsed = NumBytes; 6031 6032 // In the old ELFv1 ABI, 6033 // the prolog code of the callee may store up to 8 GPR argument registers to 6034 // the stack, allowing va_start to index over them in memory if its varargs. 6035 // Because we cannot tell if this is needed on the caller side, we have to 6036 // conservatively assume that it is needed. As such, make sure we have at 6037 // least enough stack space for the caller to store the 8 GPRs. 6038 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6039 // really requires memory operands, e.g. a vararg function. 6040 if (HasParameterArea) 6041 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6042 else 6043 NumBytes = LinkageSize; 6044 6045 // Tail call needs the stack to be aligned. 6046 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6047 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6048 6049 int SPDiff = 0; 6050 6051 // Calculate by how many bytes the stack has to be adjusted in case of tail 6052 // call optimization. 6053 if (!IsSibCall) 6054 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6055 6056 // To protect arguments on the stack from being clobbered in a tail call, 6057 // force all the loads to happen before doing any other lowering. 6058 if (CFlags.IsTailCall) 6059 Chain = DAG.getStackArgumentTokenFactor(Chain); 6060 6061 // Adjust the stack pointer for the new arguments... 6062 // These operations are automatically eliminated by the prolog/epilog pass 6063 if (!IsSibCall) 6064 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6065 SDValue CallSeqStart = Chain; 6066 6067 // Load the return address and frame pointer so it can be move somewhere else 6068 // later. 6069 SDValue LROp, FPOp; 6070 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6071 6072 // Set up a copy of the stack pointer for use loading and storing any 6073 // arguments that may not fit in the registers available for argument 6074 // passing. 6075 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6076 6077 // Figure out which arguments are going to go in registers, and which in 6078 // memory. Also, if this is a vararg function, floating point operations 6079 // must be stored to our stack, and loaded into integer regs as well, if 6080 // any integer regs are available for argument passing. 6081 unsigned ArgOffset = LinkageSize; 6082 6083 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6084 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6085 6086 SmallVector<SDValue, 8> MemOpChains; 6087 for (unsigned i = 0; i != NumOps; ++i) { 6088 SDValue Arg = OutVals[i]; 6089 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6090 EVT ArgVT = Outs[i].VT; 6091 EVT OrigVT = Outs[i].ArgVT; 6092 6093 // PtrOff will be used to store the current argument to the stack if a 6094 // register cannot be found for it. 6095 SDValue PtrOff; 6096 6097 // We re-align the argument offset for each argument, except when using the 6098 // fast calling convention, when we need to make sure we do that only when 6099 // we'll actually use a stack slot. 6100 auto ComputePtrOff = [&]() { 6101 /* Respect alignment of argument on the stack. */ 6102 auto Alignment = 6103 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6104 ArgOffset = alignTo(ArgOffset, Alignment); 6105 6106 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6107 6108 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6109 }; 6110 6111 if (!IsFastCall) { 6112 ComputePtrOff(); 6113 6114 /* Compute GPR index associated with argument offset. */ 6115 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6116 GPR_idx = std::min(GPR_idx, NumGPRs); 6117 } 6118 6119 // Promote integers to 64-bit values. 6120 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6121 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6122 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6123 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6124 } 6125 6126 // FIXME memcpy is used way more than necessary. Correctness first. 6127 // Note: "by value" is code for passing a structure by value, not 6128 // basic types. 6129 if (Flags.isByVal()) { 6130 // Note: Size includes alignment padding, so 6131 // struct x { short a; char b; } 6132 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6133 // These are the proper values we need for right-justifying the 6134 // aggregate in a parameter register. 6135 unsigned Size = Flags.getByValSize(); 6136 6137 // An empty aggregate parameter takes up no storage and no 6138 // registers. 6139 if (Size == 0) 6140 continue; 6141 6142 if (IsFastCall) 6143 ComputePtrOff(); 6144 6145 // All aggregates smaller than 8 bytes must be passed right-justified. 6146 if (Size==1 || Size==2 || Size==4) { 6147 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6148 if (GPR_idx != NumGPRs) { 6149 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6150 MachinePointerInfo(), VT); 6151 MemOpChains.push_back(Load.getValue(1)); 6152 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6153 6154 ArgOffset += PtrByteSize; 6155 continue; 6156 } 6157 } 6158 6159 if (GPR_idx == NumGPRs && Size < 8) { 6160 SDValue AddPtr = PtrOff; 6161 if (!isLittleEndian) { 6162 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6163 PtrOff.getValueType()); 6164 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6165 } 6166 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6167 CallSeqStart, 6168 Flags, DAG, dl); 6169 ArgOffset += PtrByteSize; 6170 continue; 6171 } 6172 // Copy entire object into memory. There are cases where gcc-generated 6173 // code assumes it is there, even if it could be put entirely into 6174 // registers. (This is not what the doc says.) 6175 6176 // FIXME: The above statement is likely due to a misunderstanding of the 6177 // documents. All arguments must be copied into the parameter area BY 6178 // THE CALLEE in the event that the callee takes the address of any 6179 // formal argument. That has not yet been implemented. However, it is 6180 // reasonable to use the stack area as a staging area for the register 6181 // load. 6182 6183 // Skip this for small aggregates, as we will use the same slot for a 6184 // right-justified copy, below. 6185 if (Size >= 8) 6186 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6187 CallSeqStart, 6188 Flags, DAG, dl); 6189 6190 // When a register is available, pass a small aggregate right-justified. 6191 if (Size < 8 && GPR_idx != NumGPRs) { 6192 // The easiest way to get this right-justified in a register 6193 // is to copy the structure into the rightmost portion of a 6194 // local variable slot, then load the whole slot into the 6195 // register. 6196 // FIXME: The memcpy seems to produce pretty awful code for 6197 // small aggregates, particularly for packed ones. 6198 // FIXME: It would be preferable to use the slot in the 6199 // parameter save area instead of a new local variable. 6200 SDValue AddPtr = PtrOff; 6201 if (!isLittleEndian) { 6202 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6203 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6204 } 6205 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6206 CallSeqStart, 6207 Flags, DAG, dl); 6208 6209 // Load the slot into the register. 6210 SDValue Load = 6211 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6212 MemOpChains.push_back(Load.getValue(1)); 6213 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6214 6215 // Done with this argument. 6216 ArgOffset += PtrByteSize; 6217 continue; 6218 } 6219 6220 // For aggregates larger than PtrByteSize, copy the pieces of the 6221 // object that fit into registers from the parameter save area. 6222 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6223 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6224 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6225 if (GPR_idx != NumGPRs) { 6226 SDValue Load = 6227 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6228 MemOpChains.push_back(Load.getValue(1)); 6229 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6230 ArgOffset += PtrByteSize; 6231 } else { 6232 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6233 break; 6234 } 6235 } 6236 continue; 6237 } 6238 6239 switch (Arg.getSimpleValueType().SimpleTy) { 6240 default: llvm_unreachable("Unexpected ValueType for argument!"); 6241 case MVT::i1: 6242 case MVT::i32: 6243 case MVT::i64: 6244 if (Flags.isNest()) { 6245 // The 'nest' parameter, if any, is passed in R11. 6246 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6247 break; 6248 } 6249 6250 // These can be scalar arguments or elements of an integer array type 6251 // passed directly. Clang may use those instead of "byval" aggregate 6252 // types to avoid forcing arguments to memory unnecessarily. 6253 if (GPR_idx != NumGPRs) { 6254 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6255 } else { 6256 if (IsFastCall) 6257 ComputePtrOff(); 6258 6259 assert(HasParameterArea && 6260 "Parameter area must exist to pass an argument in memory."); 6261 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6262 true, CFlags.IsTailCall, false, MemOpChains, 6263 TailCallArguments, dl); 6264 if (IsFastCall) 6265 ArgOffset += PtrByteSize; 6266 } 6267 if (!IsFastCall) 6268 ArgOffset += PtrByteSize; 6269 break; 6270 case MVT::f32: 6271 case MVT::f64: { 6272 // These can be scalar arguments or elements of a float array type 6273 // passed directly. The latter are used to implement ELFv2 homogenous 6274 // float aggregates. 6275 6276 // Named arguments go into FPRs first, and once they overflow, the 6277 // remaining arguments go into GPRs and then the parameter save area. 6278 // Unnamed arguments for vararg functions always go to GPRs and 6279 // then the parameter save area. For now, put all arguments to vararg 6280 // routines always in both locations (FPR *and* GPR or stack slot). 6281 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6282 bool NeededLoad = false; 6283 6284 // First load the argument into the next available FPR. 6285 if (FPR_idx != NumFPRs) 6286 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6287 6288 // Next, load the argument into GPR or stack slot if needed. 6289 if (!NeedGPROrStack) 6290 ; 6291 else if (GPR_idx != NumGPRs && !IsFastCall) { 6292 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6293 // once we support fp <-> gpr moves. 6294 6295 // In the non-vararg case, this can only ever happen in the 6296 // presence of f32 array types, since otherwise we never run 6297 // out of FPRs before running out of GPRs. 6298 SDValue ArgVal; 6299 6300 // Double values are always passed in a single GPR. 6301 if (Arg.getValueType() != MVT::f32) { 6302 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6303 6304 // Non-array float values are extended and passed in a GPR. 6305 } else if (!Flags.isInConsecutiveRegs()) { 6306 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6307 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6308 6309 // If we have an array of floats, we collect every odd element 6310 // together with its predecessor into one GPR. 6311 } else if (ArgOffset % PtrByteSize != 0) { 6312 SDValue Lo, Hi; 6313 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6314 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6315 if (!isLittleEndian) 6316 std::swap(Lo, Hi); 6317 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6318 6319 // The final element, if even, goes into the first half of a GPR. 6320 } else if (Flags.isInConsecutiveRegsLast()) { 6321 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6322 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6323 if (!isLittleEndian) 6324 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6325 DAG.getConstant(32, dl, MVT::i32)); 6326 6327 // Non-final even elements are skipped; they will be handled 6328 // together the with subsequent argument on the next go-around. 6329 } else 6330 ArgVal = SDValue(); 6331 6332 if (ArgVal.getNode()) 6333 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6334 } else { 6335 if (IsFastCall) 6336 ComputePtrOff(); 6337 6338 // Single-precision floating-point values are mapped to the 6339 // second (rightmost) word of the stack doubleword. 6340 if (Arg.getValueType() == MVT::f32 && 6341 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6342 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6343 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6344 } 6345 6346 assert(HasParameterArea && 6347 "Parameter area must exist to pass an argument in memory."); 6348 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6349 true, CFlags.IsTailCall, false, MemOpChains, 6350 TailCallArguments, dl); 6351 6352 NeededLoad = true; 6353 } 6354 // When passing an array of floats, the array occupies consecutive 6355 // space in the argument area; only round up to the next doubleword 6356 // at the end of the array. Otherwise, each float takes 8 bytes. 6357 if (!IsFastCall || NeededLoad) { 6358 ArgOffset += (Arg.getValueType() == MVT::f32 && 6359 Flags.isInConsecutiveRegs()) ? 4 : 8; 6360 if (Flags.isInConsecutiveRegsLast()) 6361 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6362 } 6363 break; 6364 } 6365 case MVT::v4f32: 6366 case MVT::v4i32: 6367 case MVT::v8i16: 6368 case MVT::v16i8: 6369 case MVT::v2f64: 6370 case MVT::v2i64: 6371 case MVT::v1i128: 6372 case MVT::f128: 6373 // These can be scalar arguments or elements of a vector array type 6374 // passed directly. The latter are used to implement ELFv2 homogenous 6375 // vector aggregates. 6376 6377 // For a varargs call, named arguments go into VRs or on the stack as 6378 // usual; unnamed arguments always go to the stack or the corresponding 6379 // GPRs when within range. For now, we always put the value in both 6380 // locations (or even all three). 6381 if (CFlags.IsVarArg) { 6382 assert(HasParameterArea && 6383 "Parameter area must exist if we have a varargs call."); 6384 // We could elide this store in the case where the object fits 6385 // entirely in R registers. Maybe later. 6386 SDValue Store = 6387 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6388 MemOpChains.push_back(Store); 6389 if (VR_idx != NumVRs) { 6390 SDValue Load = 6391 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6392 MemOpChains.push_back(Load.getValue(1)); 6393 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6394 } 6395 ArgOffset += 16; 6396 for (unsigned i=0; i<16; i+=PtrByteSize) { 6397 if (GPR_idx == NumGPRs) 6398 break; 6399 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6400 DAG.getConstant(i, dl, PtrVT)); 6401 SDValue Load = 6402 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6403 MemOpChains.push_back(Load.getValue(1)); 6404 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6405 } 6406 break; 6407 } 6408 6409 // Non-varargs Altivec params go into VRs or on the stack. 6410 if (VR_idx != NumVRs) { 6411 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6412 } else { 6413 if (IsFastCall) 6414 ComputePtrOff(); 6415 6416 assert(HasParameterArea && 6417 "Parameter area must exist to pass an argument in memory."); 6418 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6419 true, CFlags.IsTailCall, true, MemOpChains, 6420 TailCallArguments, dl); 6421 if (IsFastCall) 6422 ArgOffset += 16; 6423 } 6424 6425 if (!IsFastCall) 6426 ArgOffset += 16; 6427 break; 6428 } 6429 } 6430 6431 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6432 "mismatch in size of parameter area"); 6433 (void)NumBytesActuallyUsed; 6434 6435 if (!MemOpChains.empty()) 6436 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6437 6438 // Check if this is an indirect call (MTCTR/BCTRL). 6439 // See prepareDescriptorIndirectCall and buildCallOperands for more 6440 // information about calls through function pointers in the 64-bit SVR4 ABI. 6441 if (CFlags.IsIndirect) { 6442 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6443 // caller in the TOC save area. 6444 if (isTOCSaveRestoreRequired(Subtarget)) { 6445 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6446 // Load r2 into a virtual register and store it to the TOC save area. 6447 setUsesTOCBasePtr(DAG); 6448 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6449 // TOC save area offset. 6450 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6451 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6452 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6453 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6454 MachinePointerInfo::getStack( 6455 DAG.getMachineFunction(), TOCSaveOffset)); 6456 } 6457 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6458 // This does not mean the MTCTR instruction must use R12; it's easier 6459 // to model this as an extra parameter, so do that. 6460 if (isELFv2ABI && !CFlags.IsPatchPoint) 6461 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6462 } 6463 6464 // Build a sequence of copy-to-reg nodes chained together with token chain 6465 // and flag operands which copy the outgoing args into the appropriate regs. 6466 SDValue InFlag; 6467 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6468 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6469 RegsToPass[i].second, InFlag); 6470 InFlag = Chain.getValue(1); 6471 } 6472 6473 if (CFlags.IsTailCall && !IsSibCall) 6474 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6475 TailCallArguments); 6476 6477 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6478 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6479 } 6480 6481 // Returns true when the shadow of a general purpose argument register 6482 // in the parameter save area is aligned to at least 'RequiredAlign'. 6483 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6484 assert(RequiredAlign.value() <= 16 && 6485 "Required alignment greater than stack alignment."); 6486 switch (Reg) { 6487 default: 6488 report_fatal_error("called on invalid register."); 6489 case PPC::R5: 6490 case PPC::R9: 6491 case PPC::X3: 6492 case PPC::X5: 6493 case PPC::X7: 6494 case PPC::X9: 6495 // These registers are 16 byte aligned which is the most strict aligment 6496 // we can support. 6497 return true; 6498 case PPC::R3: 6499 case PPC::R7: 6500 case PPC::X4: 6501 case PPC::X6: 6502 case PPC::X8: 6503 case PPC::X10: 6504 // The shadow of these registers in the PSA is 8 byte aligned. 6505 return RequiredAlign <= 8; 6506 case PPC::R4: 6507 case PPC::R6: 6508 case PPC::R8: 6509 case PPC::R10: 6510 return RequiredAlign <= 4; 6511 } 6512 } 6513 6514 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6515 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6516 CCState &S) { 6517 AIXCCState &State = static_cast<AIXCCState &>(S); 6518 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6519 State.getMachineFunction().getSubtarget()); 6520 const bool IsPPC64 = Subtarget.isPPC64(); 6521 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6522 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6523 6524 if (ValVT == MVT::f128) 6525 report_fatal_error("f128 is unimplemented on AIX."); 6526 6527 if (ArgFlags.isNest()) 6528 report_fatal_error("Nest arguments are unimplemented."); 6529 6530 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6531 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6532 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6533 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6534 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6535 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6536 6537 static const MCPhysReg VR[] = {// Vector registers. 6538 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6539 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6540 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6541 6542 if (ArgFlags.isByVal()) { 6543 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6544 report_fatal_error("Pass-by-value arguments with alignment greater than " 6545 "register width are not supported."); 6546 6547 const unsigned ByValSize = ArgFlags.getByValSize(); 6548 6549 // An empty aggregate parameter takes up no storage and no registers, 6550 // but needs a MemLoc for a stack slot for the formal arguments side. 6551 if (ByValSize == 0) { 6552 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6553 State.getNextStackOffset(), RegVT, 6554 LocInfo)); 6555 return false; 6556 } 6557 6558 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6559 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6560 for (const unsigned E = Offset + StackSize; Offset < E; 6561 Offset += PtrAlign.value()) { 6562 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6563 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6564 else { 6565 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6566 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6567 LocInfo)); 6568 break; 6569 } 6570 } 6571 return false; 6572 } 6573 6574 // Arguments always reserve parameter save area. 6575 switch (ValVT.SimpleTy) { 6576 default: 6577 report_fatal_error("Unhandled value type for argument."); 6578 case MVT::i64: 6579 // i64 arguments should have been split to i32 for PPC32. 6580 assert(IsPPC64 && "PPC32 should have split i64 values."); 6581 LLVM_FALLTHROUGH; 6582 case MVT::i1: 6583 case MVT::i32: { 6584 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6585 // AIX integer arguments are always passed in register width. 6586 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6587 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6588 : CCValAssign::LocInfo::ZExt; 6589 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6590 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6591 else 6592 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6593 6594 return false; 6595 } 6596 case MVT::f32: 6597 case MVT::f64: { 6598 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6599 const unsigned StoreSize = LocVT.getStoreSize(); 6600 // Floats are always 4-byte aligned in the PSA on AIX. 6601 // This includes f64 in 64-bit mode for ABI compatibility. 6602 const unsigned Offset = 6603 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6604 unsigned FReg = State.AllocateReg(FPR); 6605 if (FReg) 6606 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6607 6608 // Reserve and initialize GPRs or initialize the PSA as required. 6609 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6610 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6611 assert(FReg && "An FPR should be available when a GPR is reserved."); 6612 if (State.isVarArg()) { 6613 // Successfully reserved GPRs are only initialized for vararg calls. 6614 // Custom handling is required for: 6615 // f64 in PPC32 needs to be split into 2 GPRs. 6616 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6617 State.addLoc( 6618 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6619 } 6620 } else { 6621 // If there are insufficient GPRs, the PSA needs to be initialized. 6622 // Initialization occurs even if an FPR was initialized for 6623 // compatibility with the AIX XL compiler. The full memory for the 6624 // argument will be initialized even if a prior word is saved in GPR. 6625 // A custom memLoc is used when the argument also passes in FPR so 6626 // that the callee handling can skip over it easily. 6627 State.addLoc( 6628 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6629 LocInfo) 6630 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6631 break; 6632 } 6633 } 6634 6635 return false; 6636 } 6637 case MVT::v4f32: 6638 case MVT::v4i32: 6639 case MVT::v8i16: 6640 case MVT::v16i8: 6641 case MVT::v2i64: 6642 case MVT::v2f64: 6643 case MVT::v1i128: { 6644 const unsigned VecSize = 16; 6645 const Align VecAlign(VecSize); 6646 6647 if (!State.isVarArg()) { 6648 // If there are vector registers remaining we don't consume any stack 6649 // space. 6650 if (unsigned VReg = State.AllocateReg(VR)) { 6651 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6652 return false; 6653 } 6654 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6655 // might be allocated in the portion of the PSA that is shadowed by the 6656 // GPRs. 6657 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6658 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6659 return false; 6660 } 6661 6662 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6663 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6664 6665 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6666 // Burn any underaligned registers and their shadowed stack space until 6667 // we reach the required alignment. 6668 while (NextRegIndex != GPRs.size() && 6669 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6670 // Shadow allocate register and its stack shadow. 6671 unsigned Reg = State.AllocateReg(GPRs); 6672 State.AllocateStack(PtrSize, PtrAlign); 6673 assert(Reg && "Allocating register unexpectedly failed."); 6674 (void)Reg; 6675 NextRegIndex = State.getFirstUnallocated(GPRs); 6676 } 6677 6678 // Vectors that are passed as fixed arguments are handled differently. 6679 // They are passed in VRs if any are available (unlike arguments passed 6680 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6681 // functions) 6682 if (State.isFixed(ValNo)) { 6683 if (unsigned VReg = State.AllocateReg(VR)) { 6684 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6685 // Shadow allocate GPRs and stack space even though we pass in a VR. 6686 for (unsigned I = 0; I != VecSize; I += PtrSize) 6687 State.AllocateReg(GPRs); 6688 State.AllocateStack(VecSize, VecAlign); 6689 return false; 6690 } 6691 // No vector registers remain so pass on the stack. 6692 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6693 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6694 return false; 6695 } 6696 6697 // If all GPRS are consumed then we pass the argument fully on the stack. 6698 if (NextRegIndex == GPRs.size()) { 6699 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6700 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6701 return false; 6702 } 6703 6704 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6705 // half of the argument, and then need to pass the remaining half on the 6706 // stack. 6707 if (GPRs[NextRegIndex] == PPC::R9) { 6708 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6709 State.addLoc( 6710 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6711 6712 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6713 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6714 assert(FirstReg && SecondReg && 6715 "Allocating R9 or R10 unexpectedly failed."); 6716 State.addLoc( 6717 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6718 State.addLoc( 6719 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6720 return false; 6721 } 6722 6723 // We have enough GPRs to fully pass the vector argument, and we have 6724 // already consumed any underaligned registers. Start with the custom 6725 // MemLoc and then the custom RegLocs. 6726 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6727 State.addLoc( 6728 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6729 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6730 const unsigned Reg = State.AllocateReg(GPRs); 6731 assert(Reg && "Failed to allocated register for vararg vector argument"); 6732 State.addLoc( 6733 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6734 } 6735 return false; 6736 } 6737 } 6738 return true; 6739 } 6740 6741 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6742 bool IsPPC64) { 6743 assert((IsPPC64 || SVT != MVT::i64) && 6744 "i64 should have been split for 32-bit codegen."); 6745 6746 switch (SVT) { 6747 default: 6748 report_fatal_error("Unexpected value type for formal argument"); 6749 case MVT::i1: 6750 case MVT::i32: 6751 case MVT::i64: 6752 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6753 case MVT::f32: 6754 return &PPC::F4RCRegClass; 6755 case MVT::f64: 6756 return &PPC::F8RCRegClass; 6757 case MVT::v4f32: 6758 case MVT::v4i32: 6759 case MVT::v8i16: 6760 case MVT::v16i8: 6761 case MVT::v2i64: 6762 case MVT::v2f64: 6763 case MVT::v1i128: 6764 return &PPC::VRRCRegClass; 6765 } 6766 } 6767 6768 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6769 SelectionDAG &DAG, SDValue ArgValue, 6770 MVT LocVT, const SDLoc &dl) { 6771 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6772 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6773 6774 if (Flags.isSExt()) 6775 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6776 DAG.getValueType(ValVT)); 6777 else if (Flags.isZExt()) 6778 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6779 DAG.getValueType(ValVT)); 6780 6781 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6782 } 6783 6784 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6785 const unsigned LASize = FL->getLinkageSize(); 6786 6787 if (PPC::GPRCRegClass.contains(Reg)) { 6788 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6789 "Reg must be a valid argument register!"); 6790 return LASize + 4 * (Reg - PPC::R3); 6791 } 6792 6793 if (PPC::G8RCRegClass.contains(Reg)) { 6794 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6795 "Reg must be a valid argument register!"); 6796 return LASize + 8 * (Reg - PPC::X3); 6797 } 6798 6799 llvm_unreachable("Only general purpose registers expected."); 6800 } 6801 6802 // AIX ABI Stack Frame Layout: 6803 // 6804 // Low Memory +--------------------------------------------+ 6805 // SP +---> | Back chain | ---+ 6806 // | +--------------------------------------------+ | 6807 // | | Saved Condition Register | | 6808 // | +--------------------------------------------+ | 6809 // | | Saved Linkage Register | | 6810 // | +--------------------------------------------+ | Linkage Area 6811 // | | Reserved for compilers | | 6812 // | +--------------------------------------------+ | 6813 // | | Reserved for binders | | 6814 // | +--------------------------------------------+ | 6815 // | | Saved TOC pointer | ---+ 6816 // | +--------------------------------------------+ 6817 // | | Parameter save area | 6818 // | +--------------------------------------------+ 6819 // | | Alloca space | 6820 // | +--------------------------------------------+ 6821 // | | Local variable space | 6822 // | +--------------------------------------------+ 6823 // | | Float/int conversion temporary | 6824 // | +--------------------------------------------+ 6825 // | | Save area for AltiVec registers | 6826 // | +--------------------------------------------+ 6827 // | | AltiVec alignment padding | 6828 // | +--------------------------------------------+ 6829 // | | Save area for VRSAVE register | 6830 // | +--------------------------------------------+ 6831 // | | Save area for General Purpose registers | 6832 // | +--------------------------------------------+ 6833 // | | Save area for Floating Point registers | 6834 // | +--------------------------------------------+ 6835 // +---- | Back chain | 6836 // High Memory +--------------------------------------------+ 6837 // 6838 // Specifications: 6839 // AIX 7.2 Assembler Language Reference 6840 // Subroutine linkage convention 6841 6842 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6843 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6844 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6845 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6846 6847 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6848 CallConv == CallingConv::Fast) && 6849 "Unexpected calling convention!"); 6850 6851 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6852 report_fatal_error("Tail call support is unimplemented on AIX."); 6853 6854 if (useSoftFloat()) 6855 report_fatal_error("Soft float support is unimplemented on AIX."); 6856 6857 const PPCSubtarget &Subtarget = 6858 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6859 6860 const bool IsPPC64 = Subtarget.isPPC64(); 6861 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6862 6863 // Assign locations to all of the incoming arguments. 6864 SmallVector<CCValAssign, 16> ArgLocs; 6865 MachineFunction &MF = DAG.getMachineFunction(); 6866 MachineFrameInfo &MFI = MF.getFrameInfo(); 6867 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6868 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6869 6870 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6871 // Reserve space for the linkage area on the stack. 6872 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6873 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6874 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6875 6876 SmallVector<SDValue, 8> MemOps; 6877 6878 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6879 CCValAssign &VA = ArgLocs[I++]; 6880 MVT LocVT = VA.getLocVT(); 6881 MVT ValVT = VA.getValVT(); 6882 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6883 // For compatibility with the AIX XL compiler, the float args in the 6884 // parameter save area are initialized even if the argument is available 6885 // in register. The caller is required to initialize both the register 6886 // and memory, however, the callee can choose to expect it in either. 6887 // The memloc is dismissed here because the argument is retrieved from 6888 // the register. 6889 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6890 continue; 6891 6892 auto HandleMemLoc = [&]() { 6893 const unsigned LocSize = LocVT.getStoreSize(); 6894 const unsigned ValSize = ValVT.getStoreSize(); 6895 assert((ValSize <= LocSize) && 6896 "Object size is larger than size of MemLoc"); 6897 int CurArgOffset = VA.getLocMemOffset(); 6898 // Objects are right-justified because AIX is big-endian. 6899 if (LocSize > ValSize) 6900 CurArgOffset += LocSize - ValSize; 6901 // Potential tail calls could cause overwriting of argument stack slots. 6902 const bool IsImmutable = 6903 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6904 (CallConv == CallingConv::Fast)); 6905 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6906 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6907 SDValue ArgValue = 6908 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6909 InVals.push_back(ArgValue); 6910 }; 6911 6912 // Vector arguments to VaArg functions are passed both on the stack, and 6913 // in any available GPRs. Load the value from the stack and add the GPRs 6914 // as live ins. 6915 if (VA.isMemLoc() && VA.needsCustom()) { 6916 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 6917 assert(isVarArg && "Only use custom memloc for vararg."); 6918 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 6919 // matching custom RegLocs. 6920 const unsigned OriginalValNo = VA.getValNo(); 6921 (void)OriginalValNo; 6922 6923 auto HandleCustomVecRegLoc = [&]() { 6924 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 6925 "Missing custom RegLoc."); 6926 VA = ArgLocs[I++]; 6927 assert(VA.getValVT().isVector() && 6928 "Unexpected Val type for custom RegLoc."); 6929 assert(VA.getValNo() == OriginalValNo && 6930 "ValNo mismatch between custom MemLoc and RegLoc."); 6931 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 6932 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6933 }; 6934 6935 HandleMemLoc(); 6936 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 6937 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 6938 // R10. 6939 HandleCustomVecRegLoc(); 6940 HandleCustomVecRegLoc(); 6941 6942 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 6943 // we passed the vector in R5, R6, R7 and R8. 6944 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 6945 assert(!IsPPC64 && 6946 "Only 2 custom RegLocs expected for 64-bit codegen."); 6947 HandleCustomVecRegLoc(); 6948 HandleCustomVecRegLoc(); 6949 } 6950 6951 continue; 6952 } 6953 6954 if (VA.isRegLoc()) { 6955 if (VA.getValVT().isScalarInteger()) 6956 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 6957 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) { 6958 switch (VA.getValVT().SimpleTy) { 6959 default: 6960 report_fatal_error("Unhandled value type for argument."); 6961 case MVT::f32: 6962 FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint); 6963 break; 6964 case MVT::f64: 6965 FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint); 6966 break; 6967 } 6968 } else if (VA.getValVT().isVector()) { 6969 switch (VA.getValVT().SimpleTy) { 6970 default: 6971 report_fatal_error("Unhandled value type for argument."); 6972 case MVT::v16i8: 6973 FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar); 6974 break; 6975 case MVT::v8i16: 6976 FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort); 6977 break; 6978 case MVT::v4i32: 6979 case MVT::v2i64: 6980 case MVT::v1i128: 6981 FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt); 6982 break; 6983 case MVT::v4f32: 6984 case MVT::v2f64: 6985 FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat); 6986 break; 6987 } 6988 } 6989 } 6990 6991 if (Flags.isByVal() && VA.isMemLoc()) { 6992 const unsigned Size = 6993 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 6994 PtrByteSize); 6995 const int FI = MF.getFrameInfo().CreateFixedObject( 6996 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 6997 /* IsAliased */ true); 6998 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6999 InVals.push_back(FIN); 7000 7001 continue; 7002 } 7003 7004 if (Flags.isByVal()) { 7005 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7006 7007 const MCPhysReg ArgReg = VA.getLocReg(); 7008 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7009 7010 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7011 report_fatal_error("Over aligned byvals not supported yet."); 7012 7013 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7014 const int FI = MF.getFrameInfo().CreateFixedObject( 7015 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7016 /* IsAliased */ true); 7017 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7018 InVals.push_back(FIN); 7019 7020 // Add live ins for all the RegLocs for the same ByVal. 7021 const TargetRegisterClass *RegClass = 7022 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7023 7024 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7025 unsigned Offset) { 7026 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7027 // Since the callers side has left justified the aggregate in the 7028 // register, we can simply store the entire register into the stack 7029 // slot. 7030 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7031 // The store to the fixedstack object is needed becuase accessing a 7032 // field of the ByVal will use a gep and load. Ideally we will optimize 7033 // to extracting the value from the register directly, and elide the 7034 // stores when the arguments address is not taken, but that will need to 7035 // be future work. 7036 SDValue Store = DAG.getStore( 7037 CopyFrom.getValue(1), dl, CopyFrom, 7038 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7039 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7040 7041 MemOps.push_back(Store); 7042 }; 7043 7044 unsigned Offset = 0; 7045 HandleRegLoc(VA.getLocReg(), Offset); 7046 Offset += PtrByteSize; 7047 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7048 Offset += PtrByteSize) { 7049 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7050 "RegLocs should be for ByVal argument."); 7051 7052 const CCValAssign RL = ArgLocs[I++]; 7053 HandleRegLoc(RL.getLocReg(), Offset); 7054 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7055 } 7056 7057 if (Offset != StackSize) { 7058 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7059 "Expected MemLoc for remaining bytes."); 7060 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7061 // Consume the MemLoc.The InVal has already been emitted, so nothing 7062 // more needs to be done. 7063 ++I; 7064 } 7065 7066 continue; 7067 } 7068 7069 if (VA.isRegLoc() && !VA.needsCustom()) { 7070 MVT::SimpleValueType SVT = ValVT.SimpleTy; 7071 unsigned VReg = 7072 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7073 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7074 if (ValVT.isScalarInteger() && 7075 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7076 ArgValue = 7077 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7078 } 7079 InVals.push_back(ArgValue); 7080 continue; 7081 } 7082 if (VA.isMemLoc()) { 7083 HandleMemLoc(); 7084 continue; 7085 } 7086 } 7087 7088 // On AIX a minimum of 8 words is saved to the parameter save area. 7089 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7090 // Area that is at least reserved in the caller of this function. 7091 unsigned CallerReservedArea = 7092 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7093 7094 // Set the size that is at least reserved in caller of this function. Tail 7095 // call optimized function's reserved stack space needs to be aligned so 7096 // that taking the difference between two stack areas will result in an 7097 // aligned stack. 7098 CallerReservedArea = 7099 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7100 FuncInfo->setMinReservedArea(CallerReservedArea); 7101 7102 if (isVarArg) { 7103 FuncInfo->setVarArgsFrameIndex( 7104 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7105 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7106 7107 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7108 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7109 7110 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7111 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7112 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7113 7114 // The fixed integer arguments of a variadic function are stored to the 7115 // VarArgsFrameIndex on the stack so that they may be loaded by 7116 // dereferencing the result of va_next. 7117 for (unsigned GPRIndex = 7118 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7119 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7120 7121 const unsigned VReg = 7122 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7123 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7124 7125 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7126 SDValue Store = 7127 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7128 MemOps.push_back(Store); 7129 // Increment the address for the next argument to store. 7130 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7131 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7132 } 7133 } 7134 7135 if (!MemOps.empty()) 7136 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7137 7138 return Chain; 7139 } 7140 7141 SDValue PPCTargetLowering::LowerCall_AIX( 7142 SDValue Chain, SDValue Callee, CallFlags CFlags, 7143 const SmallVectorImpl<ISD::OutputArg> &Outs, 7144 const SmallVectorImpl<SDValue> &OutVals, 7145 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7146 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7147 const CallBase *CB) const { 7148 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7149 // AIX ABI stack frame layout. 7150 7151 assert((CFlags.CallConv == CallingConv::C || 7152 CFlags.CallConv == CallingConv::Cold || 7153 CFlags.CallConv == CallingConv::Fast) && 7154 "Unexpected calling convention!"); 7155 7156 if (CFlags.IsPatchPoint) 7157 report_fatal_error("This call type is unimplemented on AIX."); 7158 7159 const PPCSubtarget& Subtarget = 7160 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7161 7162 MachineFunction &MF = DAG.getMachineFunction(); 7163 SmallVector<CCValAssign, 16> ArgLocs; 7164 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7165 *DAG.getContext()); 7166 7167 // Reserve space for the linkage save area (LSA) on the stack. 7168 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7169 // [SP][CR][LR][2 x reserved][TOC]. 7170 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7171 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7172 const bool IsPPC64 = Subtarget.isPPC64(); 7173 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7174 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7175 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7176 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7177 7178 // The prolog code of the callee may store up to 8 GPR argument registers to 7179 // the stack, allowing va_start to index over them in memory if the callee 7180 // is variadic. 7181 // Because we cannot tell if this is needed on the caller side, we have to 7182 // conservatively assume that it is needed. As such, make sure we have at 7183 // least enough stack space for the caller to store the 8 GPRs. 7184 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7185 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7186 CCInfo.getNextStackOffset()); 7187 7188 // Adjust the stack pointer for the new arguments... 7189 // These operations are automatically eliminated by the prolog/epilog pass. 7190 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7191 SDValue CallSeqStart = Chain; 7192 7193 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7194 SmallVector<SDValue, 8> MemOpChains; 7195 7196 // Set up a copy of the stack pointer for loading and storing any 7197 // arguments that may not fit in the registers available for argument 7198 // passing. 7199 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7200 : DAG.getRegister(PPC::R1, MVT::i32); 7201 7202 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7203 const unsigned ValNo = ArgLocs[I].getValNo(); 7204 SDValue Arg = OutVals[ValNo]; 7205 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7206 7207 if (Flags.isByVal()) { 7208 const unsigned ByValSize = Flags.getByValSize(); 7209 7210 // Nothing to do for zero-sized ByVals on the caller side. 7211 if (!ByValSize) { 7212 ++I; 7213 continue; 7214 } 7215 7216 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7217 return DAG.getExtLoad( 7218 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7219 (LoadOffset != 0) 7220 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7221 : Arg, 7222 MachinePointerInfo(), VT); 7223 }; 7224 7225 unsigned LoadOffset = 0; 7226 7227 // Initialize registers, which are fully occupied by the by-val argument. 7228 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7229 SDValue Load = GetLoad(PtrVT, LoadOffset); 7230 MemOpChains.push_back(Load.getValue(1)); 7231 LoadOffset += PtrByteSize; 7232 const CCValAssign &ByValVA = ArgLocs[I++]; 7233 assert(ByValVA.getValNo() == ValNo && 7234 "Unexpected location for pass-by-value argument."); 7235 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7236 } 7237 7238 if (LoadOffset == ByValSize) 7239 continue; 7240 7241 // There must be one more loc to handle the remainder. 7242 assert(ArgLocs[I].getValNo() == ValNo && 7243 "Expected additional location for by-value argument."); 7244 7245 if (ArgLocs[I].isMemLoc()) { 7246 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7247 const CCValAssign &ByValVA = ArgLocs[I++]; 7248 ISD::ArgFlagsTy MemcpyFlags = Flags; 7249 // Only memcpy the bytes that don't pass in register. 7250 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7251 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7252 (LoadOffset != 0) 7253 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7254 : Arg, 7255 DAG.getObjectPtrOffset(dl, StackPtr, 7256 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7257 CallSeqStart, MemcpyFlags, DAG, dl); 7258 continue; 7259 } 7260 7261 // Initialize the final register residue. 7262 // Any residue that occupies the final by-val arg register must be 7263 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7264 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7265 // 2 and 1 byte loads. 7266 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7267 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7268 "Unexpected register residue for by-value argument."); 7269 SDValue ResidueVal; 7270 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7271 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7272 const MVT VT = 7273 N == 1 ? MVT::i8 7274 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7275 SDValue Load = GetLoad(VT, LoadOffset); 7276 MemOpChains.push_back(Load.getValue(1)); 7277 LoadOffset += N; 7278 Bytes += N; 7279 7280 // By-val arguments are passed left-justfied in register. 7281 // Every load here needs to be shifted, otherwise a full register load 7282 // should have been used. 7283 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7284 "Unexpected load emitted during handling of pass-by-value " 7285 "argument."); 7286 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7287 EVT ShiftAmountTy = 7288 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7289 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7290 SDValue ShiftedLoad = 7291 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7292 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7293 ShiftedLoad) 7294 : ShiftedLoad; 7295 } 7296 7297 const CCValAssign &ByValVA = ArgLocs[I++]; 7298 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7299 continue; 7300 } 7301 7302 CCValAssign &VA = ArgLocs[I++]; 7303 const MVT LocVT = VA.getLocVT(); 7304 const MVT ValVT = VA.getValVT(); 7305 7306 switch (VA.getLocInfo()) { 7307 default: 7308 report_fatal_error("Unexpected argument extension type."); 7309 case CCValAssign::Full: 7310 break; 7311 case CCValAssign::ZExt: 7312 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7313 break; 7314 case CCValAssign::SExt: 7315 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7316 break; 7317 } 7318 7319 if (VA.isRegLoc() && !VA.needsCustom()) { 7320 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7321 continue; 7322 } 7323 7324 // Vector arguments passed to VarArg functions need custom handling when 7325 // they are passed (at least partially) in GPRs. 7326 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7327 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7328 // Store value to its stack slot. 7329 SDValue PtrOff = 7330 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7331 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7332 SDValue Store = 7333 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7334 MemOpChains.push_back(Store); 7335 const unsigned OriginalValNo = VA.getValNo(); 7336 // Then load the GPRs from the stack 7337 unsigned LoadOffset = 0; 7338 auto HandleCustomVecRegLoc = [&]() { 7339 assert(I != E && "Unexpected end of CCvalAssigns."); 7340 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7341 "Expected custom RegLoc."); 7342 CCValAssign RegVA = ArgLocs[I++]; 7343 assert(RegVA.getValNo() == OriginalValNo && 7344 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7345 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7346 DAG.getConstant(LoadOffset, dl, PtrVT)); 7347 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7348 MemOpChains.push_back(Load.getValue(1)); 7349 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7350 LoadOffset += PtrByteSize; 7351 }; 7352 7353 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7354 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7355 // R10. 7356 HandleCustomVecRegLoc(); 7357 HandleCustomVecRegLoc(); 7358 7359 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7360 ArgLocs[I].getValNo() == OriginalValNo) { 7361 assert(!IsPPC64 && 7362 "Only 2 custom RegLocs expected for 64-bit codegen."); 7363 HandleCustomVecRegLoc(); 7364 HandleCustomVecRegLoc(); 7365 } 7366 7367 continue; 7368 } 7369 7370 if (VA.isMemLoc()) { 7371 SDValue PtrOff = 7372 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7373 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7374 MemOpChains.push_back( 7375 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7376 7377 continue; 7378 } 7379 7380 if (!ValVT.isFloatingPoint()) 7381 report_fatal_error( 7382 "Unexpected register handling for calling convention."); 7383 7384 // Custom handling is used for GPR initializations for vararg float 7385 // arguments. 7386 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7387 LocVT.isInteger() && 7388 "Custom register handling only expected for VarArg."); 7389 7390 SDValue ArgAsInt = 7391 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7392 7393 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7394 // f32 in 32-bit GPR 7395 // f64 in 64-bit GPR 7396 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7397 else if (Arg.getValueType().getFixedSizeInBits() < 7398 LocVT.getFixedSizeInBits()) 7399 // f32 in 64-bit GPR. 7400 RegsToPass.push_back(std::make_pair( 7401 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7402 else { 7403 // f64 in two 32-bit GPRs 7404 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7405 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7406 "Unexpected custom register for argument!"); 7407 CCValAssign &GPR1 = VA; 7408 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7409 DAG.getConstant(32, dl, MVT::i8)); 7410 RegsToPass.push_back(std::make_pair( 7411 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7412 7413 if (I != E) { 7414 // If only 1 GPR was available, there will only be one custom GPR and 7415 // the argument will also pass in memory. 7416 CCValAssign &PeekArg = ArgLocs[I]; 7417 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7418 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7419 CCValAssign &GPR2 = ArgLocs[I++]; 7420 RegsToPass.push_back(std::make_pair( 7421 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7422 } 7423 } 7424 } 7425 } 7426 7427 if (!MemOpChains.empty()) 7428 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7429 7430 // For indirect calls, we need to save the TOC base to the stack for 7431 // restoration after the call. 7432 if (CFlags.IsIndirect) { 7433 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7434 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7435 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7436 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7437 const unsigned TOCSaveOffset = 7438 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7439 7440 setUsesTOCBasePtr(DAG); 7441 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7442 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7443 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7444 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7445 Chain = DAG.getStore( 7446 Val.getValue(1), dl, Val, AddPtr, 7447 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7448 } 7449 7450 // Build a sequence of copy-to-reg nodes chained together with token chain 7451 // and flag operands which copy the outgoing args into the appropriate regs. 7452 SDValue InFlag; 7453 for (auto Reg : RegsToPass) { 7454 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7455 InFlag = Chain.getValue(1); 7456 } 7457 7458 const int SPDiff = 0; 7459 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7460 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7461 } 7462 7463 bool 7464 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7465 MachineFunction &MF, bool isVarArg, 7466 const SmallVectorImpl<ISD::OutputArg> &Outs, 7467 LLVMContext &Context) const { 7468 SmallVector<CCValAssign, 16> RVLocs; 7469 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7470 return CCInfo.CheckReturn( 7471 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7472 ? RetCC_PPC_Cold 7473 : RetCC_PPC); 7474 } 7475 7476 SDValue 7477 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7478 bool isVarArg, 7479 const SmallVectorImpl<ISD::OutputArg> &Outs, 7480 const SmallVectorImpl<SDValue> &OutVals, 7481 const SDLoc &dl, SelectionDAG &DAG) const { 7482 SmallVector<CCValAssign, 16> RVLocs; 7483 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7484 *DAG.getContext()); 7485 CCInfo.AnalyzeReturn(Outs, 7486 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7487 ? RetCC_PPC_Cold 7488 : RetCC_PPC); 7489 7490 SDValue Flag; 7491 SmallVector<SDValue, 4> RetOps(1, Chain); 7492 7493 // Copy the result values into the output registers. 7494 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7495 CCValAssign &VA = RVLocs[i]; 7496 assert(VA.isRegLoc() && "Can only return in registers!"); 7497 7498 SDValue Arg = OutVals[RealResIdx]; 7499 7500 switch (VA.getLocInfo()) { 7501 default: llvm_unreachable("Unknown loc info!"); 7502 case CCValAssign::Full: break; 7503 case CCValAssign::AExt: 7504 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7505 break; 7506 case CCValAssign::ZExt: 7507 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7508 break; 7509 case CCValAssign::SExt: 7510 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7511 break; 7512 } 7513 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7514 bool isLittleEndian = Subtarget.isLittleEndian(); 7515 // Legalize ret f64 -> ret 2 x i32. 7516 SDValue SVal = 7517 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7518 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7519 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7520 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7521 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7522 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7523 Flag = Chain.getValue(1); 7524 VA = RVLocs[++i]; // skip ahead to next loc 7525 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7526 } else 7527 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7528 Flag = Chain.getValue(1); 7529 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7530 } 7531 7532 RetOps[0] = Chain; // Update chain. 7533 7534 // Add the flag if we have it. 7535 if (Flag.getNode()) 7536 RetOps.push_back(Flag); 7537 7538 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7539 } 7540 7541 SDValue 7542 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7543 SelectionDAG &DAG) const { 7544 SDLoc dl(Op); 7545 7546 // Get the correct type for integers. 7547 EVT IntVT = Op.getValueType(); 7548 7549 // Get the inputs. 7550 SDValue Chain = Op.getOperand(0); 7551 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7552 // Build a DYNAREAOFFSET node. 7553 SDValue Ops[2] = {Chain, FPSIdx}; 7554 SDVTList VTs = DAG.getVTList(IntVT); 7555 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7556 } 7557 7558 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7559 SelectionDAG &DAG) const { 7560 // When we pop the dynamic allocation we need to restore the SP link. 7561 SDLoc dl(Op); 7562 7563 // Get the correct type for pointers. 7564 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7565 7566 // Construct the stack pointer operand. 7567 bool isPPC64 = Subtarget.isPPC64(); 7568 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7569 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7570 7571 // Get the operands for the STACKRESTORE. 7572 SDValue Chain = Op.getOperand(0); 7573 SDValue SaveSP = Op.getOperand(1); 7574 7575 // Load the old link SP. 7576 SDValue LoadLinkSP = 7577 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7578 7579 // Restore the stack pointer. 7580 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7581 7582 // Store the old link SP. 7583 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7584 } 7585 7586 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7587 MachineFunction &MF = DAG.getMachineFunction(); 7588 bool isPPC64 = Subtarget.isPPC64(); 7589 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7590 7591 // Get current frame pointer save index. The users of this index will be 7592 // primarily DYNALLOC instructions. 7593 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7594 int RASI = FI->getReturnAddrSaveIndex(); 7595 7596 // If the frame pointer save index hasn't been defined yet. 7597 if (!RASI) { 7598 // Find out what the fix offset of the frame pointer save area. 7599 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7600 // Allocate the frame index for frame pointer save area. 7601 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7602 // Save the result. 7603 FI->setReturnAddrSaveIndex(RASI); 7604 } 7605 return DAG.getFrameIndex(RASI, PtrVT); 7606 } 7607 7608 SDValue 7609 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7610 MachineFunction &MF = DAG.getMachineFunction(); 7611 bool isPPC64 = Subtarget.isPPC64(); 7612 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7613 7614 // Get current frame pointer save index. The users of this index will be 7615 // primarily DYNALLOC instructions. 7616 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7617 int FPSI = FI->getFramePointerSaveIndex(); 7618 7619 // If the frame pointer save index hasn't been defined yet. 7620 if (!FPSI) { 7621 // Find out what the fix offset of the frame pointer save area. 7622 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7623 // Allocate the frame index for frame pointer save area. 7624 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7625 // Save the result. 7626 FI->setFramePointerSaveIndex(FPSI); 7627 } 7628 return DAG.getFrameIndex(FPSI, PtrVT); 7629 } 7630 7631 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7632 SelectionDAG &DAG) const { 7633 MachineFunction &MF = DAG.getMachineFunction(); 7634 // Get the inputs. 7635 SDValue Chain = Op.getOperand(0); 7636 SDValue Size = Op.getOperand(1); 7637 SDLoc dl(Op); 7638 7639 // Get the correct type for pointers. 7640 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7641 // Negate the size. 7642 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7643 DAG.getConstant(0, dl, PtrVT), Size); 7644 // Construct a node for the frame pointer save index. 7645 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7646 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7647 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7648 if (hasInlineStackProbe(MF)) 7649 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7650 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7651 } 7652 7653 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7654 SelectionDAG &DAG) const { 7655 MachineFunction &MF = DAG.getMachineFunction(); 7656 7657 bool isPPC64 = Subtarget.isPPC64(); 7658 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7659 7660 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7661 return DAG.getFrameIndex(FI, PtrVT); 7662 } 7663 7664 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7665 SelectionDAG &DAG) const { 7666 SDLoc DL(Op); 7667 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7668 DAG.getVTList(MVT::i32, MVT::Other), 7669 Op.getOperand(0), Op.getOperand(1)); 7670 } 7671 7672 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7673 SelectionDAG &DAG) const { 7674 SDLoc DL(Op); 7675 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7676 Op.getOperand(0), Op.getOperand(1)); 7677 } 7678 7679 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7680 if (Op.getValueType().isVector()) 7681 return LowerVectorLoad(Op, DAG); 7682 7683 assert(Op.getValueType() == MVT::i1 && 7684 "Custom lowering only for i1 loads"); 7685 7686 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7687 7688 SDLoc dl(Op); 7689 LoadSDNode *LD = cast<LoadSDNode>(Op); 7690 7691 SDValue Chain = LD->getChain(); 7692 SDValue BasePtr = LD->getBasePtr(); 7693 MachineMemOperand *MMO = LD->getMemOperand(); 7694 7695 SDValue NewLD = 7696 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7697 BasePtr, MVT::i8, MMO); 7698 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7699 7700 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7701 return DAG.getMergeValues(Ops, dl); 7702 } 7703 7704 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7705 if (Op.getOperand(1).getValueType().isVector()) 7706 return LowerVectorStore(Op, DAG); 7707 7708 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7709 "Custom lowering only for i1 stores"); 7710 7711 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7712 7713 SDLoc dl(Op); 7714 StoreSDNode *ST = cast<StoreSDNode>(Op); 7715 7716 SDValue Chain = ST->getChain(); 7717 SDValue BasePtr = ST->getBasePtr(); 7718 SDValue Value = ST->getValue(); 7719 MachineMemOperand *MMO = ST->getMemOperand(); 7720 7721 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7722 Value); 7723 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7724 } 7725 7726 // FIXME: Remove this once the ANDI glue bug is fixed: 7727 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7728 assert(Op.getValueType() == MVT::i1 && 7729 "Custom lowering only for i1 results"); 7730 7731 SDLoc DL(Op); 7732 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7733 } 7734 7735 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7736 SelectionDAG &DAG) const { 7737 7738 // Implements a vector truncate that fits in a vector register as a shuffle. 7739 // We want to legalize vector truncates down to where the source fits in 7740 // a vector register (and target is therefore smaller than vector register 7741 // size). At that point legalization will try to custom lower the sub-legal 7742 // result and get here - where we can contain the truncate as a single target 7743 // operation. 7744 7745 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7746 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7747 // 7748 // We will implement it for big-endian ordering as this (where x denotes 7749 // undefined): 7750 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7751 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7752 // 7753 // The same operation in little-endian ordering will be: 7754 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7755 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7756 7757 EVT TrgVT = Op.getValueType(); 7758 assert(TrgVT.isVector() && "Vector type expected."); 7759 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7760 EVT EltVT = TrgVT.getVectorElementType(); 7761 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7762 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7763 !isPowerOf2_32(EltVT.getSizeInBits())) 7764 return SDValue(); 7765 7766 SDValue N1 = Op.getOperand(0); 7767 EVT SrcVT = N1.getValueType(); 7768 unsigned SrcSize = SrcVT.getSizeInBits(); 7769 if (SrcSize > 256 || 7770 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7771 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7772 return SDValue(); 7773 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7774 return SDValue(); 7775 7776 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7777 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7778 7779 SDLoc DL(Op); 7780 SDValue Op1, Op2; 7781 if (SrcSize == 256) { 7782 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7783 EVT SplitVT = 7784 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7785 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7786 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7787 DAG.getConstant(0, DL, VecIdxTy)); 7788 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7789 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7790 } 7791 else { 7792 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7793 Op2 = DAG.getUNDEF(WideVT); 7794 } 7795 7796 // First list the elements we want to keep. 7797 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7798 SmallVector<int, 16> ShuffV; 7799 if (Subtarget.isLittleEndian()) 7800 for (unsigned i = 0; i < TrgNumElts; ++i) 7801 ShuffV.push_back(i * SizeMult); 7802 else 7803 for (unsigned i = 1; i <= TrgNumElts; ++i) 7804 ShuffV.push_back(i * SizeMult - 1); 7805 7806 // Populate the remaining elements with undefs. 7807 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7808 // ShuffV.push_back(i + WideNumElts); 7809 ShuffV.push_back(WideNumElts + 1); 7810 7811 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7812 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7813 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7814 } 7815 7816 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7817 /// possible. 7818 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7819 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7820 EVT ResVT = Op.getValueType(); 7821 EVT CmpVT = Op.getOperand(0).getValueType(); 7822 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7823 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7824 SDLoc dl(Op); 7825 7826 // Without power9-vector, we don't have native instruction for f128 comparison. 7827 // Following transformation to libcall is needed for setcc: 7828 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7829 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7830 SDValue Z = DAG.getSetCC( 7831 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7832 LHS, RHS, CC); 7833 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7834 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7835 } 7836 7837 // Not FP, or using SPE? Not a fsel. 7838 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7839 Subtarget.hasSPE()) 7840 return Op; 7841 7842 SDNodeFlags Flags = Op.getNode()->getFlags(); 7843 7844 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7845 // presence of infinities. 7846 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7847 switch (CC) { 7848 default: 7849 break; 7850 case ISD::SETOGT: 7851 case ISD::SETGT: 7852 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7853 case ISD::SETOLT: 7854 case ISD::SETLT: 7855 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7856 } 7857 } 7858 7859 // We might be able to do better than this under some circumstances, but in 7860 // general, fsel-based lowering of select is a finite-math-only optimization. 7861 // For more information, see section F.3 of the 2.06 ISA specification. 7862 // With ISA 3.0 7863 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7864 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7865 return Op; 7866 7867 // If the RHS of the comparison is a 0.0, we don't need to do the 7868 // subtraction at all. 7869 SDValue Sel1; 7870 if (isFloatingPointZero(RHS)) 7871 switch (CC) { 7872 default: break; // SETUO etc aren't handled by fsel. 7873 case ISD::SETNE: 7874 std::swap(TV, FV); 7875 LLVM_FALLTHROUGH; 7876 case ISD::SETEQ: 7877 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7878 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7879 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7880 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7881 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7882 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7883 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7884 case ISD::SETULT: 7885 case ISD::SETLT: 7886 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7887 LLVM_FALLTHROUGH; 7888 case ISD::SETOGE: 7889 case ISD::SETGE: 7890 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7891 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7892 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7893 case ISD::SETUGT: 7894 case ISD::SETGT: 7895 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7896 LLVM_FALLTHROUGH; 7897 case ISD::SETOLE: 7898 case ISD::SETLE: 7899 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7900 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7901 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7902 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7903 } 7904 7905 SDValue Cmp; 7906 switch (CC) { 7907 default: break; // SETUO etc aren't handled by fsel. 7908 case ISD::SETNE: 7909 std::swap(TV, FV); 7910 LLVM_FALLTHROUGH; 7911 case ISD::SETEQ: 7912 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7913 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7914 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7915 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7916 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7917 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7918 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7919 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7920 case ISD::SETULT: 7921 case ISD::SETLT: 7922 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7923 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7924 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7925 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7926 case ISD::SETOGE: 7927 case ISD::SETGE: 7928 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7929 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7930 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7931 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7932 case ISD::SETUGT: 7933 case ISD::SETGT: 7934 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7935 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7936 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7937 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7938 case ISD::SETOLE: 7939 case ISD::SETLE: 7940 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7941 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7942 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7943 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7944 } 7945 return Op; 7946 } 7947 7948 static unsigned getPPCStrictOpcode(unsigned Opc) { 7949 switch (Opc) { 7950 default: 7951 llvm_unreachable("No strict version of this opcode!"); 7952 case PPCISD::FCTIDZ: 7953 return PPCISD::STRICT_FCTIDZ; 7954 case PPCISD::FCTIWZ: 7955 return PPCISD::STRICT_FCTIWZ; 7956 case PPCISD::FCTIDUZ: 7957 return PPCISD::STRICT_FCTIDUZ; 7958 case PPCISD::FCTIWUZ: 7959 return PPCISD::STRICT_FCTIWUZ; 7960 case PPCISD::FCFID: 7961 return PPCISD::STRICT_FCFID; 7962 case PPCISD::FCFIDU: 7963 return PPCISD::STRICT_FCFIDU; 7964 case PPCISD::FCFIDS: 7965 return PPCISD::STRICT_FCFIDS; 7966 case PPCISD::FCFIDUS: 7967 return PPCISD::STRICT_FCFIDUS; 7968 } 7969 } 7970 7971 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 7972 const PPCSubtarget &Subtarget) { 7973 SDLoc dl(Op); 7974 bool IsStrict = Op->isStrictFPOpcode(); 7975 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7976 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7977 7978 // TODO: Any other flags to propagate? 7979 SDNodeFlags Flags; 7980 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 7981 7982 // For strict nodes, source is the second operand. 7983 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7984 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 7985 assert(Src.getValueType().isFloatingPoint()); 7986 if (Src.getValueType() == MVT::f32) { 7987 if (IsStrict) { 7988 Src = 7989 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 7990 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 7991 Chain = Src.getValue(1); 7992 } else 7993 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7994 } 7995 SDValue Conv; 7996 unsigned Opc = ISD::DELETED_NODE; 7997 switch (Op.getSimpleValueType().SimpleTy) { 7998 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7999 case MVT::i32: 8000 Opc = IsSigned ? PPCISD::FCTIWZ 8001 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8002 break; 8003 case MVT::i64: 8004 assert((IsSigned || Subtarget.hasFPCVT()) && 8005 "i64 FP_TO_UINT is supported only with FPCVT"); 8006 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8007 } 8008 if (IsStrict) { 8009 Opc = getPPCStrictOpcode(Opc); 8010 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8011 {Chain, Src}, Flags); 8012 } else { 8013 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8014 } 8015 return Conv; 8016 } 8017 8018 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8019 SelectionDAG &DAG, 8020 const SDLoc &dl) const { 8021 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8022 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8023 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8024 bool IsStrict = Op->isStrictFPOpcode(); 8025 8026 // Convert the FP value to an int value through memory. 8027 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8028 (IsSigned || Subtarget.hasFPCVT()); 8029 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8030 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8031 MachinePointerInfo MPI = 8032 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8033 8034 // Emit a store to the stack slot. 8035 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8036 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8037 if (i32Stack) { 8038 MachineFunction &MF = DAG.getMachineFunction(); 8039 Alignment = Align(4); 8040 MachineMemOperand *MMO = 8041 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8042 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8043 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8044 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8045 } else 8046 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8047 8048 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8049 // add in a bias on big endian. 8050 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8051 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8052 DAG.getConstant(4, dl, FIPtr.getValueType())); 8053 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8054 } 8055 8056 RLI.Chain = Chain; 8057 RLI.Ptr = FIPtr; 8058 RLI.MPI = MPI; 8059 RLI.Alignment = Alignment; 8060 } 8061 8062 /// Custom lowers floating point to integer conversions to use 8063 /// the direct move instructions available in ISA 2.07 to avoid the 8064 /// need for load/store combinations. 8065 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8066 SelectionDAG &DAG, 8067 const SDLoc &dl) const { 8068 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8069 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8070 if (Op->isStrictFPOpcode()) 8071 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8072 else 8073 return Mov; 8074 } 8075 8076 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8077 const SDLoc &dl) const { 8078 bool IsStrict = Op->isStrictFPOpcode(); 8079 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8080 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8081 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8082 EVT SrcVT = Src.getValueType(); 8083 EVT DstVT = Op.getValueType(); 8084 8085 // FP to INT conversions are legal for f128. 8086 if (SrcVT == MVT::f128) 8087 return Subtarget.hasP9Vector() ? Op : SDValue(); 8088 8089 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8090 // PPC (the libcall is not available). 8091 if (SrcVT == MVT::ppcf128) { 8092 if (DstVT == MVT::i32) { 8093 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8094 // set other fast-math flags to FP operations in both strict and 8095 // non-strict cases. (FP_TO_SINT, FSUB) 8096 SDNodeFlags Flags; 8097 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8098 8099 if (IsSigned) { 8100 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8101 DAG.getIntPtrConstant(0, dl)); 8102 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8103 DAG.getIntPtrConstant(1, dl)); 8104 8105 // Add the two halves of the long double in round-to-zero mode, and use 8106 // a smaller FP_TO_SINT. 8107 if (IsStrict) { 8108 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8109 DAG.getVTList(MVT::f64, MVT::Other), 8110 {Op.getOperand(0), Lo, Hi}, Flags); 8111 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8112 DAG.getVTList(MVT::i32, MVT::Other), 8113 {Res.getValue(1), Res}, Flags); 8114 } else { 8115 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8116 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8117 } 8118 } else { 8119 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8120 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8121 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8122 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8123 if (IsStrict) { 8124 // Sel = Src < 0x80000000 8125 // FltOfs = select Sel, 0.0, 0x80000000 8126 // IntOfs = select Sel, 0, 0x80000000 8127 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8128 SDValue Chain = Op.getOperand(0); 8129 EVT SetCCVT = 8130 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8131 EVT DstSetCCVT = 8132 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8133 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8134 Chain, true); 8135 Chain = Sel.getValue(1); 8136 8137 SDValue FltOfs = DAG.getSelect( 8138 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8139 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8140 8141 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8142 DAG.getVTList(SrcVT, MVT::Other), 8143 {Chain, Src, FltOfs}, Flags); 8144 Chain = Val.getValue(1); 8145 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8146 DAG.getVTList(DstVT, MVT::Other), 8147 {Chain, Val}, Flags); 8148 Chain = SInt.getValue(1); 8149 SDValue IntOfs = DAG.getSelect( 8150 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8151 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8152 return DAG.getMergeValues({Result, Chain}, dl); 8153 } else { 8154 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8155 // FIXME: generated code sucks. 8156 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8157 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8158 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8159 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8160 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8161 } 8162 } 8163 } 8164 8165 return SDValue(); 8166 } 8167 8168 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8169 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8170 8171 ReuseLoadInfo RLI; 8172 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8173 8174 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8175 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8176 } 8177 8178 // We're trying to insert a regular store, S, and then a load, L. If the 8179 // incoming value, O, is a load, we might just be able to have our load use the 8180 // address used by O. However, we don't know if anything else will store to 8181 // that address before we can load from it. To prevent this situation, we need 8182 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8183 // the same chain operand as O, we create a token factor from the chain results 8184 // of O and L, and we replace all uses of O's chain result with that token 8185 // factor (see spliceIntoChain below for this last part). 8186 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8187 ReuseLoadInfo &RLI, 8188 SelectionDAG &DAG, 8189 ISD::LoadExtType ET) const { 8190 // Conservatively skip reusing for constrained FP nodes. 8191 if (Op->isStrictFPOpcode()) 8192 return false; 8193 8194 SDLoc dl(Op); 8195 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8196 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8197 if (ET == ISD::NON_EXTLOAD && 8198 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8199 isOperationLegalOrCustom(Op.getOpcode(), 8200 Op.getOperand(0).getValueType())) { 8201 8202 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8203 return true; 8204 } 8205 8206 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8207 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8208 LD->isNonTemporal()) 8209 return false; 8210 if (LD->getMemoryVT() != MemVT) 8211 return false; 8212 8213 // If the result of the load is an illegal type, then we can't build a 8214 // valid chain for reuse since the legalised loads and token factor node that 8215 // ties the legalised loads together uses a different output chain then the 8216 // illegal load. 8217 if (!isTypeLegal(LD->getValueType(0))) 8218 return false; 8219 8220 RLI.Ptr = LD->getBasePtr(); 8221 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8222 assert(LD->getAddressingMode() == ISD::PRE_INC && 8223 "Non-pre-inc AM on PPC?"); 8224 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8225 LD->getOffset()); 8226 } 8227 8228 RLI.Chain = LD->getChain(); 8229 RLI.MPI = LD->getPointerInfo(); 8230 RLI.IsDereferenceable = LD->isDereferenceable(); 8231 RLI.IsInvariant = LD->isInvariant(); 8232 RLI.Alignment = LD->getAlign(); 8233 RLI.AAInfo = LD->getAAInfo(); 8234 RLI.Ranges = LD->getRanges(); 8235 8236 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8237 return true; 8238 } 8239 8240 // Given the head of the old chain, ResChain, insert a token factor containing 8241 // it and NewResChain, and make users of ResChain now be users of that token 8242 // factor. 8243 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8244 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8245 SDValue NewResChain, 8246 SelectionDAG &DAG) const { 8247 if (!ResChain) 8248 return; 8249 8250 SDLoc dl(NewResChain); 8251 8252 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8253 NewResChain, DAG.getUNDEF(MVT::Other)); 8254 assert(TF.getNode() != NewResChain.getNode() && 8255 "A new TF really is required here"); 8256 8257 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8258 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8259 } 8260 8261 /// Analyze profitability of direct move 8262 /// prefer float load to int load plus direct move 8263 /// when there is no integer use of int load 8264 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8265 SDNode *Origin = Op.getOperand(0).getNode(); 8266 if (Origin->getOpcode() != ISD::LOAD) 8267 return true; 8268 8269 // If there is no LXSIBZX/LXSIHZX, like Power8, 8270 // prefer direct move if the memory size is 1 or 2 bytes. 8271 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8272 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8273 return true; 8274 8275 for (SDNode::use_iterator UI = Origin->use_begin(), 8276 UE = Origin->use_end(); 8277 UI != UE; ++UI) { 8278 8279 // Only look at the users of the loaded value. 8280 if (UI.getUse().get().getResNo() != 0) 8281 continue; 8282 8283 if (UI->getOpcode() != ISD::SINT_TO_FP && 8284 UI->getOpcode() != ISD::UINT_TO_FP && 8285 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8286 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8287 return true; 8288 } 8289 8290 return false; 8291 } 8292 8293 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8294 const PPCSubtarget &Subtarget, 8295 SDValue Chain = SDValue()) { 8296 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8297 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8298 SDLoc dl(Op); 8299 8300 // TODO: Any other flags to propagate? 8301 SDNodeFlags Flags; 8302 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8303 8304 // If we have FCFIDS, then use it when converting to single-precision. 8305 // Otherwise, convert to double-precision and then round. 8306 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8307 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8308 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8309 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8310 if (Op->isStrictFPOpcode()) { 8311 if (!Chain) 8312 Chain = Op.getOperand(0); 8313 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8314 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8315 } else 8316 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8317 } 8318 8319 /// Custom lowers integer to floating point conversions to use 8320 /// the direct move instructions available in ISA 2.07 to avoid the 8321 /// need for load/store combinations. 8322 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8323 SelectionDAG &DAG, 8324 const SDLoc &dl) const { 8325 assert((Op.getValueType() == MVT::f32 || 8326 Op.getValueType() == MVT::f64) && 8327 "Invalid floating point type as target of conversion"); 8328 assert(Subtarget.hasFPCVT() && 8329 "Int to FP conversions with direct moves require FPCVT"); 8330 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8331 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8332 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8333 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8334 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8335 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8336 return convertIntToFP(Op, Mov, DAG, Subtarget); 8337 } 8338 8339 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8340 8341 EVT VecVT = Vec.getValueType(); 8342 assert(VecVT.isVector() && "Expected a vector type."); 8343 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8344 8345 EVT EltVT = VecVT.getVectorElementType(); 8346 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8347 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8348 8349 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8350 SmallVector<SDValue, 16> Ops(NumConcat); 8351 Ops[0] = Vec; 8352 SDValue UndefVec = DAG.getUNDEF(VecVT); 8353 for (unsigned i = 1; i < NumConcat; ++i) 8354 Ops[i] = UndefVec; 8355 8356 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8357 } 8358 8359 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8360 const SDLoc &dl) const { 8361 bool IsStrict = Op->isStrictFPOpcode(); 8362 unsigned Opc = Op.getOpcode(); 8363 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8364 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8365 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8366 "Unexpected conversion type"); 8367 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8368 "Supports conversions to v2f64/v4f32 only."); 8369 8370 // TODO: Any other flags to propagate? 8371 SDNodeFlags Flags; 8372 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8373 8374 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8375 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8376 8377 SDValue Wide = widenVec(DAG, Src, dl); 8378 EVT WideVT = Wide.getValueType(); 8379 unsigned WideNumElts = WideVT.getVectorNumElements(); 8380 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8381 8382 SmallVector<int, 16> ShuffV; 8383 for (unsigned i = 0; i < WideNumElts; ++i) 8384 ShuffV.push_back(i + WideNumElts); 8385 8386 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8387 int SaveElts = FourEltRes ? 4 : 2; 8388 if (Subtarget.isLittleEndian()) 8389 for (int i = 0; i < SaveElts; i++) 8390 ShuffV[i * Stride] = i; 8391 else 8392 for (int i = 1; i <= SaveElts; i++) 8393 ShuffV[i * Stride - 1] = i - 1; 8394 8395 SDValue ShuffleSrc2 = 8396 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8397 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8398 8399 SDValue Extend; 8400 if (SignedConv) { 8401 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8402 EVT ExtVT = Src.getValueType(); 8403 if (Subtarget.hasP9Altivec()) 8404 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8405 IntermediateVT.getVectorNumElements()); 8406 8407 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8408 DAG.getValueType(ExtVT)); 8409 } else 8410 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8411 8412 if (IsStrict) 8413 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8414 {Op.getOperand(0), Extend}, Flags); 8415 8416 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8417 } 8418 8419 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8420 SelectionDAG &DAG) const { 8421 SDLoc dl(Op); 8422 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8423 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8424 bool IsStrict = Op->isStrictFPOpcode(); 8425 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8426 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8427 8428 // TODO: Any other flags to propagate? 8429 SDNodeFlags Flags; 8430 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8431 8432 EVT InVT = Src.getValueType(); 8433 EVT OutVT = Op.getValueType(); 8434 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8435 isOperationCustom(Op.getOpcode(), InVT)) 8436 return LowerINT_TO_FPVector(Op, DAG, dl); 8437 8438 // Conversions to f128 are legal. 8439 if (Op.getValueType() == MVT::f128) 8440 return Subtarget.hasP9Vector() ? Op : SDValue(); 8441 8442 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8443 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8444 return SDValue(); 8445 8446 if (Src.getValueType() == MVT::i1) { 8447 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8448 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8449 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8450 if (IsStrict) 8451 return DAG.getMergeValues({Sel, Chain}, dl); 8452 else 8453 return Sel; 8454 } 8455 8456 // If we have direct moves, we can do all the conversion, skip the store/load 8457 // however, without FPCVT we can't do most conversions. 8458 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8459 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8460 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8461 8462 assert((IsSigned || Subtarget.hasFPCVT()) && 8463 "UINT_TO_FP is supported only with FPCVT"); 8464 8465 if (Src.getValueType() == MVT::i64) { 8466 SDValue SINT = Src; 8467 // When converting to single-precision, we actually need to convert 8468 // to double-precision first and then round to single-precision. 8469 // To avoid double-rounding effects during that operation, we have 8470 // to prepare the input operand. Bits that might be truncated when 8471 // converting to double-precision are replaced by a bit that won't 8472 // be lost at this stage, but is below the single-precision rounding 8473 // position. 8474 // 8475 // However, if -enable-unsafe-fp-math is in effect, accept double 8476 // rounding to avoid the extra overhead. 8477 if (Op.getValueType() == MVT::f32 && 8478 !Subtarget.hasFPCVT() && 8479 !DAG.getTarget().Options.UnsafeFPMath) { 8480 8481 // Twiddle input to make sure the low 11 bits are zero. (If this 8482 // is the case, we are guaranteed the value will fit into the 53 bit 8483 // mantissa of an IEEE double-precision value without rounding.) 8484 // If any of those low 11 bits were not zero originally, make sure 8485 // bit 12 (value 2048) is set instead, so that the final rounding 8486 // to single-precision gets the correct result. 8487 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8488 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8489 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8490 Round, DAG.getConstant(2047, dl, MVT::i64)); 8491 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8492 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8493 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8494 8495 // However, we cannot use that value unconditionally: if the magnitude 8496 // of the input value is small, the bit-twiddling we did above might 8497 // end up visibly changing the output. Fortunately, in that case, we 8498 // don't need to twiddle bits since the original input will convert 8499 // exactly to double-precision floating-point already. Therefore, 8500 // construct a conditional to use the original value if the top 11 8501 // bits are all sign-bit copies, and use the rounded value computed 8502 // above otherwise. 8503 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8504 SINT, DAG.getConstant(53, dl, MVT::i32)); 8505 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8506 Cond, DAG.getConstant(1, dl, MVT::i64)); 8507 Cond = DAG.getSetCC( 8508 dl, 8509 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8510 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8511 8512 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8513 } 8514 8515 ReuseLoadInfo RLI; 8516 SDValue Bits; 8517 8518 MachineFunction &MF = DAG.getMachineFunction(); 8519 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8520 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8521 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8522 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8523 } else if (Subtarget.hasLFIWAX() && 8524 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8525 MachineMemOperand *MMO = 8526 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8527 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8528 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8529 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8530 DAG.getVTList(MVT::f64, MVT::Other), 8531 Ops, MVT::i32, MMO); 8532 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8533 } else if (Subtarget.hasFPCVT() && 8534 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8535 MachineMemOperand *MMO = 8536 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8537 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8538 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8539 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8540 DAG.getVTList(MVT::f64, MVT::Other), 8541 Ops, MVT::i32, MMO); 8542 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8543 } else if (((Subtarget.hasLFIWAX() && 8544 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8545 (Subtarget.hasFPCVT() && 8546 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8547 SINT.getOperand(0).getValueType() == MVT::i32) { 8548 MachineFrameInfo &MFI = MF.getFrameInfo(); 8549 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8550 8551 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8552 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8553 8554 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8555 MachinePointerInfo::getFixedStack( 8556 DAG.getMachineFunction(), FrameIdx)); 8557 Chain = Store; 8558 8559 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8560 "Expected an i32 store"); 8561 8562 RLI.Ptr = FIdx; 8563 RLI.Chain = Chain; 8564 RLI.MPI = 8565 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8566 RLI.Alignment = Align(4); 8567 8568 MachineMemOperand *MMO = 8569 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8570 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8571 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8572 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8573 PPCISD::LFIWZX : PPCISD::LFIWAX, 8574 dl, DAG.getVTList(MVT::f64, MVT::Other), 8575 Ops, MVT::i32, MMO); 8576 Chain = Bits.getValue(1); 8577 } else 8578 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8579 8580 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8581 if (IsStrict) 8582 Chain = FP.getValue(1); 8583 8584 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8585 if (IsStrict) 8586 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8587 DAG.getVTList(MVT::f32, MVT::Other), 8588 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8589 else 8590 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8591 DAG.getIntPtrConstant(0, dl)); 8592 } 8593 return FP; 8594 } 8595 8596 assert(Src.getValueType() == MVT::i32 && 8597 "Unhandled INT_TO_FP type in custom expander!"); 8598 // Since we only generate this in 64-bit mode, we can take advantage of 8599 // 64-bit registers. In particular, sign extend the input value into the 8600 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8601 // then lfd it and fcfid it. 8602 MachineFunction &MF = DAG.getMachineFunction(); 8603 MachineFrameInfo &MFI = MF.getFrameInfo(); 8604 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8605 8606 SDValue Ld; 8607 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8608 ReuseLoadInfo RLI; 8609 bool ReusingLoad; 8610 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8611 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8612 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8613 8614 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8615 MachinePointerInfo::getFixedStack( 8616 DAG.getMachineFunction(), FrameIdx)); 8617 Chain = Store; 8618 8619 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8620 "Expected an i32 store"); 8621 8622 RLI.Ptr = FIdx; 8623 RLI.Chain = Chain; 8624 RLI.MPI = 8625 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8626 RLI.Alignment = Align(4); 8627 } 8628 8629 MachineMemOperand *MMO = 8630 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8631 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8632 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8633 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8634 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8635 MVT::i32, MMO); 8636 Chain = Ld.getValue(1); 8637 if (ReusingLoad) 8638 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8639 } else { 8640 assert(Subtarget.isPPC64() && 8641 "i32->FP without LFIWAX supported only on PPC64"); 8642 8643 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8644 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8645 8646 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8647 8648 // STD the extended value into the stack slot. 8649 SDValue Store = DAG.getStore( 8650 Chain, dl, Ext64, FIdx, 8651 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8652 Chain = Store; 8653 8654 // Load the value as a double. 8655 Ld = DAG.getLoad( 8656 MVT::f64, dl, Chain, FIdx, 8657 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8658 Chain = Ld.getValue(1); 8659 } 8660 8661 // FCFID it and return it. 8662 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8663 if (IsStrict) 8664 Chain = FP.getValue(1); 8665 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8666 if (IsStrict) 8667 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8668 DAG.getVTList(MVT::f32, MVT::Other), 8669 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8670 else 8671 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8672 DAG.getIntPtrConstant(0, dl)); 8673 } 8674 return FP; 8675 } 8676 8677 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8678 SelectionDAG &DAG) const { 8679 SDLoc dl(Op); 8680 /* 8681 The rounding mode is in bits 30:31 of FPSR, and has the following 8682 settings: 8683 00 Round to nearest 8684 01 Round to 0 8685 10 Round to +inf 8686 11 Round to -inf 8687 8688 FLT_ROUNDS, on the other hand, expects the following: 8689 -1 Undefined 8690 0 Round to 0 8691 1 Round to nearest 8692 2 Round to +inf 8693 3 Round to -inf 8694 8695 To perform the conversion, we do: 8696 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8697 */ 8698 8699 MachineFunction &MF = DAG.getMachineFunction(); 8700 EVT VT = Op.getValueType(); 8701 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8702 8703 // Save FP Control Word to register 8704 SDValue Chain = Op.getOperand(0); 8705 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8706 Chain = MFFS.getValue(1); 8707 8708 SDValue CWD; 8709 if (isTypeLegal(MVT::i64)) { 8710 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8711 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8712 } else { 8713 // Save FP register to stack slot 8714 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8715 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8716 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8717 8718 // Load FP Control Word from low 32 bits of stack slot. 8719 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8720 "Stack slot adjustment is valid only on big endian subtargets!"); 8721 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8722 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8723 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8724 Chain = CWD.getValue(1); 8725 } 8726 8727 // Transform as necessary 8728 SDValue CWD1 = 8729 DAG.getNode(ISD::AND, dl, MVT::i32, 8730 CWD, DAG.getConstant(3, dl, MVT::i32)); 8731 SDValue CWD2 = 8732 DAG.getNode(ISD::SRL, dl, MVT::i32, 8733 DAG.getNode(ISD::AND, dl, MVT::i32, 8734 DAG.getNode(ISD::XOR, dl, MVT::i32, 8735 CWD, DAG.getConstant(3, dl, MVT::i32)), 8736 DAG.getConstant(3, dl, MVT::i32)), 8737 DAG.getConstant(1, dl, MVT::i32)); 8738 8739 SDValue RetVal = 8740 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8741 8742 RetVal = 8743 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8744 dl, VT, RetVal); 8745 8746 return DAG.getMergeValues({RetVal, Chain}, dl); 8747 } 8748 8749 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8750 EVT VT = Op.getValueType(); 8751 unsigned BitWidth = VT.getSizeInBits(); 8752 SDLoc dl(Op); 8753 assert(Op.getNumOperands() == 3 && 8754 VT == Op.getOperand(1).getValueType() && 8755 "Unexpected SHL!"); 8756 8757 // Expand into a bunch of logical ops. Note that these ops 8758 // depend on the PPC behavior for oversized shift amounts. 8759 SDValue Lo = Op.getOperand(0); 8760 SDValue Hi = Op.getOperand(1); 8761 SDValue Amt = Op.getOperand(2); 8762 EVT AmtVT = Amt.getValueType(); 8763 8764 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8765 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8766 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8767 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8768 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8769 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8770 DAG.getConstant(-BitWidth, dl, AmtVT)); 8771 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8772 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8773 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8774 SDValue OutOps[] = { OutLo, OutHi }; 8775 return DAG.getMergeValues(OutOps, dl); 8776 } 8777 8778 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8779 EVT VT = Op.getValueType(); 8780 SDLoc dl(Op); 8781 unsigned BitWidth = VT.getSizeInBits(); 8782 assert(Op.getNumOperands() == 3 && 8783 VT == Op.getOperand(1).getValueType() && 8784 "Unexpected SRL!"); 8785 8786 // Expand into a bunch of logical ops. Note that these ops 8787 // depend on the PPC behavior for oversized shift amounts. 8788 SDValue Lo = Op.getOperand(0); 8789 SDValue Hi = Op.getOperand(1); 8790 SDValue Amt = Op.getOperand(2); 8791 EVT AmtVT = Amt.getValueType(); 8792 8793 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8794 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8795 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8796 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8797 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8798 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8799 DAG.getConstant(-BitWidth, dl, AmtVT)); 8800 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8801 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8802 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8803 SDValue OutOps[] = { OutLo, OutHi }; 8804 return DAG.getMergeValues(OutOps, dl); 8805 } 8806 8807 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8808 SDLoc dl(Op); 8809 EVT VT = Op.getValueType(); 8810 unsigned BitWidth = VT.getSizeInBits(); 8811 assert(Op.getNumOperands() == 3 && 8812 VT == Op.getOperand(1).getValueType() && 8813 "Unexpected SRA!"); 8814 8815 // Expand into a bunch of logical ops, followed by a select_cc. 8816 SDValue Lo = Op.getOperand(0); 8817 SDValue Hi = Op.getOperand(1); 8818 SDValue Amt = Op.getOperand(2); 8819 EVT AmtVT = Amt.getValueType(); 8820 8821 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8822 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8823 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8824 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8825 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8826 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8827 DAG.getConstant(-BitWidth, dl, AmtVT)); 8828 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8829 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8830 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8831 Tmp4, Tmp6, ISD::SETLE); 8832 SDValue OutOps[] = { OutLo, OutHi }; 8833 return DAG.getMergeValues(OutOps, dl); 8834 } 8835 8836 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8837 SelectionDAG &DAG) const { 8838 SDLoc dl(Op); 8839 EVT VT = Op.getValueType(); 8840 unsigned BitWidth = VT.getSizeInBits(); 8841 8842 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8843 SDValue X = Op.getOperand(0); 8844 SDValue Y = Op.getOperand(1); 8845 SDValue Z = Op.getOperand(2); 8846 EVT AmtVT = Z.getValueType(); 8847 8848 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8849 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8850 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8851 // on PowerPC shift by BW being well defined. 8852 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8853 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8854 SDValue SubZ = 8855 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8856 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8857 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8858 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8859 } 8860 8861 //===----------------------------------------------------------------------===// 8862 // Vector related lowering. 8863 // 8864 8865 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8866 /// element size of SplatSize. Cast the result to VT. 8867 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8868 SelectionDAG &DAG, const SDLoc &dl) { 8869 static const MVT VTys[] = { // canonical VT to use for each size. 8870 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8871 }; 8872 8873 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8874 8875 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8876 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8877 SplatSize = 1; 8878 Val = 0xFF; 8879 } 8880 8881 EVT CanonicalVT = VTys[SplatSize-1]; 8882 8883 // Build a canonical splat for this value. 8884 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8885 } 8886 8887 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8888 /// specified intrinsic ID. 8889 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8890 const SDLoc &dl, EVT DestVT = MVT::Other) { 8891 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8892 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8893 DAG.getConstant(IID, dl, MVT::i32), Op); 8894 } 8895 8896 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8897 /// specified intrinsic ID. 8898 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8899 SelectionDAG &DAG, const SDLoc &dl, 8900 EVT DestVT = MVT::Other) { 8901 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8902 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8903 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8904 } 8905 8906 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8907 /// specified intrinsic ID. 8908 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8909 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8910 EVT DestVT = MVT::Other) { 8911 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8912 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8913 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8914 } 8915 8916 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8917 /// amount. The result has the specified value type. 8918 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8919 SelectionDAG &DAG, const SDLoc &dl) { 8920 // Force LHS/RHS to be the right type. 8921 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8922 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8923 8924 int Ops[16]; 8925 for (unsigned i = 0; i != 16; ++i) 8926 Ops[i] = i + Amt; 8927 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8928 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8929 } 8930 8931 /// Do we have an efficient pattern in a .td file for this node? 8932 /// 8933 /// \param V - pointer to the BuildVectorSDNode being matched 8934 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8935 /// 8936 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8937 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8938 /// the opposite is true (expansion is beneficial) are: 8939 /// - The node builds a vector out of integers that are not 32 or 64-bits 8940 /// - The node builds a vector out of constants 8941 /// - The node is a "load-and-splat" 8942 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8943 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8944 bool HasDirectMove, 8945 bool HasP8Vector) { 8946 EVT VecVT = V->getValueType(0); 8947 bool RightType = VecVT == MVT::v2f64 || 8948 (HasP8Vector && VecVT == MVT::v4f32) || 8949 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8950 if (!RightType) 8951 return false; 8952 8953 bool IsSplat = true; 8954 bool IsLoad = false; 8955 SDValue Op0 = V->getOperand(0); 8956 8957 // This function is called in a block that confirms the node is not a constant 8958 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8959 // different constants. 8960 if (V->isConstant()) 8961 return false; 8962 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8963 if (V->getOperand(i).isUndef()) 8964 return false; 8965 // We want to expand nodes that represent load-and-splat even if the 8966 // loaded value is a floating point truncation or conversion to int. 8967 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8968 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8969 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8970 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8971 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8972 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8973 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8974 IsLoad = true; 8975 // If the operands are different or the input is not a load and has more 8976 // uses than just this BV node, then it isn't a splat. 8977 if (V->getOperand(i) != Op0 || 8978 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8979 IsSplat = false; 8980 } 8981 return !(IsSplat && IsLoad); 8982 } 8983 8984 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8985 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8986 8987 SDLoc dl(Op); 8988 SDValue Op0 = Op->getOperand(0); 8989 8990 if ((Op.getValueType() != MVT::f128) || 8991 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8992 (Op0.getOperand(0).getValueType() != MVT::i64) || 8993 (Op0.getOperand(1).getValueType() != MVT::i64)) 8994 return SDValue(); 8995 8996 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8997 Op0.getOperand(1)); 8998 } 8999 9000 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9001 const SDValue *InputLoad = &Op; 9002 if (InputLoad->getOpcode() == ISD::BITCAST) 9003 InputLoad = &InputLoad->getOperand(0); 9004 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9005 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9006 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9007 InputLoad = &InputLoad->getOperand(0); 9008 } 9009 if (InputLoad->getOpcode() != ISD::LOAD) 9010 return nullptr; 9011 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9012 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9013 } 9014 9015 // Convert the argument APFloat to a single precision APFloat if there is no 9016 // loss in information during the conversion to single precision APFloat and the 9017 // resulting number is not a denormal number. Return true if successful. 9018 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9019 APFloat APFloatToConvert = ArgAPFloat; 9020 bool LosesInfo = true; 9021 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9022 &LosesInfo); 9023 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9024 if (Success) 9025 ArgAPFloat = APFloatToConvert; 9026 return Success; 9027 } 9028 9029 // Bitcast the argument APInt to a double and convert it to a single precision 9030 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9031 // argument if there is no loss in information during the conversion from 9032 // double to single precision APFloat and the resulting number is not a denormal 9033 // number. Return true if successful. 9034 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9035 double DpValue = ArgAPInt.bitsToDouble(); 9036 APFloat APFloatDp(DpValue); 9037 bool Success = convertToNonDenormSingle(APFloatDp); 9038 if (Success) 9039 ArgAPInt = APFloatDp.bitcastToAPInt(); 9040 return Success; 9041 } 9042 9043 // Nondestructive check for convertTonNonDenormSingle. 9044 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 9045 // Only convert if it loses info, since XXSPLTIDP should 9046 // handle the other case. 9047 APFloat APFloatToConvert = ArgAPFloat; 9048 bool LosesInfo = true; 9049 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9050 &LosesInfo); 9051 9052 return (!LosesInfo && !APFloatToConvert.isDenormal()); 9053 } 9054 9055 // If this is a case we can't handle, return null and let the default 9056 // expansion code take care of it. If we CAN select this case, and if it 9057 // selects to a single instruction, return Op. Otherwise, if we can codegen 9058 // this case more efficiently than a constant pool load, lower it to the 9059 // sequence of ops that should be used. 9060 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9061 SelectionDAG &DAG) const { 9062 SDLoc dl(Op); 9063 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9064 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9065 9066 // Check if this is a splat of a constant value. 9067 APInt APSplatBits, APSplatUndef; 9068 unsigned SplatBitSize; 9069 bool HasAnyUndefs; 9070 bool BVNIsConstantSplat = 9071 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9072 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9073 9074 // If it is a splat of a double, check if we can shrink it to a 32 bit 9075 // non-denormal float which when converted back to double gives us the same 9076 // double. This is to exploit the XXSPLTIDP instruction. 9077 // If we lose precision, we use XXSPLTI32DX. 9078 if (BVNIsConstantSplat && (SplatBitSize == 64) && 9079 Subtarget.hasPrefixInstrs()) { 9080 // Check the type first to short-circuit so we don't modify APSplatBits if 9081 // this block isn't executed. 9082 if ((Op->getValueType(0) == MVT::v2f64) && 9083 convertToNonDenormSingle(APSplatBits)) { 9084 SDValue SplatNode = DAG.getNode( 9085 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9086 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9087 return DAG.getBitcast(Op.getValueType(), SplatNode); 9088 } else { 9089 // We may lose precision, so we have to use XXSPLTI32DX. 9090 9091 uint32_t Hi = 9092 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 9093 uint32_t Lo = 9094 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 9095 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 9096 9097 if (!Hi || !Lo) 9098 // If either load is 0, then we should generate XXLXOR to set to 0. 9099 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 9100 9101 if (Hi) 9102 SplatNode = DAG.getNode( 9103 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9104 DAG.getTargetConstant(0, dl, MVT::i32), 9105 DAG.getTargetConstant(Hi, dl, MVT::i32)); 9106 9107 if (Lo) 9108 SplatNode = 9109 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9110 DAG.getTargetConstant(1, dl, MVT::i32), 9111 DAG.getTargetConstant(Lo, dl, MVT::i32)); 9112 9113 return DAG.getBitcast(Op.getValueType(), SplatNode); 9114 } 9115 } 9116 9117 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9118 9119 bool IsPermutedLoad = false; 9120 const SDValue *InputLoad = 9121 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9122 // Handle load-and-splat patterns as we have instructions that will do this 9123 // in one go. 9124 if (InputLoad && DAG.isSplatValue(Op, true)) { 9125 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9126 9127 // We have handling for 4 and 8 byte elements. 9128 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9129 9130 // Checking for a single use of this load, we have to check for vector 9131 // width (128 bits) / ElementSize uses (since each operand of the 9132 // BUILD_VECTOR is a separate use of the value. 9133 unsigned NumUsesOfInputLD = 128 / ElementSize; 9134 for (SDValue BVInOp : Op->ops()) 9135 if (BVInOp.isUndef()) 9136 NumUsesOfInputLD--; 9137 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9138 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9139 ((Subtarget.hasVSX() && ElementSize == 64) || 9140 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9141 SDValue Ops[] = { 9142 LD->getChain(), // Chain 9143 LD->getBasePtr(), // Ptr 9144 DAG.getValueType(Op.getValueType()) // VT 9145 }; 9146 SDValue LdSplt = DAG.getMemIntrinsicNode( 9147 PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 9148 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9149 // Replace all uses of the output chain of the original load with the 9150 // output chain of the new load. 9151 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9152 LdSplt.getValue(1)); 9153 return LdSplt; 9154 } 9155 } 9156 9157 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9158 // 32-bits can be lowered to VSX instructions under certain conditions. 9159 // Without VSX, there is no pattern more efficient than expanding the node. 9160 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9161 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9162 Subtarget.hasP8Vector())) 9163 return Op; 9164 return SDValue(); 9165 } 9166 9167 uint64_t SplatBits = APSplatBits.getZExtValue(); 9168 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9169 unsigned SplatSize = SplatBitSize / 8; 9170 9171 // First, handle single instruction cases. 9172 9173 // All zeros? 9174 if (SplatBits == 0) { 9175 // Canonicalize all zero vectors to be v4i32. 9176 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9177 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9178 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9179 } 9180 return Op; 9181 } 9182 9183 // We have XXSPLTIW for constant splats four bytes wide. 9184 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9185 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9186 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9187 // turned into a 4-byte splat of 0xABABABAB. 9188 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9189 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9190 Op.getValueType(), DAG, dl); 9191 9192 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9193 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9194 dl); 9195 9196 // We have XXSPLTIB for constant splats one byte wide. 9197 if (Subtarget.hasP9Vector() && SplatSize == 1) 9198 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9199 dl); 9200 9201 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9202 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9203 (32-SplatBitSize)); 9204 if (SextVal >= -16 && SextVal <= 15) 9205 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9206 dl); 9207 9208 // Two instruction sequences. 9209 9210 // If this value is in the range [-32,30] and is even, use: 9211 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9212 // If this value is in the range [17,31] and is odd, use: 9213 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9214 // If this value is in the range [-31,-17] and is odd, use: 9215 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9216 // Note the last two are three-instruction sequences. 9217 if (SextVal >= -32 && SextVal <= 31) { 9218 // To avoid having these optimizations undone by constant folding, 9219 // we convert to a pseudo that will be expanded later into one of 9220 // the above forms. 9221 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9222 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9223 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9224 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9225 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9226 if (VT == Op.getValueType()) 9227 return RetVal; 9228 else 9229 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9230 } 9231 9232 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9233 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9234 // for fneg/fabs. 9235 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9236 // Make -1 and vspltisw -1: 9237 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9238 9239 // Make the VSLW intrinsic, computing 0x8000_0000. 9240 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9241 OnesV, DAG, dl); 9242 9243 // xor by OnesV to invert it. 9244 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9245 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9246 } 9247 9248 // Check to see if this is a wide variety of vsplti*, binop self cases. 9249 static const signed char SplatCsts[] = { 9250 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9251 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9252 }; 9253 9254 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9255 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9256 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9257 int i = SplatCsts[idx]; 9258 9259 // Figure out what shift amount will be used by altivec if shifted by i in 9260 // this splat size. 9261 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9262 9263 // vsplti + shl self. 9264 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9265 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9266 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9267 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9268 Intrinsic::ppc_altivec_vslw 9269 }; 9270 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9271 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9272 } 9273 9274 // vsplti + srl self. 9275 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9276 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9277 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9278 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9279 Intrinsic::ppc_altivec_vsrw 9280 }; 9281 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9282 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9283 } 9284 9285 // vsplti + rol self. 9286 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9287 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9288 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9289 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9290 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9291 Intrinsic::ppc_altivec_vrlw 9292 }; 9293 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9294 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9295 } 9296 9297 // t = vsplti c, result = vsldoi t, t, 1 9298 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9299 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9300 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9301 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9302 } 9303 // t = vsplti c, result = vsldoi t, t, 2 9304 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9305 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9306 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9307 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9308 } 9309 // t = vsplti c, result = vsldoi t, t, 3 9310 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9311 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9312 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9313 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9314 } 9315 } 9316 9317 return SDValue(); 9318 } 9319 9320 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9321 /// the specified operations to build the shuffle. 9322 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9323 SDValue RHS, SelectionDAG &DAG, 9324 const SDLoc &dl) { 9325 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9326 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9327 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9328 9329 enum { 9330 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9331 OP_VMRGHW, 9332 OP_VMRGLW, 9333 OP_VSPLTISW0, 9334 OP_VSPLTISW1, 9335 OP_VSPLTISW2, 9336 OP_VSPLTISW3, 9337 OP_VSLDOI4, 9338 OP_VSLDOI8, 9339 OP_VSLDOI12 9340 }; 9341 9342 if (OpNum == OP_COPY) { 9343 if (LHSID == (1*9+2)*9+3) return LHS; 9344 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9345 return RHS; 9346 } 9347 9348 SDValue OpLHS, OpRHS; 9349 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9350 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9351 9352 int ShufIdxs[16]; 9353 switch (OpNum) { 9354 default: llvm_unreachable("Unknown i32 permute!"); 9355 case OP_VMRGHW: 9356 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9357 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9358 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9359 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9360 break; 9361 case OP_VMRGLW: 9362 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9363 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9364 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9365 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9366 break; 9367 case OP_VSPLTISW0: 9368 for (unsigned i = 0; i != 16; ++i) 9369 ShufIdxs[i] = (i&3)+0; 9370 break; 9371 case OP_VSPLTISW1: 9372 for (unsigned i = 0; i != 16; ++i) 9373 ShufIdxs[i] = (i&3)+4; 9374 break; 9375 case OP_VSPLTISW2: 9376 for (unsigned i = 0; i != 16; ++i) 9377 ShufIdxs[i] = (i&3)+8; 9378 break; 9379 case OP_VSPLTISW3: 9380 for (unsigned i = 0; i != 16; ++i) 9381 ShufIdxs[i] = (i&3)+12; 9382 break; 9383 case OP_VSLDOI4: 9384 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9385 case OP_VSLDOI8: 9386 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9387 case OP_VSLDOI12: 9388 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9389 } 9390 EVT VT = OpLHS.getValueType(); 9391 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9392 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9393 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9394 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9395 } 9396 9397 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9398 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9399 /// SDValue. 9400 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9401 SelectionDAG &DAG) const { 9402 const unsigned BytesInVector = 16; 9403 bool IsLE = Subtarget.isLittleEndian(); 9404 SDLoc dl(N); 9405 SDValue V1 = N->getOperand(0); 9406 SDValue V2 = N->getOperand(1); 9407 unsigned ShiftElts = 0, InsertAtByte = 0; 9408 bool Swap = false; 9409 9410 // Shifts required to get the byte we want at element 7. 9411 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9412 0, 15, 14, 13, 12, 11, 10, 9}; 9413 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9414 1, 2, 3, 4, 5, 6, 7, 8}; 9415 9416 ArrayRef<int> Mask = N->getMask(); 9417 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9418 9419 // For each mask element, find out if we're just inserting something 9420 // from V2 into V1 or vice versa. 9421 // Possible permutations inserting an element from V2 into V1: 9422 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9423 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9424 // ... 9425 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9426 // Inserting from V1 into V2 will be similar, except mask range will be 9427 // [16,31]. 9428 9429 bool FoundCandidate = false; 9430 // If both vector operands for the shuffle are the same vector, the mask 9431 // will contain only elements from the first one and the second one will be 9432 // undef. 9433 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9434 // Go through the mask of half-words to find an element that's being moved 9435 // from one vector to the other. 9436 for (unsigned i = 0; i < BytesInVector; ++i) { 9437 unsigned CurrentElement = Mask[i]; 9438 // If 2nd operand is undefined, we should only look for element 7 in the 9439 // Mask. 9440 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9441 continue; 9442 9443 bool OtherElementsInOrder = true; 9444 // Examine the other elements in the Mask to see if they're in original 9445 // order. 9446 for (unsigned j = 0; j < BytesInVector; ++j) { 9447 if (j == i) 9448 continue; 9449 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9450 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9451 // in which we always assume we're always picking from the 1st operand. 9452 int MaskOffset = 9453 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9454 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9455 OtherElementsInOrder = false; 9456 break; 9457 } 9458 } 9459 // If other elements are in original order, we record the number of shifts 9460 // we need to get the element we want into element 7. Also record which byte 9461 // in the vector we should insert into. 9462 if (OtherElementsInOrder) { 9463 // If 2nd operand is undefined, we assume no shifts and no swapping. 9464 if (V2.isUndef()) { 9465 ShiftElts = 0; 9466 Swap = false; 9467 } else { 9468 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9469 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9470 : BigEndianShifts[CurrentElement & 0xF]; 9471 Swap = CurrentElement < BytesInVector; 9472 } 9473 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9474 FoundCandidate = true; 9475 break; 9476 } 9477 } 9478 9479 if (!FoundCandidate) 9480 return SDValue(); 9481 9482 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9483 // optionally with VECSHL if shift is required. 9484 if (Swap) 9485 std::swap(V1, V2); 9486 if (V2.isUndef()) 9487 V2 = V1; 9488 if (ShiftElts) { 9489 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9490 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9491 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9492 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9493 } 9494 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9495 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9496 } 9497 9498 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9499 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9500 /// SDValue. 9501 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9502 SelectionDAG &DAG) const { 9503 const unsigned NumHalfWords = 8; 9504 const unsigned BytesInVector = NumHalfWords * 2; 9505 // Check that the shuffle is on half-words. 9506 if (!isNByteElemShuffleMask(N, 2, 1)) 9507 return SDValue(); 9508 9509 bool IsLE = Subtarget.isLittleEndian(); 9510 SDLoc dl(N); 9511 SDValue V1 = N->getOperand(0); 9512 SDValue V2 = N->getOperand(1); 9513 unsigned ShiftElts = 0, InsertAtByte = 0; 9514 bool Swap = false; 9515 9516 // Shifts required to get the half-word we want at element 3. 9517 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9518 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9519 9520 uint32_t Mask = 0; 9521 uint32_t OriginalOrderLow = 0x1234567; 9522 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9523 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9524 // 32-bit space, only need 4-bit nibbles per element. 9525 for (unsigned i = 0; i < NumHalfWords; ++i) { 9526 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9527 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9528 } 9529 9530 // For each mask element, find out if we're just inserting something 9531 // from V2 into V1 or vice versa. Possible permutations inserting an element 9532 // from V2 into V1: 9533 // X, 1, 2, 3, 4, 5, 6, 7 9534 // 0, X, 2, 3, 4, 5, 6, 7 9535 // 0, 1, X, 3, 4, 5, 6, 7 9536 // 0, 1, 2, X, 4, 5, 6, 7 9537 // 0, 1, 2, 3, X, 5, 6, 7 9538 // 0, 1, 2, 3, 4, X, 6, 7 9539 // 0, 1, 2, 3, 4, 5, X, 7 9540 // 0, 1, 2, 3, 4, 5, 6, X 9541 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9542 9543 bool FoundCandidate = false; 9544 // Go through the mask of half-words to find an element that's being moved 9545 // from one vector to the other. 9546 for (unsigned i = 0; i < NumHalfWords; ++i) { 9547 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9548 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9549 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9550 uint32_t TargetOrder = 0x0; 9551 9552 // If both vector operands for the shuffle are the same vector, the mask 9553 // will contain only elements from the first one and the second one will be 9554 // undef. 9555 if (V2.isUndef()) { 9556 ShiftElts = 0; 9557 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9558 TargetOrder = OriginalOrderLow; 9559 Swap = false; 9560 // Skip if not the correct element or mask of other elements don't equal 9561 // to our expected order. 9562 if (MaskOneElt == VINSERTHSrcElem && 9563 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9564 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9565 FoundCandidate = true; 9566 break; 9567 } 9568 } else { // If both operands are defined. 9569 // Target order is [8,15] if the current mask is between [0,7]. 9570 TargetOrder = 9571 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9572 // Skip if mask of other elements don't equal our expected order. 9573 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9574 // We only need the last 3 bits for the number of shifts. 9575 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9576 : BigEndianShifts[MaskOneElt & 0x7]; 9577 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9578 Swap = MaskOneElt < NumHalfWords; 9579 FoundCandidate = true; 9580 break; 9581 } 9582 } 9583 } 9584 9585 if (!FoundCandidate) 9586 return SDValue(); 9587 9588 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9589 // optionally with VECSHL if shift is required. 9590 if (Swap) 9591 std::swap(V1, V2); 9592 if (V2.isUndef()) 9593 V2 = V1; 9594 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9595 if (ShiftElts) { 9596 // Double ShiftElts because we're left shifting on v16i8 type. 9597 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9598 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9599 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9600 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9601 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9602 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9603 } 9604 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9605 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9606 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9607 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9608 } 9609 9610 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9611 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9612 /// return the default SDValue. 9613 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9614 SelectionDAG &DAG) const { 9615 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9616 // to v16i8. Peek through the bitcasts to get the actual operands. 9617 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9618 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9619 9620 auto ShuffleMask = SVN->getMask(); 9621 SDValue VecShuffle(SVN, 0); 9622 SDLoc DL(SVN); 9623 9624 // Check that we have a four byte shuffle. 9625 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9626 return SDValue(); 9627 9628 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9629 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9630 std::swap(LHS, RHS); 9631 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9632 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9633 } 9634 9635 // Ensure that the RHS is a vector of constants. 9636 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9637 if (!BVN) 9638 return SDValue(); 9639 9640 // Check if RHS is a splat of 4-bytes (or smaller). 9641 APInt APSplatValue, APSplatUndef; 9642 unsigned SplatBitSize; 9643 bool HasAnyUndefs; 9644 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9645 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9646 SplatBitSize > 32) 9647 return SDValue(); 9648 9649 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9650 // The instruction splats a constant C into two words of the source vector 9651 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9652 // Thus we check that the shuffle mask is the equivalent of 9653 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9654 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9655 // within each word are consecutive, so we only need to check the first byte. 9656 SDValue Index; 9657 bool IsLE = Subtarget.isLittleEndian(); 9658 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9659 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9660 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9661 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9662 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9663 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9664 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9665 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9666 else 9667 return SDValue(); 9668 9669 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9670 // for XXSPLTI32DX. 9671 unsigned SplatVal = APSplatValue.getZExtValue(); 9672 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9673 SplatVal |= (SplatVal << SplatBitSize); 9674 9675 SDValue SplatNode = DAG.getNode( 9676 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9677 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9678 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9679 } 9680 9681 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9682 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9683 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9684 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9685 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9686 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9687 assert(Op.getValueType() == MVT::v1i128 && 9688 "Only set v1i128 as custom, other type shouldn't reach here!"); 9689 SDLoc dl(Op); 9690 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9691 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9692 unsigned SHLAmt = N1.getConstantOperandVal(0); 9693 if (SHLAmt % 8 == 0) { 9694 SmallVector<int, 16> Mask(16, 0); 9695 std::iota(Mask.begin(), Mask.end(), 0); 9696 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9697 if (SDValue Shuffle = 9698 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9699 DAG.getUNDEF(MVT::v16i8), Mask)) 9700 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9701 } 9702 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9703 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9704 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9705 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9706 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9707 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9708 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9709 } 9710 9711 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9712 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9713 /// return the code it can be lowered into. Worst case, it can always be 9714 /// lowered into a vperm. 9715 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9716 SelectionDAG &DAG) const { 9717 SDLoc dl(Op); 9718 SDValue V1 = Op.getOperand(0); 9719 SDValue V2 = Op.getOperand(1); 9720 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9721 9722 // Any nodes that were combined in the target-independent combiner prior 9723 // to vector legalization will not be sent to the target combine. Try to 9724 // combine it here. 9725 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9726 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9727 return NewShuffle; 9728 Op = NewShuffle; 9729 SVOp = cast<ShuffleVectorSDNode>(Op); 9730 V1 = Op.getOperand(0); 9731 V2 = Op.getOperand(1); 9732 } 9733 EVT VT = Op.getValueType(); 9734 bool isLittleEndian = Subtarget.isLittleEndian(); 9735 9736 unsigned ShiftElts, InsertAtByte; 9737 bool Swap = false; 9738 9739 // If this is a load-and-splat, we can do that with a single instruction 9740 // in some cases. However if the load has multiple uses, we don't want to 9741 // combine it because that will just produce multiple loads. 9742 bool IsPermutedLoad = false; 9743 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9744 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9745 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9746 InputLoad->hasOneUse()) { 9747 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9748 int SplatIdx = 9749 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9750 9751 // The splat index for permuted loads will be in the left half of the vector 9752 // which is strictly wider than the loaded value by 8 bytes. So we need to 9753 // adjust the splat index to point to the correct address in memory. 9754 if (IsPermutedLoad) { 9755 assert((isLittleEndian || IsFourByte) && 9756 "Unexpected size for permuted load on big endian target"); 9757 SplatIdx += IsFourByte ? 2 : 1; 9758 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9759 "Splat of a value outside of the loaded memory"); 9760 } 9761 9762 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9763 // For 4-byte load-and-splat, we need Power9. 9764 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9765 uint64_t Offset = 0; 9766 if (IsFourByte) 9767 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9768 else 9769 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9770 9771 // If the width of the load is the same as the width of the splat, 9772 // loading with an offset would load the wrong memory. 9773 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9774 Offset = 0; 9775 9776 SDValue BasePtr = LD->getBasePtr(); 9777 if (Offset != 0) 9778 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9779 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9780 SDValue Ops[] = { 9781 LD->getChain(), // Chain 9782 BasePtr, // BasePtr 9783 DAG.getValueType(Op.getValueType()) // VT 9784 }; 9785 SDVTList VTL = 9786 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9787 SDValue LdSplt = 9788 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9789 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9790 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9791 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9792 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9793 return LdSplt; 9794 } 9795 } 9796 if (Subtarget.hasP9Vector() && 9797 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9798 isLittleEndian)) { 9799 if (Swap) 9800 std::swap(V1, V2); 9801 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9802 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9803 if (ShiftElts) { 9804 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9805 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9806 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9807 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9808 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9809 } 9810 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9811 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9812 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9813 } 9814 9815 if (Subtarget.hasPrefixInstrs()) { 9816 SDValue SplatInsertNode; 9817 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9818 return SplatInsertNode; 9819 } 9820 9821 if (Subtarget.hasP9Altivec()) { 9822 SDValue NewISDNode; 9823 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9824 return NewISDNode; 9825 9826 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9827 return NewISDNode; 9828 } 9829 9830 if (Subtarget.hasVSX() && 9831 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9832 if (Swap) 9833 std::swap(V1, V2); 9834 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9835 SDValue Conv2 = 9836 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9837 9838 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9839 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9840 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9841 } 9842 9843 if (Subtarget.hasVSX() && 9844 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9845 if (Swap) 9846 std::swap(V1, V2); 9847 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9848 SDValue Conv2 = 9849 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9850 9851 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9852 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9853 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9854 } 9855 9856 if (Subtarget.hasP9Vector()) { 9857 if (PPC::isXXBRHShuffleMask(SVOp)) { 9858 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9859 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9860 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9861 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9862 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9863 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9864 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9865 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9866 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9867 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9868 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9869 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9870 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9871 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9872 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9873 } 9874 } 9875 9876 if (Subtarget.hasVSX()) { 9877 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9878 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9879 9880 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9881 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9882 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9883 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9884 } 9885 9886 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9887 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9888 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9889 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9890 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9891 } 9892 } 9893 9894 // Cases that are handled by instructions that take permute immediates 9895 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9896 // selected by the instruction selector. 9897 if (V2.isUndef()) { 9898 if (PPC::isSplatShuffleMask(SVOp, 1) || 9899 PPC::isSplatShuffleMask(SVOp, 2) || 9900 PPC::isSplatShuffleMask(SVOp, 4) || 9901 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9902 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9903 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9904 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9905 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9906 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9907 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9908 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9909 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9910 (Subtarget.hasP8Altivec() && ( 9911 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9912 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9913 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9914 return Op; 9915 } 9916 } 9917 9918 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9919 // and produce a fixed permutation. If any of these match, do not lower to 9920 // VPERM. 9921 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9922 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9923 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9924 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9925 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9926 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9927 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9928 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9929 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9930 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9931 (Subtarget.hasP8Altivec() && ( 9932 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9933 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9934 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9935 return Op; 9936 9937 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9938 // perfect shuffle table to emit an optimal matching sequence. 9939 ArrayRef<int> PermMask = SVOp->getMask(); 9940 9941 unsigned PFIndexes[4]; 9942 bool isFourElementShuffle = true; 9943 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9944 unsigned EltNo = 8; // Start out undef. 9945 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9946 if (PermMask[i*4+j] < 0) 9947 continue; // Undef, ignore it. 9948 9949 unsigned ByteSource = PermMask[i*4+j]; 9950 if ((ByteSource & 3) != j) { 9951 isFourElementShuffle = false; 9952 break; 9953 } 9954 9955 if (EltNo == 8) { 9956 EltNo = ByteSource/4; 9957 } else if (EltNo != ByteSource/4) { 9958 isFourElementShuffle = false; 9959 break; 9960 } 9961 } 9962 PFIndexes[i] = EltNo; 9963 } 9964 9965 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9966 // perfect shuffle vector to determine if it is cost effective to do this as 9967 // discrete instructions, or whether we should use a vperm. 9968 // For now, we skip this for little endian until such time as we have a 9969 // little-endian perfect shuffle table. 9970 if (isFourElementShuffle && !isLittleEndian) { 9971 // Compute the index in the perfect shuffle table. 9972 unsigned PFTableIndex = 9973 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9974 9975 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9976 unsigned Cost = (PFEntry >> 30); 9977 9978 // Determining when to avoid vperm is tricky. Many things affect the cost 9979 // of vperm, particularly how many times the perm mask needs to be computed. 9980 // For example, if the perm mask can be hoisted out of a loop or is already 9981 // used (perhaps because there are multiple permutes with the same shuffle 9982 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9983 // the loop requires an extra register. 9984 // 9985 // As a compromise, we only emit discrete instructions if the shuffle can be 9986 // generated in 3 or fewer operations. When we have loop information 9987 // available, if this block is within a loop, we should avoid using vperm 9988 // for 3-operation perms and use a constant pool load instead. 9989 if (Cost < 3) 9990 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9991 } 9992 9993 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9994 // vector that will get spilled to the constant pool. 9995 if (V2.isUndef()) V2 = V1; 9996 9997 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9998 // that it is in input element units, not in bytes. Convert now. 9999 10000 // For little endian, the order of the input vectors is reversed, and 10001 // the permutation mask is complemented with respect to 31. This is 10002 // necessary to produce proper semantics with the big-endian-biased vperm 10003 // instruction. 10004 EVT EltVT = V1.getValueType().getVectorElementType(); 10005 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10006 10007 SmallVector<SDValue, 16> ResultMask; 10008 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10009 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10010 10011 for (unsigned j = 0; j != BytesPerElement; ++j) 10012 if (isLittleEndian) 10013 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10014 dl, MVT::i32)); 10015 else 10016 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10017 MVT::i32)); 10018 } 10019 10020 ShufflesHandledWithVPERM++; 10021 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10022 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10023 LLVM_DEBUG(SVOp->dump()); 10024 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10025 LLVM_DEBUG(VPermMask.dump()); 10026 10027 if (isLittleEndian) 10028 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10029 V2, V1, VPermMask); 10030 else 10031 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10032 V1, V2, VPermMask); 10033 } 10034 10035 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10036 /// vector comparison. If it is, return true and fill in Opc/isDot with 10037 /// information about the intrinsic. 10038 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10039 bool &isDot, const PPCSubtarget &Subtarget) { 10040 unsigned IntrinsicID = 10041 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10042 CompareOpc = -1; 10043 isDot = false; 10044 switch (IntrinsicID) { 10045 default: 10046 return false; 10047 // Comparison predicates. 10048 case Intrinsic::ppc_altivec_vcmpbfp_p: 10049 CompareOpc = 966; 10050 isDot = true; 10051 break; 10052 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10053 CompareOpc = 198; 10054 isDot = true; 10055 break; 10056 case Intrinsic::ppc_altivec_vcmpequb_p: 10057 CompareOpc = 6; 10058 isDot = true; 10059 break; 10060 case Intrinsic::ppc_altivec_vcmpequh_p: 10061 CompareOpc = 70; 10062 isDot = true; 10063 break; 10064 case Intrinsic::ppc_altivec_vcmpequw_p: 10065 CompareOpc = 134; 10066 isDot = true; 10067 break; 10068 case Intrinsic::ppc_altivec_vcmpequd_p: 10069 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10070 CompareOpc = 199; 10071 isDot = true; 10072 } else 10073 return false; 10074 break; 10075 case Intrinsic::ppc_altivec_vcmpneb_p: 10076 case Intrinsic::ppc_altivec_vcmpneh_p: 10077 case Intrinsic::ppc_altivec_vcmpnew_p: 10078 case Intrinsic::ppc_altivec_vcmpnezb_p: 10079 case Intrinsic::ppc_altivec_vcmpnezh_p: 10080 case Intrinsic::ppc_altivec_vcmpnezw_p: 10081 if (Subtarget.hasP9Altivec()) { 10082 switch (IntrinsicID) { 10083 default: 10084 llvm_unreachable("Unknown comparison intrinsic."); 10085 case Intrinsic::ppc_altivec_vcmpneb_p: 10086 CompareOpc = 7; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpneh_p: 10089 CompareOpc = 71; 10090 break; 10091 case Intrinsic::ppc_altivec_vcmpnew_p: 10092 CompareOpc = 135; 10093 break; 10094 case Intrinsic::ppc_altivec_vcmpnezb_p: 10095 CompareOpc = 263; 10096 break; 10097 case Intrinsic::ppc_altivec_vcmpnezh_p: 10098 CompareOpc = 327; 10099 break; 10100 case Intrinsic::ppc_altivec_vcmpnezw_p: 10101 CompareOpc = 391; 10102 break; 10103 } 10104 isDot = true; 10105 } else 10106 return false; 10107 break; 10108 case Intrinsic::ppc_altivec_vcmpgefp_p: 10109 CompareOpc = 454; 10110 isDot = true; 10111 break; 10112 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10113 CompareOpc = 710; 10114 isDot = true; 10115 break; 10116 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10117 CompareOpc = 774; 10118 isDot = true; 10119 break; 10120 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10121 CompareOpc = 838; 10122 isDot = true; 10123 break; 10124 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10125 CompareOpc = 902; 10126 isDot = true; 10127 break; 10128 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10129 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10130 CompareOpc = 967; 10131 isDot = true; 10132 } else 10133 return false; 10134 break; 10135 case Intrinsic::ppc_altivec_vcmpgtub_p: 10136 CompareOpc = 518; 10137 isDot = true; 10138 break; 10139 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10140 CompareOpc = 582; 10141 isDot = true; 10142 break; 10143 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10144 CompareOpc = 646; 10145 isDot = true; 10146 break; 10147 case Intrinsic::ppc_altivec_vcmpgtud_p: 10148 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10149 CompareOpc = 711; 10150 isDot = true; 10151 } else 10152 return false; 10153 break; 10154 10155 case Intrinsic::ppc_altivec_vcmpequq: 10156 case Intrinsic::ppc_altivec_vcmpgtsq: 10157 case Intrinsic::ppc_altivec_vcmpgtuq: 10158 if (!Subtarget.isISA3_1()) 10159 return false; 10160 switch (IntrinsicID) { 10161 default: 10162 llvm_unreachable("Unknown comparison intrinsic."); 10163 case Intrinsic::ppc_altivec_vcmpequq: 10164 CompareOpc = 455; 10165 break; 10166 case Intrinsic::ppc_altivec_vcmpgtsq: 10167 CompareOpc = 903; 10168 break; 10169 case Intrinsic::ppc_altivec_vcmpgtuq: 10170 CompareOpc = 647; 10171 break; 10172 } 10173 break; 10174 10175 // VSX predicate comparisons use the same infrastructure 10176 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10177 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10178 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10179 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10180 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10181 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10182 if (Subtarget.hasVSX()) { 10183 switch (IntrinsicID) { 10184 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10185 CompareOpc = 99; 10186 break; 10187 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10188 CompareOpc = 115; 10189 break; 10190 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10191 CompareOpc = 107; 10192 break; 10193 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10194 CompareOpc = 67; 10195 break; 10196 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10197 CompareOpc = 83; 10198 break; 10199 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10200 CompareOpc = 75; 10201 break; 10202 } 10203 isDot = true; 10204 } else 10205 return false; 10206 break; 10207 10208 // Normal Comparisons. 10209 case Intrinsic::ppc_altivec_vcmpbfp: 10210 CompareOpc = 966; 10211 break; 10212 case Intrinsic::ppc_altivec_vcmpeqfp: 10213 CompareOpc = 198; 10214 break; 10215 case Intrinsic::ppc_altivec_vcmpequb: 10216 CompareOpc = 6; 10217 break; 10218 case Intrinsic::ppc_altivec_vcmpequh: 10219 CompareOpc = 70; 10220 break; 10221 case Intrinsic::ppc_altivec_vcmpequw: 10222 CompareOpc = 134; 10223 break; 10224 case Intrinsic::ppc_altivec_vcmpequd: 10225 if (Subtarget.hasP8Altivec()) 10226 CompareOpc = 199; 10227 else 10228 return false; 10229 break; 10230 case Intrinsic::ppc_altivec_vcmpneb: 10231 case Intrinsic::ppc_altivec_vcmpneh: 10232 case Intrinsic::ppc_altivec_vcmpnew: 10233 case Intrinsic::ppc_altivec_vcmpnezb: 10234 case Intrinsic::ppc_altivec_vcmpnezh: 10235 case Intrinsic::ppc_altivec_vcmpnezw: 10236 if (Subtarget.hasP9Altivec()) 10237 switch (IntrinsicID) { 10238 default: 10239 llvm_unreachable("Unknown comparison intrinsic."); 10240 case Intrinsic::ppc_altivec_vcmpneb: 10241 CompareOpc = 7; 10242 break; 10243 case Intrinsic::ppc_altivec_vcmpneh: 10244 CompareOpc = 71; 10245 break; 10246 case Intrinsic::ppc_altivec_vcmpnew: 10247 CompareOpc = 135; 10248 break; 10249 case Intrinsic::ppc_altivec_vcmpnezb: 10250 CompareOpc = 263; 10251 break; 10252 case Intrinsic::ppc_altivec_vcmpnezh: 10253 CompareOpc = 327; 10254 break; 10255 case Intrinsic::ppc_altivec_vcmpnezw: 10256 CompareOpc = 391; 10257 break; 10258 } 10259 else 10260 return false; 10261 break; 10262 case Intrinsic::ppc_altivec_vcmpgefp: 10263 CompareOpc = 454; 10264 break; 10265 case Intrinsic::ppc_altivec_vcmpgtfp: 10266 CompareOpc = 710; 10267 break; 10268 case Intrinsic::ppc_altivec_vcmpgtsb: 10269 CompareOpc = 774; 10270 break; 10271 case Intrinsic::ppc_altivec_vcmpgtsh: 10272 CompareOpc = 838; 10273 break; 10274 case Intrinsic::ppc_altivec_vcmpgtsw: 10275 CompareOpc = 902; 10276 break; 10277 case Intrinsic::ppc_altivec_vcmpgtsd: 10278 if (Subtarget.hasP8Altivec()) 10279 CompareOpc = 967; 10280 else 10281 return false; 10282 break; 10283 case Intrinsic::ppc_altivec_vcmpgtub: 10284 CompareOpc = 518; 10285 break; 10286 case Intrinsic::ppc_altivec_vcmpgtuh: 10287 CompareOpc = 582; 10288 break; 10289 case Intrinsic::ppc_altivec_vcmpgtuw: 10290 CompareOpc = 646; 10291 break; 10292 case Intrinsic::ppc_altivec_vcmpgtud: 10293 if (Subtarget.hasP8Altivec()) 10294 CompareOpc = 711; 10295 else 10296 return false; 10297 break; 10298 case Intrinsic::ppc_altivec_vcmpequq_p: 10299 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10300 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10301 if (!Subtarget.isISA3_1()) 10302 return false; 10303 switch (IntrinsicID) { 10304 default: 10305 llvm_unreachable("Unknown comparison intrinsic."); 10306 case Intrinsic::ppc_altivec_vcmpequq_p: 10307 CompareOpc = 455; 10308 break; 10309 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10310 CompareOpc = 903; 10311 break; 10312 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10313 CompareOpc = 647; 10314 break; 10315 } 10316 isDot = true; 10317 break; 10318 } 10319 return true; 10320 } 10321 10322 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10323 /// lower, do it, otherwise return null. 10324 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10325 SelectionDAG &DAG) const { 10326 unsigned IntrinsicID = 10327 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10328 10329 SDLoc dl(Op); 10330 10331 switch (IntrinsicID) { 10332 case Intrinsic::thread_pointer: 10333 // Reads the thread pointer register, used for __builtin_thread_pointer. 10334 if (Subtarget.isPPC64()) 10335 return DAG.getRegister(PPC::X13, MVT::i64); 10336 return DAG.getRegister(PPC::R2, MVT::i32); 10337 10338 case Intrinsic::ppc_mma_disassemble_acc: 10339 case Intrinsic::ppc_vsx_disassemble_pair: { 10340 int NumVecs = 2; 10341 SDValue WideVec = Op.getOperand(1); 10342 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10343 NumVecs = 4; 10344 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10345 } 10346 SmallVector<SDValue, 4> RetOps; 10347 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10348 SDValue Extract = DAG.getNode( 10349 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10350 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10351 : VecNo, 10352 dl, getPointerTy(DAG.getDataLayout()))); 10353 RetOps.push_back(Extract); 10354 } 10355 return DAG.getMergeValues(RetOps, dl); 10356 } 10357 } 10358 10359 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10360 // opcode number of the comparison. 10361 int CompareOpc; 10362 bool isDot; 10363 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10364 return SDValue(); // Don't custom lower most intrinsics. 10365 10366 // If this is a non-dot comparison, make the VCMP node and we are done. 10367 if (!isDot) { 10368 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10369 Op.getOperand(1), Op.getOperand(2), 10370 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10371 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10372 } 10373 10374 // Create the PPCISD altivec 'dot' comparison node. 10375 SDValue Ops[] = { 10376 Op.getOperand(2), // LHS 10377 Op.getOperand(3), // RHS 10378 DAG.getConstant(CompareOpc, dl, MVT::i32) 10379 }; 10380 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10381 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10382 10383 // Now that we have the comparison, emit a copy from the CR to a GPR. 10384 // This is flagged to the above dot comparison. 10385 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10386 DAG.getRegister(PPC::CR6, MVT::i32), 10387 CompNode.getValue(1)); 10388 10389 // Unpack the result based on how the target uses it. 10390 unsigned BitNo; // Bit # of CR6. 10391 bool InvertBit; // Invert result? 10392 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10393 default: // Can't happen, don't crash on invalid number though. 10394 case 0: // Return the value of the EQ bit of CR6. 10395 BitNo = 0; InvertBit = false; 10396 break; 10397 case 1: // Return the inverted value of the EQ bit of CR6. 10398 BitNo = 0; InvertBit = true; 10399 break; 10400 case 2: // Return the value of the LT bit of CR6. 10401 BitNo = 2; InvertBit = false; 10402 break; 10403 case 3: // Return the inverted value of the LT bit of CR6. 10404 BitNo = 2; InvertBit = true; 10405 break; 10406 } 10407 10408 // Shift the bit into the low position. 10409 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10410 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10411 // Isolate the bit. 10412 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10413 DAG.getConstant(1, dl, MVT::i32)); 10414 10415 // If we are supposed to, toggle the bit. 10416 if (InvertBit) 10417 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10418 DAG.getConstant(1, dl, MVT::i32)); 10419 return Flags; 10420 } 10421 10422 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10423 SelectionDAG &DAG) const { 10424 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10425 // the beginning of the argument list. 10426 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10427 SDLoc DL(Op); 10428 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10429 case Intrinsic::ppc_cfence: { 10430 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10431 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10432 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10433 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10434 Op.getOperand(ArgStart + 1)), 10435 Op.getOperand(0)), 10436 0); 10437 } 10438 default: 10439 break; 10440 } 10441 return SDValue(); 10442 } 10443 10444 // Lower scalar BSWAP64 to xxbrd. 10445 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10446 SDLoc dl(Op); 10447 if (!Subtarget.isPPC64()) 10448 return Op; 10449 // MTVSRDD 10450 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10451 Op.getOperand(0)); 10452 // XXBRD 10453 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10454 // MFVSRD 10455 int VectorIndex = 0; 10456 if (Subtarget.isLittleEndian()) 10457 VectorIndex = 1; 10458 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10459 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10460 return Op; 10461 } 10462 10463 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10464 // compared to a value that is atomically loaded (atomic loads zero-extend). 10465 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10466 SelectionDAG &DAG) const { 10467 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10468 "Expecting an atomic compare-and-swap here."); 10469 SDLoc dl(Op); 10470 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10471 EVT MemVT = AtomicNode->getMemoryVT(); 10472 if (MemVT.getSizeInBits() >= 32) 10473 return Op; 10474 10475 SDValue CmpOp = Op.getOperand(2); 10476 // If this is already correctly zero-extended, leave it alone. 10477 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10478 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10479 return Op; 10480 10481 // Clear the high bits of the compare operand. 10482 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10483 SDValue NewCmpOp = 10484 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10485 DAG.getConstant(MaskVal, dl, MVT::i32)); 10486 10487 // Replace the existing compare operand with the properly zero-extended one. 10488 SmallVector<SDValue, 4> Ops; 10489 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10490 Ops.push_back(AtomicNode->getOperand(i)); 10491 Ops[2] = NewCmpOp; 10492 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10493 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10494 auto NodeTy = 10495 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10496 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10497 } 10498 10499 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10500 SelectionDAG &DAG) const { 10501 SDLoc dl(Op); 10502 // Create a stack slot that is 16-byte aligned. 10503 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10504 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10505 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10506 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10507 10508 // Store the input value into Value#0 of the stack slot. 10509 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10510 MachinePointerInfo()); 10511 // Load it out. 10512 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10513 } 10514 10515 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10516 SelectionDAG &DAG) const { 10517 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10518 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10519 10520 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10521 10522 EVT VT = Op.getValueType(); 10523 SDLoc dl(Op); 10524 SDValue V1 = Op.getOperand(0); 10525 SDValue V2 = Op.getOperand(1); 10526 SDValue V3 = Op.getOperand(2); 10527 10528 if (VT == MVT::v2f64 && C) 10529 return Op; 10530 10531 if (Subtarget.isISA3_1()) { 10532 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64()) 10533 return SDValue(); 10534 // On P10, we have legal lowering for constant and variable indices for 10535 // integer vectors. 10536 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10537 VT == MVT::v2i64) 10538 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10539 // For f32 and f64 vectors, we have legal lowering for variable indices. 10540 // For f32 we also have legal lowering when the element is loaded from 10541 // memory. 10542 if (VT == MVT::v4f32 || VT == MVT::v2f64) { 10543 if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2))) 10544 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10545 return Op; 10546 } 10547 } 10548 10549 // Before P10, we have legal lowering for constant indices but not for 10550 // variable ones. 10551 if (!C) 10552 return SDValue(); 10553 10554 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10555 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10556 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10557 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10558 unsigned InsertAtElement = C->getZExtValue(); 10559 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10560 if (Subtarget.isLittleEndian()) { 10561 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10562 } 10563 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10564 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10565 } 10566 return Op; 10567 } 10568 10569 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10570 SelectionDAG &DAG) const { 10571 SDLoc dl(Op); 10572 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10573 SDValue LoadChain = LN->getChain(); 10574 SDValue BasePtr = LN->getBasePtr(); 10575 EVT VT = Op.getValueType(); 10576 10577 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10578 return Op; 10579 10580 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10581 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10582 // 2 or 4 vsx registers. 10583 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10584 "Type unsupported without MMA"); 10585 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10586 "Type unsupported without paired vector support"); 10587 Align Alignment = LN->getAlign(); 10588 SmallVector<SDValue, 4> Loads; 10589 SmallVector<SDValue, 4> LoadChains; 10590 unsigned NumVecs = VT.getSizeInBits() / 128; 10591 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10592 SDValue Load = 10593 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10594 LN->getPointerInfo().getWithOffset(Idx * 16), 10595 commonAlignment(Alignment, Idx * 16), 10596 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10597 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10598 DAG.getConstant(16, dl, BasePtr.getValueType())); 10599 Loads.push_back(Load); 10600 LoadChains.push_back(Load.getValue(1)); 10601 } 10602 if (Subtarget.isLittleEndian()) { 10603 std::reverse(Loads.begin(), Loads.end()); 10604 std::reverse(LoadChains.begin(), LoadChains.end()); 10605 } 10606 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10607 SDValue Value = 10608 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10609 dl, VT, Loads); 10610 SDValue RetOps[] = {Value, TF}; 10611 return DAG.getMergeValues(RetOps, dl); 10612 } 10613 10614 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10615 SelectionDAG &DAG) const { 10616 SDLoc dl(Op); 10617 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10618 SDValue StoreChain = SN->getChain(); 10619 SDValue BasePtr = SN->getBasePtr(); 10620 SDValue Value = SN->getValue(); 10621 EVT StoreVT = Value.getValueType(); 10622 10623 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10624 return Op; 10625 10626 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10627 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10628 // underlying registers individually. 10629 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10630 "Type unsupported without MMA"); 10631 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10632 "Type unsupported without paired vector support"); 10633 Align Alignment = SN->getAlign(); 10634 SmallVector<SDValue, 4> Stores; 10635 unsigned NumVecs = 2; 10636 if (StoreVT == MVT::v512i1) { 10637 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10638 NumVecs = 4; 10639 } 10640 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10641 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10642 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10643 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 10644 SDValue Store = 10645 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10646 SN->getPointerInfo().getWithOffset(Idx * 16), 10647 commonAlignment(Alignment, Idx * 16), 10648 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10649 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10650 DAG.getConstant(16, dl, BasePtr.getValueType())); 10651 Stores.push_back(Store); 10652 } 10653 SDValue TF = DAG.getTokenFactor(dl, Stores); 10654 return TF; 10655 } 10656 10657 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10658 SDLoc dl(Op); 10659 if (Op.getValueType() == MVT::v4i32) { 10660 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10661 10662 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10663 // +16 as shift amt. 10664 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10665 SDValue RHSSwap = // = vrlw RHS, 16 10666 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10667 10668 // Shrinkify inputs to v8i16. 10669 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10670 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10671 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10672 10673 // Low parts multiplied together, generating 32-bit results (we ignore the 10674 // top parts). 10675 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10676 LHS, RHS, DAG, dl, MVT::v4i32); 10677 10678 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10679 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10680 // Shift the high parts up 16 bits. 10681 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10682 Neg16, DAG, dl); 10683 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10684 } else if (Op.getValueType() == MVT::v16i8) { 10685 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10686 bool isLittleEndian = Subtarget.isLittleEndian(); 10687 10688 // Multiply the even 8-bit parts, producing 16-bit sums. 10689 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10690 LHS, RHS, DAG, dl, MVT::v8i16); 10691 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10692 10693 // Multiply the odd 8-bit parts, producing 16-bit sums. 10694 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10695 LHS, RHS, DAG, dl, MVT::v8i16); 10696 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10697 10698 // Merge the results together. Because vmuleub and vmuloub are 10699 // instructions with a big-endian bias, we must reverse the 10700 // element numbering and reverse the meaning of "odd" and "even" 10701 // when generating little endian code. 10702 int Ops[16]; 10703 for (unsigned i = 0; i != 8; ++i) { 10704 if (isLittleEndian) { 10705 Ops[i*2 ] = 2*i; 10706 Ops[i*2+1] = 2*i+16; 10707 } else { 10708 Ops[i*2 ] = 2*i+1; 10709 Ops[i*2+1] = 2*i+1+16; 10710 } 10711 } 10712 if (isLittleEndian) 10713 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10714 else 10715 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10716 } else { 10717 llvm_unreachable("Unknown mul to lower!"); 10718 } 10719 } 10720 10721 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10722 bool IsStrict = Op->isStrictFPOpcode(); 10723 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10724 !Subtarget.hasP9Vector()) 10725 return SDValue(); 10726 10727 return Op; 10728 } 10729 10730 // Custom lowering for fpext vf32 to v2f64 10731 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10732 10733 assert(Op.getOpcode() == ISD::FP_EXTEND && 10734 "Should only be called for ISD::FP_EXTEND"); 10735 10736 // FIXME: handle extends from half precision float vectors on P9. 10737 // We only want to custom lower an extend from v2f32 to v2f64. 10738 if (Op.getValueType() != MVT::v2f64 || 10739 Op.getOperand(0).getValueType() != MVT::v2f32) 10740 return SDValue(); 10741 10742 SDLoc dl(Op); 10743 SDValue Op0 = Op.getOperand(0); 10744 10745 switch (Op0.getOpcode()) { 10746 default: 10747 return SDValue(); 10748 case ISD::EXTRACT_SUBVECTOR: { 10749 assert(Op0.getNumOperands() == 2 && 10750 isa<ConstantSDNode>(Op0->getOperand(1)) && 10751 "Node should have 2 operands with second one being a constant!"); 10752 10753 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10754 return SDValue(); 10755 10756 // Custom lower is only done for high or low doubleword. 10757 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10758 if (Idx % 2 != 0) 10759 return SDValue(); 10760 10761 // Since input is v4f32, at this point Idx is either 0 or 2. 10762 // Shift to get the doubleword position we want. 10763 int DWord = Idx >> 1; 10764 10765 // High and low word positions are different on little endian. 10766 if (Subtarget.isLittleEndian()) 10767 DWord ^= 0x1; 10768 10769 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10770 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10771 } 10772 case ISD::FADD: 10773 case ISD::FMUL: 10774 case ISD::FSUB: { 10775 SDValue NewLoad[2]; 10776 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10777 // Ensure both input are loads. 10778 SDValue LdOp = Op0.getOperand(i); 10779 if (LdOp.getOpcode() != ISD::LOAD) 10780 return SDValue(); 10781 // Generate new load node. 10782 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10783 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10784 NewLoad[i] = DAG.getMemIntrinsicNode( 10785 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10786 LD->getMemoryVT(), LD->getMemOperand()); 10787 } 10788 SDValue NewOp = 10789 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10790 NewLoad[1], Op0.getNode()->getFlags()); 10791 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10792 DAG.getConstant(0, dl, MVT::i32)); 10793 } 10794 case ISD::LOAD: { 10795 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10796 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10797 SDValue NewLd = DAG.getMemIntrinsicNode( 10798 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10799 LD->getMemoryVT(), LD->getMemOperand()); 10800 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10801 DAG.getConstant(0, dl, MVT::i32)); 10802 } 10803 } 10804 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10805 } 10806 10807 /// LowerOperation - Provide custom lowering hooks for some operations. 10808 /// 10809 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10810 switch (Op.getOpcode()) { 10811 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10812 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10813 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10814 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10815 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10816 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10817 case ISD::STRICT_FSETCC: 10818 case ISD::STRICT_FSETCCS: 10819 case ISD::SETCC: return LowerSETCC(Op, DAG); 10820 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10821 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10822 10823 case ISD::INLINEASM: 10824 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG); 10825 // Variable argument lowering. 10826 case ISD::VASTART: return LowerVASTART(Op, DAG); 10827 case ISD::VAARG: return LowerVAARG(Op, DAG); 10828 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10829 10830 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10831 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10832 case ISD::GET_DYNAMIC_AREA_OFFSET: 10833 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10834 10835 // Exception handling lowering. 10836 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10837 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10838 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10839 10840 case ISD::LOAD: return LowerLOAD(Op, DAG); 10841 case ISD::STORE: return LowerSTORE(Op, DAG); 10842 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10843 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10844 case ISD::STRICT_FP_TO_UINT: 10845 case ISD::STRICT_FP_TO_SINT: 10846 case ISD::FP_TO_UINT: 10847 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10848 case ISD::STRICT_UINT_TO_FP: 10849 case ISD::STRICT_SINT_TO_FP: 10850 case ISD::UINT_TO_FP: 10851 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10852 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10853 10854 // Lower 64-bit shifts. 10855 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10856 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10857 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10858 10859 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10860 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10861 10862 // Vector-related lowering. 10863 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10864 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10865 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10866 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10867 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10868 case ISD::MUL: return LowerMUL(Op, DAG); 10869 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10870 case ISD::STRICT_FP_ROUND: 10871 case ISD::FP_ROUND: 10872 return LowerFP_ROUND(Op, DAG); 10873 case ISD::ROTL: return LowerROTL(Op, DAG); 10874 10875 // For counter-based loop handling. 10876 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10877 10878 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10879 10880 // Frame & Return address. 10881 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10882 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10883 10884 case ISD::INTRINSIC_VOID: 10885 return LowerINTRINSIC_VOID(Op, DAG); 10886 case ISD::BSWAP: 10887 return LowerBSWAP(Op, DAG); 10888 case ISD::ATOMIC_CMP_SWAP: 10889 return LowerATOMIC_CMP_SWAP(Op, DAG); 10890 } 10891 } 10892 10893 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10894 SmallVectorImpl<SDValue>&Results, 10895 SelectionDAG &DAG) const { 10896 SDLoc dl(N); 10897 switch (N->getOpcode()) { 10898 default: 10899 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10900 case ISD::READCYCLECOUNTER: { 10901 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10902 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10903 10904 Results.push_back( 10905 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10906 Results.push_back(RTB.getValue(2)); 10907 break; 10908 } 10909 case ISD::INTRINSIC_W_CHAIN: { 10910 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10911 Intrinsic::loop_decrement) 10912 break; 10913 10914 assert(N->getValueType(0) == MVT::i1 && 10915 "Unexpected result type for CTR decrement intrinsic"); 10916 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10917 N->getValueType(0)); 10918 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10919 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10920 N->getOperand(1)); 10921 10922 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10923 Results.push_back(NewInt.getValue(1)); 10924 break; 10925 } 10926 case ISD::VAARG: { 10927 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10928 return; 10929 10930 EVT VT = N->getValueType(0); 10931 10932 if (VT == MVT::i64) { 10933 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10934 10935 Results.push_back(NewNode); 10936 Results.push_back(NewNode.getValue(1)); 10937 } 10938 return; 10939 } 10940 case ISD::STRICT_FP_TO_SINT: 10941 case ISD::STRICT_FP_TO_UINT: 10942 case ISD::FP_TO_SINT: 10943 case ISD::FP_TO_UINT: 10944 // LowerFP_TO_INT() can only handle f32 and f64. 10945 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10946 MVT::ppcf128) 10947 return; 10948 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10949 return; 10950 case ISD::TRUNCATE: { 10951 if (!N->getValueType(0).isVector()) 10952 return; 10953 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10954 if (Lowered) 10955 Results.push_back(Lowered); 10956 return; 10957 } 10958 case ISD::FSHL: 10959 case ISD::FSHR: 10960 // Don't handle funnel shifts here. 10961 return; 10962 case ISD::BITCAST: 10963 // Don't handle bitcast here. 10964 return; 10965 case ISD::FP_EXTEND: 10966 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10967 if (Lowered) 10968 Results.push_back(Lowered); 10969 return; 10970 } 10971 } 10972 10973 //===----------------------------------------------------------------------===// 10974 // Other Lowering Code 10975 //===----------------------------------------------------------------------===// 10976 10977 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) { 10978 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10979 Function *Func = Intrinsic::getDeclaration(M, Id); 10980 return Builder.CreateCall(Func, {}); 10981 } 10982 10983 // The mappings for emitLeading/TrailingFence is taken from 10984 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10985 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10986 Instruction *Inst, 10987 AtomicOrdering Ord) const { 10988 if (Ord == AtomicOrdering::SequentiallyConsistent) 10989 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10990 if (isReleaseOrStronger(Ord)) 10991 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10992 return nullptr; 10993 } 10994 10995 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10996 Instruction *Inst, 10997 AtomicOrdering Ord) const { 10998 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10999 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11000 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11001 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11002 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11003 return Builder.CreateCall( 11004 Intrinsic::getDeclaration( 11005 Builder.GetInsertBlock()->getParent()->getParent(), 11006 Intrinsic::ppc_cfence, {Inst->getType()}), 11007 {Inst}); 11008 // FIXME: Can use isync for rmw operation. 11009 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11010 } 11011 return nullptr; 11012 } 11013 11014 MachineBasicBlock * 11015 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11016 unsigned AtomicSize, 11017 unsigned BinOpcode, 11018 unsigned CmpOpcode, 11019 unsigned CmpPred) const { 11020 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11021 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11022 11023 auto LoadMnemonic = PPC::LDARX; 11024 auto StoreMnemonic = PPC::STDCX; 11025 switch (AtomicSize) { 11026 default: 11027 llvm_unreachable("Unexpected size of atomic entity"); 11028 case 1: 11029 LoadMnemonic = PPC::LBARX; 11030 StoreMnemonic = PPC::STBCX; 11031 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11032 break; 11033 case 2: 11034 LoadMnemonic = PPC::LHARX; 11035 StoreMnemonic = PPC::STHCX; 11036 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11037 break; 11038 case 4: 11039 LoadMnemonic = PPC::LWARX; 11040 StoreMnemonic = PPC::STWCX; 11041 break; 11042 case 8: 11043 LoadMnemonic = PPC::LDARX; 11044 StoreMnemonic = PPC::STDCX; 11045 break; 11046 } 11047 11048 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11049 MachineFunction *F = BB->getParent(); 11050 MachineFunction::iterator It = ++BB->getIterator(); 11051 11052 Register dest = MI.getOperand(0).getReg(); 11053 Register ptrA = MI.getOperand(1).getReg(); 11054 Register ptrB = MI.getOperand(2).getReg(); 11055 Register incr = MI.getOperand(3).getReg(); 11056 DebugLoc dl = MI.getDebugLoc(); 11057 11058 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11059 MachineBasicBlock *loop2MBB = 11060 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11061 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11062 F->insert(It, loopMBB); 11063 if (CmpOpcode) 11064 F->insert(It, loop2MBB); 11065 F->insert(It, exitMBB); 11066 exitMBB->splice(exitMBB->begin(), BB, 11067 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11068 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11069 11070 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11071 Register TmpReg = (!BinOpcode) ? incr : 11072 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11073 : &PPC::GPRCRegClass); 11074 11075 // thisMBB: 11076 // ... 11077 // fallthrough --> loopMBB 11078 BB->addSuccessor(loopMBB); 11079 11080 // loopMBB: 11081 // l[wd]arx dest, ptr 11082 // add r0, dest, incr 11083 // st[wd]cx. r0, ptr 11084 // bne- loopMBB 11085 // fallthrough --> exitMBB 11086 11087 // For max/min... 11088 // loopMBB: 11089 // l[wd]arx dest, ptr 11090 // cmpl?[wd] incr, dest 11091 // bgt exitMBB 11092 // loop2MBB: 11093 // st[wd]cx. dest, ptr 11094 // bne- loopMBB 11095 // fallthrough --> exitMBB 11096 11097 BB = loopMBB; 11098 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11099 .addReg(ptrA).addReg(ptrB); 11100 if (BinOpcode) 11101 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11102 if (CmpOpcode) { 11103 // Signed comparisons of byte or halfword values must be sign-extended. 11104 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11105 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11106 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11107 ExtReg).addReg(dest); 11108 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11109 .addReg(incr).addReg(ExtReg); 11110 } else 11111 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11112 .addReg(incr).addReg(dest); 11113 11114 BuildMI(BB, dl, TII->get(PPC::BCC)) 11115 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11116 BB->addSuccessor(loop2MBB); 11117 BB->addSuccessor(exitMBB); 11118 BB = loop2MBB; 11119 } 11120 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11121 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11122 BuildMI(BB, dl, TII->get(PPC::BCC)) 11123 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11124 BB->addSuccessor(loopMBB); 11125 BB->addSuccessor(exitMBB); 11126 11127 // exitMBB: 11128 // ... 11129 BB = exitMBB; 11130 return BB; 11131 } 11132 11133 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 11134 switch(MI.getOpcode()) { 11135 default: 11136 return false; 11137 case PPC::COPY: 11138 return TII->isSignExtended(MI); 11139 case PPC::LHA: 11140 case PPC::LHA8: 11141 case PPC::LHAU: 11142 case PPC::LHAU8: 11143 case PPC::LHAUX: 11144 case PPC::LHAUX8: 11145 case PPC::LHAX: 11146 case PPC::LHAX8: 11147 case PPC::LWA: 11148 case PPC::LWAUX: 11149 case PPC::LWAX: 11150 case PPC::LWAX_32: 11151 case PPC::LWA_32: 11152 case PPC::PLHA: 11153 case PPC::PLHA8: 11154 case PPC::PLHA8pc: 11155 case PPC::PLHApc: 11156 case PPC::PLWA: 11157 case PPC::PLWA8: 11158 case PPC::PLWA8pc: 11159 case PPC::PLWApc: 11160 case PPC::EXTSB: 11161 case PPC::EXTSB8: 11162 case PPC::EXTSB8_32_64: 11163 case PPC::EXTSB8_rec: 11164 case PPC::EXTSB_rec: 11165 case PPC::EXTSH: 11166 case PPC::EXTSH8: 11167 case PPC::EXTSH8_32_64: 11168 case PPC::EXTSH8_rec: 11169 case PPC::EXTSH_rec: 11170 case PPC::EXTSW: 11171 case PPC::EXTSWSLI: 11172 case PPC::EXTSWSLI_32_64: 11173 case PPC::EXTSWSLI_32_64_rec: 11174 case PPC::EXTSWSLI_rec: 11175 case PPC::EXTSW_32: 11176 case PPC::EXTSW_32_64: 11177 case PPC::EXTSW_32_64_rec: 11178 case PPC::EXTSW_rec: 11179 case PPC::SRAW: 11180 case PPC::SRAWI: 11181 case PPC::SRAWI_rec: 11182 case PPC::SRAW_rec: 11183 return true; 11184 } 11185 return false; 11186 } 11187 11188 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11189 MachineInstr &MI, MachineBasicBlock *BB, 11190 bool is8bit, // operation 11191 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11192 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11193 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 11194 11195 // If this is a signed comparison and the value being compared is not known 11196 // to be sign extended, sign extend it here. 11197 DebugLoc dl = MI.getDebugLoc(); 11198 MachineFunction *F = BB->getParent(); 11199 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11200 Register incr = MI.getOperand(3).getReg(); 11201 bool IsSignExtended = Register::isVirtualRegister(incr) && 11202 isSignExtended(*RegInfo.getVRegDef(incr), TII); 11203 11204 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11205 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11206 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11207 .addReg(MI.getOperand(3).getReg()); 11208 MI.getOperand(3).setReg(ValueReg); 11209 } 11210 // If we support part-word atomic mnemonics, just use them 11211 if (Subtarget.hasPartwordAtomics()) 11212 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11213 CmpPred); 11214 11215 // In 64 bit mode we have to use 64 bits for addresses, even though the 11216 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11217 // registers without caring whether they're 32 or 64, but here we're 11218 // doing actual arithmetic on the addresses. 11219 bool is64bit = Subtarget.isPPC64(); 11220 bool isLittleEndian = Subtarget.isLittleEndian(); 11221 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11222 11223 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11224 MachineFunction::iterator It = ++BB->getIterator(); 11225 11226 Register dest = MI.getOperand(0).getReg(); 11227 Register ptrA = MI.getOperand(1).getReg(); 11228 Register ptrB = MI.getOperand(2).getReg(); 11229 11230 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11231 MachineBasicBlock *loop2MBB = 11232 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11233 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11234 F->insert(It, loopMBB); 11235 if (CmpOpcode) 11236 F->insert(It, loop2MBB); 11237 F->insert(It, exitMBB); 11238 exitMBB->splice(exitMBB->begin(), BB, 11239 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11240 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11241 11242 const TargetRegisterClass *RC = 11243 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11244 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11245 11246 Register PtrReg = RegInfo.createVirtualRegister(RC); 11247 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11248 Register ShiftReg = 11249 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11250 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11251 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11252 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11253 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11254 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11255 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11256 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11257 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11258 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC); 11259 Register Ptr1Reg; 11260 Register TmpReg = 11261 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11262 11263 // thisMBB: 11264 // ... 11265 // fallthrough --> loopMBB 11266 BB->addSuccessor(loopMBB); 11267 11268 // The 4-byte load must be aligned, while a char or short may be 11269 // anywhere in the word. Hence all this nasty bookkeeping code. 11270 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11271 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11272 // xori shift, shift1, 24 [16] 11273 // rlwinm ptr, ptr1, 0, 0, 29 11274 // slw incr2, incr, shift 11275 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11276 // slw mask, mask2, shift 11277 // loopMBB: 11278 // lwarx tmpDest, ptr 11279 // add tmp, tmpDest, incr2 11280 // andc tmp2, tmpDest, mask 11281 // and tmp3, tmp, mask 11282 // or tmp4, tmp3, tmp2 11283 // stwcx. tmp4, ptr 11284 // bne- loopMBB 11285 // fallthrough --> exitMBB 11286 // srw SrwDest, tmpDest, shift 11287 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31 11288 if (ptrA != ZeroReg) { 11289 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11290 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11291 .addReg(ptrA) 11292 .addReg(ptrB); 11293 } else { 11294 Ptr1Reg = ptrB; 11295 } 11296 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11297 // mode. 11298 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11299 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11300 .addImm(3) 11301 .addImm(27) 11302 .addImm(is8bit ? 28 : 27); 11303 if (!isLittleEndian) 11304 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11305 .addReg(Shift1Reg) 11306 .addImm(is8bit ? 24 : 16); 11307 if (is64bit) 11308 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11309 .addReg(Ptr1Reg) 11310 .addImm(0) 11311 .addImm(61); 11312 else 11313 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11314 .addReg(Ptr1Reg) 11315 .addImm(0) 11316 .addImm(0) 11317 .addImm(29); 11318 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11319 if (is8bit) 11320 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11321 else { 11322 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11323 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11324 .addReg(Mask3Reg) 11325 .addImm(65535); 11326 } 11327 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11328 .addReg(Mask2Reg) 11329 .addReg(ShiftReg); 11330 11331 BB = loopMBB; 11332 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11333 .addReg(ZeroReg) 11334 .addReg(PtrReg); 11335 if (BinOpcode) 11336 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11337 .addReg(Incr2Reg) 11338 .addReg(TmpDestReg); 11339 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11340 .addReg(TmpDestReg) 11341 .addReg(MaskReg); 11342 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11343 if (CmpOpcode) { 11344 // For unsigned comparisons, we can directly compare the shifted values. 11345 // For signed comparisons we shift and sign extend. 11346 Register SReg = RegInfo.createVirtualRegister(GPRC); 11347 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11348 .addReg(TmpDestReg) 11349 .addReg(MaskReg); 11350 unsigned ValueReg = SReg; 11351 unsigned CmpReg = Incr2Reg; 11352 if (CmpOpcode == PPC::CMPW) { 11353 ValueReg = RegInfo.createVirtualRegister(GPRC); 11354 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11355 .addReg(SReg) 11356 .addReg(ShiftReg); 11357 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11358 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11359 .addReg(ValueReg); 11360 ValueReg = ValueSReg; 11361 CmpReg = incr; 11362 } 11363 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11364 .addReg(CmpReg) 11365 .addReg(ValueReg); 11366 BuildMI(BB, dl, TII->get(PPC::BCC)) 11367 .addImm(CmpPred) 11368 .addReg(PPC::CR0) 11369 .addMBB(exitMBB); 11370 BB->addSuccessor(loop2MBB); 11371 BB->addSuccessor(exitMBB); 11372 BB = loop2MBB; 11373 } 11374 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11375 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11376 .addReg(Tmp4Reg) 11377 .addReg(ZeroReg) 11378 .addReg(PtrReg); 11379 BuildMI(BB, dl, TII->get(PPC::BCC)) 11380 .addImm(PPC::PRED_NE) 11381 .addReg(PPC::CR0) 11382 .addMBB(loopMBB); 11383 BB->addSuccessor(loopMBB); 11384 BB->addSuccessor(exitMBB); 11385 11386 // exitMBB: 11387 // ... 11388 BB = exitMBB; 11389 // Since the shift amount is not a constant, we need to clear 11390 // the upper bits with a separate RLWINM. 11391 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest) 11392 .addReg(SrwDestReg) 11393 .addImm(0) 11394 .addImm(is8bit ? 24 : 16) 11395 .addImm(31); 11396 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg) 11397 .addReg(TmpDestReg) 11398 .addReg(ShiftReg); 11399 return BB; 11400 } 11401 11402 llvm::MachineBasicBlock * 11403 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11404 MachineBasicBlock *MBB) const { 11405 DebugLoc DL = MI.getDebugLoc(); 11406 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11407 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11408 11409 MachineFunction *MF = MBB->getParent(); 11410 MachineRegisterInfo &MRI = MF->getRegInfo(); 11411 11412 const BasicBlock *BB = MBB->getBasicBlock(); 11413 MachineFunction::iterator I = ++MBB->getIterator(); 11414 11415 Register DstReg = MI.getOperand(0).getReg(); 11416 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11417 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11418 Register mainDstReg = MRI.createVirtualRegister(RC); 11419 Register restoreDstReg = MRI.createVirtualRegister(RC); 11420 11421 MVT PVT = getPointerTy(MF->getDataLayout()); 11422 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11423 "Invalid Pointer Size!"); 11424 // For v = setjmp(buf), we generate 11425 // 11426 // thisMBB: 11427 // SjLjSetup mainMBB 11428 // bl mainMBB 11429 // v_restore = 1 11430 // b sinkMBB 11431 // 11432 // mainMBB: 11433 // buf[LabelOffset] = LR 11434 // v_main = 0 11435 // 11436 // sinkMBB: 11437 // v = phi(main, restore) 11438 // 11439 11440 MachineBasicBlock *thisMBB = MBB; 11441 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11442 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11443 MF->insert(I, mainMBB); 11444 MF->insert(I, sinkMBB); 11445 11446 MachineInstrBuilder MIB; 11447 11448 // Transfer the remainder of BB and its successor edges to sinkMBB. 11449 sinkMBB->splice(sinkMBB->begin(), MBB, 11450 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11451 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11452 11453 // Note that the structure of the jmp_buf used here is not compatible 11454 // with that used by libc, and is not designed to be. Specifically, it 11455 // stores only those 'reserved' registers that LLVM does not otherwise 11456 // understand how to spill. Also, by convention, by the time this 11457 // intrinsic is called, Clang has already stored the frame address in the 11458 // first slot of the buffer and stack address in the third. Following the 11459 // X86 target code, we'll store the jump address in the second slot. We also 11460 // need to save the TOC pointer (R2) to handle jumps between shared 11461 // libraries, and that will be stored in the fourth slot. The thread 11462 // identifier (R13) is not affected. 11463 11464 // thisMBB: 11465 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11466 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11467 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11468 11469 // Prepare IP either in reg. 11470 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11471 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11472 Register BufReg = MI.getOperand(1).getReg(); 11473 11474 if (Subtarget.is64BitELFABI()) { 11475 setUsesTOCBasePtr(*MBB->getParent()); 11476 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11477 .addReg(PPC::X2) 11478 .addImm(TOCOffset) 11479 .addReg(BufReg) 11480 .cloneMemRefs(MI); 11481 } 11482 11483 // Naked functions never have a base pointer, and so we use r1. For all 11484 // other functions, this decision must be delayed until during PEI. 11485 unsigned BaseReg; 11486 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11487 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11488 else 11489 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11490 11491 MIB = BuildMI(*thisMBB, MI, DL, 11492 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11493 .addReg(BaseReg) 11494 .addImm(BPOffset) 11495 .addReg(BufReg) 11496 .cloneMemRefs(MI); 11497 11498 // Setup 11499 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11500 MIB.addRegMask(TRI->getNoPreservedMask()); 11501 11502 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11503 11504 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11505 .addMBB(mainMBB); 11506 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11507 11508 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11509 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11510 11511 // mainMBB: 11512 // mainDstReg = 0 11513 MIB = 11514 BuildMI(mainMBB, DL, 11515 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11516 11517 // Store IP 11518 if (Subtarget.isPPC64()) { 11519 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11520 .addReg(LabelReg) 11521 .addImm(LabelOffset) 11522 .addReg(BufReg); 11523 } else { 11524 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11525 .addReg(LabelReg) 11526 .addImm(LabelOffset) 11527 .addReg(BufReg); 11528 } 11529 MIB.cloneMemRefs(MI); 11530 11531 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11532 mainMBB->addSuccessor(sinkMBB); 11533 11534 // sinkMBB: 11535 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11536 TII->get(PPC::PHI), DstReg) 11537 .addReg(mainDstReg).addMBB(mainMBB) 11538 .addReg(restoreDstReg).addMBB(thisMBB); 11539 11540 MI.eraseFromParent(); 11541 return sinkMBB; 11542 } 11543 11544 MachineBasicBlock * 11545 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11546 MachineBasicBlock *MBB) const { 11547 DebugLoc DL = MI.getDebugLoc(); 11548 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11549 11550 MachineFunction *MF = MBB->getParent(); 11551 MachineRegisterInfo &MRI = MF->getRegInfo(); 11552 11553 MVT PVT = getPointerTy(MF->getDataLayout()); 11554 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11555 "Invalid Pointer Size!"); 11556 11557 const TargetRegisterClass *RC = 11558 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11559 Register Tmp = MRI.createVirtualRegister(RC); 11560 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11561 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11562 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11563 unsigned BP = 11564 (PVT == MVT::i64) 11565 ? PPC::X30 11566 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11567 : PPC::R30); 11568 11569 MachineInstrBuilder MIB; 11570 11571 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11572 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11573 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11574 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11575 11576 Register BufReg = MI.getOperand(0).getReg(); 11577 11578 // Reload FP (the jumped-to function may not have had a 11579 // frame pointer, and if so, then its r31 will be restored 11580 // as necessary). 11581 if (PVT == MVT::i64) { 11582 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11583 .addImm(0) 11584 .addReg(BufReg); 11585 } else { 11586 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11587 .addImm(0) 11588 .addReg(BufReg); 11589 } 11590 MIB.cloneMemRefs(MI); 11591 11592 // Reload IP 11593 if (PVT == MVT::i64) { 11594 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11595 .addImm(LabelOffset) 11596 .addReg(BufReg); 11597 } else { 11598 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11599 .addImm(LabelOffset) 11600 .addReg(BufReg); 11601 } 11602 MIB.cloneMemRefs(MI); 11603 11604 // Reload SP 11605 if (PVT == MVT::i64) { 11606 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11607 .addImm(SPOffset) 11608 .addReg(BufReg); 11609 } else { 11610 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11611 .addImm(SPOffset) 11612 .addReg(BufReg); 11613 } 11614 MIB.cloneMemRefs(MI); 11615 11616 // Reload BP 11617 if (PVT == MVT::i64) { 11618 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11619 .addImm(BPOffset) 11620 .addReg(BufReg); 11621 } else { 11622 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11623 .addImm(BPOffset) 11624 .addReg(BufReg); 11625 } 11626 MIB.cloneMemRefs(MI); 11627 11628 // Reload TOC 11629 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11630 setUsesTOCBasePtr(*MBB->getParent()); 11631 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11632 .addImm(TOCOffset) 11633 .addReg(BufReg) 11634 .cloneMemRefs(MI); 11635 } 11636 11637 // Jump 11638 BuildMI(*MBB, MI, DL, 11639 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11640 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11641 11642 MI.eraseFromParent(); 11643 return MBB; 11644 } 11645 11646 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11647 // If the function specifically requests inline stack probes, emit them. 11648 if (MF.getFunction().hasFnAttribute("probe-stack")) 11649 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11650 "inline-asm"; 11651 return false; 11652 } 11653 11654 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11655 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11656 unsigned StackAlign = TFI->getStackAlignment(); 11657 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11658 "Unexpected stack alignment"); 11659 // The default stack probe size is 4096 if the function has no 11660 // stack-probe-size attribute. 11661 unsigned StackProbeSize = 4096; 11662 const Function &Fn = MF.getFunction(); 11663 if (Fn.hasFnAttribute("stack-probe-size")) 11664 Fn.getFnAttribute("stack-probe-size") 11665 .getValueAsString() 11666 .getAsInteger(0, StackProbeSize); 11667 // Round down to the stack alignment. 11668 StackProbeSize &= ~(StackAlign - 1); 11669 return StackProbeSize ? StackProbeSize : StackAlign; 11670 } 11671 11672 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11673 // into three phases. In the first phase, it uses pseudo instruction 11674 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11675 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11676 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11677 // MaxCallFrameSize so that it can calculate correct data area pointer. 11678 MachineBasicBlock * 11679 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11680 MachineBasicBlock *MBB) const { 11681 const bool isPPC64 = Subtarget.isPPC64(); 11682 MachineFunction *MF = MBB->getParent(); 11683 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11684 DebugLoc DL = MI.getDebugLoc(); 11685 const unsigned ProbeSize = getStackProbeSize(*MF); 11686 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11687 MachineRegisterInfo &MRI = MF->getRegInfo(); 11688 // The CFG of probing stack looks as 11689 // +-----+ 11690 // | MBB | 11691 // +--+--+ 11692 // | 11693 // +----v----+ 11694 // +--->+ TestMBB +---+ 11695 // | +----+----+ | 11696 // | | | 11697 // | +-----v----+ | 11698 // +---+ BlockMBB | | 11699 // +----------+ | 11700 // | 11701 // +---------+ | 11702 // | TailMBB +<--+ 11703 // +---------+ 11704 // In MBB, calculate previous frame pointer and final stack pointer. 11705 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11706 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11707 // TailMBB is spliced via \p MI. 11708 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11709 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11710 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11711 11712 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11713 MF->insert(MBBIter, TestMBB); 11714 MF->insert(MBBIter, BlockMBB); 11715 MF->insert(MBBIter, TailMBB); 11716 11717 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11718 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11719 11720 Register DstReg = MI.getOperand(0).getReg(); 11721 Register NegSizeReg = MI.getOperand(1).getReg(); 11722 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11723 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11724 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11725 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11726 11727 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11728 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11729 // NegSize. 11730 unsigned ProbeOpc; 11731 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11732 ProbeOpc = 11733 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11734 else 11735 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11736 // and NegSizeReg will be allocated in the same phyreg to avoid 11737 // redundant copy when NegSizeReg has only one use which is current MI and 11738 // will be replaced by PREPARE_PROBED_ALLOCA then. 11739 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11740 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11741 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11742 .addDef(ActualNegSizeReg) 11743 .addReg(NegSizeReg) 11744 .add(MI.getOperand(2)) 11745 .add(MI.getOperand(3)); 11746 11747 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11748 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11749 FinalStackPtr) 11750 .addReg(SPReg) 11751 .addReg(ActualNegSizeReg); 11752 11753 // Materialize a scratch register for update. 11754 int64_t NegProbeSize = -(int64_t)ProbeSize; 11755 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11756 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11757 if (!isInt<16>(NegProbeSize)) { 11758 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11759 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11760 .addImm(NegProbeSize >> 16); 11761 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11762 ScratchReg) 11763 .addReg(TempReg) 11764 .addImm(NegProbeSize & 0xFFFF); 11765 } else 11766 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11767 .addImm(NegProbeSize); 11768 11769 { 11770 // Probing leading residual part. 11771 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11772 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11773 .addReg(ActualNegSizeReg) 11774 .addReg(ScratchReg); 11775 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11776 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11777 .addReg(Div) 11778 .addReg(ScratchReg); 11779 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11780 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11781 .addReg(Mul) 11782 .addReg(ActualNegSizeReg); 11783 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11784 .addReg(FramePointer) 11785 .addReg(SPReg) 11786 .addReg(NegMod); 11787 } 11788 11789 { 11790 // Remaining part should be multiple of ProbeSize. 11791 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11792 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11793 .addReg(SPReg) 11794 .addReg(FinalStackPtr); 11795 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11796 .addImm(PPC::PRED_EQ) 11797 .addReg(CmpResult) 11798 .addMBB(TailMBB); 11799 TestMBB->addSuccessor(BlockMBB); 11800 TestMBB->addSuccessor(TailMBB); 11801 } 11802 11803 { 11804 // Touch the block. 11805 // |P...|P...|P... 11806 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11807 .addReg(FramePointer) 11808 .addReg(SPReg) 11809 .addReg(ScratchReg); 11810 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11811 BlockMBB->addSuccessor(TestMBB); 11812 } 11813 11814 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11815 // DYNAREAOFFSET pseudo instruction to get the future result. 11816 Register MaxCallFrameSizeReg = 11817 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11818 BuildMI(TailMBB, DL, 11819 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11820 MaxCallFrameSizeReg) 11821 .add(MI.getOperand(2)) 11822 .add(MI.getOperand(3)); 11823 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11824 .addReg(SPReg) 11825 .addReg(MaxCallFrameSizeReg); 11826 11827 // Splice instructions after MI to TailMBB. 11828 TailMBB->splice(TailMBB->end(), MBB, 11829 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11830 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11831 MBB->addSuccessor(TestMBB); 11832 11833 // Delete the pseudo instruction. 11834 MI.eraseFromParent(); 11835 11836 ++NumDynamicAllocaProbed; 11837 return TailMBB; 11838 } 11839 11840 MachineBasicBlock * 11841 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11842 MachineBasicBlock *BB) const { 11843 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11844 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11845 if (Subtarget.is64BitELFABI() && 11846 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11847 !Subtarget.isUsingPCRelativeCalls()) { 11848 // Call lowering should have added an r2 operand to indicate a dependence 11849 // on the TOC base pointer value. It can't however, because there is no 11850 // way to mark the dependence as implicit there, and so the stackmap code 11851 // will confuse it with a regular operand. Instead, add the dependence 11852 // here. 11853 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11854 } 11855 11856 return emitPatchPoint(MI, BB); 11857 } 11858 11859 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11860 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11861 return emitEHSjLjSetJmp(MI, BB); 11862 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11863 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11864 return emitEHSjLjLongJmp(MI, BB); 11865 } 11866 11867 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11868 11869 // To "insert" these instructions we actually have to insert their 11870 // control-flow patterns. 11871 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11872 MachineFunction::iterator It = ++BB->getIterator(); 11873 11874 MachineFunction *F = BB->getParent(); 11875 11876 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11877 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11878 MI.getOpcode() == PPC::SELECT_I8) { 11879 SmallVector<MachineOperand, 2> Cond; 11880 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11881 MI.getOpcode() == PPC::SELECT_CC_I8) 11882 Cond.push_back(MI.getOperand(4)); 11883 else 11884 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11885 Cond.push_back(MI.getOperand(1)); 11886 11887 DebugLoc dl = MI.getDebugLoc(); 11888 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11889 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11890 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11891 MI.getOpcode() == PPC::SELECT_CC_F8 || 11892 MI.getOpcode() == PPC::SELECT_CC_F16 || 11893 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11894 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11895 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11896 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11897 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11898 MI.getOpcode() == PPC::SELECT_CC_SPE || 11899 MI.getOpcode() == PPC::SELECT_F4 || 11900 MI.getOpcode() == PPC::SELECT_F8 || 11901 MI.getOpcode() == PPC::SELECT_F16 || 11902 MI.getOpcode() == PPC::SELECT_SPE || 11903 MI.getOpcode() == PPC::SELECT_SPE4 || 11904 MI.getOpcode() == PPC::SELECT_VRRC || 11905 MI.getOpcode() == PPC::SELECT_VSFRC || 11906 MI.getOpcode() == PPC::SELECT_VSSRC || 11907 MI.getOpcode() == PPC::SELECT_VSRC) { 11908 // The incoming instruction knows the destination vreg to set, the 11909 // condition code register to branch on, the true/false values to 11910 // select between, and a branch opcode to use. 11911 11912 // thisMBB: 11913 // ... 11914 // TrueVal = ... 11915 // cmpTY ccX, r1, r2 11916 // bCC copy1MBB 11917 // fallthrough --> copy0MBB 11918 MachineBasicBlock *thisMBB = BB; 11919 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11920 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11921 DebugLoc dl = MI.getDebugLoc(); 11922 F->insert(It, copy0MBB); 11923 F->insert(It, sinkMBB); 11924 11925 // Transfer the remainder of BB and its successor edges to sinkMBB. 11926 sinkMBB->splice(sinkMBB->begin(), BB, 11927 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11928 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11929 11930 // Next, add the true and fallthrough blocks as its successors. 11931 BB->addSuccessor(copy0MBB); 11932 BB->addSuccessor(sinkMBB); 11933 11934 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11935 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11936 MI.getOpcode() == PPC::SELECT_F16 || 11937 MI.getOpcode() == PPC::SELECT_SPE4 || 11938 MI.getOpcode() == PPC::SELECT_SPE || 11939 MI.getOpcode() == PPC::SELECT_VRRC || 11940 MI.getOpcode() == PPC::SELECT_VSFRC || 11941 MI.getOpcode() == PPC::SELECT_VSSRC || 11942 MI.getOpcode() == PPC::SELECT_VSRC) { 11943 BuildMI(BB, dl, TII->get(PPC::BC)) 11944 .addReg(MI.getOperand(1).getReg()) 11945 .addMBB(sinkMBB); 11946 } else { 11947 unsigned SelectPred = MI.getOperand(4).getImm(); 11948 BuildMI(BB, dl, TII->get(PPC::BCC)) 11949 .addImm(SelectPred) 11950 .addReg(MI.getOperand(1).getReg()) 11951 .addMBB(sinkMBB); 11952 } 11953 11954 // copy0MBB: 11955 // %FalseValue = ... 11956 // # fallthrough to sinkMBB 11957 BB = copy0MBB; 11958 11959 // Update machine-CFG edges 11960 BB->addSuccessor(sinkMBB); 11961 11962 // sinkMBB: 11963 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11964 // ... 11965 BB = sinkMBB; 11966 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11967 .addReg(MI.getOperand(3).getReg()) 11968 .addMBB(copy0MBB) 11969 .addReg(MI.getOperand(2).getReg()) 11970 .addMBB(thisMBB); 11971 } else if (MI.getOpcode() == PPC::ReadTB) { 11972 // To read the 64-bit time-base register on a 32-bit target, we read the 11973 // two halves. Should the counter have wrapped while it was being read, we 11974 // need to try again. 11975 // ... 11976 // readLoop: 11977 // mfspr Rx,TBU # load from TBU 11978 // mfspr Ry,TB # load from TB 11979 // mfspr Rz,TBU # load from TBU 11980 // cmpw crX,Rx,Rz # check if 'old'='new' 11981 // bne readLoop # branch if they're not equal 11982 // ... 11983 11984 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11985 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11986 DebugLoc dl = MI.getDebugLoc(); 11987 F->insert(It, readMBB); 11988 F->insert(It, sinkMBB); 11989 11990 // Transfer the remainder of BB and its successor edges to sinkMBB. 11991 sinkMBB->splice(sinkMBB->begin(), BB, 11992 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11993 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11994 11995 BB->addSuccessor(readMBB); 11996 BB = readMBB; 11997 11998 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11999 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12000 Register LoReg = MI.getOperand(0).getReg(); 12001 Register HiReg = MI.getOperand(1).getReg(); 12002 12003 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12004 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12005 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12006 12007 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12008 12009 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12010 .addReg(HiReg) 12011 .addReg(ReadAgainReg); 12012 BuildMI(BB, dl, TII->get(PPC::BCC)) 12013 .addImm(PPC::PRED_NE) 12014 .addReg(CmpReg) 12015 .addMBB(readMBB); 12016 12017 BB->addSuccessor(readMBB); 12018 BB->addSuccessor(sinkMBB); 12019 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12020 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12021 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12022 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12023 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12024 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12025 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12026 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12027 12028 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12029 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12030 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12031 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12032 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12033 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12034 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12035 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12036 12037 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12038 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12039 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12040 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12041 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12042 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12043 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12044 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12045 12046 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12047 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12048 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12049 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12050 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12051 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12052 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12053 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12054 12055 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12056 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12057 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12058 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12059 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12060 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12061 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12062 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12063 12064 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12065 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12066 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12067 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12068 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12069 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12070 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12071 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12072 12073 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12074 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12075 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12076 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12077 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12078 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12079 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12080 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12081 12082 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12083 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12084 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12085 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12086 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12087 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12088 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12089 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12090 12091 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12092 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12093 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12094 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12095 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12096 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12097 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12098 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12099 12100 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12101 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12102 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12103 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12104 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12105 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12106 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12107 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12108 12109 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12110 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12111 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12112 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12113 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12114 BB = EmitAtomicBinary(MI, BB, 4, 0); 12115 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12116 BB = EmitAtomicBinary(MI, BB, 8, 0); 12117 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12118 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12119 (Subtarget.hasPartwordAtomics() && 12120 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12121 (Subtarget.hasPartwordAtomics() && 12122 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12123 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12124 12125 auto LoadMnemonic = PPC::LDARX; 12126 auto StoreMnemonic = PPC::STDCX; 12127 switch (MI.getOpcode()) { 12128 default: 12129 llvm_unreachable("Compare and swap of unknown size"); 12130 case PPC::ATOMIC_CMP_SWAP_I8: 12131 LoadMnemonic = PPC::LBARX; 12132 StoreMnemonic = PPC::STBCX; 12133 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12134 break; 12135 case PPC::ATOMIC_CMP_SWAP_I16: 12136 LoadMnemonic = PPC::LHARX; 12137 StoreMnemonic = PPC::STHCX; 12138 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12139 break; 12140 case PPC::ATOMIC_CMP_SWAP_I32: 12141 LoadMnemonic = PPC::LWARX; 12142 StoreMnemonic = PPC::STWCX; 12143 break; 12144 case PPC::ATOMIC_CMP_SWAP_I64: 12145 LoadMnemonic = PPC::LDARX; 12146 StoreMnemonic = PPC::STDCX; 12147 break; 12148 } 12149 Register dest = MI.getOperand(0).getReg(); 12150 Register ptrA = MI.getOperand(1).getReg(); 12151 Register ptrB = MI.getOperand(2).getReg(); 12152 Register oldval = MI.getOperand(3).getReg(); 12153 Register newval = MI.getOperand(4).getReg(); 12154 DebugLoc dl = MI.getDebugLoc(); 12155 12156 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12157 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12158 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12159 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12160 F->insert(It, loop1MBB); 12161 F->insert(It, loop2MBB); 12162 F->insert(It, midMBB); 12163 F->insert(It, exitMBB); 12164 exitMBB->splice(exitMBB->begin(), BB, 12165 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12166 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12167 12168 // thisMBB: 12169 // ... 12170 // fallthrough --> loopMBB 12171 BB->addSuccessor(loop1MBB); 12172 12173 // loop1MBB: 12174 // l[bhwd]arx dest, ptr 12175 // cmp[wd] dest, oldval 12176 // bne- midMBB 12177 // loop2MBB: 12178 // st[bhwd]cx. newval, ptr 12179 // bne- loopMBB 12180 // b exitBB 12181 // midMBB: 12182 // st[bhwd]cx. dest, ptr 12183 // exitBB: 12184 BB = loop1MBB; 12185 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12186 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12187 .addReg(oldval) 12188 .addReg(dest); 12189 BuildMI(BB, dl, TII->get(PPC::BCC)) 12190 .addImm(PPC::PRED_NE) 12191 .addReg(PPC::CR0) 12192 .addMBB(midMBB); 12193 BB->addSuccessor(loop2MBB); 12194 BB->addSuccessor(midMBB); 12195 12196 BB = loop2MBB; 12197 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12198 .addReg(newval) 12199 .addReg(ptrA) 12200 .addReg(ptrB); 12201 BuildMI(BB, dl, TII->get(PPC::BCC)) 12202 .addImm(PPC::PRED_NE) 12203 .addReg(PPC::CR0) 12204 .addMBB(loop1MBB); 12205 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12206 BB->addSuccessor(loop1MBB); 12207 BB->addSuccessor(exitMBB); 12208 12209 BB = midMBB; 12210 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12211 .addReg(dest) 12212 .addReg(ptrA) 12213 .addReg(ptrB); 12214 BB->addSuccessor(exitMBB); 12215 12216 // exitMBB: 12217 // ... 12218 BB = exitMBB; 12219 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12220 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12221 // We must use 64-bit registers for addresses when targeting 64-bit, 12222 // since we're actually doing arithmetic on them. Other registers 12223 // can be 32-bit. 12224 bool is64bit = Subtarget.isPPC64(); 12225 bool isLittleEndian = Subtarget.isLittleEndian(); 12226 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12227 12228 Register dest = MI.getOperand(0).getReg(); 12229 Register ptrA = MI.getOperand(1).getReg(); 12230 Register ptrB = MI.getOperand(2).getReg(); 12231 Register oldval = MI.getOperand(3).getReg(); 12232 Register newval = MI.getOperand(4).getReg(); 12233 DebugLoc dl = MI.getDebugLoc(); 12234 12235 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12236 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12237 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12238 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12239 F->insert(It, loop1MBB); 12240 F->insert(It, loop2MBB); 12241 F->insert(It, midMBB); 12242 F->insert(It, exitMBB); 12243 exitMBB->splice(exitMBB->begin(), BB, 12244 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12245 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12246 12247 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12248 const TargetRegisterClass *RC = 12249 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12250 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12251 12252 Register PtrReg = RegInfo.createVirtualRegister(RC); 12253 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12254 Register ShiftReg = 12255 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12256 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12257 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12258 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12259 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12260 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12261 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12262 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12263 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12264 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12265 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12266 Register Ptr1Reg; 12267 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12268 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12269 // thisMBB: 12270 // ... 12271 // fallthrough --> loopMBB 12272 BB->addSuccessor(loop1MBB); 12273 12274 // The 4-byte load must be aligned, while a char or short may be 12275 // anywhere in the word. Hence all this nasty bookkeeping code. 12276 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12277 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12278 // xori shift, shift1, 24 [16] 12279 // rlwinm ptr, ptr1, 0, 0, 29 12280 // slw newval2, newval, shift 12281 // slw oldval2, oldval,shift 12282 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12283 // slw mask, mask2, shift 12284 // and newval3, newval2, mask 12285 // and oldval3, oldval2, mask 12286 // loop1MBB: 12287 // lwarx tmpDest, ptr 12288 // and tmp, tmpDest, mask 12289 // cmpw tmp, oldval3 12290 // bne- midMBB 12291 // loop2MBB: 12292 // andc tmp2, tmpDest, mask 12293 // or tmp4, tmp2, newval3 12294 // stwcx. tmp4, ptr 12295 // bne- loop1MBB 12296 // b exitBB 12297 // midMBB: 12298 // stwcx. tmpDest, ptr 12299 // exitBB: 12300 // srw dest, tmpDest, shift 12301 if (ptrA != ZeroReg) { 12302 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12303 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12304 .addReg(ptrA) 12305 .addReg(ptrB); 12306 } else { 12307 Ptr1Reg = ptrB; 12308 } 12309 12310 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12311 // mode. 12312 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12313 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12314 .addImm(3) 12315 .addImm(27) 12316 .addImm(is8bit ? 28 : 27); 12317 if (!isLittleEndian) 12318 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12319 .addReg(Shift1Reg) 12320 .addImm(is8bit ? 24 : 16); 12321 if (is64bit) 12322 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12323 .addReg(Ptr1Reg) 12324 .addImm(0) 12325 .addImm(61); 12326 else 12327 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12328 .addReg(Ptr1Reg) 12329 .addImm(0) 12330 .addImm(0) 12331 .addImm(29); 12332 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12333 .addReg(newval) 12334 .addReg(ShiftReg); 12335 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12336 .addReg(oldval) 12337 .addReg(ShiftReg); 12338 if (is8bit) 12339 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12340 else { 12341 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12342 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12343 .addReg(Mask3Reg) 12344 .addImm(65535); 12345 } 12346 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12347 .addReg(Mask2Reg) 12348 .addReg(ShiftReg); 12349 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12350 .addReg(NewVal2Reg) 12351 .addReg(MaskReg); 12352 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12353 .addReg(OldVal2Reg) 12354 .addReg(MaskReg); 12355 12356 BB = loop1MBB; 12357 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12358 .addReg(ZeroReg) 12359 .addReg(PtrReg); 12360 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12361 .addReg(TmpDestReg) 12362 .addReg(MaskReg); 12363 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12364 .addReg(TmpReg) 12365 .addReg(OldVal3Reg); 12366 BuildMI(BB, dl, TII->get(PPC::BCC)) 12367 .addImm(PPC::PRED_NE) 12368 .addReg(PPC::CR0) 12369 .addMBB(midMBB); 12370 BB->addSuccessor(loop2MBB); 12371 BB->addSuccessor(midMBB); 12372 12373 BB = loop2MBB; 12374 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12375 .addReg(TmpDestReg) 12376 .addReg(MaskReg); 12377 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12378 .addReg(Tmp2Reg) 12379 .addReg(NewVal3Reg); 12380 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12381 .addReg(Tmp4Reg) 12382 .addReg(ZeroReg) 12383 .addReg(PtrReg); 12384 BuildMI(BB, dl, TII->get(PPC::BCC)) 12385 .addImm(PPC::PRED_NE) 12386 .addReg(PPC::CR0) 12387 .addMBB(loop1MBB); 12388 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12389 BB->addSuccessor(loop1MBB); 12390 BB->addSuccessor(exitMBB); 12391 12392 BB = midMBB; 12393 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12394 .addReg(TmpDestReg) 12395 .addReg(ZeroReg) 12396 .addReg(PtrReg); 12397 BB->addSuccessor(exitMBB); 12398 12399 // exitMBB: 12400 // ... 12401 BB = exitMBB; 12402 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12403 .addReg(TmpReg) 12404 .addReg(ShiftReg); 12405 } else if (MI.getOpcode() == PPC::FADDrtz) { 12406 // This pseudo performs an FADD with rounding mode temporarily forced 12407 // to round-to-zero. We emit this via custom inserter since the FPSCR 12408 // is not modeled at the SelectionDAG level. 12409 Register Dest = MI.getOperand(0).getReg(); 12410 Register Src1 = MI.getOperand(1).getReg(); 12411 Register Src2 = MI.getOperand(2).getReg(); 12412 DebugLoc dl = MI.getDebugLoc(); 12413 12414 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12415 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12416 12417 // Save FPSCR value. 12418 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12419 12420 // Set rounding mode to round-to-zero. 12421 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12422 .addImm(31) 12423 .addReg(PPC::RM, RegState::ImplicitDefine); 12424 12425 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12426 .addImm(30) 12427 .addReg(PPC::RM, RegState::ImplicitDefine); 12428 12429 // Perform addition. 12430 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12431 .addReg(Src1) 12432 .addReg(Src2); 12433 if (MI.getFlag(MachineInstr::NoFPExcept)) 12434 MIB.setMIFlag(MachineInstr::NoFPExcept); 12435 12436 // Restore FPSCR value. 12437 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12438 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12439 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12440 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12441 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12442 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12443 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12444 ? PPC::ANDI8_rec 12445 : PPC::ANDI_rec; 12446 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12447 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12448 12449 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12450 Register Dest = RegInfo.createVirtualRegister( 12451 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12452 12453 DebugLoc Dl = MI.getDebugLoc(); 12454 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12455 .addReg(MI.getOperand(1).getReg()) 12456 .addImm(1); 12457 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12458 MI.getOperand(0).getReg()) 12459 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12460 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12461 DebugLoc Dl = MI.getDebugLoc(); 12462 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12463 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12464 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12465 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12466 MI.getOperand(0).getReg()) 12467 .addReg(CRReg); 12468 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12469 DebugLoc Dl = MI.getDebugLoc(); 12470 unsigned Imm = MI.getOperand(1).getImm(); 12471 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12472 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12473 MI.getOperand(0).getReg()) 12474 .addReg(PPC::CR0EQ); 12475 } else if (MI.getOpcode() == PPC::SETRNDi) { 12476 DebugLoc dl = MI.getDebugLoc(); 12477 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12478 12479 // Save FPSCR value. 12480 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12481 12482 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12483 // the following settings: 12484 // 00 Round to nearest 12485 // 01 Round to 0 12486 // 10 Round to +inf 12487 // 11 Round to -inf 12488 12489 // When the operand is immediate, using the two least significant bits of 12490 // the immediate to set the bits 62:63 of FPSCR. 12491 unsigned Mode = MI.getOperand(1).getImm(); 12492 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12493 .addImm(31) 12494 .addReg(PPC::RM, RegState::ImplicitDefine); 12495 12496 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12497 .addImm(30) 12498 .addReg(PPC::RM, RegState::ImplicitDefine); 12499 } else if (MI.getOpcode() == PPC::SETRND) { 12500 DebugLoc dl = MI.getDebugLoc(); 12501 12502 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12503 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12504 // If the target doesn't have DirectMove, we should use stack to do the 12505 // conversion, because the target doesn't have the instructions like mtvsrd 12506 // or mfvsrd to do this conversion directly. 12507 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12508 if (Subtarget.hasDirectMove()) { 12509 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12510 .addReg(SrcReg); 12511 } else { 12512 // Use stack to do the register copy. 12513 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12514 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12515 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12516 if (RC == &PPC::F8RCRegClass) { 12517 // Copy register from F8RCRegClass to G8RCRegclass. 12518 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12519 "Unsupported RegClass."); 12520 12521 StoreOp = PPC::STFD; 12522 LoadOp = PPC::LD; 12523 } else { 12524 // Copy register from G8RCRegClass to F8RCRegclass. 12525 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12526 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12527 "Unsupported RegClass."); 12528 } 12529 12530 MachineFrameInfo &MFI = F->getFrameInfo(); 12531 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12532 12533 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12534 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12535 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12536 MFI.getObjectAlign(FrameIdx)); 12537 12538 // Store the SrcReg into the stack. 12539 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12540 .addReg(SrcReg) 12541 .addImm(0) 12542 .addFrameIndex(FrameIdx) 12543 .addMemOperand(MMOStore); 12544 12545 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12546 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12547 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12548 MFI.getObjectAlign(FrameIdx)); 12549 12550 // Load from the stack where SrcReg is stored, and save to DestReg, 12551 // so we have done the RegClass conversion from RegClass::SrcReg to 12552 // RegClass::DestReg. 12553 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12554 .addImm(0) 12555 .addFrameIndex(FrameIdx) 12556 .addMemOperand(MMOLoad); 12557 } 12558 }; 12559 12560 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12561 12562 // Save FPSCR value. 12563 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12564 12565 // When the operand is gprc register, use two least significant bits of the 12566 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12567 // 12568 // copy OldFPSCRTmpReg, OldFPSCRReg 12569 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12570 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12571 // copy NewFPSCRReg, NewFPSCRTmpReg 12572 // mtfsf 255, NewFPSCRReg 12573 MachineOperand SrcOp = MI.getOperand(1); 12574 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12575 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12576 12577 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12578 12579 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12580 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12581 12582 // The first operand of INSERT_SUBREG should be a register which has 12583 // subregisters, we only care about its RegClass, so we should use an 12584 // IMPLICIT_DEF register. 12585 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12586 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12587 .addReg(ImDefReg) 12588 .add(SrcOp) 12589 .addImm(1); 12590 12591 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12592 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12593 .addReg(OldFPSCRTmpReg) 12594 .addReg(ExtSrcReg) 12595 .addImm(0) 12596 .addImm(62); 12597 12598 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12599 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12600 12601 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12602 // bits of FPSCR. 12603 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12604 .addImm(255) 12605 .addReg(NewFPSCRReg) 12606 .addImm(0) 12607 .addImm(0); 12608 } else if (MI.getOpcode() == PPC::SETFLM) { 12609 DebugLoc Dl = MI.getDebugLoc(); 12610 12611 // Result of setflm is previous FPSCR content, so we need to save it first. 12612 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12613 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12614 12615 // Put bits in 32:63 to FPSCR. 12616 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12617 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12618 .addImm(255) 12619 .addReg(NewFPSCRReg) 12620 .addImm(0) 12621 .addImm(0); 12622 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12623 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12624 return emitProbedAlloca(MI, BB); 12625 } else { 12626 llvm_unreachable("Unexpected instr type to insert"); 12627 } 12628 12629 MI.eraseFromParent(); // The pseudo instruction is gone now. 12630 return BB; 12631 } 12632 12633 //===----------------------------------------------------------------------===// 12634 // Target Optimization Hooks 12635 //===----------------------------------------------------------------------===// 12636 12637 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12638 // For the estimates, convergence is quadratic, so we essentially double the 12639 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12640 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12641 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12642 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12643 if (VT.getScalarType() == MVT::f64) 12644 RefinementSteps++; 12645 return RefinementSteps; 12646 } 12647 12648 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12649 const DenormalMode &Mode) const { 12650 // We only have VSX Vector Test for software Square Root. 12651 EVT VT = Op.getValueType(); 12652 if (!isTypeLegal(MVT::i1) || 12653 (VT != MVT::f64 && 12654 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12655 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 12656 12657 SDLoc DL(Op); 12658 // The output register of FTSQRT is CR field. 12659 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12660 // ftsqrt BF,FRB 12661 // Let e_b be the unbiased exponent of the double-precision 12662 // floating-point operand in register FRB. 12663 // fe_flag is set to 1 if either of the following conditions occurs. 12664 // - The double-precision floating-point operand in register FRB is a zero, 12665 // a NaN, or an infinity, or a negative value. 12666 // - e_b is less than or equal to -970. 12667 // Otherwise fe_flag is set to 0. 12668 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 12669 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 12670 // exponent is less than -970) 12671 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 12672 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 12673 FTSQRT, SRIdxVal), 12674 0); 12675 } 12676 12677 SDValue 12678 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 12679 SelectionDAG &DAG) const { 12680 // We only have VSX Vector Square Root. 12681 EVT VT = Op.getValueType(); 12682 if (VT != MVT::f64 && 12683 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 12684 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 12685 12686 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 12687 } 12688 12689 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12690 int Enabled, int &RefinementSteps, 12691 bool &UseOneConstNR, 12692 bool Reciprocal) const { 12693 EVT VT = Operand.getValueType(); 12694 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12695 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12696 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12697 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12698 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12699 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12700 12701 // The Newton-Raphson computation with a single constant does not provide 12702 // enough accuracy on some CPUs. 12703 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12704 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12705 } 12706 return SDValue(); 12707 } 12708 12709 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12710 int Enabled, 12711 int &RefinementSteps) const { 12712 EVT VT = Operand.getValueType(); 12713 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12714 (VT == MVT::f64 && Subtarget.hasFRE()) || 12715 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12716 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12717 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12718 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12719 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12720 } 12721 return SDValue(); 12722 } 12723 12724 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12725 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12726 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12727 // enabled for division), this functionality is redundant with the default 12728 // combiner logic (once the division -> reciprocal/multiply transformation 12729 // has taken place). As a result, this matters more for older cores than for 12730 // newer ones. 12731 12732 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12733 // reciprocal if there are two or more FDIVs (for embedded cores with only 12734 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12735 switch (Subtarget.getCPUDirective()) { 12736 default: 12737 return 3; 12738 case PPC::DIR_440: 12739 case PPC::DIR_A2: 12740 case PPC::DIR_E500: 12741 case PPC::DIR_E500mc: 12742 case PPC::DIR_E5500: 12743 return 2; 12744 } 12745 } 12746 12747 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12748 // collapsed, and so we need to look through chains of them. 12749 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12750 int64_t& Offset, SelectionDAG &DAG) { 12751 if (DAG.isBaseWithConstantOffset(Loc)) { 12752 Base = Loc.getOperand(0); 12753 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12754 12755 // The base might itself be a base plus an offset, and if so, accumulate 12756 // that as well. 12757 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12758 } 12759 } 12760 12761 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12762 unsigned Bytes, int Dist, 12763 SelectionDAG &DAG) { 12764 if (VT.getSizeInBits() / 8 != Bytes) 12765 return false; 12766 12767 SDValue BaseLoc = Base->getBasePtr(); 12768 if (Loc.getOpcode() == ISD::FrameIndex) { 12769 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12770 return false; 12771 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12772 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12773 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12774 int FS = MFI.getObjectSize(FI); 12775 int BFS = MFI.getObjectSize(BFI); 12776 if (FS != BFS || FS != (int)Bytes) return false; 12777 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12778 } 12779 12780 SDValue Base1 = Loc, Base2 = BaseLoc; 12781 int64_t Offset1 = 0, Offset2 = 0; 12782 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12783 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12784 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12785 return true; 12786 12787 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12788 const GlobalValue *GV1 = nullptr; 12789 const GlobalValue *GV2 = nullptr; 12790 Offset1 = 0; 12791 Offset2 = 0; 12792 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12793 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12794 if (isGA1 && isGA2 && GV1 == GV2) 12795 return Offset1 == (Offset2 + Dist*Bytes); 12796 return false; 12797 } 12798 12799 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12800 // not enforce equality of the chain operands. 12801 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12802 unsigned Bytes, int Dist, 12803 SelectionDAG &DAG) { 12804 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12805 EVT VT = LS->getMemoryVT(); 12806 SDValue Loc = LS->getBasePtr(); 12807 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12808 } 12809 12810 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12811 EVT VT; 12812 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12813 default: return false; 12814 case Intrinsic::ppc_altivec_lvx: 12815 case Intrinsic::ppc_altivec_lvxl: 12816 case Intrinsic::ppc_vsx_lxvw4x: 12817 case Intrinsic::ppc_vsx_lxvw4x_be: 12818 VT = MVT::v4i32; 12819 break; 12820 case Intrinsic::ppc_vsx_lxvd2x: 12821 case Intrinsic::ppc_vsx_lxvd2x_be: 12822 VT = MVT::v2f64; 12823 break; 12824 case Intrinsic::ppc_altivec_lvebx: 12825 VT = MVT::i8; 12826 break; 12827 case Intrinsic::ppc_altivec_lvehx: 12828 VT = MVT::i16; 12829 break; 12830 case Intrinsic::ppc_altivec_lvewx: 12831 VT = MVT::i32; 12832 break; 12833 } 12834 12835 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12836 } 12837 12838 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12839 EVT VT; 12840 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12841 default: return false; 12842 case Intrinsic::ppc_altivec_stvx: 12843 case Intrinsic::ppc_altivec_stvxl: 12844 case Intrinsic::ppc_vsx_stxvw4x: 12845 VT = MVT::v4i32; 12846 break; 12847 case Intrinsic::ppc_vsx_stxvd2x: 12848 VT = MVT::v2f64; 12849 break; 12850 case Intrinsic::ppc_vsx_stxvw4x_be: 12851 VT = MVT::v4i32; 12852 break; 12853 case Intrinsic::ppc_vsx_stxvd2x_be: 12854 VT = MVT::v2f64; 12855 break; 12856 case Intrinsic::ppc_altivec_stvebx: 12857 VT = MVT::i8; 12858 break; 12859 case Intrinsic::ppc_altivec_stvehx: 12860 VT = MVT::i16; 12861 break; 12862 case Intrinsic::ppc_altivec_stvewx: 12863 VT = MVT::i32; 12864 break; 12865 } 12866 12867 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12868 } 12869 12870 return false; 12871 } 12872 12873 // Return true is there is a nearyby consecutive load to the one provided 12874 // (regardless of alignment). We search up and down the chain, looking though 12875 // token factors and other loads (but nothing else). As a result, a true result 12876 // indicates that it is safe to create a new consecutive load adjacent to the 12877 // load provided. 12878 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12879 SDValue Chain = LD->getChain(); 12880 EVT VT = LD->getMemoryVT(); 12881 12882 SmallSet<SDNode *, 16> LoadRoots; 12883 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12884 SmallSet<SDNode *, 16> Visited; 12885 12886 // First, search up the chain, branching to follow all token-factor operands. 12887 // If we find a consecutive load, then we're done, otherwise, record all 12888 // nodes just above the top-level loads and token factors. 12889 while (!Queue.empty()) { 12890 SDNode *ChainNext = Queue.pop_back_val(); 12891 if (!Visited.insert(ChainNext).second) 12892 continue; 12893 12894 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12895 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12896 return true; 12897 12898 if (!Visited.count(ChainLD->getChain().getNode())) 12899 Queue.push_back(ChainLD->getChain().getNode()); 12900 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12901 for (const SDUse &O : ChainNext->ops()) 12902 if (!Visited.count(O.getNode())) 12903 Queue.push_back(O.getNode()); 12904 } else 12905 LoadRoots.insert(ChainNext); 12906 } 12907 12908 // Second, search down the chain, starting from the top-level nodes recorded 12909 // in the first phase. These top-level nodes are the nodes just above all 12910 // loads and token factors. Starting with their uses, recursively look though 12911 // all loads (just the chain uses) and token factors to find a consecutive 12912 // load. 12913 Visited.clear(); 12914 Queue.clear(); 12915 12916 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12917 IE = LoadRoots.end(); I != IE; ++I) { 12918 Queue.push_back(*I); 12919 12920 while (!Queue.empty()) { 12921 SDNode *LoadRoot = Queue.pop_back_val(); 12922 if (!Visited.insert(LoadRoot).second) 12923 continue; 12924 12925 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12926 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12927 return true; 12928 12929 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12930 UE = LoadRoot->use_end(); UI != UE; ++UI) 12931 if (((isa<MemSDNode>(*UI) && 12932 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12933 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12934 Queue.push_back(*UI); 12935 } 12936 } 12937 12938 return false; 12939 } 12940 12941 /// This function is called when we have proved that a SETCC node can be replaced 12942 /// by subtraction (and other supporting instructions) so that the result of 12943 /// comparison is kept in a GPR instead of CR. This function is purely for 12944 /// codegen purposes and has some flags to guide the codegen process. 12945 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12946 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12947 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12948 12949 // Zero extend the operands to the largest legal integer. Originally, they 12950 // must be of a strictly smaller size. 12951 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12952 DAG.getConstant(Size, DL, MVT::i32)); 12953 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12954 DAG.getConstant(Size, DL, MVT::i32)); 12955 12956 // Swap if needed. Depends on the condition code. 12957 if (Swap) 12958 std::swap(Op0, Op1); 12959 12960 // Subtract extended integers. 12961 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12962 12963 // Move the sign bit to the least significant position and zero out the rest. 12964 // Now the least significant bit carries the result of original comparison. 12965 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12966 DAG.getConstant(Size - 1, DL, MVT::i32)); 12967 auto Final = Shifted; 12968 12969 // Complement the result if needed. Based on the condition code. 12970 if (Complement) 12971 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12972 DAG.getConstant(1, DL, MVT::i64)); 12973 12974 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12975 } 12976 12977 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12978 DAGCombinerInfo &DCI) const { 12979 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12980 12981 SelectionDAG &DAG = DCI.DAG; 12982 SDLoc DL(N); 12983 12984 // Size of integers being compared has a critical role in the following 12985 // analysis, so we prefer to do this when all types are legal. 12986 if (!DCI.isAfterLegalizeDAG()) 12987 return SDValue(); 12988 12989 // If all users of SETCC extend its value to a legal integer type 12990 // then we replace SETCC with a subtraction 12991 for (SDNode::use_iterator UI = N->use_begin(), 12992 UE = N->use_end(); UI != UE; ++UI) { 12993 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12994 return SDValue(); 12995 } 12996 12997 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12998 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12999 13000 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 13001 13002 if (OpSize < Size) { 13003 switch (CC) { 13004 default: break; 13005 case ISD::SETULT: 13006 return generateEquivalentSub(N, Size, false, false, DL, DAG); 13007 case ISD::SETULE: 13008 return generateEquivalentSub(N, Size, true, true, DL, DAG); 13009 case ISD::SETUGT: 13010 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13011 case ISD::SETUGE: 13012 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13013 } 13014 } 13015 13016 return SDValue(); 13017 } 13018 13019 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13020 DAGCombinerInfo &DCI) const { 13021 SelectionDAG &DAG = DCI.DAG; 13022 SDLoc dl(N); 13023 13024 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13025 // If we're tracking CR bits, we need to be careful that we don't have: 13026 // trunc(binary-ops(zext(x), zext(y))) 13027 // or 13028 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13029 // such that we're unnecessarily moving things into GPRs when it would be 13030 // better to keep them in CR bits. 13031 13032 // Note that trunc here can be an actual i1 trunc, or can be the effective 13033 // truncation that comes from a setcc or select_cc. 13034 if (N->getOpcode() == ISD::TRUNCATE && 13035 N->getValueType(0) != MVT::i1) 13036 return SDValue(); 13037 13038 if (N->getOperand(0).getValueType() != MVT::i32 && 13039 N->getOperand(0).getValueType() != MVT::i64) 13040 return SDValue(); 13041 13042 if (N->getOpcode() == ISD::SETCC || 13043 N->getOpcode() == ISD::SELECT_CC) { 13044 // If we're looking at a comparison, then we need to make sure that the 13045 // high bits (all except for the first) don't matter the result. 13046 ISD::CondCode CC = 13047 cast<CondCodeSDNode>(N->getOperand( 13048 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13049 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13050 13051 if (ISD::isSignedIntSetCC(CC)) { 13052 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13053 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13054 return SDValue(); 13055 } else if (ISD::isUnsignedIntSetCC(CC)) { 13056 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13057 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13058 !DAG.MaskedValueIsZero(N->getOperand(1), 13059 APInt::getHighBitsSet(OpBits, OpBits-1))) 13060 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13061 : SDValue()); 13062 } else { 13063 // This is neither a signed nor an unsigned comparison, just make sure 13064 // that the high bits are equal. 13065 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13066 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13067 13068 // We don't really care about what is known about the first bit (if 13069 // anything), so pretend that it is known zero for both to ensure they can 13070 // be compared as constants. 13071 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13072 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13073 13074 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13075 Op1Known.getConstant() != Op2Known.getConstant()) 13076 return SDValue(); 13077 } 13078 } 13079 13080 // We now know that the higher-order bits are irrelevant, we just need to 13081 // make sure that all of the intermediate operations are bit operations, and 13082 // all inputs are extensions. 13083 if (N->getOperand(0).getOpcode() != ISD::AND && 13084 N->getOperand(0).getOpcode() != ISD::OR && 13085 N->getOperand(0).getOpcode() != ISD::XOR && 13086 N->getOperand(0).getOpcode() != ISD::SELECT && 13087 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13088 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13089 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13090 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13091 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13092 return SDValue(); 13093 13094 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13095 N->getOperand(1).getOpcode() != ISD::AND && 13096 N->getOperand(1).getOpcode() != ISD::OR && 13097 N->getOperand(1).getOpcode() != ISD::XOR && 13098 N->getOperand(1).getOpcode() != ISD::SELECT && 13099 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13100 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13101 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13102 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13103 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13104 return SDValue(); 13105 13106 SmallVector<SDValue, 4> Inputs; 13107 SmallVector<SDValue, 8> BinOps, PromOps; 13108 SmallPtrSet<SDNode *, 16> Visited; 13109 13110 for (unsigned i = 0; i < 2; ++i) { 13111 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13112 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13113 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13114 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13115 isa<ConstantSDNode>(N->getOperand(i))) 13116 Inputs.push_back(N->getOperand(i)); 13117 else 13118 BinOps.push_back(N->getOperand(i)); 13119 13120 if (N->getOpcode() == ISD::TRUNCATE) 13121 break; 13122 } 13123 13124 // Visit all inputs, collect all binary operations (and, or, xor and 13125 // select) that are all fed by extensions. 13126 while (!BinOps.empty()) { 13127 SDValue BinOp = BinOps.pop_back_val(); 13128 13129 if (!Visited.insert(BinOp.getNode()).second) 13130 continue; 13131 13132 PromOps.push_back(BinOp); 13133 13134 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13135 // The condition of the select is not promoted. 13136 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13137 continue; 13138 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13139 continue; 13140 13141 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13142 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13143 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13144 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13145 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13146 Inputs.push_back(BinOp.getOperand(i)); 13147 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13148 BinOp.getOperand(i).getOpcode() == ISD::OR || 13149 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13150 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13151 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13152 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13153 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13154 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13155 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13156 BinOps.push_back(BinOp.getOperand(i)); 13157 } else { 13158 // We have an input that is not an extension or another binary 13159 // operation; we'll abort this transformation. 13160 return SDValue(); 13161 } 13162 } 13163 } 13164 13165 // Make sure that this is a self-contained cluster of operations (which 13166 // is not quite the same thing as saying that everything has only one 13167 // use). 13168 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13169 if (isa<ConstantSDNode>(Inputs[i])) 13170 continue; 13171 13172 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13173 UE = Inputs[i].getNode()->use_end(); 13174 UI != UE; ++UI) { 13175 SDNode *User = *UI; 13176 if (User != N && !Visited.count(User)) 13177 return SDValue(); 13178 13179 // Make sure that we're not going to promote the non-output-value 13180 // operand(s) or SELECT or SELECT_CC. 13181 // FIXME: Although we could sometimes handle this, and it does occur in 13182 // practice that one of the condition inputs to the select is also one of 13183 // the outputs, we currently can't deal with this. 13184 if (User->getOpcode() == ISD::SELECT) { 13185 if (User->getOperand(0) == Inputs[i]) 13186 return SDValue(); 13187 } else if (User->getOpcode() == ISD::SELECT_CC) { 13188 if (User->getOperand(0) == Inputs[i] || 13189 User->getOperand(1) == Inputs[i]) 13190 return SDValue(); 13191 } 13192 } 13193 } 13194 13195 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13196 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13197 UE = PromOps[i].getNode()->use_end(); 13198 UI != UE; ++UI) { 13199 SDNode *User = *UI; 13200 if (User != N && !Visited.count(User)) 13201 return SDValue(); 13202 13203 // Make sure that we're not going to promote the non-output-value 13204 // operand(s) or SELECT or SELECT_CC. 13205 // FIXME: Although we could sometimes handle this, and it does occur in 13206 // practice that one of the condition inputs to the select is also one of 13207 // the outputs, we currently can't deal with this. 13208 if (User->getOpcode() == ISD::SELECT) { 13209 if (User->getOperand(0) == PromOps[i]) 13210 return SDValue(); 13211 } else if (User->getOpcode() == ISD::SELECT_CC) { 13212 if (User->getOperand(0) == PromOps[i] || 13213 User->getOperand(1) == PromOps[i]) 13214 return SDValue(); 13215 } 13216 } 13217 } 13218 13219 // Replace all inputs with the extension operand. 13220 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13221 // Constants may have users outside the cluster of to-be-promoted nodes, 13222 // and so we need to replace those as we do the promotions. 13223 if (isa<ConstantSDNode>(Inputs[i])) 13224 continue; 13225 else 13226 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13227 } 13228 13229 std::list<HandleSDNode> PromOpHandles; 13230 for (auto &PromOp : PromOps) 13231 PromOpHandles.emplace_back(PromOp); 13232 13233 // Replace all operations (these are all the same, but have a different 13234 // (i1) return type). DAG.getNode will validate that the types of 13235 // a binary operator match, so go through the list in reverse so that 13236 // we've likely promoted both operands first. Any intermediate truncations or 13237 // extensions disappear. 13238 while (!PromOpHandles.empty()) { 13239 SDValue PromOp = PromOpHandles.back().getValue(); 13240 PromOpHandles.pop_back(); 13241 13242 if (PromOp.getOpcode() == ISD::TRUNCATE || 13243 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13244 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13245 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13246 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13247 PromOp.getOperand(0).getValueType() != MVT::i1) { 13248 // The operand is not yet ready (see comment below). 13249 PromOpHandles.emplace_front(PromOp); 13250 continue; 13251 } 13252 13253 SDValue RepValue = PromOp.getOperand(0); 13254 if (isa<ConstantSDNode>(RepValue)) 13255 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13256 13257 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13258 continue; 13259 } 13260 13261 unsigned C; 13262 switch (PromOp.getOpcode()) { 13263 default: C = 0; break; 13264 case ISD::SELECT: C = 1; break; 13265 case ISD::SELECT_CC: C = 2; break; 13266 } 13267 13268 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13269 PromOp.getOperand(C).getValueType() != MVT::i1) || 13270 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13271 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13272 // The to-be-promoted operands of this node have not yet been 13273 // promoted (this should be rare because we're going through the 13274 // list backward, but if one of the operands has several users in 13275 // this cluster of to-be-promoted nodes, it is possible). 13276 PromOpHandles.emplace_front(PromOp); 13277 continue; 13278 } 13279 13280 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13281 PromOp.getNode()->op_end()); 13282 13283 // If there are any constant inputs, make sure they're replaced now. 13284 for (unsigned i = 0; i < 2; ++i) 13285 if (isa<ConstantSDNode>(Ops[C+i])) 13286 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13287 13288 DAG.ReplaceAllUsesOfValueWith(PromOp, 13289 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13290 } 13291 13292 // Now we're left with the initial truncation itself. 13293 if (N->getOpcode() == ISD::TRUNCATE) 13294 return N->getOperand(0); 13295 13296 // Otherwise, this is a comparison. The operands to be compared have just 13297 // changed type (to i1), but everything else is the same. 13298 return SDValue(N, 0); 13299 } 13300 13301 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13302 DAGCombinerInfo &DCI) const { 13303 SelectionDAG &DAG = DCI.DAG; 13304 SDLoc dl(N); 13305 13306 // If we're tracking CR bits, we need to be careful that we don't have: 13307 // zext(binary-ops(trunc(x), trunc(y))) 13308 // or 13309 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13310 // such that we're unnecessarily moving things into CR bits that can more 13311 // efficiently stay in GPRs. Note that if we're not certain that the high 13312 // bits are set as required by the final extension, we still may need to do 13313 // some masking to get the proper behavior. 13314 13315 // This same functionality is important on PPC64 when dealing with 13316 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13317 // the return values of functions. Because it is so similar, it is handled 13318 // here as well. 13319 13320 if (N->getValueType(0) != MVT::i32 && 13321 N->getValueType(0) != MVT::i64) 13322 return SDValue(); 13323 13324 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13325 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13326 return SDValue(); 13327 13328 if (N->getOperand(0).getOpcode() != ISD::AND && 13329 N->getOperand(0).getOpcode() != ISD::OR && 13330 N->getOperand(0).getOpcode() != ISD::XOR && 13331 N->getOperand(0).getOpcode() != ISD::SELECT && 13332 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13333 return SDValue(); 13334 13335 SmallVector<SDValue, 4> Inputs; 13336 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13337 SmallPtrSet<SDNode *, 16> Visited; 13338 13339 // Visit all inputs, collect all binary operations (and, or, xor and 13340 // select) that are all fed by truncations. 13341 while (!BinOps.empty()) { 13342 SDValue BinOp = BinOps.pop_back_val(); 13343 13344 if (!Visited.insert(BinOp.getNode()).second) 13345 continue; 13346 13347 PromOps.push_back(BinOp); 13348 13349 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13350 // The condition of the select is not promoted. 13351 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13352 continue; 13353 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13354 continue; 13355 13356 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13357 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13358 Inputs.push_back(BinOp.getOperand(i)); 13359 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13360 BinOp.getOperand(i).getOpcode() == ISD::OR || 13361 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13362 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13363 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13364 BinOps.push_back(BinOp.getOperand(i)); 13365 } else { 13366 // We have an input that is not a truncation or another binary 13367 // operation; we'll abort this transformation. 13368 return SDValue(); 13369 } 13370 } 13371 } 13372 13373 // The operands of a select that must be truncated when the select is 13374 // promoted because the operand is actually part of the to-be-promoted set. 13375 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13376 13377 // Make sure that this is a self-contained cluster of operations (which 13378 // is not quite the same thing as saying that everything has only one 13379 // use). 13380 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13381 if (isa<ConstantSDNode>(Inputs[i])) 13382 continue; 13383 13384 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13385 UE = Inputs[i].getNode()->use_end(); 13386 UI != UE; ++UI) { 13387 SDNode *User = *UI; 13388 if (User != N && !Visited.count(User)) 13389 return SDValue(); 13390 13391 // If we're going to promote the non-output-value operand(s) or SELECT or 13392 // SELECT_CC, record them for truncation. 13393 if (User->getOpcode() == ISD::SELECT) { 13394 if (User->getOperand(0) == Inputs[i]) 13395 SelectTruncOp[0].insert(std::make_pair(User, 13396 User->getOperand(0).getValueType())); 13397 } else if (User->getOpcode() == ISD::SELECT_CC) { 13398 if (User->getOperand(0) == Inputs[i]) 13399 SelectTruncOp[0].insert(std::make_pair(User, 13400 User->getOperand(0).getValueType())); 13401 if (User->getOperand(1) == Inputs[i]) 13402 SelectTruncOp[1].insert(std::make_pair(User, 13403 User->getOperand(1).getValueType())); 13404 } 13405 } 13406 } 13407 13408 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13409 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13410 UE = PromOps[i].getNode()->use_end(); 13411 UI != UE; ++UI) { 13412 SDNode *User = *UI; 13413 if (User != N && !Visited.count(User)) 13414 return SDValue(); 13415 13416 // If we're going to promote the non-output-value operand(s) or SELECT or 13417 // SELECT_CC, record them for truncation. 13418 if (User->getOpcode() == ISD::SELECT) { 13419 if (User->getOperand(0) == PromOps[i]) 13420 SelectTruncOp[0].insert(std::make_pair(User, 13421 User->getOperand(0).getValueType())); 13422 } else if (User->getOpcode() == ISD::SELECT_CC) { 13423 if (User->getOperand(0) == PromOps[i]) 13424 SelectTruncOp[0].insert(std::make_pair(User, 13425 User->getOperand(0).getValueType())); 13426 if (User->getOperand(1) == PromOps[i]) 13427 SelectTruncOp[1].insert(std::make_pair(User, 13428 User->getOperand(1).getValueType())); 13429 } 13430 } 13431 } 13432 13433 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13434 bool ReallyNeedsExt = false; 13435 if (N->getOpcode() != ISD::ANY_EXTEND) { 13436 // If all of the inputs are not already sign/zero extended, then 13437 // we'll still need to do that at the end. 13438 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13439 if (isa<ConstantSDNode>(Inputs[i])) 13440 continue; 13441 13442 unsigned OpBits = 13443 Inputs[i].getOperand(0).getValueSizeInBits(); 13444 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13445 13446 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13447 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13448 APInt::getHighBitsSet(OpBits, 13449 OpBits-PromBits))) || 13450 (N->getOpcode() == ISD::SIGN_EXTEND && 13451 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13452 (OpBits-(PromBits-1)))) { 13453 ReallyNeedsExt = true; 13454 break; 13455 } 13456 } 13457 } 13458 13459 // Replace all inputs, either with the truncation operand, or a 13460 // truncation or extension to the final output type. 13461 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13462 // Constant inputs need to be replaced with the to-be-promoted nodes that 13463 // use them because they might have users outside of the cluster of 13464 // promoted nodes. 13465 if (isa<ConstantSDNode>(Inputs[i])) 13466 continue; 13467 13468 SDValue InSrc = Inputs[i].getOperand(0); 13469 if (Inputs[i].getValueType() == N->getValueType(0)) 13470 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13471 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13472 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13473 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13474 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13475 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13476 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13477 else 13478 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13479 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13480 } 13481 13482 std::list<HandleSDNode> PromOpHandles; 13483 for (auto &PromOp : PromOps) 13484 PromOpHandles.emplace_back(PromOp); 13485 13486 // Replace all operations (these are all the same, but have a different 13487 // (promoted) return type). DAG.getNode will validate that the types of 13488 // a binary operator match, so go through the list in reverse so that 13489 // we've likely promoted both operands first. 13490 while (!PromOpHandles.empty()) { 13491 SDValue PromOp = PromOpHandles.back().getValue(); 13492 PromOpHandles.pop_back(); 13493 13494 unsigned C; 13495 switch (PromOp.getOpcode()) { 13496 default: C = 0; break; 13497 case ISD::SELECT: C = 1; break; 13498 case ISD::SELECT_CC: C = 2; break; 13499 } 13500 13501 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13502 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13503 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13504 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13505 // The to-be-promoted operands of this node have not yet been 13506 // promoted (this should be rare because we're going through the 13507 // list backward, but if one of the operands has several users in 13508 // this cluster of to-be-promoted nodes, it is possible). 13509 PromOpHandles.emplace_front(PromOp); 13510 continue; 13511 } 13512 13513 // For SELECT and SELECT_CC nodes, we do a similar check for any 13514 // to-be-promoted comparison inputs. 13515 if (PromOp.getOpcode() == ISD::SELECT || 13516 PromOp.getOpcode() == ISD::SELECT_CC) { 13517 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13518 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13519 (SelectTruncOp[1].count(PromOp.getNode()) && 13520 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13521 PromOpHandles.emplace_front(PromOp); 13522 continue; 13523 } 13524 } 13525 13526 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13527 PromOp.getNode()->op_end()); 13528 13529 // If this node has constant inputs, then they'll need to be promoted here. 13530 for (unsigned i = 0; i < 2; ++i) { 13531 if (!isa<ConstantSDNode>(Ops[C+i])) 13532 continue; 13533 if (Ops[C+i].getValueType() == N->getValueType(0)) 13534 continue; 13535 13536 if (N->getOpcode() == ISD::SIGN_EXTEND) 13537 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13538 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13539 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13540 else 13541 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13542 } 13543 13544 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13545 // truncate them again to the original value type. 13546 if (PromOp.getOpcode() == ISD::SELECT || 13547 PromOp.getOpcode() == ISD::SELECT_CC) { 13548 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13549 if (SI0 != SelectTruncOp[0].end()) 13550 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13551 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13552 if (SI1 != SelectTruncOp[1].end()) 13553 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13554 } 13555 13556 DAG.ReplaceAllUsesOfValueWith(PromOp, 13557 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13558 } 13559 13560 // Now we're left with the initial extension itself. 13561 if (!ReallyNeedsExt) 13562 return N->getOperand(0); 13563 13564 // To zero extend, just mask off everything except for the first bit (in the 13565 // i1 case). 13566 if (N->getOpcode() == ISD::ZERO_EXTEND) 13567 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13568 DAG.getConstant(APInt::getLowBitsSet( 13569 N->getValueSizeInBits(0), PromBits), 13570 dl, N->getValueType(0))); 13571 13572 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13573 "Invalid extension type"); 13574 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13575 SDValue ShiftCst = 13576 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13577 return DAG.getNode( 13578 ISD::SRA, dl, N->getValueType(0), 13579 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13580 ShiftCst); 13581 } 13582 13583 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13584 DAGCombinerInfo &DCI) const { 13585 assert(N->getOpcode() == ISD::SETCC && 13586 "Should be called with a SETCC node"); 13587 13588 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13589 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13590 SDValue LHS = N->getOperand(0); 13591 SDValue RHS = N->getOperand(1); 13592 13593 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13594 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13595 LHS.hasOneUse()) 13596 std::swap(LHS, RHS); 13597 13598 // x == 0-y --> x+y == 0 13599 // x != 0-y --> x+y != 0 13600 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13601 RHS.hasOneUse()) { 13602 SDLoc DL(N); 13603 SelectionDAG &DAG = DCI.DAG; 13604 EVT VT = N->getValueType(0); 13605 EVT OpVT = LHS.getValueType(); 13606 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13607 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13608 } 13609 } 13610 13611 return DAGCombineTruncBoolExt(N, DCI); 13612 } 13613 13614 // Is this an extending load from an f32 to an f64? 13615 static bool isFPExtLoad(SDValue Op) { 13616 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13617 return LD->getExtensionType() == ISD::EXTLOAD && 13618 Op.getValueType() == MVT::f64; 13619 return false; 13620 } 13621 13622 /// Reduces the number of fp-to-int conversion when building a vector. 13623 /// 13624 /// If this vector is built out of floating to integer conversions, 13625 /// transform it to a vector built out of floating point values followed by a 13626 /// single floating to integer conversion of the vector. 13627 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13628 /// becomes (fptosi (build_vector ($A, $B, ...))) 13629 SDValue PPCTargetLowering:: 13630 combineElementTruncationToVectorTruncation(SDNode *N, 13631 DAGCombinerInfo &DCI) const { 13632 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13633 "Should be called with a BUILD_VECTOR node"); 13634 13635 SelectionDAG &DAG = DCI.DAG; 13636 SDLoc dl(N); 13637 13638 SDValue FirstInput = N->getOperand(0); 13639 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13640 "The input operand must be an fp-to-int conversion."); 13641 13642 // This combine happens after legalization so the fp_to_[su]i nodes are 13643 // already converted to PPCSISD nodes. 13644 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13645 if (FirstConversion == PPCISD::FCTIDZ || 13646 FirstConversion == PPCISD::FCTIDUZ || 13647 FirstConversion == PPCISD::FCTIWZ || 13648 FirstConversion == PPCISD::FCTIWUZ) { 13649 bool IsSplat = true; 13650 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13651 FirstConversion == PPCISD::FCTIWUZ; 13652 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13653 SmallVector<SDValue, 4> Ops; 13654 EVT TargetVT = N->getValueType(0); 13655 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13656 SDValue NextOp = N->getOperand(i); 13657 if (NextOp.getOpcode() != PPCISD::MFVSR) 13658 return SDValue(); 13659 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13660 if (NextConversion != FirstConversion) 13661 return SDValue(); 13662 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13663 // This is not valid if the input was originally double precision. It is 13664 // also not profitable to do unless this is an extending load in which 13665 // case doing this combine will allow us to combine consecutive loads. 13666 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13667 return SDValue(); 13668 if (N->getOperand(i) != FirstInput) 13669 IsSplat = false; 13670 } 13671 13672 // If this is a splat, we leave it as-is since there will be only a single 13673 // fp-to-int conversion followed by a splat of the integer. This is better 13674 // for 32-bit and smaller ints and neutral for 64-bit ints. 13675 if (IsSplat) 13676 return SDValue(); 13677 13678 // Now that we know we have the right type of node, get its operands 13679 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13680 SDValue In = N->getOperand(i).getOperand(0); 13681 if (Is32Bit) { 13682 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13683 // here, we know that all inputs are extending loads so this is safe). 13684 if (In.isUndef()) 13685 Ops.push_back(DAG.getUNDEF(SrcVT)); 13686 else { 13687 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13688 MVT::f32, In.getOperand(0), 13689 DAG.getIntPtrConstant(1, dl)); 13690 Ops.push_back(Trunc); 13691 } 13692 } else 13693 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13694 } 13695 13696 unsigned Opcode; 13697 if (FirstConversion == PPCISD::FCTIDZ || 13698 FirstConversion == PPCISD::FCTIWZ) 13699 Opcode = ISD::FP_TO_SINT; 13700 else 13701 Opcode = ISD::FP_TO_UINT; 13702 13703 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13704 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13705 return DAG.getNode(Opcode, dl, TargetVT, BV); 13706 } 13707 return SDValue(); 13708 } 13709 13710 /// Reduce the number of loads when building a vector. 13711 /// 13712 /// Building a vector out of multiple loads can be converted to a load 13713 /// of the vector type if the loads are consecutive. If the loads are 13714 /// consecutive but in descending order, a shuffle is added at the end 13715 /// to reorder the vector. 13716 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13717 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13718 "Should be called with a BUILD_VECTOR node"); 13719 13720 SDLoc dl(N); 13721 13722 // Return early for non byte-sized type, as they can't be consecutive. 13723 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13724 return SDValue(); 13725 13726 bool InputsAreConsecutiveLoads = true; 13727 bool InputsAreReverseConsecutive = true; 13728 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13729 SDValue FirstInput = N->getOperand(0); 13730 bool IsRoundOfExtLoad = false; 13731 13732 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13733 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13734 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13735 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13736 } 13737 // Not a build vector of (possibly fp_rounded) loads. 13738 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13739 N->getNumOperands() == 1) 13740 return SDValue(); 13741 13742 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13743 // If any inputs are fp_round(extload), they all must be. 13744 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13745 return SDValue(); 13746 13747 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13748 N->getOperand(i); 13749 if (NextInput.getOpcode() != ISD::LOAD) 13750 return SDValue(); 13751 13752 SDValue PreviousInput = 13753 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13754 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13755 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13756 13757 // If any inputs are fp_round(extload), they all must be. 13758 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13759 return SDValue(); 13760 13761 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13762 InputsAreConsecutiveLoads = false; 13763 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13764 InputsAreReverseConsecutive = false; 13765 13766 // Exit early if the loads are neither consecutive nor reverse consecutive. 13767 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13768 return SDValue(); 13769 } 13770 13771 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13772 "The loads cannot be both consecutive and reverse consecutive."); 13773 13774 SDValue FirstLoadOp = 13775 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13776 SDValue LastLoadOp = 13777 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13778 N->getOperand(N->getNumOperands()-1); 13779 13780 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13781 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13782 if (InputsAreConsecutiveLoads) { 13783 assert(LD1 && "Input needs to be a LoadSDNode."); 13784 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13785 LD1->getBasePtr(), LD1->getPointerInfo(), 13786 LD1->getAlignment()); 13787 } 13788 if (InputsAreReverseConsecutive) { 13789 assert(LDL && "Input needs to be a LoadSDNode."); 13790 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13791 LDL->getBasePtr(), LDL->getPointerInfo(), 13792 LDL->getAlignment()); 13793 SmallVector<int, 16> Ops; 13794 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13795 Ops.push_back(i); 13796 13797 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13798 DAG.getUNDEF(N->getValueType(0)), Ops); 13799 } 13800 return SDValue(); 13801 } 13802 13803 // This function adds the required vector_shuffle needed to get 13804 // the elements of the vector extract in the correct position 13805 // as specified by the CorrectElems encoding. 13806 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13807 SDValue Input, uint64_t Elems, 13808 uint64_t CorrectElems) { 13809 SDLoc dl(N); 13810 13811 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13812 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13813 13814 // Knowing the element indices being extracted from the original 13815 // vector and the order in which they're being inserted, just put 13816 // them at element indices required for the instruction. 13817 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13818 if (DAG.getDataLayout().isLittleEndian()) 13819 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13820 else 13821 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13822 CorrectElems = CorrectElems >> 8; 13823 Elems = Elems >> 8; 13824 } 13825 13826 SDValue Shuffle = 13827 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13828 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13829 13830 EVT VT = N->getValueType(0); 13831 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13832 13833 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13834 Input.getValueType().getVectorElementType(), 13835 VT.getVectorNumElements()); 13836 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13837 DAG.getValueType(ExtVT)); 13838 } 13839 13840 // Look for build vector patterns where input operands come from sign 13841 // extended vector_extract elements of specific indices. If the correct indices 13842 // aren't used, add a vector shuffle to fix up the indices and create 13843 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13844 // during instruction selection. 13845 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13846 // This array encodes the indices that the vector sign extend instructions 13847 // extract from when extending from one type to another for both BE and LE. 13848 // The right nibble of each byte corresponds to the LE incides. 13849 // and the left nibble of each byte corresponds to the BE incides. 13850 // For example: 0x3074B8FC byte->word 13851 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13852 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13853 // For example: 0x000070F8 byte->double word 13854 // For LE: the allowed indices are: 0x0,0x8 13855 // For BE: the allowed indices are: 0x7,0xF 13856 uint64_t TargetElems[] = { 13857 0x3074B8FC, // b->w 13858 0x000070F8, // b->d 13859 0x10325476, // h->w 13860 0x00003074, // h->d 13861 0x00001032, // w->d 13862 }; 13863 13864 uint64_t Elems = 0; 13865 int Index; 13866 SDValue Input; 13867 13868 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13869 if (!Op) 13870 return false; 13871 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13872 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13873 return false; 13874 13875 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13876 // of the right width. 13877 SDValue Extract = Op.getOperand(0); 13878 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13879 Extract = Extract.getOperand(0); 13880 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13881 return false; 13882 13883 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13884 if (!ExtOp) 13885 return false; 13886 13887 Index = ExtOp->getZExtValue(); 13888 if (Input && Input != Extract.getOperand(0)) 13889 return false; 13890 13891 if (!Input) 13892 Input = Extract.getOperand(0); 13893 13894 Elems = Elems << 8; 13895 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13896 Elems |= Index; 13897 13898 return true; 13899 }; 13900 13901 // If the build vector operands aren't sign extended vector extracts, 13902 // of the same input vector, then return. 13903 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13904 if (!isSExtOfVecExtract(N->getOperand(i))) { 13905 return SDValue(); 13906 } 13907 } 13908 13909 // If the vector extract indicies are not correct, add the appropriate 13910 // vector_shuffle. 13911 int TgtElemArrayIdx; 13912 int InputSize = Input.getValueType().getScalarSizeInBits(); 13913 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13914 if (InputSize + OutputSize == 40) 13915 TgtElemArrayIdx = 0; 13916 else if (InputSize + OutputSize == 72) 13917 TgtElemArrayIdx = 1; 13918 else if (InputSize + OutputSize == 48) 13919 TgtElemArrayIdx = 2; 13920 else if (InputSize + OutputSize == 80) 13921 TgtElemArrayIdx = 3; 13922 else if (InputSize + OutputSize == 96) 13923 TgtElemArrayIdx = 4; 13924 else 13925 return SDValue(); 13926 13927 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13928 CorrectElems = DAG.getDataLayout().isLittleEndian() 13929 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13930 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13931 if (Elems != CorrectElems) { 13932 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13933 } 13934 13935 // Regular lowering will catch cases where a shuffle is not needed. 13936 return SDValue(); 13937 } 13938 13939 // Look for the pattern of a load from a narrow width to i128, feeding 13940 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13941 // (LXVRZX). This node represents a zero extending load that will be matched 13942 // to the Load VSX Vector Rightmost instructions. 13943 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13944 SDLoc DL(N); 13945 13946 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13947 if (N->getValueType(0) != MVT::v1i128) 13948 return SDValue(); 13949 13950 SDValue Operand = N->getOperand(0); 13951 // Proceed with the transformation if the operand to the BUILD_VECTOR 13952 // is a load instruction. 13953 if (Operand.getOpcode() != ISD::LOAD) 13954 return SDValue(); 13955 13956 auto *LD = cast<LoadSDNode>(Operand); 13957 EVT MemoryType = LD->getMemoryVT(); 13958 13959 // This transformation is only valid if the we are loading either a byte, 13960 // halfword, word, or doubleword. 13961 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13962 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13963 13964 // Ensure that the load from the narrow width is being zero extended to i128. 13965 if (!ValidLDType || 13966 (LD->getExtensionType() != ISD::ZEXTLOAD && 13967 LD->getExtensionType() != ISD::EXTLOAD)) 13968 return SDValue(); 13969 13970 SDValue LoadOps[] = { 13971 LD->getChain(), LD->getBasePtr(), 13972 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13973 13974 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13975 DAG.getVTList(MVT::v1i128, MVT::Other), 13976 LoadOps, MemoryType, LD->getMemOperand()); 13977 } 13978 13979 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13980 DAGCombinerInfo &DCI) const { 13981 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13982 "Should be called with a BUILD_VECTOR node"); 13983 13984 SelectionDAG &DAG = DCI.DAG; 13985 SDLoc dl(N); 13986 13987 if (!Subtarget.hasVSX()) 13988 return SDValue(); 13989 13990 // The target independent DAG combiner will leave a build_vector of 13991 // float-to-int conversions intact. We can generate MUCH better code for 13992 // a float-to-int conversion of a vector of floats. 13993 SDValue FirstInput = N->getOperand(0); 13994 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13995 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13996 if (Reduced) 13997 return Reduced; 13998 } 13999 14000 // If we're building a vector out of consecutive loads, just load that 14001 // vector type. 14002 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 14003 if (Reduced) 14004 return Reduced; 14005 14006 // If we're building a vector out of extended elements from another vector 14007 // we have P9 vector integer extend instructions. The code assumes legal 14008 // input types (i.e. it can't handle things like v4i16) so do not run before 14009 // legalization. 14010 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14011 Reduced = combineBVOfVecSExt(N, DAG); 14012 if (Reduced) 14013 return Reduced; 14014 } 14015 14016 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14017 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14018 // is a load from <valid narrow width> to i128. 14019 if (Subtarget.isISA3_1()) { 14020 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14021 if (BVOfZLoad) 14022 return BVOfZLoad; 14023 } 14024 14025 if (N->getValueType(0) != MVT::v2f64) 14026 return SDValue(); 14027 14028 // Looking for: 14029 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14030 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14031 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14032 return SDValue(); 14033 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14034 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14035 return SDValue(); 14036 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14037 return SDValue(); 14038 14039 SDValue Ext1 = FirstInput.getOperand(0); 14040 SDValue Ext2 = N->getOperand(1).getOperand(0); 14041 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14042 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14043 return SDValue(); 14044 14045 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14046 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14047 if (!Ext1Op || !Ext2Op) 14048 return SDValue(); 14049 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14050 Ext1.getOperand(0) != Ext2.getOperand(0)) 14051 return SDValue(); 14052 14053 int FirstElem = Ext1Op->getZExtValue(); 14054 int SecondElem = Ext2Op->getZExtValue(); 14055 int SubvecIdx; 14056 if (FirstElem == 0 && SecondElem == 1) 14057 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14058 else if (FirstElem == 2 && SecondElem == 3) 14059 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14060 else 14061 return SDValue(); 14062 14063 SDValue SrcVec = Ext1.getOperand(0); 14064 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14065 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14066 return DAG.getNode(NodeType, dl, MVT::v2f64, 14067 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14068 } 14069 14070 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14071 DAGCombinerInfo &DCI) const { 14072 assert((N->getOpcode() == ISD::SINT_TO_FP || 14073 N->getOpcode() == ISD::UINT_TO_FP) && 14074 "Need an int -> FP conversion node here"); 14075 14076 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14077 return SDValue(); 14078 14079 SelectionDAG &DAG = DCI.DAG; 14080 SDLoc dl(N); 14081 SDValue Op(N, 0); 14082 14083 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14084 // from the hardware. 14085 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14086 return SDValue(); 14087 if (!Op.getOperand(0).getValueType().isSimple()) 14088 return SDValue(); 14089 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14090 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14091 return SDValue(); 14092 14093 SDValue FirstOperand(Op.getOperand(0)); 14094 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14095 (FirstOperand.getValueType() == MVT::i8 || 14096 FirstOperand.getValueType() == MVT::i16); 14097 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14098 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14099 bool DstDouble = Op.getValueType() == MVT::f64; 14100 unsigned ConvOp = Signed ? 14101 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14102 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14103 SDValue WidthConst = 14104 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14105 dl, false); 14106 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14107 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14108 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14109 DAG.getVTList(MVT::f64, MVT::Other), 14110 Ops, MVT::i8, LDN->getMemOperand()); 14111 14112 // For signed conversion, we need to sign-extend the value in the VSR 14113 if (Signed) { 14114 SDValue ExtOps[] = { Ld, WidthConst }; 14115 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14116 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14117 } else 14118 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14119 } 14120 14121 14122 // For i32 intermediate values, unfortunately, the conversion functions 14123 // leave the upper 32 bits of the value are undefined. Within the set of 14124 // scalar instructions, we have no method for zero- or sign-extending the 14125 // value. Thus, we cannot handle i32 intermediate values here. 14126 if (Op.getOperand(0).getValueType() == MVT::i32) 14127 return SDValue(); 14128 14129 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14130 "UINT_TO_FP is supported only with FPCVT"); 14131 14132 // If we have FCFIDS, then use it when converting to single-precision. 14133 // Otherwise, convert to double-precision and then round. 14134 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14135 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14136 : PPCISD::FCFIDS) 14137 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14138 : PPCISD::FCFID); 14139 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14140 ? MVT::f32 14141 : MVT::f64; 14142 14143 // If we're converting from a float, to an int, and back to a float again, 14144 // then we don't need the store/load pair at all. 14145 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14146 Subtarget.hasFPCVT()) || 14147 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14148 SDValue Src = Op.getOperand(0).getOperand(0); 14149 if (Src.getValueType() == MVT::f32) { 14150 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14151 DCI.AddToWorklist(Src.getNode()); 14152 } else if (Src.getValueType() != MVT::f64) { 14153 // Make sure that we don't pick up a ppc_fp128 source value. 14154 return SDValue(); 14155 } 14156 14157 unsigned FCTOp = 14158 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14159 PPCISD::FCTIDUZ; 14160 14161 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14162 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14163 14164 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14165 FP = DAG.getNode(ISD::FP_ROUND, dl, 14166 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14167 DCI.AddToWorklist(FP.getNode()); 14168 } 14169 14170 return FP; 14171 } 14172 14173 return SDValue(); 14174 } 14175 14176 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14177 // builtins) into loads with swaps. 14178 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14179 DAGCombinerInfo &DCI) const { 14180 SelectionDAG &DAG = DCI.DAG; 14181 SDLoc dl(N); 14182 SDValue Chain; 14183 SDValue Base; 14184 MachineMemOperand *MMO; 14185 14186 switch (N->getOpcode()) { 14187 default: 14188 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14189 case ISD::LOAD: { 14190 LoadSDNode *LD = cast<LoadSDNode>(N); 14191 Chain = LD->getChain(); 14192 Base = LD->getBasePtr(); 14193 MMO = LD->getMemOperand(); 14194 // If the MMO suggests this isn't a load of a full vector, leave 14195 // things alone. For a built-in, we have to make the change for 14196 // correctness, so if there is a size problem that will be a bug. 14197 if (MMO->getSize() < 16) 14198 return SDValue(); 14199 break; 14200 } 14201 case ISD::INTRINSIC_W_CHAIN: { 14202 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14203 Chain = Intrin->getChain(); 14204 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14205 // us what we want. Get operand 2 instead. 14206 Base = Intrin->getOperand(2); 14207 MMO = Intrin->getMemOperand(); 14208 break; 14209 } 14210 } 14211 14212 MVT VecTy = N->getValueType(0).getSimpleVT(); 14213 14214 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14215 // aligned and the type is a vector with elements up to 4 bytes 14216 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14217 VecTy.getScalarSizeInBits() <= 32) { 14218 return SDValue(); 14219 } 14220 14221 SDValue LoadOps[] = { Chain, Base }; 14222 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14223 DAG.getVTList(MVT::v2f64, MVT::Other), 14224 LoadOps, MVT::v2f64, MMO); 14225 14226 DCI.AddToWorklist(Load.getNode()); 14227 Chain = Load.getValue(1); 14228 SDValue Swap = DAG.getNode( 14229 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14230 DCI.AddToWorklist(Swap.getNode()); 14231 14232 // Add a bitcast if the resulting load type doesn't match v2f64. 14233 if (VecTy != MVT::v2f64) { 14234 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14235 DCI.AddToWorklist(N.getNode()); 14236 // Package {bitcast value, swap's chain} to match Load's shape. 14237 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14238 N, Swap.getValue(1)); 14239 } 14240 14241 return Swap; 14242 } 14243 14244 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14245 // builtins) into stores with swaps. 14246 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14247 DAGCombinerInfo &DCI) const { 14248 SelectionDAG &DAG = DCI.DAG; 14249 SDLoc dl(N); 14250 SDValue Chain; 14251 SDValue Base; 14252 unsigned SrcOpnd; 14253 MachineMemOperand *MMO; 14254 14255 switch (N->getOpcode()) { 14256 default: 14257 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14258 case ISD::STORE: { 14259 StoreSDNode *ST = cast<StoreSDNode>(N); 14260 Chain = ST->getChain(); 14261 Base = ST->getBasePtr(); 14262 MMO = ST->getMemOperand(); 14263 SrcOpnd = 1; 14264 // If the MMO suggests this isn't a store of a full vector, leave 14265 // things alone. For a built-in, we have to make the change for 14266 // correctness, so if there is a size problem that will be a bug. 14267 if (MMO->getSize() < 16) 14268 return SDValue(); 14269 break; 14270 } 14271 case ISD::INTRINSIC_VOID: { 14272 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14273 Chain = Intrin->getChain(); 14274 // Intrin->getBasePtr() oddly does not get what we want. 14275 Base = Intrin->getOperand(3); 14276 MMO = Intrin->getMemOperand(); 14277 SrcOpnd = 2; 14278 break; 14279 } 14280 } 14281 14282 SDValue Src = N->getOperand(SrcOpnd); 14283 MVT VecTy = Src.getValueType().getSimpleVT(); 14284 14285 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14286 // aligned and the type is a vector with elements up to 4 bytes 14287 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14288 VecTy.getScalarSizeInBits() <= 32) { 14289 return SDValue(); 14290 } 14291 14292 // All stores are done as v2f64 and possible bit cast. 14293 if (VecTy != MVT::v2f64) { 14294 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14295 DCI.AddToWorklist(Src.getNode()); 14296 } 14297 14298 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14299 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14300 DCI.AddToWorklist(Swap.getNode()); 14301 Chain = Swap.getValue(1); 14302 SDValue StoreOps[] = { Chain, Swap, Base }; 14303 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14304 DAG.getVTList(MVT::Other), 14305 StoreOps, VecTy, MMO); 14306 DCI.AddToWorklist(Store.getNode()); 14307 return Store; 14308 } 14309 14310 // Handle DAG combine for STORE (FP_TO_INT F). 14311 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14312 DAGCombinerInfo &DCI) const { 14313 14314 SelectionDAG &DAG = DCI.DAG; 14315 SDLoc dl(N); 14316 unsigned Opcode = N->getOperand(1).getOpcode(); 14317 14318 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14319 && "Not a FP_TO_INT Instruction!"); 14320 14321 SDValue Val = N->getOperand(1).getOperand(0); 14322 EVT Op1VT = N->getOperand(1).getValueType(); 14323 EVT ResVT = Val.getValueType(); 14324 14325 if (!isTypeLegal(ResVT)) 14326 return SDValue(); 14327 14328 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14329 bool ValidTypeForStoreFltAsInt = 14330 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14331 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14332 14333 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14334 return SDValue(); 14335 14336 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14337 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14338 return SDValue(); 14339 14340 // Extend f32 values to f64 14341 if (ResVT.getScalarSizeInBits() == 32) { 14342 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14343 DCI.AddToWorklist(Val.getNode()); 14344 } 14345 14346 // Set signed or unsigned conversion opcode. 14347 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14348 PPCISD::FP_TO_SINT_IN_VSR : 14349 PPCISD::FP_TO_UINT_IN_VSR; 14350 14351 Val = DAG.getNode(ConvOpcode, 14352 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14353 DCI.AddToWorklist(Val.getNode()); 14354 14355 // Set number of bytes being converted. 14356 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14357 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14358 DAG.getIntPtrConstant(ByteSize, dl, false), 14359 DAG.getValueType(Op1VT) }; 14360 14361 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14362 DAG.getVTList(MVT::Other), Ops, 14363 cast<StoreSDNode>(N)->getMemoryVT(), 14364 cast<StoreSDNode>(N)->getMemOperand()); 14365 14366 DCI.AddToWorklist(Val.getNode()); 14367 return Val; 14368 } 14369 14370 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14371 // Check that the source of the element keeps flipping 14372 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14373 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14374 for (int i = 1, e = Mask.size(); i < e; i++) { 14375 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14376 return false; 14377 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14378 return false; 14379 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14380 } 14381 return true; 14382 } 14383 14384 static bool isSplatBV(SDValue Op) { 14385 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14386 return false; 14387 SDValue FirstOp; 14388 14389 // Find first non-undef input. 14390 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14391 FirstOp = Op.getOperand(i); 14392 if (!FirstOp.isUndef()) 14393 break; 14394 } 14395 14396 // All inputs are undef or the same as the first non-undef input. 14397 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14398 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14399 return false; 14400 return true; 14401 } 14402 14403 static SDValue isScalarToVec(SDValue Op) { 14404 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14405 return Op; 14406 if (Op.getOpcode() != ISD::BITCAST) 14407 return SDValue(); 14408 Op = Op.getOperand(0); 14409 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14410 return Op; 14411 return SDValue(); 14412 } 14413 14414 // Fix up the shuffle mask to account for the fact that the result of 14415 // scalar_to_vector is not in lane zero. This just takes all values in 14416 // the ranges specified by the min/max indices and adds the number of 14417 // elements required to ensure each element comes from the respective 14418 // position in the valid lane. 14419 // On little endian, that's just the corresponding element in the other 14420 // half of the vector. On big endian, it is in the same half but right 14421 // justified rather than left justified in that half. 14422 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14423 int LHSMaxIdx, int RHSMinIdx, 14424 int RHSMaxIdx, int HalfVec, 14425 unsigned ValidLaneWidth, 14426 const PPCSubtarget &Subtarget) { 14427 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14428 int Idx = ShuffV[i]; 14429 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14430 ShuffV[i] += 14431 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14432 } 14433 } 14434 14435 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14436 // the original is: 14437 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14438 // In such a case, just change the shuffle mask to extract the element 14439 // from the permuted index. 14440 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14441 const PPCSubtarget &Subtarget) { 14442 SDLoc dl(OrigSToV); 14443 EVT VT = OrigSToV.getValueType(); 14444 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14445 "Expecting a SCALAR_TO_VECTOR here"); 14446 SDValue Input = OrigSToV.getOperand(0); 14447 14448 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14449 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14450 SDValue OrigVector = Input.getOperand(0); 14451 14452 // Can't handle non-const element indices or different vector types 14453 // for the input to the extract and the output of the scalar_to_vector. 14454 if (Idx && VT == OrigVector.getValueType()) { 14455 unsigned NumElts = VT.getVectorNumElements(); 14456 assert( 14457 NumElts > 1 && 14458 "Cannot produce a permuted scalar_to_vector for one element vector"); 14459 SmallVector<int, 16> NewMask(NumElts, -1); 14460 unsigned ResultInElt = NumElts / 2; 14461 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14462 NewMask[ResultInElt] = Idx->getZExtValue(); 14463 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14464 } 14465 } 14466 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14467 OrigSToV.getOperand(0)); 14468 } 14469 14470 // On little endian subtargets, combine shuffles such as: 14471 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14472 // into: 14473 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14474 // because the latter can be matched to a single instruction merge. 14475 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14476 // to put the value into element zero. Adjust the shuffle mask so that the 14477 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14478 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 14479 // nodes with elements smaller than doubleword because all the ways 14480 // of getting scalar data into a vector register put the value in the 14481 // rightmost element of the left half of the vector. 14482 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14483 SelectionDAG &DAG) const { 14484 SDValue LHS = SVN->getOperand(0); 14485 SDValue RHS = SVN->getOperand(1); 14486 auto Mask = SVN->getMask(); 14487 int NumElts = LHS.getValueType().getVectorNumElements(); 14488 SDValue Res(SVN, 0); 14489 SDLoc dl(SVN); 14490 bool IsLittleEndian = Subtarget.isLittleEndian(); 14491 14492 // On little endian targets, do these combines on all VSX targets since 14493 // canonical shuffles match efficient permutes. On big endian targets, 14494 // this is only useful for targets with direct moves. 14495 if (!Subtarget.hasDirectMove() && !(IsLittleEndian && Subtarget.hasVSX())) 14496 return Res; 14497 14498 // If this is not a shuffle of a shuffle and the first element comes from 14499 // the second vector, canonicalize to the commuted form. This will make it 14500 // more likely to match one of the single instruction patterns. 14501 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14502 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14503 std::swap(LHS, RHS); 14504 Res = DAG.getCommutedVectorShuffle(*SVN); 14505 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14506 } 14507 14508 // Adjust the shuffle mask if either input vector comes from a 14509 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14510 // form (to prevent the need for a swap). 14511 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14512 SDValue SToVLHS = isScalarToVec(LHS); 14513 SDValue SToVRHS = isScalarToVec(RHS); 14514 if (SToVLHS || SToVRHS) { 14515 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14516 : SToVRHS.getValueType().getVectorNumElements(); 14517 int NumEltsOut = ShuffV.size(); 14518 unsigned InElemSizeInBits = 14519 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() 14520 : SToVRHS.getValueType().getScalarSizeInBits(); 14521 unsigned OutElemSizeInBits = SToVLHS 14522 ? LHS.getValueType().getScalarSizeInBits() 14523 : RHS.getValueType().getScalarSizeInBits(); 14524 14525 // The width of the "valid lane" (i.e. the lane that contains the value that 14526 // is vectorized) needs to be expressed in terms of the number of elements 14527 // of the shuffle. It is thereby the ratio of the values before and after 14528 // any bitcast. 14529 unsigned ValidLaneWidth = InElemSizeInBits / OutElemSizeInBits; 14530 14531 // Initially assume that neither input is permuted. These will be adjusted 14532 // accordingly if either input is. 14533 int LHSMaxIdx = -1; 14534 int RHSMinIdx = -1; 14535 int RHSMaxIdx = -1; 14536 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14537 14538 // Get the permuted scalar to vector nodes for the source(s) that come from 14539 // ISD::SCALAR_TO_VECTOR. 14540 // On big endian systems, this only makes sense for element sizes smaller 14541 // than 64 bits since for 64-bit elements, all instructions already put 14542 // the value into element zero. 14543 if (SToVLHS) { 14544 if (!IsLittleEndian && InElemSizeInBits >= 64) 14545 return Res; 14546 // Set up the values for the shuffle vector fixup. 14547 LHSMaxIdx = NumEltsOut / NumEltsIn; 14548 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 14549 if (SToVLHS.getValueType() != LHS.getValueType()) 14550 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14551 LHS = SToVLHS; 14552 } 14553 if (SToVRHS) { 14554 if (!IsLittleEndian && InElemSizeInBits >= 64) 14555 return Res; 14556 RHSMinIdx = NumEltsOut; 14557 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14558 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 14559 if (SToVRHS.getValueType() != RHS.getValueType()) 14560 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14561 RHS = SToVRHS; 14562 } 14563 14564 // Fix up the shuffle mask to reflect where the desired element actually is. 14565 // The minimum and maximum indices that correspond to element zero for both 14566 // the LHS and RHS are computed and will control which shuffle mask entries 14567 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14568 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 14569 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14570 HalfVec, ValidLaneWidth, Subtarget); 14571 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14572 14573 // We may have simplified away the shuffle. We won't be able to do anything 14574 // further with it here. 14575 if (!isa<ShuffleVectorSDNode>(Res)) 14576 return Res; 14577 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14578 } 14579 14580 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 14581 // The common case after we commuted the shuffle is that the RHS is a splat 14582 // and we have elements coming in from the splat at indices that are not 14583 // conducive to using a merge. 14584 // Example: 14585 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14586 if (!isSplatBV(TheSplat)) 14587 return Res; 14588 14589 // We are looking for a mask such that all even elements are from 14590 // one vector and all odd elements from the other. 14591 if (!isAlternatingShuffMask(Mask, NumElts)) 14592 return Res; 14593 14594 // Adjust the mask so we are pulling in the same index from the splat 14595 // as the index from the interesting vector in consecutive elements. 14596 if (IsLittleEndian) { 14597 // Example (even elements from first vector): 14598 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14599 if (Mask[0] < NumElts) 14600 for (int i = 1, e = Mask.size(); i < e; i += 2) 14601 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14602 // Example (odd elements from first vector): 14603 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14604 else 14605 for (int i = 0, e = Mask.size(); i < e; i += 2) 14606 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14607 } else { 14608 // Example (even elements from first vector): 14609 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 14610 if (Mask[0] < NumElts) 14611 for (int i = 0, e = Mask.size(); i < e; i += 2) 14612 ShuffV[i] = ShuffV[i + 1] - NumElts; 14613 // Example (odd elements from first vector): 14614 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 14615 else 14616 for (int i = 1, e = Mask.size(); i < e; i += 2) 14617 ShuffV[i] = ShuffV[i - 1] - NumElts; 14618 } 14619 14620 // If the RHS has undefs, we need to remove them since we may have created 14621 // a shuffle that adds those instead of the splat value. 14622 SDValue SplatVal = 14623 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 14624 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 14625 14626 if (IsLittleEndian) 14627 RHS = TheSplat; 14628 else 14629 LHS = TheSplat; 14630 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14631 } 14632 14633 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14634 LSBaseSDNode *LSBase, 14635 DAGCombinerInfo &DCI) const { 14636 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14637 "Not a reverse memop pattern!"); 14638 14639 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14640 auto Mask = SVN->getMask(); 14641 int i = 0; 14642 auto I = Mask.rbegin(); 14643 auto E = Mask.rend(); 14644 14645 for (; I != E; ++I) { 14646 if (*I != i) 14647 return false; 14648 i++; 14649 } 14650 return true; 14651 }; 14652 14653 SelectionDAG &DAG = DCI.DAG; 14654 EVT VT = SVN->getValueType(0); 14655 14656 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14657 return SDValue(); 14658 14659 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14660 // See comment in PPCVSXSwapRemoval.cpp. 14661 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14662 if (!Subtarget.hasP9Vector()) 14663 return SDValue(); 14664 14665 if(!IsElementReverse(SVN)) 14666 return SDValue(); 14667 14668 if (LSBase->getOpcode() == ISD::LOAD) { 14669 // If the load return value 0 has more than one user except the 14670 // shufflevector instruction, it is not profitable to replace the 14671 // shufflevector with a reverse load. 14672 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end(); 14673 UI != UE; ++UI) 14674 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE) 14675 return SDValue(); 14676 14677 SDLoc dl(LSBase); 14678 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14679 return DAG.getMemIntrinsicNode( 14680 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14681 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14682 } 14683 14684 if (LSBase->getOpcode() == ISD::STORE) { 14685 // If there are other uses of the shuffle, the swap cannot be avoided. 14686 // Forcing the use of an X-Form (since swapped stores only have 14687 // X-Forms) without removing the swap is unprofitable. 14688 if (!SVN->hasOneUse()) 14689 return SDValue(); 14690 14691 SDLoc dl(LSBase); 14692 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14693 LSBase->getBasePtr()}; 14694 return DAG.getMemIntrinsicNode( 14695 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14696 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14697 } 14698 14699 llvm_unreachable("Expected a load or store node here"); 14700 } 14701 14702 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14703 DAGCombinerInfo &DCI) const { 14704 SelectionDAG &DAG = DCI.DAG; 14705 SDLoc dl(N); 14706 switch (N->getOpcode()) { 14707 default: break; 14708 case ISD::ADD: 14709 return combineADD(N, DCI); 14710 case ISD::SHL: 14711 return combineSHL(N, DCI); 14712 case ISD::SRA: 14713 return combineSRA(N, DCI); 14714 case ISD::SRL: 14715 return combineSRL(N, DCI); 14716 case ISD::MUL: 14717 return combineMUL(N, DCI); 14718 case ISD::FMA: 14719 case PPCISD::FNMSUB: 14720 return combineFMALike(N, DCI); 14721 case PPCISD::SHL: 14722 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14723 return N->getOperand(0); 14724 break; 14725 case PPCISD::SRL: 14726 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14727 return N->getOperand(0); 14728 break; 14729 case PPCISD::SRA: 14730 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14731 if (C->isNullValue() || // 0 >>s V -> 0. 14732 C->isAllOnesValue()) // -1 >>s V -> -1. 14733 return N->getOperand(0); 14734 } 14735 break; 14736 case ISD::SIGN_EXTEND: 14737 case ISD::ZERO_EXTEND: 14738 case ISD::ANY_EXTEND: 14739 return DAGCombineExtBoolTrunc(N, DCI); 14740 case ISD::TRUNCATE: 14741 return combineTRUNCATE(N, DCI); 14742 case ISD::SETCC: 14743 if (SDValue CSCC = combineSetCC(N, DCI)) 14744 return CSCC; 14745 LLVM_FALLTHROUGH; 14746 case ISD::SELECT_CC: 14747 return DAGCombineTruncBoolExt(N, DCI); 14748 case ISD::SINT_TO_FP: 14749 case ISD::UINT_TO_FP: 14750 return combineFPToIntToFP(N, DCI); 14751 case ISD::VECTOR_SHUFFLE: 14752 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14753 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14754 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14755 } 14756 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14757 case ISD::STORE: { 14758 14759 EVT Op1VT = N->getOperand(1).getValueType(); 14760 unsigned Opcode = N->getOperand(1).getOpcode(); 14761 14762 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14763 SDValue Val= combineStoreFPToInt(N, DCI); 14764 if (Val) 14765 return Val; 14766 } 14767 14768 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14769 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14770 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14771 if (Val) 14772 return Val; 14773 } 14774 14775 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14776 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14777 N->getOperand(1).getNode()->hasOneUse() && 14778 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14779 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14780 14781 // STBRX can only handle simple types and it makes no sense to store less 14782 // two bytes in byte-reversed order. 14783 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14784 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14785 break; 14786 14787 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14788 // Do an any-extend to 32-bits if this is a half-word input. 14789 if (BSwapOp.getValueType() == MVT::i16) 14790 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14791 14792 // If the type of BSWAP operand is wider than stored memory width 14793 // it need to be shifted to the right side before STBRX. 14794 if (Op1VT.bitsGT(mVT)) { 14795 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14796 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14797 DAG.getConstant(Shift, dl, MVT::i32)); 14798 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14799 if (Op1VT == MVT::i64) 14800 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14801 } 14802 14803 SDValue Ops[] = { 14804 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14805 }; 14806 return 14807 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14808 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14809 cast<StoreSDNode>(N)->getMemOperand()); 14810 } 14811 14812 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14813 // So it can increase the chance of CSE constant construction. 14814 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14815 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14816 // Need to sign-extended to 64-bits to handle negative values. 14817 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14818 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14819 MemVT.getSizeInBits()); 14820 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14821 14822 // DAG.getTruncStore() can't be used here because it doesn't accept 14823 // the general (base + offset) addressing mode. 14824 // So we use UpdateNodeOperands and setTruncatingStore instead. 14825 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14826 N->getOperand(3)); 14827 cast<StoreSDNode>(N)->setTruncatingStore(true); 14828 return SDValue(N, 0); 14829 } 14830 14831 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14832 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14833 if (Op1VT.isSimple()) { 14834 MVT StoreVT = Op1VT.getSimpleVT(); 14835 if (Subtarget.needsSwapsForVSXMemOps() && 14836 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14837 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14838 return expandVSXStoreForLE(N, DCI); 14839 } 14840 break; 14841 } 14842 case ISD::LOAD: { 14843 LoadSDNode *LD = cast<LoadSDNode>(N); 14844 EVT VT = LD->getValueType(0); 14845 14846 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14847 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14848 if (VT.isSimple()) { 14849 MVT LoadVT = VT.getSimpleVT(); 14850 if (Subtarget.needsSwapsForVSXMemOps() && 14851 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14852 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14853 return expandVSXLoadForLE(N, DCI); 14854 } 14855 14856 // We sometimes end up with a 64-bit integer load, from which we extract 14857 // two single-precision floating-point numbers. This happens with 14858 // std::complex<float>, and other similar structures, because of the way we 14859 // canonicalize structure copies. However, if we lack direct moves, 14860 // then the final bitcasts from the extracted integer values to the 14861 // floating-point numbers turn into store/load pairs. Even with direct moves, 14862 // just loading the two floating-point numbers is likely better. 14863 auto ReplaceTwoFloatLoad = [&]() { 14864 if (VT != MVT::i64) 14865 return false; 14866 14867 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14868 LD->isVolatile()) 14869 return false; 14870 14871 // We're looking for a sequence like this: 14872 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14873 // t16: i64 = srl t13, Constant:i32<32> 14874 // t17: i32 = truncate t16 14875 // t18: f32 = bitcast t17 14876 // t19: i32 = truncate t13 14877 // t20: f32 = bitcast t19 14878 14879 if (!LD->hasNUsesOfValue(2, 0)) 14880 return false; 14881 14882 auto UI = LD->use_begin(); 14883 while (UI.getUse().getResNo() != 0) ++UI; 14884 SDNode *Trunc = *UI++; 14885 while (UI.getUse().getResNo() != 0) ++UI; 14886 SDNode *RightShift = *UI; 14887 if (Trunc->getOpcode() != ISD::TRUNCATE) 14888 std::swap(Trunc, RightShift); 14889 14890 if (Trunc->getOpcode() != ISD::TRUNCATE || 14891 Trunc->getValueType(0) != MVT::i32 || 14892 !Trunc->hasOneUse()) 14893 return false; 14894 if (RightShift->getOpcode() != ISD::SRL || 14895 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14896 RightShift->getConstantOperandVal(1) != 32 || 14897 !RightShift->hasOneUse()) 14898 return false; 14899 14900 SDNode *Trunc2 = *RightShift->use_begin(); 14901 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14902 Trunc2->getValueType(0) != MVT::i32 || 14903 !Trunc2->hasOneUse()) 14904 return false; 14905 14906 SDNode *Bitcast = *Trunc->use_begin(); 14907 SDNode *Bitcast2 = *Trunc2->use_begin(); 14908 14909 if (Bitcast->getOpcode() != ISD::BITCAST || 14910 Bitcast->getValueType(0) != MVT::f32) 14911 return false; 14912 if (Bitcast2->getOpcode() != ISD::BITCAST || 14913 Bitcast2->getValueType(0) != MVT::f32) 14914 return false; 14915 14916 if (Subtarget.isLittleEndian()) 14917 std::swap(Bitcast, Bitcast2); 14918 14919 // Bitcast has the second float (in memory-layout order) and Bitcast2 14920 // has the first one. 14921 14922 SDValue BasePtr = LD->getBasePtr(); 14923 if (LD->isIndexed()) { 14924 assert(LD->getAddressingMode() == ISD::PRE_INC && 14925 "Non-pre-inc AM on PPC?"); 14926 BasePtr = 14927 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14928 LD->getOffset()); 14929 } 14930 14931 auto MMOFlags = 14932 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14933 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14934 LD->getPointerInfo(), LD->getAlignment(), 14935 MMOFlags, LD->getAAInfo()); 14936 SDValue AddPtr = 14937 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14938 BasePtr, DAG.getIntPtrConstant(4, dl)); 14939 SDValue FloatLoad2 = DAG.getLoad( 14940 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14941 LD->getPointerInfo().getWithOffset(4), 14942 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14943 14944 if (LD->isIndexed()) { 14945 // Note that DAGCombine should re-form any pre-increment load(s) from 14946 // what is produced here if that makes sense. 14947 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14948 } 14949 14950 DCI.CombineTo(Bitcast2, FloatLoad); 14951 DCI.CombineTo(Bitcast, FloatLoad2); 14952 14953 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14954 SDValue(FloatLoad2.getNode(), 1)); 14955 return true; 14956 }; 14957 14958 if (ReplaceTwoFloatLoad()) 14959 return SDValue(N, 0); 14960 14961 EVT MemVT = LD->getMemoryVT(); 14962 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14963 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14964 if (LD->isUnindexed() && VT.isVector() && 14965 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14966 // P8 and later hardware should just use LOAD. 14967 !Subtarget.hasP8Vector() && 14968 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14969 VT == MVT::v4f32))) && 14970 LD->getAlign() < ABIAlignment) { 14971 // This is a type-legal unaligned Altivec load. 14972 SDValue Chain = LD->getChain(); 14973 SDValue Ptr = LD->getBasePtr(); 14974 bool isLittleEndian = Subtarget.isLittleEndian(); 14975 14976 // This implements the loading of unaligned vectors as described in 14977 // the venerable Apple Velocity Engine overview. Specifically: 14978 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14979 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14980 // 14981 // The general idea is to expand a sequence of one or more unaligned 14982 // loads into an alignment-based permutation-control instruction (lvsl 14983 // or lvsr), a series of regular vector loads (which always truncate 14984 // their input address to an aligned address), and a series of 14985 // permutations. The results of these permutations are the requested 14986 // loaded values. The trick is that the last "extra" load is not taken 14987 // from the address you might suspect (sizeof(vector) bytes after the 14988 // last requested load), but rather sizeof(vector) - 1 bytes after the 14989 // last requested vector. The point of this is to avoid a page fault if 14990 // the base address happened to be aligned. This works because if the 14991 // base address is aligned, then adding less than a full vector length 14992 // will cause the last vector in the sequence to be (re)loaded. 14993 // Otherwise, the next vector will be fetched as you might suspect was 14994 // necessary. 14995 14996 // We might be able to reuse the permutation generation from 14997 // a different base address offset from this one by an aligned amount. 14998 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14999 // optimization later. 15000 Intrinsic::ID Intr, IntrLD, IntrPerm; 15001 MVT PermCntlTy, PermTy, LDTy; 15002 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15003 : Intrinsic::ppc_altivec_lvsl; 15004 IntrLD = Intrinsic::ppc_altivec_lvx; 15005 IntrPerm = Intrinsic::ppc_altivec_vperm; 15006 PermCntlTy = MVT::v16i8; 15007 PermTy = MVT::v4i32; 15008 LDTy = MVT::v4i32; 15009 15010 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 15011 15012 // Create the new MMO for the new base load. It is like the original MMO, 15013 // but represents an area in memory almost twice the vector size centered 15014 // on the original address. If the address is unaligned, we might start 15015 // reading up to (sizeof(vector)-1) bytes below the address of the 15016 // original unaligned load. 15017 MachineFunction &MF = DAG.getMachineFunction(); 15018 MachineMemOperand *BaseMMO = 15019 MF.getMachineMemOperand(LD->getMemOperand(), 15020 -(long)MemVT.getStoreSize()+1, 15021 2*MemVT.getStoreSize()-1); 15022 15023 // Create the new base load. 15024 SDValue LDXIntID = 15025 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 15026 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 15027 SDValue BaseLoad = 15028 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15029 DAG.getVTList(PermTy, MVT::Other), 15030 BaseLoadOps, LDTy, BaseMMO); 15031 15032 // Note that the value of IncOffset (which is provided to the next 15033 // load's pointer info offset value, and thus used to calculate the 15034 // alignment), and the value of IncValue (which is actually used to 15035 // increment the pointer value) are different! This is because we 15036 // require the next load to appear to be aligned, even though it 15037 // is actually offset from the base pointer by a lesser amount. 15038 int IncOffset = VT.getSizeInBits() / 8; 15039 int IncValue = IncOffset; 15040 15041 // Walk (both up and down) the chain looking for another load at the real 15042 // (aligned) offset (the alignment of the other load does not matter in 15043 // this case). If found, then do not use the offset reduction trick, as 15044 // that will prevent the loads from being later combined (as they would 15045 // otherwise be duplicates). 15046 if (!findConsecutiveLoad(LD, DAG)) 15047 --IncValue; 15048 15049 SDValue Increment = 15050 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15051 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15052 15053 MachineMemOperand *ExtraMMO = 15054 MF.getMachineMemOperand(LD->getMemOperand(), 15055 1, 2*MemVT.getStoreSize()-1); 15056 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15057 SDValue ExtraLoad = 15058 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15059 DAG.getVTList(PermTy, MVT::Other), 15060 ExtraLoadOps, LDTy, ExtraMMO); 15061 15062 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15063 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15064 15065 // Because vperm has a big-endian bias, we must reverse the order 15066 // of the input vectors and complement the permute control vector 15067 // when generating little endian code. We have already handled the 15068 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15069 // and ExtraLoad here. 15070 SDValue Perm; 15071 if (isLittleEndian) 15072 Perm = BuildIntrinsicOp(IntrPerm, 15073 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15074 else 15075 Perm = BuildIntrinsicOp(IntrPerm, 15076 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15077 15078 if (VT != PermTy) 15079 Perm = Subtarget.hasAltivec() 15080 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15081 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15082 DAG.getTargetConstant(1, dl, MVT::i64)); 15083 // second argument is 1 because this rounding 15084 // is always exact. 15085 15086 // The output of the permutation is our loaded result, the TokenFactor is 15087 // our new chain. 15088 DCI.CombineTo(N, Perm, TF); 15089 return SDValue(N, 0); 15090 } 15091 } 15092 break; 15093 case ISD::INTRINSIC_WO_CHAIN: { 15094 bool isLittleEndian = Subtarget.isLittleEndian(); 15095 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15096 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15097 : Intrinsic::ppc_altivec_lvsl); 15098 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15099 SDValue Add = N->getOperand(1); 15100 15101 int Bits = 4 /* 16 byte alignment */; 15102 15103 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15104 APInt::getAllOnesValue(Bits /* alignment */) 15105 .zext(Add.getScalarValueSizeInBits()))) { 15106 SDNode *BasePtr = Add->getOperand(0).getNode(); 15107 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15108 UE = BasePtr->use_end(); 15109 UI != UE; ++UI) { 15110 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15111 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 15112 IID) { 15113 // We've found another LVSL/LVSR, and this address is an aligned 15114 // multiple of that one. The results will be the same, so use the 15115 // one we've just found instead. 15116 15117 return SDValue(*UI, 0); 15118 } 15119 } 15120 } 15121 15122 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15123 SDNode *BasePtr = Add->getOperand(0).getNode(); 15124 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15125 UE = BasePtr->use_end(); UI != UE; ++UI) { 15126 if (UI->getOpcode() == ISD::ADD && 15127 isa<ConstantSDNode>(UI->getOperand(1)) && 15128 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15129 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 15130 (1ULL << Bits) == 0) { 15131 SDNode *OtherAdd = *UI; 15132 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 15133 VE = OtherAdd->use_end(); VI != VE; ++VI) { 15134 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15135 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 15136 return SDValue(*VI, 0); 15137 } 15138 } 15139 } 15140 } 15141 } 15142 } 15143 15144 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15145 // Expose the vabsduw/h/b opportunity for down stream 15146 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15147 (IID == Intrinsic::ppc_altivec_vmaxsw || 15148 IID == Intrinsic::ppc_altivec_vmaxsh || 15149 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15150 SDValue V1 = N->getOperand(1); 15151 SDValue V2 = N->getOperand(2); 15152 if ((V1.getSimpleValueType() == MVT::v4i32 || 15153 V1.getSimpleValueType() == MVT::v8i16 || 15154 V1.getSimpleValueType() == MVT::v16i8) && 15155 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15156 // (0-a, a) 15157 if (V1.getOpcode() == ISD::SUB && 15158 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15159 V1.getOperand(1) == V2) { 15160 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15161 } 15162 // (a, 0-a) 15163 if (V2.getOpcode() == ISD::SUB && 15164 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15165 V2.getOperand(1) == V1) { 15166 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15167 } 15168 // (x-y, y-x) 15169 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15170 V1.getOperand(0) == V2.getOperand(1) && 15171 V1.getOperand(1) == V2.getOperand(0)) { 15172 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15173 } 15174 } 15175 } 15176 } 15177 15178 break; 15179 case ISD::INTRINSIC_W_CHAIN: 15180 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15181 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15182 if (Subtarget.needsSwapsForVSXMemOps()) { 15183 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15184 default: 15185 break; 15186 case Intrinsic::ppc_vsx_lxvw4x: 15187 case Intrinsic::ppc_vsx_lxvd2x: 15188 return expandVSXLoadForLE(N, DCI); 15189 } 15190 } 15191 break; 15192 case ISD::INTRINSIC_VOID: 15193 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15194 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15195 if (Subtarget.needsSwapsForVSXMemOps()) { 15196 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15197 default: 15198 break; 15199 case Intrinsic::ppc_vsx_stxvw4x: 15200 case Intrinsic::ppc_vsx_stxvd2x: 15201 return expandVSXStoreForLE(N, DCI); 15202 } 15203 } 15204 break; 15205 case ISD::BSWAP: 15206 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15207 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 15208 N->getOperand(0).hasOneUse() && 15209 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15210 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 15211 N->getValueType(0) == MVT::i64))) { 15212 SDValue Load = N->getOperand(0); 15213 LoadSDNode *LD = cast<LoadSDNode>(Load); 15214 // Create the byte-swapping load. 15215 SDValue Ops[] = { 15216 LD->getChain(), // Chain 15217 LD->getBasePtr(), // Ptr 15218 DAG.getValueType(N->getValueType(0)) // VT 15219 }; 15220 SDValue BSLoad = 15221 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15222 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15223 MVT::i64 : MVT::i32, MVT::Other), 15224 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15225 15226 // If this is an i16 load, insert the truncate. 15227 SDValue ResVal = BSLoad; 15228 if (N->getValueType(0) == MVT::i16) 15229 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15230 15231 // First, combine the bswap away. This makes the value produced by the 15232 // load dead. 15233 DCI.CombineTo(N, ResVal); 15234 15235 // Next, combine the load away, we give it a bogus result value but a real 15236 // chain result. The result value is dead because the bswap is dead. 15237 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15238 15239 // Return N so it doesn't get rechecked! 15240 return SDValue(N, 0); 15241 } 15242 break; 15243 case PPCISD::VCMP: 15244 // If a VCMP_rec node already exists with exactly the same operands as this 15245 // node, use its result instead of this node (VCMP_rec computes both a CR6 15246 // and a normal output). 15247 // 15248 if (!N->getOperand(0).hasOneUse() && 15249 !N->getOperand(1).hasOneUse() && 15250 !N->getOperand(2).hasOneUse()) { 15251 15252 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15253 SDNode *VCMPrecNode = nullptr; 15254 15255 SDNode *LHSN = N->getOperand(0).getNode(); 15256 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15257 UI != E; ++UI) 15258 if (UI->getOpcode() == PPCISD::VCMP_rec && 15259 UI->getOperand(1) == N->getOperand(1) && 15260 UI->getOperand(2) == N->getOperand(2) && 15261 UI->getOperand(0) == N->getOperand(0)) { 15262 VCMPrecNode = *UI; 15263 break; 15264 } 15265 15266 // If there is no VCMP_rec node, or if the flag value has a single use, 15267 // don't transform this. 15268 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15269 break; 15270 15271 // Look at the (necessarily single) use of the flag value. If it has a 15272 // chain, this transformation is more complex. Note that multiple things 15273 // could use the value result, which we should ignore. 15274 SDNode *FlagUser = nullptr; 15275 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15276 FlagUser == nullptr; ++UI) { 15277 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15278 SDNode *User = *UI; 15279 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15280 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15281 FlagUser = User; 15282 break; 15283 } 15284 } 15285 } 15286 15287 // If the user is a MFOCRF instruction, we know this is safe. 15288 // Otherwise we give up for right now. 15289 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15290 return SDValue(VCMPrecNode, 0); 15291 } 15292 break; 15293 case ISD::BRCOND: { 15294 SDValue Cond = N->getOperand(1); 15295 SDValue Target = N->getOperand(2); 15296 15297 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15298 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15299 Intrinsic::loop_decrement) { 15300 15301 // We now need to make the intrinsic dead (it cannot be instruction 15302 // selected). 15303 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15304 assert(Cond.getNode()->hasOneUse() && 15305 "Counter decrement has more than one use"); 15306 15307 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15308 N->getOperand(0), Target); 15309 } 15310 } 15311 break; 15312 case ISD::BR_CC: { 15313 // If this is a branch on an altivec predicate comparison, lower this so 15314 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15315 // lowering is done pre-legalize, because the legalizer lowers the predicate 15316 // compare down to code that is difficult to reassemble. 15317 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15318 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15319 15320 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15321 // value. If so, pass-through the AND to get to the intrinsic. 15322 if (LHS.getOpcode() == ISD::AND && 15323 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15324 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15325 Intrinsic::loop_decrement && 15326 isa<ConstantSDNode>(LHS.getOperand(1)) && 15327 !isNullConstant(LHS.getOperand(1))) 15328 LHS = LHS.getOperand(0); 15329 15330 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15331 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15332 Intrinsic::loop_decrement && 15333 isa<ConstantSDNode>(RHS)) { 15334 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15335 "Counter decrement comparison is not EQ or NE"); 15336 15337 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15338 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15339 (CC == ISD::SETNE && !Val); 15340 15341 // We now need to make the intrinsic dead (it cannot be instruction 15342 // selected). 15343 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15344 assert(LHS.getNode()->hasOneUse() && 15345 "Counter decrement has more than one use"); 15346 15347 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15348 N->getOperand(0), N->getOperand(4)); 15349 } 15350 15351 int CompareOpc; 15352 bool isDot; 15353 15354 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15355 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15356 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15357 assert(isDot && "Can't compare against a vector result!"); 15358 15359 // If this is a comparison against something other than 0/1, then we know 15360 // that the condition is never/always true. 15361 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15362 if (Val != 0 && Val != 1) { 15363 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15364 return N->getOperand(0); 15365 // Always !=, turn it into an unconditional branch. 15366 return DAG.getNode(ISD::BR, dl, MVT::Other, 15367 N->getOperand(0), N->getOperand(4)); 15368 } 15369 15370 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15371 15372 // Create the PPCISD altivec 'dot' comparison node. 15373 SDValue Ops[] = { 15374 LHS.getOperand(2), // LHS of compare 15375 LHS.getOperand(3), // RHS of compare 15376 DAG.getConstant(CompareOpc, dl, MVT::i32) 15377 }; 15378 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15379 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15380 15381 // Unpack the result based on how the target uses it. 15382 PPC::Predicate CompOpc; 15383 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15384 default: // Can't happen, don't crash on invalid number though. 15385 case 0: // Branch on the value of the EQ bit of CR6. 15386 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15387 break; 15388 case 1: // Branch on the inverted value of the EQ bit of CR6. 15389 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15390 break; 15391 case 2: // Branch on the value of the LT bit of CR6. 15392 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15393 break; 15394 case 3: // Branch on the inverted value of the LT bit of CR6. 15395 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15396 break; 15397 } 15398 15399 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15400 DAG.getConstant(CompOpc, dl, MVT::i32), 15401 DAG.getRegister(PPC::CR6, MVT::i32), 15402 N->getOperand(4), CompNode.getValue(1)); 15403 } 15404 break; 15405 } 15406 case ISD::BUILD_VECTOR: 15407 return DAGCombineBuildVector(N, DCI); 15408 case ISD::ABS: 15409 return combineABS(N, DCI); 15410 case ISD::VSELECT: 15411 return combineVSelect(N, DCI); 15412 } 15413 15414 return SDValue(); 15415 } 15416 15417 SDValue 15418 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15419 SelectionDAG &DAG, 15420 SmallVectorImpl<SDNode *> &Created) const { 15421 // fold (sdiv X, pow2) 15422 EVT VT = N->getValueType(0); 15423 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15424 return SDValue(); 15425 if ((VT != MVT::i32 && VT != MVT::i64) || 15426 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15427 return SDValue(); 15428 15429 SDLoc DL(N); 15430 SDValue N0 = N->getOperand(0); 15431 15432 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15433 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15434 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15435 15436 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15437 Created.push_back(Op.getNode()); 15438 15439 if (IsNegPow2) { 15440 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15441 Created.push_back(Op.getNode()); 15442 } 15443 15444 return Op; 15445 } 15446 15447 //===----------------------------------------------------------------------===// 15448 // Inline Assembly Support 15449 //===----------------------------------------------------------------------===// 15450 15451 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15452 KnownBits &Known, 15453 const APInt &DemandedElts, 15454 const SelectionDAG &DAG, 15455 unsigned Depth) const { 15456 Known.resetAll(); 15457 switch (Op.getOpcode()) { 15458 default: break; 15459 case PPCISD::LBRX: { 15460 // lhbrx is known to have the top bits cleared out. 15461 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15462 Known.Zero = 0xFFFF0000; 15463 break; 15464 } 15465 case ISD::INTRINSIC_WO_CHAIN: { 15466 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15467 default: break; 15468 case Intrinsic::ppc_altivec_vcmpbfp_p: 15469 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15470 case Intrinsic::ppc_altivec_vcmpequb_p: 15471 case Intrinsic::ppc_altivec_vcmpequh_p: 15472 case Intrinsic::ppc_altivec_vcmpequw_p: 15473 case Intrinsic::ppc_altivec_vcmpequd_p: 15474 case Intrinsic::ppc_altivec_vcmpequq_p: 15475 case Intrinsic::ppc_altivec_vcmpgefp_p: 15476 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15477 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15478 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15479 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15480 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15481 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15482 case Intrinsic::ppc_altivec_vcmpgtub_p: 15483 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15484 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15485 case Intrinsic::ppc_altivec_vcmpgtud_p: 15486 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15487 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15488 break; 15489 } 15490 } 15491 } 15492 } 15493 15494 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15495 switch (Subtarget.getCPUDirective()) { 15496 default: break; 15497 case PPC::DIR_970: 15498 case PPC::DIR_PWR4: 15499 case PPC::DIR_PWR5: 15500 case PPC::DIR_PWR5X: 15501 case PPC::DIR_PWR6: 15502 case PPC::DIR_PWR6X: 15503 case PPC::DIR_PWR7: 15504 case PPC::DIR_PWR8: 15505 case PPC::DIR_PWR9: 15506 case PPC::DIR_PWR10: 15507 case PPC::DIR_PWR_FUTURE: { 15508 if (!ML) 15509 break; 15510 15511 if (!DisableInnermostLoopAlign32) { 15512 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15513 // so that we can decrease cache misses and branch-prediction misses. 15514 // Actual alignment of the loop will depend on the hotness check and other 15515 // logic in alignBlocks. 15516 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15517 return Align(32); 15518 } 15519 15520 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15521 15522 // For small loops (between 5 and 8 instructions), align to a 32-byte 15523 // boundary so that the entire loop fits in one instruction-cache line. 15524 uint64_t LoopSize = 0; 15525 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15526 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15527 LoopSize += TII->getInstSizeInBytes(*J); 15528 if (LoopSize > 32) 15529 break; 15530 } 15531 15532 if (LoopSize > 16 && LoopSize <= 32) 15533 return Align(32); 15534 15535 break; 15536 } 15537 } 15538 15539 return TargetLowering::getPrefLoopAlignment(ML); 15540 } 15541 15542 /// getConstraintType - Given a constraint, return the type of 15543 /// constraint it is for this target. 15544 PPCTargetLowering::ConstraintType 15545 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15546 if (Constraint.size() == 1) { 15547 switch (Constraint[0]) { 15548 default: break; 15549 case 'b': 15550 case 'r': 15551 case 'f': 15552 case 'd': 15553 case 'v': 15554 case 'y': 15555 return C_RegisterClass; 15556 case 'Z': 15557 // FIXME: While Z does indicate a memory constraint, it specifically 15558 // indicates an r+r address (used in conjunction with the 'y' modifier 15559 // in the replacement string). Currently, we're forcing the base 15560 // register to be r0 in the asm printer (which is interpreted as zero) 15561 // and forming the complete address in the second register. This is 15562 // suboptimal. 15563 return C_Memory; 15564 } 15565 } else if (Constraint == "wc") { // individual CR bits. 15566 return C_RegisterClass; 15567 } else if (Constraint == "wa" || Constraint == "wd" || 15568 Constraint == "wf" || Constraint == "ws" || 15569 Constraint == "wi" || Constraint == "ww") { 15570 return C_RegisterClass; // VSX registers. 15571 } 15572 return TargetLowering::getConstraintType(Constraint); 15573 } 15574 15575 /// Examine constraint type and operand type and determine a weight value. 15576 /// This object must already have been set up with the operand type 15577 /// and the current alternative constraint selected. 15578 TargetLowering::ConstraintWeight 15579 PPCTargetLowering::getSingleConstraintMatchWeight( 15580 AsmOperandInfo &info, const char *constraint) const { 15581 ConstraintWeight weight = CW_Invalid; 15582 Value *CallOperandVal = info.CallOperandVal; 15583 // If we don't have a value, we can't do a match, 15584 // but allow it at the lowest weight. 15585 if (!CallOperandVal) 15586 return CW_Default; 15587 Type *type = CallOperandVal->getType(); 15588 15589 // Look at the constraint type. 15590 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15591 return CW_Register; // an individual CR bit. 15592 else if ((StringRef(constraint) == "wa" || 15593 StringRef(constraint) == "wd" || 15594 StringRef(constraint) == "wf") && 15595 type->isVectorTy()) 15596 return CW_Register; 15597 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15598 return CW_Register; // just hold 64-bit integers data. 15599 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15600 return CW_Register; 15601 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15602 return CW_Register; 15603 15604 switch (*constraint) { 15605 default: 15606 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15607 break; 15608 case 'b': 15609 if (type->isIntegerTy()) 15610 weight = CW_Register; 15611 break; 15612 case 'f': 15613 if (type->isFloatTy()) 15614 weight = CW_Register; 15615 break; 15616 case 'd': 15617 if (type->isDoubleTy()) 15618 weight = CW_Register; 15619 break; 15620 case 'v': 15621 if (type->isVectorTy()) 15622 weight = CW_Register; 15623 break; 15624 case 'y': 15625 weight = CW_Register; 15626 break; 15627 case 'Z': 15628 weight = CW_Memory; 15629 break; 15630 } 15631 return weight; 15632 } 15633 15634 std::pair<unsigned, const TargetRegisterClass *> 15635 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15636 StringRef Constraint, 15637 MVT VT) const { 15638 if (Constraint.size() == 1) { 15639 // GCC RS6000 Constraint Letters 15640 switch (Constraint[0]) { 15641 case 'b': // R1-R31 15642 if (VT == MVT::i64 && Subtarget.isPPC64()) 15643 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15644 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15645 case 'r': // R0-R31 15646 if (VT == MVT::i64 && Subtarget.isPPC64()) 15647 return std::make_pair(0U, &PPC::G8RCRegClass); 15648 return std::make_pair(0U, &PPC::GPRCRegClass); 15649 // 'd' and 'f' constraints are both defined to be "the floating point 15650 // registers", where one is for 32-bit and the other for 64-bit. We don't 15651 // really care overly much here so just give them all the same reg classes. 15652 case 'd': 15653 case 'f': 15654 if (Subtarget.hasSPE()) { 15655 if (VT == MVT::f32 || VT == MVT::i32) 15656 return std::make_pair(0U, &PPC::GPRCRegClass); 15657 if (VT == MVT::f64 || VT == MVT::i64) 15658 return std::make_pair(0U, &PPC::SPERCRegClass); 15659 } else { 15660 if (VT == MVT::f32 || VT == MVT::i32) 15661 return std::make_pair(0U, &PPC::F4RCRegClass); 15662 if (VT == MVT::f64 || VT == MVT::i64) 15663 return std::make_pair(0U, &PPC::F8RCRegClass); 15664 } 15665 break; 15666 case 'v': 15667 if (Subtarget.hasAltivec()) 15668 return std::make_pair(0U, &PPC::VRRCRegClass); 15669 break; 15670 case 'y': // crrc 15671 return std::make_pair(0U, &PPC::CRRCRegClass); 15672 } 15673 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15674 // An individual CR bit. 15675 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15676 } else if ((Constraint == "wa" || Constraint == "wd" || 15677 Constraint == "wf" || Constraint == "wi") && 15678 Subtarget.hasVSX()) { 15679 // A VSX register for either a scalar (FP) or vector. There is no 15680 // support for single precision scalars on subtargets prior to Power8. 15681 if (VT.isVector()) 15682 return std::make_pair(0U, &PPC::VSRCRegClass); 15683 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15684 return std::make_pair(0U, &PPC::VSSRCRegClass); 15685 return std::make_pair(0U, &PPC::VSFRCRegClass); 15686 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15687 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15688 return std::make_pair(0U, &PPC::VSSRCRegClass); 15689 else 15690 return std::make_pair(0U, &PPC::VSFRCRegClass); 15691 } else if (Constraint == "lr") { 15692 if (VT == MVT::i64) 15693 return std::make_pair(0U, &PPC::LR8RCRegClass); 15694 else 15695 return std::make_pair(0U, &PPC::LRRCRegClass); 15696 } 15697 15698 // Handle special cases of physical registers that are not properly handled 15699 // by the base class. 15700 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 15701 // If we name a VSX register, we can't defer to the base class because it 15702 // will not recognize the correct register (their names will be VSL{0-31} 15703 // and V{0-31} so they won't match). So we match them here. 15704 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15705 int VSNum = atoi(Constraint.data() + 3); 15706 assert(VSNum >= 0 && VSNum <= 63 && 15707 "Attempted to access a vsr out of range"); 15708 if (VSNum < 32) 15709 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15710 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15711 } 15712 15713 // For float registers, we can't defer to the base class as it will match 15714 // the SPILLTOVSRRC class. 15715 if (Constraint.size() > 3 && Constraint[1] == 'f') { 15716 int RegNum = atoi(Constraint.data() + 2); 15717 if (RegNum > 31 || RegNum < 0) 15718 report_fatal_error("Invalid floating point register number"); 15719 if (VT == MVT::f32 || VT == MVT::i32) 15720 return Subtarget.hasSPE() 15721 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 15722 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 15723 if (VT == MVT::f64 || VT == MVT::i64) 15724 return Subtarget.hasSPE() 15725 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 15726 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 15727 } 15728 } 15729 15730 std::pair<unsigned, const TargetRegisterClass *> R = 15731 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15732 15733 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15734 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15735 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15736 // register. 15737 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15738 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15739 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15740 PPC::GPRCRegClass.contains(R.first)) 15741 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15742 PPC::sub_32, &PPC::G8RCRegClass), 15743 &PPC::G8RCRegClass); 15744 15745 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15746 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15747 R.first = PPC::CR0; 15748 R.second = &PPC::CRRCRegClass; 15749 } 15750 // FIXME: This warning should ideally be emitted in the front end. 15751 const auto &TM = getTargetMachine(); 15752 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 15753 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 15754 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 15755 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 15756 errs() << "warning: vector registers 20 to 32 are reserved in the " 15757 "default AIX AltiVec ABI and cannot be used\n"; 15758 } 15759 15760 return R; 15761 } 15762 15763 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15764 /// vector. If it is invalid, don't add anything to Ops. 15765 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15766 std::string &Constraint, 15767 std::vector<SDValue>&Ops, 15768 SelectionDAG &DAG) const { 15769 SDValue Result; 15770 15771 // Only support length 1 constraints. 15772 if (Constraint.length() > 1) return; 15773 15774 char Letter = Constraint[0]; 15775 switch (Letter) { 15776 default: break; 15777 case 'I': 15778 case 'J': 15779 case 'K': 15780 case 'L': 15781 case 'M': 15782 case 'N': 15783 case 'O': 15784 case 'P': { 15785 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15786 if (!CST) return; // Must be an immediate to match. 15787 SDLoc dl(Op); 15788 int64_t Value = CST->getSExtValue(); 15789 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15790 // numbers are printed as such. 15791 switch (Letter) { 15792 default: llvm_unreachable("Unknown constraint letter!"); 15793 case 'I': // "I" is a signed 16-bit constant. 15794 if (isInt<16>(Value)) 15795 Result = DAG.getTargetConstant(Value, dl, TCVT); 15796 break; 15797 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15798 if (isShiftedUInt<16, 16>(Value)) 15799 Result = DAG.getTargetConstant(Value, dl, TCVT); 15800 break; 15801 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15802 if (isShiftedInt<16, 16>(Value)) 15803 Result = DAG.getTargetConstant(Value, dl, TCVT); 15804 break; 15805 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15806 if (isUInt<16>(Value)) 15807 Result = DAG.getTargetConstant(Value, dl, TCVT); 15808 break; 15809 case 'M': // "M" is a constant that is greater than 31. 15810 if (Value > 31) 15811 Result = DAG.getTargetConstant(Value, dl, TCVT); 15812 break; 15813 case 'N': // "N" is a positive constant that is an exact power of two. 15814 if (Value > 0 && isPowerOf2_64(Value)) 15815 Result = DAG.getTargetConstant(Value, dl, TCVT); 15816 break; 15817 case 'O': // "O" is the constant zero. 15818 if (Value == 0) 15819 Result = DAG.getTargetConstant(Value, dl, TCVT); 15820 break; 15821 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15822 if (isInt<16>(-Value)) 15823 Result = DAG.getTargetConstant(Value, dl, TCVT); 15824 break; 15825 } 15826 break; 15827 } 15828 } 15829 15830 if (Result.getNode()) { 15831 Ops.push_back(Result); 15832 return; 15833 } 15834 15835 // Handle standard constraint letters. 15836 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15837 } 15838 15839 // isLegalAddressingMode - Return true if the addressing mode represented 15840 // by AM is legal for this target, for a load/store of the specified type. 15841 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15842 const AddrMode &AM, Type *Ty, 15843 unsigned AS, 15844 Instruction *I) const { 15845 // Vector type r+i form is supported since power9 as DQ form. We don't check 15846 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15847 // imm form is preferred and the offset can be adjusted to use imm form later 15848 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15849 // max offset to check legal addressing mode, we should be a little aggressive 15850 // to contain other offsets for that LSRUse. 15851 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15852 return false; 15853 15854 // PPC allows a sign-extended 16-bit immediate field. 15855 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15856 return false; 15857 15858 // No global is ever allowed as a base. 15859 if (AM.BaseGV) 15860 return false; 15861 15862 // PPC only support r+r, 15863 switch (AM.Scale) { 15864 case 0: // "r+i" or just "i", depending on HasBaseReg. 15865 break; 15866 case 1: 15867 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15868 return false; 15869 // Otherwise we have r+r or r+i. 15870 break; 15871 case 2: 15872 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15873 return false; 15874 // Allow 2*r as r+r. 15875 break; 15876 default: 15877 // No other scales are supported. 15878 return false; 15879 } 15880 15881 return true; 15882 } 15883 15884 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15885 SelectionDAG &DAG) const { 15886 MachineFunction &MF = DAG.getMachineFunction(); 15887 MachineFrameInfo &MFI = MF.getFrameInfo(); 15888 MFI.setReturnAddressIsTaken(true); 15889 15890 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15891 return SDValue(); 15892 15893 SDLoc dl(Op); 15894 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15895 15896 // Make sure the function does not optimize away the store of the RA to 15897 // the stack. 15898 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15899 FuncInfo->setLRStoreRequired(); 15900 bool isPPC64 = Subtarget.isPPC64(); 15901 auto PtrVT = getPointerTy(MF.getDataLayout()); 15902 15903 if (Depth > 0) { 15904 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15905 SDValue Offset = 15906 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15907 isPPC64 ? MVT::i64 : MVT::i32); 15908 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15909 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15910 MachinePointerInfo()); 15911 } 15912 15913 // Just load the return address off the stack. 15914 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15915 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15916 MachinePointerInfo()); 15917 } 15918 15919 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15920 SelectionDAG &DAG) const { 15921 SDLoc dl(Op); 15922 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15923 15924 MachineFunction &MF = DAG.getMachineFunction(); 15925 MachineFrameInfo &MFI = MF.getFrameInfo(); 15926 MFI.setFrameAddressIsTaken(true); 15927 15928 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15929 bool isPPC64 = PtrVT == MVT::i64; 15930 15931 // Naked functions never have a frame pointer, and so we use r1. For all 15932 // other functions, this decision must be delayed until during PEI. 15933 unsigned FrameReg; 15934 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15935 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15936 else 15937 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15938 15939 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15940 PtrVT); 15941 while (Depth--) 15942 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15943 FrameAddr, MachinePointerInfo()); 15944 return FrameAddr; 15945 } 15946 15947 // FIXME? Maybe this could be a TableGen attribute on some registers and 15948 // this table could be generated automatically from RegInfo. 15949 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15950 const MachineFunction &MF) const { 15951 bool isPPC64 = Subtarget.isPPC64(); 15952 15953 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15954 if (!is64Bit && VT != LLT::scalar(32)) 15955 report_fatal_error("Invalid register global variable type"); 15956 15957 Register Reg = StringSwitch<Register>(RegName) 15958 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15959 .Case("r2", isPPC64 ? Register() : PPC::R2) 15960 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15961 .Default(Register()); 15962 15963 if (Reg) 15964 return Reg; 15965 report_fatal_error("Invalid register name global variable"); 15966 } 15967 15968 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15969 // 32-bit SVR4 ABI access everything as got-indirect. 15970 if (Subtarget.is32BitELFABI()) 15971 return true; 15972 15973 // AIX accesses everything indirectly through the TOC, which is similar to 15974 // the GOT. 15975 if (Subtarget.isAIXABI()) 15976 return true; 15977 15978 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15979 // If it is small or large code model, module locals are accessed 15980 // indirectly by loading their address from .toc/.got. 15981 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15982 return true; 15983 15984 // JumpTable and BlockAddress are accessed as got-indirect. 15985 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15986 return true; 15987 15988 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15989 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15990 15991 return false; 15992 } 15993 15994 bool 15995 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15996 // The PowerPC target isn't yet aware of offsets. 15997 return false; 15998 } 15999 16000 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16001 const CallInst &I, 16002 MachineFunction &MF, 16003 unsigned Intrinsic) const { 16004 switch (Intrinsic) { 16005 case Intrinsic::ppc_altivec_lvx: 16006 case Intrinsic::ppc_altivec_lvxl: 16007 case Intrinsic::ppc_altivec_lvebx: 16008 case Intrinsic::ppc_altivec_lvehx: 16009 case Intrinsic::ppc_altivec_lvewx: 16010 case Intrinsic::ppc_vsx_lxvd2x: 16011 case Intrinsic::ppc_vsx_lxvw4x: 16012 case Intrinsic::ppc_vsx_lxvd2x_be: 16013 case Intrinsic::ppc_vsx_lxvw4x_be: 16014 case Intrinsic::ppc_vsx_lxvl: 16015 case Intrinsic::ppc_vsx_lxvll: { 16016 EVT VT; 16017 switch (Intrinsic) { 16018 case Intrinsic::ppc_altivec_lvebx: 16019 VT = MVT::i8; 16020 break; 16021 case Intrinsic::ppc_altivec_lvehx: 16022 VT = MVT::i16; 16023 break; 16024 case Intrinsic::ppc_altivec_lvewx: 16025 VT = MVT::i32; 16026 break; 16027 case Intrinsic::ppc_vsx_lxvd2x: 16028 case Intrinsic::ppc_vsx_lxvd2x_be: 16029 VT = MVT::v2f64; 16030 break; 16031 default: 16032 VT = MVT::v4i32; 16033 break; 16034 } 16035 16036 Info.opc = ISD::INTRINSIC_W_CHAIN; 16037 Info.memVT = VT; 16038 Info.ptrVal = I.getArgOperand(0); 16039 Info.offset = -VT.getStoreSize()+1; 16040 Info.size = 2*VT.getStoreSize()-1; 16041 Info.align = Align(1); 16042 Info.flags = MachineMemOperand::MOLoad; 16043 return true; 16044 } 16045 case Intrinsic::ppc_altivec_stvx: 16046 case Intrinsic::ppc_altivec_stvxl: 16047 case Intrinsic::ppc_altivec_stvebx: 16048 case Intrinsic::ppc_altivec_stvehx: 16049 case Intrinsic::ppc_altivec_stvewx: 16050 case Intrinsic::ppc_vsx_stxvd2x: 16051 case Intrinsic::ppc_vsx_stxvw4x: 16052 case Intrinsic::ppc_vsx_stxvd2x_be: 16053 case Intrinsic::ppc_vsx_stxvw4x_be: 16054 case Intrinsic::ppc_vsx_stxvl: 16055 case Intrinsic::ppc_vsx_stxvll: { 16056 EVT VT; 16057 switch (Intrinsic) { 16058 case Intrinsic::ppc_altivec_stvebx: 16059 VT = MVT::i8; 16060 break; 16061 case Intrinsic::ppc_altivec_stvehx: 16062 VT = MVT::i16; 16063 break; 16064 case Intrinsic::ppc_altivec_stvewx: 16065 VT = MVT::i32; 16066 break; 16067 case Intrinsic::ppc_vsx_stxvd2x: 16068 case Intrinsic::ppc_vsx_stxvd2x_be: 16069 VT = MVT::v2f64; 16070 break; 16071 default: 16072 VT = MVT::v4i32; 16073 break; 16074 } 16075 16076 Info.opc = ISD::INTRINSIC_VOID; 16077 Info.memVT = VT; 16078 Info.ptrVal = I.getArgOperand(1); 16079 Info.offset = -VT.getStoreSize()+1; 16080 Info.size = 2*VT.getStoreSize()-1; 16081 Info.align = Align(1); 16082 Info.flags = MachineMemOperand::MOStore; 16083 return true; 16084 } 16085 default: 16086 break; 16087 } 16088 16089 return false; 16090 } 16091 16092 /// It returns EVT::Other if the type should be determined using generic 16093 /// target-independent logic. 16094 EVT PPCTargetLowering::getOptimalMemOpType( 16095 const MemOp &Op, const AttributeList &FuncAttributes) const { 16096 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16097 // We should use Altivec/VSX loads and stores when available. For unaligned 16098 // addresses, unaligned VSX loads are only fast starting with the P8. 16099 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16100 (Op.isAligned(Align(16)) || 16101 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16102 return MVT::v4i32; 16103 } 16104 16105 if (Subtarget.isPPC64()) { 16106 return MVT::i64; 16107 } 16108 16109 return MVT::i32; 16110 } 16111 16112 /// Returns true if it is beneficial to convert a load of a constant 16113 /// to just the constant itself. 16114 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16115 Type *Ty) const { 16116 assert(Ty->isIntegerTy()); 16117 16118 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16119 return !(BitSize == 0 || BitSize > 64); 16120 } 16121 16122 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16123 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16124 return false; 16125 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16126 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16127 return NumBits1 == 64 && NumBits2 == 32; 16128 } 16129 16130 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16131 if (!VT1.isInteger() || !VT2.isInteger()) 16132 return false; 16133 unsigned NumBits1 = VT1.getSizeInBits(); 16134 unsigned NumBits2 = VT2.getSizeInBits(); 16135 return NumBits1 == 64 && NumBits2 == 32; 16136 } 16137 16138 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16139 // Generally speaking, zexts are not free, but they are free when they can be 16140 // folded with other operations. 16141 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16142 EVT MemVT = LD->getMemoryVT(); 16143 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16144 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16145 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16146 LD->getExtensionType() == ISD::ZEXTLOAD)) 16147 return true; 16148 } 16149 16150 // FIXME: Add other cases... 16151 // - 32-bit shifts with a zext to i64 16152 // - zext after ctlz, bswap, etc. 16153 // - zext after and by a constant mask 16154 16155 return TargetLowering::isZExtFree(Val, VT2); 16156 } 16157 16158 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16159 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16160 "invalid fpext types"); 16161 // Extending to float128 is not free. 16162 if (DestVT == MVT::f128) 16163 return false; 16164 return true; 16165 } 16166 16167 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16168 return isInt<16>(Imm) || isUInt<16>(Imm); 16169 } 16170 16171 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16172 return isInt<16>(Imm) || isUInt<16>(Imm); 16173 } 16174 16175 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 16176 MachineMemOperand::Flags, 16177 bool *Fast) const { 16178 if (DisablePPCUnaligned) 16179 return false; 16180 16181 // PowerPC supports unaligned memory access for simple non-vector types. 16182 // Although accessing unaligned addresses is not as efficient as accessing 16183 // aligned addresses, it is generally more efficient than manual expansion, 16184 // and generally only traps for software emulation when crossing page 16185 // boundaries. 16186 16187 if (!VT.isSimple()) 16188 return false; 16189 16190 if (VT.isFloatingPoint() && !VT.isVector() && 16191 !Subtarget.allowsUnalignedFPAccess()) 16192 return false; 16193 16194 if (VT.getSimpleVT().isVector()) { 16195 if (Subtarget.hasVSX()) { 16196 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16197 VT != MVT::v4f32 && VT != MVT::v4i32) 16198 return false; 16199 } else { 16200 return false; 16201 } 16202 } 16203 16204 if (VT == MVT::ppcf128) 16205 return false; 16206 16207 if (Fast) 16208 *Fast = true; 16209 16210 return true; 16211 } 16212 16213 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16214 SDValue C) const { 16215 // Check integral scalar types. 16216 if (!VT.isScalarInteger()) 16217 return false; 16218 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16219 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16220 return false; 16221 // This transformation will generate >= 2 operations. But the following 16222 // cases will generate <= 2 instructions during ISEL. So exclude them. 16223 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16224 // HW instruction, ie. MULLI 16225 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16226 // instruction is needed than case 1, ie. MULLI and RLDICR 16227 int64_t Imm = ConstNode->getSExtValue(); 16228 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16229 Imm >>= Shift; 16230 if (isInt<16>(Imm)) 16231 return false; 16232 uint64_t UImm = static_cast<uint64_t>(Imm); 16233 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16234 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16235 return true; 16236 } 16237 return false; 16238 } 16239 16240 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16241 EVT VT) const { 16242 return isFMAFasterThanFMulAndFAdd( 16243 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16244 } 16245 16246 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16247 Type *Ty) const { 16248 switch (Ty->getScalarType()->getTypeID()) { 16249 case Type::FloatTyID: 16250 case Type::DoubleTyID: 16251 return true; 16252 case Type::FP128TyID: 16253 return Subtarget.hasP9Vector(); 16254 default: 16255 return false; 16256 } 16257 } 16258 16259 // FIXME: add more patterns which are not profitable to hoist. 16260 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16261 if (!I->hasOneUse()) 16262 return true; 16263 16264 Instruction *User = I->user_back(); 16265 assert(User && "A single use instruction with no uses."); 16266 16267 switch (I->getOpcode()) { 16268 case Instruction::FMul: { 16269 // Don't break FMA, PowerPC prefers FMA. 16270 if (User->getOpcode() != Instruction::FSub && 16271 User->getOpcode() != Instruction::FAdd) 16272 return true; 16273 16274 const TargetOptions &Options = getTargetMachine().Options; 16275 const Function *F = I->getFunction(); 16276 const DataLayout &DL = F->getParent()->getDataLayout(); 16277 Type *Ty = User->getOperand(0)->getType(); 16278 16279 return !( 16280 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16281 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16282 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16283 } 16284 case Instruction::Load: { 16285 // Don't break "store (load float*)" pattern, this pattern will be combined 16286 // to "store (load int32)" in later InstCombine pass. See function 16287 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16288 // cycles than loading a 32 bit integer. 16289 LoadInst *LI = cast<LoadInst>(I); 16290 // For the loads that combineLoadToOperationType does nothing, like 16291 // ordered load, it should be profitable to hoist them. 16292 // For swifterror load, it can only be used for pointer to pointer type, so 16293 // later type check should get rid of this case. 16294 if (!LI->isUnordered()) 16295 return true; 16296 16297 if (User->getOpcode() != Instruction::Store) 16298 return true; 16299 16300 if (I->getType()->getTypeID() != Type::FloatTyID) 16301 return true; 16302 16303 return false; 16304 } 16305 default: 16306 return true; 16307 } 16308 return true; 16309 } 16310 16311 const MCPhysReg * 16312 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16313 // LR is a callee-save register, but we must treat it as clobbered by any call 16314 // site. Hence we include LR in the scratch registers, which are in turn added 16315 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16316 // to CTR, which is used by any indirect call. 16317 static const MCPhysReg ScratchRegs[] = { 16318 PPC::X12, PPC::LR8, PPC::CTR8, 0 16319 }; 16320 16321 return ScratchRegs; 16322 } 16323 16324 Register PPCTargetLowering::getExceptionPointerRegister( 16325 const Constant *PersonalityFn) const { 16326 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16327 } 16328 16329 Register PPCTargetLowering::getExceptionSelectorRegister( 16330 const Constant *PersonalityFn) const { 16331 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16332 } 16333 16334 bool 16335 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16336 EVT VT , unsigned DefinedValues) const { 16337 if (VT == MVT::v2i64) 16338 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16339 16340 if (Subtarget.hasVSX()) 16341 return true; 16342 16343 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16344 } 16345 16346 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16347 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16348 return TargetLowering::getSchedulingPreference(N); 16349 16350 return Sched::ILP; 16351 } 16352 16353 // Create a fast isel object. 16354 FastISel * 16355 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16356 const TargetLibraryInfo *LibInfo) const { 16357 return PPC::createFastISel(FuncInfo, LibInfo); 16358 } 16359 16360 // 'Inverted' means the FMA opcode after negating one multiplicand. 16361 // For example, (fma -a b c) = (fnmsub a b c) 16362 static unsigned invertFMAOpcode(unsigned Opc) { 16363 switch (Opc) { 16364 default: 16365 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16366 case ISD::FMA: 16367 return PPCISD::FNMSUB; 16368 case PPCISD::FNMSUB: 16369 return ISD::FMA; 16370 } 16371 } 16372 16373 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16374 bool LegalOps, bool OptForSize, 16375 NegatibleCost &Cost, 16376 unsigned Depth) const { 16377 if (Depth > SelectionDAG::MaxRecursionDepth) 16378 return SDValue(); 16379 16380 unsigned Opc = Op.getOpcode(); 16381 EVT VT = Op.getValueType(); 16382 SDNodeFlags Flags = Op.getNode()->getFlags(); 16383 16384 switch (Opc) { 16385 case PPCISD::FNMSUB: 16386 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16387 break; 16388 16389 const TargetOptions &Options = getTargetMachine().Options; 16390 SDValue N0 = Op.getOperand(0); 16391 SDValue N1 = Op.getOperand(1); 16392 SDValue N2 = Op.getOperand(2); 16393 SDLoc Loc(Op); 16394 16395 NegatibleCost N2Cost = NegatibleCost::Expensive; 16396 SDValue NegN2 = 16397 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16398 16399 if (!NegN2) 16400 return SDValue(); 16401 16402 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16403 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16404 // These transformations may change sign of zeroes. For example, 16405 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16406 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16407 // Try and choose the cheaper one to negate. 16408 NegatibleCost N0Cost = NegatibleCost::Expensive; 16409 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16410 N0Cost, Depth + 1); 16411 16412 NegatibleCost N1Cost = NegatibleCost::Expensive; 16413 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16414 N1Cost, Depth + 1); 16415 16416 if (NegN0 && N0Cost <= N1Cost) { 16417 Cost = std::min(N0Cost, N2Cost); 16418 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16419 } else if (NegN1) { 16420 Cost = std::min(N1Cost, N2Cost); 16421 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16422 } 16423 } 16424 16425 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16426 if (isOperationLegal(ISD::FMA, VT)) { 16427 Cost = N2Cost; 16428 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16429 } 16430 16431 break; 16432 } 16433 16434 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16435 Cost, Depth); 16436 } 16437 16438 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16439 bool PPCTargetLowering::useLoadStackGuardNode() const { 16440 if (!Subtarget.isTargetLinux()) 16441 return TargetLowering::useLoadStackGuardNode(); 16442 return true; 16443 } 16444 16445 // Override to disable global variable loading on Linux and insert AIX canary 16446 // word declaration. 16447 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16448 if (Subtarget.isAIXABI()) { 16449 M.getOrInsertGlobal(AIXSSPCanaryWordName, 16450 Type::getInt8PtrTy(M.getContext())); 16451 return; 16452 } 16453 if (!Subtarget.isTargetLinux()) 16454 return TargetLowering::insertSSPDeclarations(M); 16455 } 16456 16457 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const { 16458 if (Subtarget.isAIXABI()) 16459 return M.getGlobalVariable(AIXSSPCanaryWordName); 16460 return TargetLowering::getSDagStackGuard(M); 16461 } 16462 16463 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16464 bool ForCodeSize) const { 16465 if (!VT.isSimple() || !Subtarget.hasVSX()) 16466 return false; 16467 16468 switch(VT.getSimpleVT().SimpleTy) { 16469 default: 16470 // For FP types that are currently not supported by PPC backend, return 16471 // false. Examples: f16, f80. 16472 return false; 16473 case MVT::f32: 16474 case MVT::f64: 16475 if (Subtarget.hasPrefixInstrs()) { 16476 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 16477 return true; 16478 } 16479 LLVM_FALLTHROUGH; 16480 case MVT::ppcf128: 16481 return Imm.isPosZero(); 16482 } 16483 } 16484 16485 // For vector shift operation op, fold 16486 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16487 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16488 SelectionDAG &DAG) { 16489 SDValue N0 = N->getOperand(0); 16490 SDValue N1 = N->getOperand(1); 16491 EVT VT = N0.getValueType(); 16492 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16493 unsigned Opcode = N->getOpcode(); 16494 unsigned TargetOpcode; 16495 16496 switch (Opcode) { 16497 default: 16498 llvm_unreachable("Unexpected shift operation"); 16499 case ISD::SHL: 16500 TargetOpcode = PPCISD::SHL; 16501 break; 16502 case ISD::SRL: 16503 TargetOpcode = PPCISD::SRL; 16504 break; 16505 case ISD::SRA: 16506 TargetOpcode = PPCISD::SRA; 16507 break; 16508 } 16509 16510 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16511 N1->getOpcode() == ISD::AND) 16512 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16513 if (Mask->getZExtValue() == OpSizeInBits - 1) 16514 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16515 16516 return SDValue(); 16517 } 16518 16519 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16520 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16521 return Value; 16522 16523 SDValue N0 = N->getOperand(0); 16524 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16525 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16526 N0.getOpcode() != ISD::SIGN_EXTEND || 16527 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16528 N->getValueType(0) != MVT::i64) 16529 return SDValue(); 16530 16531 // We can't save an operation here if the value is already extended, and 16532 // the existing shift is easier to combine. 16533 SDValue ExtsSrc = N0.getOperand(0); 16534 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16535 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16536 return SDValue(); 16537 16538 SDLoc DL(N0); 16539 SDValue ShiftBy = SDValue(CN1, 0); 16540 // We want the shift amount to be i32 on the extswli, but the shift could 16541 // have an i64. 16542 if (ShiftBy.getValueType() == MVT::i64) 16543 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16544 16545 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16546 ShiftBy); 16547 } 16548 16549 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16550 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16551 return Value; 16552 16553 return SDValue(); 16554 } 16555 16556 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16557 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16558 return Value; 16559 16560 return SDValue(); 16561 } 16562 16563 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16564 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16565 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16566 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16567 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16568 const PPCSubtarget &Subtarget) { 16569 if (!Subtarget.isPPC64()) 16570 return SDValue(); 16571 16572 SDValue LHS = N->getOperand(0); 16573 SDValue RHS = N->getOperand(1); 16574 16575 auto isZextOfCompareWithConstant = [](SDValue Op) { 16576 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16577 Op.getValueType() != MVT::i64) 16578 return false; 16579 16580 SDValue Cmp = Op.getOperand(0); 16581 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16582 Cmp.getOperand(0).getValueType() != MVT::i64) 16583 return false; 16584 16585 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16586 int64_t NegConstant = 0 - Constant->getSExtValue(); 16587 // Due to the limitations of the addi instruction, 16588 // -C is required to be [-32768, 32767]. 16589 return isInt<16>(NegConstant); 16590 } 16591 16592 return false; 16593 }; 16594 16595 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16596 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16597 16598 // If there is a pattern, canonicalize a zext operand to the RHS. 16599 if (LHSHasPattern && !RHSHasPattern) 16600 std::swap(LHS, RHS); 16601 else if (!LHSHasPattern && !RHSHasPattern) 16602 return SDValue(); 16603 16604 SDLoc DL(N); 16605 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16606 SDValue Cmp = RHS.getOperand(0); 16607 SDValue Z = Cmp.getOperand(0); 16608 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1)); 16609 int64_t NegConstant = 0 - Constant->getSExtValue(); 16610 16611 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16612 default: break; 16613 case ISD::SETNE: { 16614 // when C == 0 16615 // --> addze X, (addic Z, -1).carry 16616 // / 16617 // add X, (zext(setne Z, C))-- 16618 // \ when -32768 <= -C <= 32767 && C != 0 16619 // --> addze X, (addic (addi Z, -C), -1).carry 16620 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16621 DAG.getConstant(NegConstant, DL, MVT::i64)); 16622 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16623 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16624 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16625 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16626 SDValue(Addc.getNode(), 1)); 16627 } 16628 case ISD::SETEQ: { 16629 // when C == 0 16630 // --> addze X, (subfic Z, 0).carry 16631 // / 16632 // add X, (zext(sete Z, C))-- 16633 // \ when -32768 <= -C <= 32767 && C != 0 16634 // --> addze X, (subfic (addi Z, -C), 0).carry 16635 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16636 DAG.getConstant(NegConstant, DL, MVT::i64)); 16637 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16638 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16639 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16640 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16641 SDValue(Subc.getNode(), 1)); 16642 } 16643 } 16644 16645 return SDValue(); 16646 } 16647 16648 // Transform 16649 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16650 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16651 // In this case both C1 and C2 must be known constants. 16652 // C1+C2 must fit into a 34 bit signed integer. 16653 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16654 const PPCSubtarget &Subtarget) { 16655 if (!Subtarget.isUsingPCRelativeCalls()) 16656 return SDValue(); 16657 16658 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16659 // If we find that node try to cast the Global Address and the Constant. 16660 SDValue LHS = N->getOperand(0); 16661 SDValue RHS = N->getOperand(1); 16662 16663 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16664 std::swap(LHS, RHS); 16665 16666 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16667 return SDValue(); 16668 16669 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16670 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16671 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16672 16673 // Check that both casts succeeded. 16674 if (!GSDN || !ConstNode) 16675 return SDValue(); 16676 16677 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16678 SDLoc DL(GSDN); 16679 16680 // The signed int offset needs to fit in 34 bits. 16681 if (!isInt<34>(NewOffset)) 16682 return SDValue(); 16683 16684 // The new global address is a copy of the old global address except 16685 // that it has the updated Offset. 16686 SDValue GA = 16687 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16688 NewOffset, GSDN->getTargetFlags()); 16689 SDValue MatPCRel = 16690 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16691 return MatPCRel; 16692 } 16693 16694 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16695 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16696 return Value; 16697 16698 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16699 return Value; 16700 16701 return SDValue(); 16702 } 16703 16704 // Detect TRUNCATE operations on bitcasts of float128 values. 16705 // What we are looking for here is the situtation where we extract a subset 16706 // of bits from a 128 bit float. 16707 // This can be of two forms: 16708 // 1) BITCAST of f128 feeding TRUNCATE 16709 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16710 // The reason this is required is because we do not have a legal i128 type 16711 // and so we want to prevent having to store the f128 and then reload part 16712 // of it. 16713 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16714 DAGCombinerInfo &DCI) const { 16715 // If we are using CRBits then try that first. 16716 if (Subtarget.useCRBits()) { 16717 // Check if CRBits did anything and return that if it did. 16718 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16719 return CRTruncValue; 16720 } 16721 16722 SDLoc dl(N); 16723 SDValue Op0 = N->getOperand(0); 16724 16725 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16726 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16727 EVT VT = N->getValueType(0); 16728 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16729 return SDValue(); 16730 SDValue Sub = Op0.getOperand(0); 16731 if (Sub.getOpcode() == ISD::SUB) { 16732 SDValue SubOp0 = Sub.getOperand(0); 16733 SDValue SubOp1 = Sub.getOperand(1); 16734 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16735 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16736 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16737 SubOp1.getOperand(0), 16738 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16739 } 16740 } 16741 } 16742 16743 // Looking for a truncate of i128 to i64. 16744 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16745 return SDValue(); 16746 16747 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16748 16749 // SRL feeding TRUNCATE. 16750 if (Op0.getOpcode() == ISD::SRL) { 16751 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16752 // The right shift has to be by 64 bits. 16753 if (!ConstNode || ConstNode->getZExtValue() != 64) 16754 return SDValue(); 16755 16756 // Switch the element number to extract. 16757 EltToExtract = EltToExtract ? 0 : 1; 16758 // Update Op0 past the SRL. 16759 Op0 = Op0.getOperand(0); 16760 } 16761 16762 // BITCAST feeding a TRUNCATE possibly via SRL. 16763 if (Op0.getOpcode() == ISD::BITCAST && 16764 Op0.getValueType() == MVT::i128 && 16765 Op0.getOperand(0).getValueType() == MVT::f128) { 16766 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16767 return DCI.DAG.getNode( 16768 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16769 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16770 } 16771 return SDValue(); 16772 } 16773 16774 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16775 SelectionDAG &DAG = DCI.DAG; 16776 16777 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16778 if (!ConstOpOrElement) 16779 return SDValue(); 16780 16781 // An imul is usually smaller than the alternative sequence for legal type. 16782 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16783 isOperationLegal(ISD::MUL, N->getValueType(0))) 16784 return SDValue(); 16785 16786 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16787 switch (this->Subtarget.getCPUDirective()) { 16788 default: 16789 // TODO: enhance the condition for subtarget before pwr8 16790 return false; 16791 case PPC::DIR_PWR8: 16792 // type mul add shl 16793 // scalar 4 1 1 16794 // vector 7 2 2 16795 return true; 16796 case PPC::DIR_PWR9: 16797 case PPC::DIR_PWR10: 16798 case PPC::DIR_PWR_FUTURE: 16799 // type mul add shl 16800 // scalar 5 2 2 16801 // vector 7 2 2 16802 16803 // The cycle RATIO of related operations are showed as a table above. 16804 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16805 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16806 // are 4, it is always profitable; but for 3 instrs patterns 16807 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16808 // So we should only do it for vector type. 16809 return IsAddOne && IsNeg ? VT.isVector() : true; 16810 } 16811 }; 16812 16813 EVT VT = N->getValueType(0); 16814 SDLoc DL(N); 16815 16816 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16817 bool IsNeg = MulAmt.isNegative(); 16818 APInt MulAmtAbs = MulAmt.abs(); 16819 16820 if ((MulAmtAbs - 1).isPowerOf2()) { 16821 // (mul x, 2^N + 1) => (add (shl x, N), x) 16822 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16823 16824 if (!IsProfitable(IsNeg, true, VT)) 16825 return SDValue(); 16826 16827 SDValue Op0 = N->getOperand(0); 16828 SDValue Op1 = 16829 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16830 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16831 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16832 16833 if (!IsNeg) 16834 return Res; 16835 16836 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16837 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16838 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16839 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16840 16841 if (!IsProfitable(IsNeg, false, VT)) 16842 return SDValue(); 16843 16844 SDValue Op0 = N->getOperand(0); 16845 SDValue Op1 = 16846 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16847 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16848 16849 if (!IsNeg) 16850 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16851 else 16852 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16853 16854 } else { 16855 return SDValue(); 16856 } 16857 } 16858 16859 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16860 // in combiner since we need to check SD flags and other subtarget features. 16861 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16862 DAGCombinerInfo &DCI) const { 16863 SDValue N0 = N->getOperand(0); 16864 SDValue N1 = N->getOperand(1); 16865 SDValue N2 = N->getOperand(2); 16866 SDNodeFlags Flags = N->getFlags(); 16867 EVT VT = N->getValueType(0); 16868 SelectionDAG &DAG = DCI.DAG; 16869 const TargetOptions &Options = getTargetMachine().Options; 16870 unsigned Opc = N->getOpcode(); 16871 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16872 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16873 SDLoc Loc(N); 16874 16875 if (!isOperationLegal(ISD::FMA, VT)) 16876 return SDValue(); 16877 16878 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16879 // since (fnmsub a b c)=-0 while c-ab=+0. 16880 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16881 return SDValue(); 16882 16883 // (fma (fneg a) b c) => (fnmsub a b c) 16884 // (fnmsub (fneg a) b c) => (fma a b c) 16885 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16886 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16887 16888 // (fma a (fneg b) c) => (fnmsub a b c) 16889 // (fnmsub a (fneg b) c) => (fma a b c) 16890 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16891 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16892 16893 return SDValue(); 16894 } 16895 16896 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16897 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16898 if (!Subtarget.is64BitELFABI()) 16899 return false; 16900 16901 // If not a tail call then no need to proceed. 16902 if (!CI->isTailCall()) 16903 return false; 16904 16905 // If sibling calls have been disabled and tail-calls aren't guaranteed 16906 // there is no reason to duplicate. 16907 auto &TM = getTargetMachine(); 16908 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16909 return false; 16910 16911 // Can't tail call a function called indirectly, or if it has variadic args. 16912 const Function *Callee = CI->getCalledFunction(); 16913 if (!Callee || Callee->isVarArg()) 16914 return false; 16915 16916 // Make sure the callee and caller calling conventions are eligible for tco. 16917 const Function *Caller = CI->getParent()->getParent(); 16918 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16919 CI->getCallingConv())) 16920 return false; 16921 16922 // If the function is local then we have a good chance at tail-calling it 16923 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16924 } 16925 16926 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16927 if (!Subtarget.hasVSX()) 16928 return false; 16929 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16930 return true; 16931 return VT == MVT::f32 || VT == MVT::f64 || 16932 VT == MVT::v4f32 || VT == MVT::v2f64; 16933 } 16934 16935 bool PPCTargetLowering:: 16936 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16937 const Value *Mask = AndI.getOperand(1); 16938 // If the mask is suitable for andi. or andis. we should sink the and. 16939 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16940 // Can't handle constants wider than 64-bits. 16941 if (CI->getBitWidth() > 64) 16942 return false; 16943 int64_t ConstVal = CI->getZExtValue(); 16944 return isUInt<16>(ConstVal) || 16945 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16946 } 16947 16948 // For non-constant masks, we can always use the record-form and. 16949 return true; 16950 } 16951 16952 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16953 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16954 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16955 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16956 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16957 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16958 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16959 assert(Subtarget.hasP9Altivec() && 16960 "Only combine this when P9 altivec supported!"); 16961 EVT VT = N->getValueType(0); 16962 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16963 return SDValue(); 16964 16965 SelectionDAG &DAG = DCI.DAG; 16966 SDLoc dl(N); 16967 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16968 // Even for signed integers, if it's known to be positive (as signed 16969 // integer) due to zero-extended inputs. 16970 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16971 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16972 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16973 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16974 (SubOpcd1 == ISD::ZERO_EXTEND || 16975 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16976 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16977 N->getOperand(0)->getOperand(0), 16978 N->getOperand(0)->getOperand(1), 16979 DAG.getTargetConstant(0, dl, MVT::i32)); 16980 } 16981 16982 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16983 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16984 N->getOperand(0).hasOneUse()) { 16985 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16986 N->getOperand(0)->getOperand(0), 16987 N->getOperand(0)->getOperand(1), 16988 DAG.getTargetConstant(1, dl, MVT::i32)); 16989 } 16990 } 16991 16992 return SDValue(); 16993 } 16994 16995 // For type v4i32/v8ii16/v16i8, transform 16996 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16997 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16998 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16999 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 17000 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 17001 DAGCombinerInfo &DCI) const { 17002 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 17003 assert(Subtarget.hasP9Altivec() && 17004 "Only combine this when P9 altivec supported!"); 17005 17006 SelectionDAG &DAG = DCI.DAG; 17007 SDLoc dl(N); 17008 SDValue Cond = N->getOperand(0); 17009 SDValue TrueOpnd = N->getOperand(1); 17010 SDValue FalseOpnd = N->getOperand(2); 17011 EVT VT = N->getOperand(1).getValueType(); 17012 17013 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 17014 FalseOpnd.getOpcode() != ISD::SUB) 17015 return SDValue(); 17016 17017 // ABSD only available for type v4i32/v8i16/v16i8 17018 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17019 return SDValue(); 17020 17021 // At least to save one more dependent computation 17022 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 17023 return SDValue(); 17024 17025 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 17026 17027 // Can only handle unsigned comparison here 17028 switch (CC) { 17029 default: 17030 return SDValue(); 17031 case ISD::SETUGT: 17032 case ISD::SETUGE: 17033 break; 17034 case ISD::SETULT: 17035 case ISD::SETULE: 17036 std::swap(TrueOpnd, FalseOpnd); 17037 break; 17038 } 17039 17040 SDValue CmpOpnd1 = Cond.getOperand(0); 17041 SDValue CmpOpnd2 = Cond.getOperand(1); 17042 17043 // SETCC CmpOpnd1 CmpOpnd2 cond 17044 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17045 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17046 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17047 TrueOpnd.getOperand(1) == CmpOpnd2 && 17048 FalseOpnd.getOperand(0) == CmpOpnd2 && 17049 FalseOpnd.getOperand(1) == CmpOpnd1) { 17050 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 17051 CmpOpnd1, CmpOpnd2, 17052 DAG.getTargetConstant(0, dl, MVT::i32)); 17053 } 17054 17055 return SDValue(); 17056 } 17057 17058 /// getAddrModeForFlags - Based on the set of address flags, select the most 17059 /// optimal instruction format to match by. 17060 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const { 17061 // This is not a node we should be handling here. 17062 if (Flags == PPC::MOF_None) 17063 return PPC::AM_None; 17064 // Unaligned D-Forms are tried first, followed by the aligned D-Forms. 17065 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm)) 17066 if ((Flags & FlagSet) == FlagSet) 17067 return PPC::AM_DForm; 17068 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm)) 17069 if ((Flags & FlagSet) == FlagSet) 17070 return PPC::AM_DSForm; 17071 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm)) 17072 if ((Flags & FlagSet) == FlagSet) 17073 return PPC::AM_DQForm; 17074 // If no other forms are selected, return an X-Form as it is the most 17075 // general addressing mode. 17076 return PPC::AM_XForm; 17077 } 17078 17079 /// Set alignment flags based on whether or not the Frame Index is aligned. 17080 /// Utilized when computing flags for address computation when selecting 17081 /// load and store instructions. 17082 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, 17083 SelectionDAG &DAG) { 17084 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR)); 17085 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N); 17086 if (!FI) 17087 return; 17088 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17089 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value(); 17090 // If this is (add $FI, $S16Imm), the alignment flags are already set 17091 // based on the immediate. We just need to clear the alignment flags 17092 // if the FI alignment is weaker. 17093 if ((FrameIndexAlign % 4) != 0) 17094 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4; 17095 if ((FrameIndexAlign % 16) != 0) 17096 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16; 17097 // If the address is a plain FrameIndex, set alignment flags based on 17098 // FI alignment. 17099 if (!IsAdd) { 17100 if ((FrameIndexAlign % 4) == 0) 17101 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17102 if ((FrameIndexAlign % 16) == 0) 17103 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17104 } 17105 } 17106 17107 /// Given a node, compute flags that are used for address computation when 17108 /// selecting load and store instructions. The flags computed are stored in 17109 /// FlagSet. This function takes into account whether the node is a constant, 17110 /// an ADD, OR, or a constant, and computes the address flags accordingly. 17111 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, 17112 SelectionDAG &DAG) { 17113 // Set the alignment flags for the node depending on if the node is 17114 // 4-byte or 16-byte aligned. 17115 auto SetAlignFlagsForImm = [&](uint64_t Imm) { 17116 if ((Imm & 0x3) == 0) 17117 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17118 if ((Imm & 0xf) == 0) 17119 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17120 }; 17121 17122 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 17123 // All 32-bit constants can be computed as LIS + Disp. 17124 const APInt &ConstImm = CN->getAPIntValue(); 17125 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants. 17126 FlagSet |= PPC::MOF_AddrIsSImm32; 17127 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17128 setAlignFlagsForFI(N, FlagSet, DAG); 17129 } 17130 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants. 17131 FlagSet |= PPC::MOF_RPlusSImm34; 17132 else // Let constant materialization handle large constants. 17133 FlagSet |= PPC::MOF_NotAddNorCst; 17134 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) { 17135 // This address can be represented as an addition of: 17136 // - Register + Imm16 (possibly a multiple of 4/16) 17137 // - Register + Imm34 17138 // - Register + PPCISD::Lo 17139 // - Register + Register 17140 // In any case, we won't have to match this as Base + Zero. 17141 SDValue RHS = N.getOperand(1); 17142 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) { 17143 const APInt &ConstImm = CN->getAPIntValue(); 17144 if (ConstImm.isSignedIntN(16)) { 17145 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates. 17146 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17147 setAlignFlagsForFI(N, FlagSet, DAG); 17148 } 17149 if (ConstImm.isSignedIntN(34)) 17150 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates. 17151 else 17152 FlagSet |= PPC::MOF_RPlusR; // Register. 17153 } else if (RHS.getOpcode() == PPCISD::Lo && 17154 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue()) 17155 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo. 17156 else 17157 FlagSet |= PPC::MOF_RPlusR; 17158 } else { // The address computation is not a constant or an addition. 17159 setAlignFlagsForFI(N, FlagSet, DAG); 17160 FlagSet |= PPC::MOF_NotAddNorCst; 17161 } 17162 } 17163 17164 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute 17165 /// the address flags of the load/store instruction that is to be matched. 17166 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N, 17167 SelectionDAG &DAG) const { 17168 unsigned FlagSet = PPC::MOF_None; 17169 17170 // Compute subtarget flags. 17171 if (!Subtarget.hasP9Vector()) 17172 FlagSet |= PPC::MOF_SubtargetBeforeP9; 17173 else { 17174 FlagSet |= PPC::MOF_SubtargetP9; 17175 if (Subtarget.hasPrefixInstrs()) 17176 FlagSet |= PPC::MOF_SubtargetP10; 17177 } 17178 if (Subtarget.hasSPE()) 17179 FlagSet |= PPC::MOF_SubtargetSPE; 17180 17181 // Mark this as something we don't want to handle here if it is atomic 17182 // or pre-increment instruction. 17183 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent)) 17184 if (LSB->isIndexed()) 17185 return PPC::MOF_None; 17186 17187 // Compute in-memory type flags. This is based on if there are scalars, 17188 // floats or vectors. 17189 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent); 17190 assert(MN && "Parent should be a MemSDNode!"); 17191 EVT MemVT = MN->getMemoryVT(); 17192 unsigned Size = MemVT.getSizeInBits(); 17193 if (MemVT.isScalarInteger()) { 17194 assert(Size <= 64 && "Not expecting scalar integers larger than 8 bytes!"); 17195 if (Size < 32) 17196 FlagSet |= PPC::MOF_SubWordInt; 17197 else if (Size == 32) 17198 FlagSet |= PPC::MOF_WordInt; 17199 else 17200 FlagSet |= PPC::MOF_DoubleWordInt; 17201 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors. 17202 if (Size == 128) 17203 FlagSet |= PPC::MOF_Vector; 17204 else if (Size == 256) 17205 FlagSet |= PPC::MOF_Vector256; 17206 else 17207 llvm_unreachable("Not expecting illegal vectors!"); 17208 } else { // Floating point type: can be scalar, f128 or vector types. 17209 if (Size == 32 || Size == 64) 17210 FlagSet |= PPC::MOF_ScalarFloat; 17211 else if (MemVT == MVT::f128 || MemVT.isVector()) 17212 FlagSet |= PPC::MOF_Vector; 17213 else 17214 llvm_unreachable("Not expecting illegal scalar floats!"); 17215 } 17216 17217 // Compute flags for address computation. 17218 computeFlagsForAddressComputation(N, FlagSet, DAG); 17219 17220 // Compute type extension flags. 17221 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) { 17222 switch (LN->getExtensionType()) { 17223 case ISD::SEXTLOAD: 17224 FlagSet |= PPC::MOF_SExt; 17225 break; 17226 case ISD::EXTLOAD: 17227 case ISD::ZEXTLOAD: 17228 FlagSet |= PPC::MOF_ZExt; 17229 break; 17230 case ISD::NON_EXTLOAD: 17231 FlagSet |= PPC::MOF_NoExt; 17232 break; 17233 } 17234 } else 17235 FlagSet |= PPC::MOF_NoExt; 17236 17237 // For integers, no extension is the same as zero extension. 17238 // We set the extension mode to zero extension so we don't have 17239 // to add separate entries in AddrModesMap for loads and stores. 17240 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) { 17241 FlagSet |= PPC::MOF_ZExt; 17242 FlagSet &= ~PPC::MOF_NoExt; 17243 } 17244 17245 // If we don't have prefixed instructions, 34-bit constants should be 17246 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms. 17247 bool IsNonP1034BitConst = 17248 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) & 17249 FlagSet) == PPC::MOF_RPlusSImm34; 17250 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR && 17251 IsNonP1034BitConst) 17252 FlagSet |= PPC::MOF_NotAddNorCst; 17253 17254 return FlagSet; 17255 } 17256 17257 /// SelectForceXFormMode - Given the specified address, force it to be 17258 /// represented as an indexed [r+r] operation (an XForm instruction). 17259 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp, 17260 SDValue &Base, 17261 SelectionDAG &DAG) const { 17262 17263 PPC::AddrMode Mode = PPC::AM_XForm; 17264 int16_t ForceXFormImm = 0; 17265 if (provablyDisjointOr(DAG, N) && 17266 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) { 17267 Disp = N.getOperand(0); 17268 Base = N.getOperand(1); 17269 return Mode; 17270 } 17271 17272 // If the address is the result of an add, we will utilize the fact that the 17273 // address calculation includes an implicit add. However, we can reduce 17274 // register pressure if we do not materialize a constant just for use as the 17275 // index register. We only get rid of the add if it is not an add of a 17276 // value and a 16-bit signed constant and both have a single use. 17277 if (N.getOpcode() == ISD::ADD && 17278 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) || 17279 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 17280 Disp = N.getOperand(0); 17281 Base = N.getOperand(1); 17282 return Mode; 17283 } 17284 17285 // Otherwise, use R0 as the base register. 17286 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17287 N.getValueType()); 17288 Base = N; 17289 17290 return Mode; 17291 } 17292 17293 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), 17294 /// compute the address flags of the node, get the optimal address mode based 17295 /// on the flags, and set the Base and Disp based on the address mode. 17296 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent, 17297 SDValue N, SDValue &Disp, 17298 SDValue &Base, 17299 SelectionDAG &DAG, 17300 MaybeAlign Align) const { 17301 SDLoc DL(Parent); 17302 17303 // Compute the address flags. 17304 unsigned Flags = computeMOFlags(Parent, N, DAG); 17305 17306 // Get the optimal address mode based on the Flags. 17307 PPC::AddrMode Mode = getAddrModeForFlags(Flags); 17308 17309 // Set Base and Disp accordingly depending on the address mode. 17310 switch (Mode) { 17311 case PPC::AM_DForm: 17312 case PPC::AM_DSForm: 17313 case PPC::AM_DQForm: { 17314 // This is a register plus a 16-bit immediate. The base will be the 17315 // register and the displacement will be the immediate unless it 17316 // isn't sufficiently aligned. 17317 if (Flags & PPC::MOF_RPlusSImm16) { 17318 SDValue Op0 = N.getOperand(0); 17319 SDValue Op1 = N.getOperand(1); 17320 int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue(); 17321 if (!Align || isAligned(*Align, Imm)) { 17322 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType()); 17323 Base = Op0; 17324 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) { 17325 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17326 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17327 } 17328 break; 17329 } 17330 } 17331 // This is a register plus the @lo relocation. The base is the register 17332 // and the displacement is the global address. 17333 else if (Flags & PPC::MOF_RPlusLo) { 17334 Disp = N.getOperand(1).getOperand(0); // The global address. 17335 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 17336 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 17337 Disp.getOpcode() == ISD::TargetConstantPool || 17338 Disp.getOpcode() == ISD::TargetJumpTable); 17339 Base = N.getOperand(0); 17340 break; 17341 } 17342 // This is a constant address at most 32 bits. The base will be 17343 // zero or load-immediate-shifted and the displacement will be 17344 // the low 16 bits of the address. 17345 else if (Flags & PPC::MOF_AddrIsSImm32) { 17346 auto *CN = cast<ConstantSDNode>(N); 17347 EVT CNType = CN->getValueType(0); 17348 uint64_t CNImm = CN->getZExtValue(); 17349 // If this address fits entirely in a 16-bit sext immediate field, codegen 17350 // this as "d, 0". 17351 int16_t Imm; 17352 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) { 17353 Disp = DAG.getTargetConstant(Imm, DL, CNType); 17354 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17355 CNType); 17356 break; 17357 } 17358 // Handle 32-bit sext immediate with LIS + Addr mode. 17359 if ((CNType == MVT::i32 || isInt<32>(CNImm)) && 17360 (!Align || isAligned(*Align, CNImm))) { 17361 int32_t Addr = (int32_t)CNImm; 17362 // Otherwise, break this down into LIS + Disp. 17363 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32); 17364 Base = 17365 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32); 17366 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8; 17367 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0); 17368 break; 17369 } 17370 } 17371 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable. 17372 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout())); 17373 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 17374 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17375 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17376 } else 17377 Base = N; 17378 break; 17379 } 17380 case PPC::AM_None: 17381 break; 17382 default: { // By default, X-Form is always available to be selected. 17383 // When a frame index is not aligned, we also match by XForm. 17384 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N); 17385 Base = FI ? N : N.getOperand(1); 17386 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17387 N.getValueType()) 17388 : N.getOperand(0); 17389 break; 17390 } 17391 } 17392 return Mode; 17393 } 17394 17395 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC, 17396 bool Return, 17397 bool IsVarArg) const { 17398 switch (CC) { 17399 case CallingConv::Cold: 17400 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS); 17401 default: 17402 return CC_PPC64_ELF_FIS; 17403 } 17404 } 17405