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 FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32 6959 ? PPCFunctionInfo::ShortFloatPoint 6960 : PPCFunctionInfo::LongFloatPoint); 6961 } 6962 6963 if (Flags.isByVal() && VA.isMemLoc()) { 6964 const unsigned Size = 6965 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 6966 PtrByteSize); 6967 const int FI = MF.getFrameInfo().CreateFixedObject( 6968 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 6969 /* IsAliased */ true); 6970 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6971 InVals.push_back(FIN); 6972 6973 continue; 6974 } 6975 6976 if (Flags.isByVal()) { 6977 assert(VA.isRegLoc() && "MemLocs should already be handled."); 6978 6979 const MCPhysReg ArgReg = VA.getLocReg(); 6980 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 6981 6982 if (Flags.getNonZeroByValAlign() > PtrByteSize) 6983 report_fatal_error("Over aligned byvals not supported yet."); 6984 6985 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 6986 const int FI = MF.getFrameInfo().CreateFixedObject( 6987 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 6988 /* IsAliased */ true); 6989 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6990 InVals.push_back(FIN); 6991 6992 // Add live ins for all the RegLocs for the same ByVal. 6993 const TargetRegisterClass *RegClass = 6994 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6995 6996 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 6997 unsigned Offset) { 6998 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 6999 // Since the callers side has left justified the aggregate in the 7000 // register, we can simply store the entire register into the stack 7001 // slot. 7002 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7003 // The store to the fixedstack object is needed becuase accessing a 7004 // field of the ByVal will use a gep and load. Ideally we will optimize 7005 // to extracting the value from the register directly, and elide the 7006 // stores when the arguments address is not taken, but that will need to 7007 // be future work. 7008 SDValue Store = DAG.getStore( 7009 CopyFrom.getValue(1), dl, CopyFrom, 7010 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7011 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7012 7013 MemOps.push_back(Store); 7014 }; 7015 7016 unsigned Offset = 0; 7017 HandleRegLoc(VA.getLocReg(), Offset); 7018 Offset += PtrByteSize; 7019 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7020 Offset += PtrByteSize) { 7021 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7022 "RegLocs should be for ByVal argument."); 7023 7024 const CCValAssign RL = ArgLocs[I++]; 7025 HandleRegLoc(RL.getLocReg(), Offset); 7026 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7027 } 7028 7029 if (Offset != StackSize) { 7030 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7031 "Expected MemLoc for remaining bytes."); 7032 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7033 // Consume the MemLoc.The InVal has already been emitted, so nothing 7034 // more needs to be done. 7035 ++I; 7036 } 7037 7038 continue; 7039 } 7040 7041 if (VA.isRegLoc() && !VA.needsCustom()) { 7042 MVT::SimpleValueType SVT = ValVT.SimpleTy; 7043 unsigned VReg = 7044 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7045 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7046 if (ValVT.isScalarInteger() && 7047 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7048 ArgValue = 7049 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7050 } 7051 InVals.push_back(ArgValue); 7052 continue; 7053 } 7054 if (VA.isMemLoc()) { 7055 HandleMemLoc(); 7056 continue; 7057 } 7058 } 7059 7060 // On AIX a minimum of 8 words is saved to the parameter save area. 7061 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7062 // Area that is at least reserved in the caller of this function. 7063 unsigned CallerReservedArea = 7064 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7065 7066 // Set the size that is at least reserved in caller of this function. Tail 7067 // call optimized function's reserved stack space needs to be aligned so 7068 // that taking the difference between two stack areas will result in an 7069 // aligned stack. 7070 CallerReservedArea = 7071 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7072 FuncInfo->setMinReservedArea(CallerReservedArea); 7073 7074 if (isVarArg) { 7075 FuncInfo->setVarArgsFrameIndex( 7076 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7077 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7078 7079 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7080 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7081 7082 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7083 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7084 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7085 7086 // The fixed integer arguments of a variadic function are stored to the 7087 // VarArgsFrameIndex on the stack so that they may be loaded by 7088 // dereferencing the result of va_next. 7089 for (unsigned GPRIndex = 7090 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7091 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7092 7093 const unsigned VReg = 7094 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7095 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7096 7097 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7098 SDValue Store = 7099 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7100 MemOps.push_back(Store); 7101 // Increment the address for the next argument to store. 7102 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7103 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7104 } 7105 } 7106 7107 if (!MemOps.empty()) 7108 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7109 7110 return Chain; 7111 } 7112 7113 SDValue PPCTargetLowering::LowerCall_AIX( 7114 SDValue Chain, SDValue Callee, CallFlags CFlags, 7115 const SmallVectorImpl<ISD::OutputArg> &Outs, 7116 const SmallVectorImpl<SDValue> &OutVals, 7117 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7118 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7119 const CallBase *CB) const { 7120 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7121 // AIX ABI stack frame layout. 7122 7123 assert((CFlags.CallConv == CallingConv::C || 7124 CFlags.CallConv == CallingConv::Cold || 7125 CFlags.CallConv == CallingConv::Fast) && 7126 "Unexpected calling convention!"); 7127 7128 if (CFlags.IsPatchPoint) 7129 report_fatal_error("This call type is unimplemented on AIX."); 7130 7131 const PPCSubtarget& Subtarget = 7132 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7133 7134 MachineFunction &MF = DAG.getMachineFunction(); 7135 SmallVector<CCValAssign, 16> ArgLocs; 7136 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7137 *DAG.getContext()); 7138 7139 // Reserve space for the linkage save area (LSA) on the stack. 7140 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7141 // [SP][CR][LR][2 x reserved][TOC]. 7142 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7143 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7144 const bool IsPPC64 = Subtarget.isPPC64(); 7145 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7146 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7147 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7148 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7149 7150 // The prolog code of the callee may store up to 8 GPR argument registers to 7151 // the stack, allowing va_start to index over them in memory if the callee 7152 // is variadic. 7153 // Because we cannot tell if this is needed on the caller side, we have to 7154 // conservatively assume that it is needed. As such, make sure we have at 7155 // least enough stack space for the caller to store the 8 GPRs. 7156 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7157 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7158 CCInfo.getNextStackOffset()); 7159 7160 // Adjust the stack pointer for the new arguments... 7161 // These operations are automatically eliminated by the prolog/epilog pass. 7162 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7163 SDValue CallSeqStart = Chain; 7164 7165 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7166 SmallVector<SDValue, 8> MemOpChains; 7167 7168 // Set up a copy of the stack pointer for loading and storing any 7169 // arguments that may not fit in the registers available for argument 7170 // passing. 7171 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7172 : DAG.getRegister(PPC::R1, MVT::i32); 7173 7174 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7175 const unsigned ValNo = ArgLocs[I].getValNo(); 7176 SDValue Arg = OutVals[ValNo]; 7177 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7178 7179 if (Flags.isByVal()) { 7180 const unsigned ByValSize = Flags.getByValSize(); 7181 7182 // Nothing to do for zero-sized ByVals on the caller side. 7183 if (!ByValSize) { 7184 ++I; 7185 continue; 7186 } 7187 7188 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7189 return DAG.getExtLoad( 7190 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7191 (LoadOffset != 0) 7192 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7193 : Arg, 7194 MachinePointerInfo(), VT); 7195 }; 7196 7197 unsigned LoadOffset = 0; 7198 7199 // Initialize registers, which are fully occupied by the by-val argument. 7200 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7201 SDValue Load = GetLoad(PtrVT, LoadOffset); 7202 MemOpChains.push_back(Load.getValue(1)); 7203 LoadOffset += PtrByteSize; 7204 const CCValAssign &ByValVA = ArgLocs[I++]; 7205 assert(ByValVA.getValNo() == ValNo && 7206 "Unexpected location for pass-by-value argument."); 7207 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7208 } 7209 7210 if (LoadOffset == ByValSize) 7211 continue; 7212 7213 // There must be one more loc to handle the remainder. 7214 assert(ArgLocs[I].getValNo() == ValNo && 7215 "Expected additional location for by-value argument."); 7216 7217 if (ArgLocs[I].isMemLoc()) { 7218 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7219 const CCValAssign &ByValVA = ArgLocs[I++]; 7220 ISD::ArgFlagsTy MemcpyFlags = Flags; 7221 // Only memcpy the bytes that don't pass in register. 7222 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7223 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7224 (LoadOffset != 0) 7225 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7226 : Arg, 7227 DAG.getObjectPtrOffset(dl, StackPtr, 7228 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7229 CallSeqStart, MemcpyFlags, DAG, dl); 7230 continue; 7231 } 7232 7233 // Initialize the final register residue. 7234 // Any residue that occupies the final by-val arg register must be 7235 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7236 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7237 // 2 and 1 byte loads. 7238 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7239 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7240 "Unexpected register residue for by-value argument."); 7241 SDValue ResidueVal; 7242 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7243 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7244 const MVT VT = 7245 N == 1 ? MVT::i8 7246 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7247 SDValue Load = GetLoad(VT, LoadOffset); 7248 MemOpChains.push_back(Load.getValue(1)); 7249 LoadOffset += N; 7250 Bytes += N; 7251 7252 // By-val arguments are passed left-justfied in register. 7253 // Every load here needs to be shifted, otherwise a full register load 7254 // should have been used. 7255 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7256 "Unexpected load emitted during handling of pass-by-value " 7257 "argument."); 7258 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7259 EVT ShiftAmountTy = 7260 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7261 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7262 SDValue ShiftedLoad = 7263 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7264 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7265 ShiftedLoad) 7266 : ShiftedLoad; 7267 } 7268 7269 const CCValAssign &ByValVA = ArgLocs[I++]; 7270 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7271 continue; 7272 } 7273 7274 CCValAssign &VA = ArgLocs[I++]; 7275 const MVT LocVT = VA.getLocVT(); 7276 const MVT ValVT = VA.getValVT(); 7277 7278 switch (VA.getLocInfo()) { 7279 default: 7280 report_fatal_error("Unexpected argument extension type."); 7281 case CCValAssign::Full: 7282 break; 7283 case CCValAssign::ZExt: 7284 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7285 break; 7286 case CCValAssign::SExt: 7287 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7288 break; 7289 } 7290 7291 if (VA.isRegLoc() && !VA.needsCustom()) { 7292 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7293 continue; 7294 } 7295 7296 // Vector arguments passed to VarArg functions need custom handling when 7297 // they are passed (at least partially) in GPRs. 7298 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7299 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7300 // Store value to its stack slot. 7301 SDValue PtrOff = 7302 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7303 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7304 SDValue Store = 7305 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7306 MemOpChains.push_back(Store); 7307 const unsigned OriginalValNo = VA.getValNo(); 7308 // Then load the GPRs from the stack 7309 unsigned LoadOffset = 0; 7310 auto HandleCustomVecRegLoc = [&]() { 7311 assert(I != E && "Unexpected end of CCvalAssigns."); 7312 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7313 "Expected custom RegLoc."); 7314 CCValAssign RegVA = ArgLocs[I++]; 7315 assert(RegVA.getValNo() == OriginalValNo && 7316 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7317 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7318 DAG.getConstant(LoadOffset, dl, PtrVT)); 7319 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7320 MemOpChains.push_back(Load.getValue(1)); 7321 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7322 LoadOffset += PtrByteSize; 7323 }; 7324 7325 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7326 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7327 // R10. 7328 HandleCustomVecRegLoc(); 7329 HandleCustomVecRegLoc(); 7330 7331 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7332 ArgLocs[I].getValNo() == OriginalValNo) { 7333 assert(!IsPPC64 && 7334 "Only 2 custom RegLocs expected for 64-bit codegen."); 7335 HandleCustomVecRegLoc(); 7336 HandleCustomVecRegLoc(); 7337 } 7338 7339 continue; 7340 } 7341 7342 if (VA.isMemLoc()) { 7343 SDValue PtrOff = 7344 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7345 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7346 MemOpChains.push_back( 7347 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7348 7349 continue; 7350 } 7351 7352 if (!ValVT.isFloatingPoint()) 7353 report_fatal_error( 7354 "Unexpected register handling for calling convention."); 7355 7356 // Custom handling is used for GPR initializations for vararg float 7357 // arguments. 7358 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7359 LocVT.isInteger() && 7360 "Custom register handling only expected for VarArg."); 7361 7362 SDValue ArgAsInt = 7363 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7364 7365 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7366 // f32 in 32-bit GPR 7367 // f64 in 64-bit GPR 7368 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7369 else if (Arg.getValueType().getFixedSizeInBits() < 7370 LocVT.getFixedSizeInBits()) 7371 // f32 in 64-bit GPR. 7372 RegsToPass.push_back(std::make_pair( 7373 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7374 else { 7375 // f64 in two 32-bit GPRs 7376 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7377 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7378 "Unexpected custom register for argument!"); 7379 CCValAssign &GPR1 = VA; 7380 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7381 DAG.getConstant(32, dl, MVT::i8)); 7382 RegsToPass.push_back(std::make_pair( 7383 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7384 7385 if (I != E) { 7386 // If only 1 GPR was available, there will only be one custom GPR and 7387 // the argument will also pass in memory. 7388 CCValAssign &PeekArg = ArgLocs[I]; 7389 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7390 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7391 CCValAssign &GPR2 = ArgLocs[I++]; 7392 RegsToPass.push_back(std::make_pair( 7393 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7394 } 7395 } 7396 } 7397 } 7398 7399 if (!MemOpChains.empty()) 7400 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7401 7402 // For indirect calls, we need to save the TOC base to the stack for 7403 // restoration after the call. 7404 if (CFlags.IsIndirect) { 7405 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7406 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7407 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7408 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7409 const unsigned TOCSaveOffset = 7410 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7411 7412 setUsesTOCBasePtr(DAG); 7413 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7414 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7415 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7416 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7417 Chain = DAG.getStore( 7418 Val.getValue(1), dl, Val, AddPtr, 7419 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7420 } 7421 7422 // Build a sequence of copy-to-reg nodes chained together with token chain 7423 // and flag operands which copy the outgoing args into the appropriate regs. 7424 SDValue InFlag; 7425 for (auto Reg : RegsToPass) { 7426 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7427 InFlag = Chain.getValue(1); 7428 } 7429 7430 const int SPDiff = 0; 7431 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7432 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7433 } 7434 7435 bool 7436 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7437 MachineFunction &MF, bool isVarArg, 7438 const SmallVectorImpl<ISD::OutputArg> &Outs, 7439 LLVMContext &Context) const { 7440 SmallVector<CCValAssign, 16> RVLocs; 7441 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7442 return CCInfo.CheckReturn( 7443 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7444 ? RetCC_PPC_Cold 7445 : RetCC_PPC); 7446 } 7447 7448 SDValue 7449 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7450 bool isVarArg, 7451 const SmallVectorImpl<ISD::OutputArg> &Outs, 7452 const SmallVectorImpl<SDValue> &OutVals, 7453 const SDLoc &dl, SelectionDAG &DAG) const { 7454 SmallVector<CCValAssign, 16> RVLocs; 7455 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7456 *DAG.getContext()); 7457 CCInfo.AnalyzeReturn(Outs, 7458 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7459 ? RetCC_PPC_Cold 7460 : RetCC_PPC); 7461 7462 SDValue Flag; 7463 SmallVector<SDValue, 4> RetOps(1, Chain); 7464 7465 // Copy the result values into the output registers. 7466 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7467 CCValAssign &VA = RVLocs[i]; 7468 assert(VA.isRegLoc() && "Can only return in registers!"); 7469 7470 SDValue Arg = OutVals[RealResIdx]; 7471 7472 switch (VA.getLocInfo()) { 7473 default: llvm_unreachable("Unknown loc info!"); 7474 case CCValAssign::Full: break; 7475 case CCValAssign::AExt: 7476 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7477 break; 7478 case CCValAssign::ZExt: 7479 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7480 break; 7481 case CCValAssign::SExt: 7482 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7483 break; 7484 } 7485 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7486 bool isLittleEndian = Subtarget.isLittleEndian(); 7487 // Legalize ret f64 -> ret 2 x i32. 7488 SDValue SVal = 7489 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7490 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7491 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7492 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7493 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7494 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7495 Flag = Chain.getValue(1); 7496 VA = RVLocs[++i]; // skip ahead to next loc 7497 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7498 } else 7499 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7500 Flag = Chain.getValue(1); 7501 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7502 } 7503 7504 RetOps[0] = Chain; // Update chain. 7505 7506 // Add the flag if we have it. 7507 if (Flag.getNode()) 7508 RetOps.push_back(Flag); 7509 7510 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7511 } 7512 7513 SDValue 7514 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7515 SelectionDAG &DAG) const { 7516 SDLoc dl(Op); 7517 7518 // Get the correct type for integers. 7519 EVT IntVT = Op.getValueType(); 7520 7521 // Get the inputs. 7522 SDValue Chain = Op.getOperand(0); 7523 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7524 // Build a DYNAREAOFFSET node. 7525 SDValue Ops[2] = {Chain, FPSIdx}; 7526 SDVTList VTs = DAG.getVTList(IntVT); 7527 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7528 } 7529 7530 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7531 SelectionDAG &DAG) const { 7532 // When we pop the dynamic allocation we need to restore the SP link. 7533 SDLoc dl(Op); 7534 7535 // Get the correct type for pointers. 7536 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7537 7538 // Construct the stack pointer operand. 7539 bool isPPC64 = Subtarget.isPPC64(); 7540 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7541 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7542 7543 // Get the operands for the STACKRESTORE. 7544 SDValue Chain = Op.getOperand(0); 7545 SDValue SaveSP = Op.getOperand(1); 7546 7547 // Load the old link SP. 7548 SDValue LoadLinkSP = 7549 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7550 7551 // Restore the stack pointer. 7552 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7553 7554 // Store the old link SP. 7555 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7556 } 7557 7558 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7559 MachineFunction &MF = DAG.getMachineFunction(); 7560 bool isPPC64 = Subtarget.isPPC64(); 7561 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7562 7563 // Get current frame pointer save index. The users of this index will be 7564 // primarily DYNALLOC instructions. 7565 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7566 int RASI = FI->getReturnAddrSaveIndex(); 7567 7568 // If the frame pointer save index hasn't been defined yet. 7569 if (!RASI) { 7570 // Find out what the fix offset of the frame pointer save area. 7571 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7572 // Allocate the frame index for frame pointer save area. 7573 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7574 // Save the result. 7575 FI->setReturnAddrSaveIndex(RASI); 7576 } 7577 return DAG.getFrameIndex(RASI, PtrVT); 7578 } 7579 7580 SDValue 7581 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7582 MachineFunction &MF = DAG.getMachineFunction(); 7583 bool isPPC64 = Subtarget.isPPC64(); 7584 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7585 7586 // Get current frame pointer save index. The users of this index will be 7587 // primarily DYNALLOC instructions. 7588 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7589 int FPSI = FI->getFramePointerSaveIndex(); 7590 7591 // If the frame pointer save index hasn't been defined yet. 7592 if (!FPSI) { 7593 // Find out what the fix offset of the frame pointer save area. 7594 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7595 // Allocate the frame index for frame pointer save area. 7596 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7597 // Save the result. 7598 FI->setFramePointerSaveIndex(FPSI); 7599 } 7600 return DAG.getFrameIndex(FPSI, PtrVT); 7601 } 7602 7603 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7604 SelectionDAG &DAG) const { 7605 MachineFunction &MF = DAG.getMachineFunction(); 7606 // Get the inputs. 7607 SDValue Chain = Op.getOperand(0); 7608 SDValue Size = Op.getOperand(1); 7609 SDLoc dl(Op); 7610 7611 // Get the correct type for pointers. 7612 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7613 // Negate the size. 7614 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7615 DAG.getConstant(0, dl, PtrVT), Size); 7616 // Construct a node for the frame pointer save index. 7617 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7618 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7619 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7620 if (hasInlineStackProbe(MF)) 7621 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7622 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7623 } 7624 7625 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7626 SelectionDAG &DAG) const { 7627 MachineFunction &MF = DAG.getMachineFunction(); 7628 7629 bool isPPC64 = Subtarget.isPPC64(); 7630 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7631 7632 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7633 return DAG.getFrameIndex(FI, PtrVT); 7634 } 7635 7636 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7637 SelectionDAG &DAG) const { 7638 SDLoc DL(Op); 7639 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7640 DAG.getVTList(MVT::i32, MVT::Other), 7641 Op.getOperand(0), Op.getOperand(1)); 7642 } 7643 7644 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7645 SelectionDAG &DAG) const { 7646 SDLoc DL(Op); 7647 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7648 Op.getOperand(0), Op.getOperand(1)); 7649 } 7650 7651 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7652 if (Op.getValueType().isVector()) 7653 return LowerVectorLoad(Op, DAG); 7654 7655 assert(Op.getValueType() == MVT::i1 && 7656 "Custom lowering only for i1 loads"); 7657 7658 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7659 7660 SDLoc dl(Op); 7661 LoadSDNode *LD = cast<LoadSDNode>(Op); 7662 7663 SDValue Chain = LD->getChain(); 7664 SDValue BasePtr = LD->getBasePtr(); 7665 MachineMemOperand *MMO = LD->getMemOperand(); 7666 7667 SDValue NewLD = 7668 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7669 BasePtr, MVT::i8, MMO); 7670 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7671 7672 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7673 return DAG.getMergeValues(Ops, dl); 7674 } 7675 7676 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7677 if (Op.getOperand(1).getValueType().isVector()) 7678 return LowerVectorStore(Op, DAG); 7679 7680 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7681 "Custom lowering only for i1 stores"); 7682 7683 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7684 7685 SDLoc dl(Op); 7686 StoreSDNode *ST = cast<StoreSDNode>(Op); 7687 7688 SDValue Chain = ST->getChain(); 7689 SDValue BasePtr = ST->getBasePtr(); 7690 SDValue Value = ST->getValue(); 7691 MachineMemOperand *MMO = ST->getMemOperand(); 7692 7693 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7694 Value); 7695 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7696 } 7697 7698 // FIXME: Remove this once the ANDI glue bug is fixed: 7699 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7700 assert(Op.getValueType() == MVT::i1 && 7701 "Custom lowering only for i1 results"); 7702 7703 SDLoc DL(Op); 7704 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7705 } 7706 7707 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7708 SelectionDAG &DAG) const { 7709 7710 // Implements a vector truncate that fits in a vector register as a shuffle. 7711 // We want to legalize vector truncates down to where the source fits in 7712 // a vector register (and target is therefore smaller than vector register 7713 // size). At that point legalization will try to custom lower the sub-legal 7714 // result and get here - where we can contain the truncate as a single target 7715 // operation. 7716 7717 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7718 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7719 // 7720 // We will implement it for big-endian ordering as this (where x denotes 7721 // undefined): 7722 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7723 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7724 // 7725 // The same operation in little-endian ordering will be: 7726 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7727 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7728 7729 EVT TrgVT = Op.getValueType(); 7730 assert(TrgVT.isVector() && "Vector type expected."); 7731 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7732 EVT EltVT = TrgVT.getVectorElementType(); 7733 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7734 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7735 !isPowerOf2_32(EltVT.getSizeInBits())) 7736 return SDValue(); 7737 7738 SDValue N1 = Op.getOperand(0); 7739 EVT SrcVT = N1.getValueType(); 7740 unsigned SrcSize = SrcVT.getSizeInBits(); 7741 if (SrcSize > 256 || 7742 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7743 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7744 return SDValue(); 7745 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7746 return SDValue(); 7747 7748 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7749 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7750 7751 SDLoc DL(Op); 7752 SDValue Op1, Op2; 7753 if (SrcSize == 256) { 7754 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7755 EVT SplitVT = 7756 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7757 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7758 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7759 DAG.getConstant(0, DL, VecIdxTy)); 7760 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7761 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7762 } 7763 else { 7764 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7765 Op2 = DAG.getUNDEF(WideVT); 7766 } 7767 7768 // First list the elements we want to keep. 7769 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7770 SmallVector<int, 16> ShuffV; 7771 if (Subtarget.isLittleEndian()) 7772 for (unsigned i = 0; i < TrgNumElts; ++i) 7773 ShuffV.push_back(i * SizeMult); 7774 else 7775 for (unsigned i = 1; i <= TrgNumElts; ++i) 7776 ShuffV.push_back(i * SizeMult - 1); 7777 7778 // Populate the remaining elements with undefs. 7779 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7780 // ShuffV.push_back(i + WideNumElts); 7781 ShuffV.push_back(WideNumElts + 1); 7782 7783 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7784 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7785 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7786 } 7787 7788 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7789 /// possible. 7790 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7791 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7792 EVT ResVT = Op.getValueType(); 7793 EVT CmpVT = Op.getOperand(0).getValueType(); 7794 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7795 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7796 SDLoc dl(Op); 7797 7798 // Without power9-vector, we don't have native instruction for f128 comparison. 7799 // Following transformation to libcall is needed for setcc: 7800 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7801 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7802 SDValue Z = DAG.getSetCC( 7803 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7804 LHS, RHS, CC); 7805 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7806 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7807 } 7808 7809 // Not FP, or using SPE? Not a fsel. 7810 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7811 Subtarget.hasSPE()) 7812 return Op; 7813 7814 SDNodeFlags Flags = Op.getNode()->getFlags(); 7815 7816 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7817 // presence of infinities. 7818 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7819 switch (CC) { 7820 default: 7821 break; 7822 case ISD::SETOGT: 7823 case ISD::SETGT: 7824 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7825 case ISD::SETOLT: 7826 case ISD::SETLT: 7827 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7828 } 7829 } 7830 7831 // We might be able to do better than this under some circumstances, but in 7832 // general, fsel-based lowering of select is a finite-math-only optimization. 7833 // For more information, see section F.3 of the 2.06 ISA specification. 7834 // With ISA 3.0 7835 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7836 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7837 return Op; 7838 7839 // If the RHS of the comparison is a 0.0, we don't need to do the 7840 // subtraction at all. 7841 SDValue Sel1; 7842 if (isFloatingPointZero(RHS)) 7843 switch (CC) { 7844 default: break; // SETUO etc aren't handled by fsel. 7845 case ISD::SETNE: 7846 std::swap(TV, FV); 7847 LLVM_FALLTHROUGH; 7848 case ISD::SETEQ: 7849 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7850 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7851 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7852 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7853 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7854 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7855 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7856 case ISD::SETULT: 7857 case ISD::SETLT: 7858 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7859 LLVM_FALLTHROUGH; 7860 case ISD::SETOGE: 7861 case ISD::SETGE: 7862 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7863 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7864 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7865 case ISD::SETUGT: 7866 case ISD::SETGT: 7867 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7868 LLVM_FALLTHROUGH; 7869 case ISD::SETOLE: 7870 case ISD::SETLE: 7871 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7872 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7873 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7874 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7875 } 7876 7877 SDValue Cmp; 7878 switch (CC) { 7879 default: break; // SETUO etc aren't handled by fsel. 7880 case ISD::SETNE: 7881 std::swap(TV, FV); 7882 LLVM_FALLTHROUGH; 7883 case ISD::SETEQ: 7884 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7885 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7886 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7887 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7888 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7889 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7890 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7891 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7892 case ISD::SETULT: 7893 case ISD::SETLT: 7894 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7895 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7896 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7897 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7898 case ISD::SETOGE: 7899 case ISD::SETGE: 7900 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7901 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7902 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7903 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7904 case ISD::SETUGT: 7905 case ISD::SETGT: 7906 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7907 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7908 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7909 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7910 case ISD::SETOLE: 7911 case ISD::SETLE: 7912 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7913 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7914 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7915 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7916 } 7917 return Op; 7918 } 7919 7920 static unsigned getPPCStrictOpcode(unsigned Opc) { 7921 switch (Opc) { 7922 default: 7923 llvm_unreachable("No strict version of this opcode!"); 7924 case PPCISD::FCTIDZ: 7925 return PPCISD::STRICT_FCTIDZ; 7926 case PPCISD::FCTIWZ: 7927 return PPCISD::STRICT_FCTIWZ; 7928 case PPCISD::FCTIDUZ: 7929 return PPCISD::STRICT_FCTIDUZ; 7930 case PPCISD::FCTIWUZ: 7931 return PPCISD::STRICT_FCTIWUZ; 7932 case PPCISD::FCFID: 7933 return PPCISD::STRICT_FCFID; 7934 case PPCISD::FCFIDU: 7935 return PPCISD::STRICT_FCFIDU; 7936 case PPCISD::FCFIDS: 7937 return PPCISD::STRICT_FCFIDS; 7938 case PPCISD::FCFIDUS: 7939 return PPCISD::STRICT_FCFIDUS; 7940 } 7941 } 7942 7943 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 7944 const PPCSubtarget &Subtarget) { 7945 SDLoc dl(Op); 7946 bool IsStrict = Op->isStrictFPOpcode(); 7947 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7948 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7949 7950 // TODO: Any other flags to propagate? 7951 SDNodeFlags Flags; 7952 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 7953 7954 // For strict nodes, source is the second operand. 7955 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7956 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 7957 assert(Src.getValueType().isFloatingPoint()); 7958 if (Src.getValueType() == MVT::f32) { 7959 if (IsStrict) { 7960 Src = 7961 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 7962 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 7963 Chain = Src.getValue(1); 7964 } else 7965 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7966 } 7967 SDValue Conv; 7968 unsigned Opc = ISD::DELETED_NODE; 7969 switch (Op.getSimpleValueType().SimpleTy) { 7970 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7971 case MVT::i32: 7972 Opc = IsSigned ? PPCISD::FCTIWZ 7973 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 7974 break; 7975 case MVT::i64: 7976 assert((IsSigned || Subtarget.hasFPCVT()) && 7977 "i64 FP_TO_UINT is supported only with FPCVT"); 7978 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 7979 } 7980 if (IsStrict) { 7981 Opc = getPPCStrictOpcode(Opc); 7982 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 7983 {Chain, Src}, Flags); 7984 } else { 7985 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 7986 } 7987 return Conv; 7988 } 7989 7990 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7991 SelectionDAG &DAG, 7992 const SDLoc &dl) const { 7993 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 7994 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7995 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7996 bool IsStrict = Op->isStrictFPOpcode(); 7997 7998 // Convert the FP value to an int value through memory. 7999 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8000 (IsSigned || Subtarget.hasFPCVT()); 8001 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8002 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8003 MachinePointerInfo MPI = 8004 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8005 8006 // Emit a store to the stack slot. 8007 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8008 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8009 if (i32Stack) { 8010 MachineFunction &MF = DAG.getMachineFunction(); 8011 Alignment = Align(4); 8012 MachineMemOperand *MMO = 8013 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8014 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8015 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8016 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8017 } else 8018 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8019 8020 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8021 // add in a bias on big endian. 8022 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8023 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8024 DAG.getConstant(4, dl, FIPtr.getValueType())); 8025 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8026 } 8027 8028 RLI.Chain = Chain; 8029 RLI.Ptr = FIPtr; 8030 RLI.MPI = MPI; 8031 RLI.Alignment = Alignment; 8032 } 8033 8034 /// Custom lowers floating point to integer conversions to use 8035 /// the direct move instructions available in ISA 2.07 to avoid the 8036 /// need for load/store combinations. 8037 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8038 SelectionDAG &DAG, 8039 const SDLoc &dl) const { 8040 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8041 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8042 if (Op->isStrictFPOpcode()) 8043 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8044 else 8045 return Mov; 8046 } 8047 8048 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8049 const SDLoc &dl) const { 8050 bool IsStrict = Op->isStrictFPOpcode(); 8051 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8052 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8053 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8054 EVT SrcVT = Src.getValueType(); 8055 EVT DstVT = Op.getValueType(); 8056 8057 // FP to INT conversions are legal for f128. 8058 if (SrcVT == MVT::f128) 8059 return Subtarget.hasP9Vector() ? Op : SDValue(); 8060 8061 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8062 // PPC (the libcall is not available). 8063 if (SrcVT == MVT::ppcf128) { 8064 if (DstVT == MVT::i32) { 8065 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8066 // set other fast-math flags to FP operations in both strict and 8067 // non-strict cases. (FP_TO_SINT, FSUB) 8068 SDNodeFlags Flags; 8069 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8070 8071 if (IsSigned) { 8072 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8073 DAG.getIntPtrConstant(0, dl)); 8074 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8075 DAG.getIntPtrConstant(1, dl)); 8076 8077 // Add the two halves of the long double in round-to-zero mode, and use 8078 // a smaller FP_TO_SINT. 8079 if (IsStrict) { 8080 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8081 DAG.getVTList(MVT::f64, MVT::Other), 8082 {Op.getOperand(0), Lo, Hi}, Flags); 8083 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8084 DAG.getVTList(MVT::i32, MVT::Other), 8085 {Res.getValue(1), Res}, Flags); 8086 } else { 8087 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8088 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8089 } 8090 } else { 8091 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8092 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8093 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8094 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8095 if (IsStrict) { 8096 // Sel = Src < 0x80000000 8097 // FltOfs = select Sel, 0.0, 0x80000000 8098 // IntOfs = select Sel, 0, 0x80000000 8099 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8100 SDValue Chain = Op.getOperand(0); 8101 EVT SetCCVT = 8102 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8103 EVT DstSetCCVT = 8104 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8105 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8106 Chain, true); 8107 Chain = Sel.getValue(1); 8108 8109 SDValue FltOfs = DAG.getSelect( 8110 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8111 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8112 8113 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8114 DAG.getVTList(SrcVT, MVT::Other), 8115 {Chain, Src, FltOfs}, Flags); 8116 Chain = Val.getValue(1); 8117 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8118 DAG.getVTList(DstVT, MVT::Other), 8119 {Chain, Val}, Flags); 8120 Chain = SInt.getValue(1); 8121 SDValue IntOfs = DAG.getSelect( 8122 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8123 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8124 return DAG.getMergeValues({Result, Chain}, dl); 8125 } else { 8126 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8127 // FIXME: generated code sucks. 8128 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8129 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8130 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8131 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8132 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8133 } 8134 } 8135 } 8136 8137 return SDValue(); 8138 } 8139 8140 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8141 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8142 8143 ReuseLoadInfo RLI; 8144 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8145 8146 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8147 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8148 } 8149 8150 // We're trying to insert a regular store, S, and then a load, L. If the 8151 // incoming value, O, is a load, we might just be able to have our load use the 8152 // address used by O. However, we don't know if anything else will store to 8153 // that address before we can load from it. To prevent this situation, we need 8154 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8155 // the same chain operand as O, we create a token factor from the chain results 8156 // of O and L, and we replace all uses of O's chain result with that token 8157 // factor (see spliceIntoChain below for this last part). 8158 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8159 ReuseLoadInfo &RLI, 8160 SelectionDAG &DAG, 8161 ISD::LoadExtType ET) const { 8162 // Conservatively skip reusing for constrained FP nodes. 8163 if (Op->isStrictFPOpcode()) 8164 return false; 8165 8166 SDLoc dl(Op); 8167 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8168 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8169 if (ET == ISD::NON_EXTLOAD && 8170 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8171 isOperationLegalOrCustom(Op.getOpcode(), 8172 Op.getOperand(0).getValueType())) { 8173 8174 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8175 return true; 8176 } 8177 8178 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8179 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8180 LD->isNonTemporal()) 8181 return false; 8182 if (LD->getMemoryVT() != MemVT) 8183 return false; 8184 8185 // If the result of the load is an illegal type, then we can't build a 8186 // valid chain for reuse since the legalised loads and token factor node that 8187 // ties the legalised loads together uses a different output chain then the 8188 // illegal load. 8189 if (!isTypeLegal(LD->getValueType(0))) 8190 return false; 8191 8192 RLI.Ptr = LD->getBasePtr(); 8193 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8194 assert(LD->getAddressingMode() == ISD::PRE_INC && 8195 "Non-pre-inc AM on PPC?"); 8196 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8197 LD->getOffset()); 8198 } 8199 8200 RLI.Chain = LD->getChain(); 8201 RLI.MPI = LD->getPointerInfo(); 8202 RLI.IsDereferenceable = LD->isDereferenceable(); 8203 RLI.IsInvariant = LD->isInvariant(); 8204 RLI.Alignment = LD->getAlign(); 8205 RLI.AAInfo = LD->getAAInfo(); 8206 RLI.Ranges = LD->getRanges(); 8207 8208 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8209 return true; 8210 } 8211 8212 // Given the head of the old chain, ResChain, insert a token factor containing 8213 // it and NewResChain, and make users of ResChain now be users of that token 8214 // factor. 8215 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8216 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8217 SDValue NewResChain, 8218 SelectionDAG &DAG) const { 8219 if (!ResChain) 8220 return; 8221 8222 SDLoc dl(NewResChain); 8223 8224 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8225 NewResChain, DAG.getUNDEF(MVT::Other)); 8226 assert(TF.getNode() != NewResChain.getNode() && 8227 "A new TF really is required here"); 8228 8229 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8230 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8231 } 8232 8233 /// Analyze profitability of direct move 8234 /// prefer float load to int load plus direct move 8235 /// when there is no integer use of int load 8236 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8237 SDNode *Origin = Op.getOperand(0).getNode(); 8238 if (Origin->getOpcode() != ISD::LOAD) 8239 return true; 8240 8241 // If there is no LXSIBZX/LXSIHZX, like Power8, 8242 // prefer direct move if the memory size is 1 or 2 bytes. 8243 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8244 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8245 return true; 8246 8247 for (SDNode::use_iterator UI = Origin->use_begin(), 8248 UE = Origin->use_end(); 8249 UI != UE; ++UI) { 8250 8251 // Only look at the users of the loaded value. 8252 if (UI.getUse().get().getResNo() != 0) 8253 continue; 8254 8255 if (UI->getOpcode() != ISD::SINT_TO_FP && 8256 UI->getOpcode() != ISD::UINT_TO_FP && 8257 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8258 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8259 return true; 8260 } 8261 8262 return false; 8263 } 8264 8265 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8266 const PPCSubtarget &Subtarget, 8267 SDValue Chain = SDValue()) { 8268 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8269 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8270 SDLoc dl(Op); 8271 8272 // TODO: Any other flags to propagate? 8273 SDNodeFlags Flags; 8274 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8275 8276 // If we have FCFIDS, then use it when converting to single-precision. 8277 // Otherwise, convert to double-precision and then round. 8278 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8279 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8280 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8281 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8282 if (Op->isStrictFPOpcode()) { 8283 if (!Chain) 8284 Chain = Op.getOperand(0); 8285 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8286 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8287 } else 8288 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8289 } 8290 8291 /// Custom lowers integer to floating point conversions to use 8292 /// the direct move instructions available in ISA 2.07 to avoid the 8293 /// need for load/store combinations. 8294 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8295 SelectionDAG &DAG, 8296 const SDLoc &dl) const { 8297 assert((Op.getValueType() == MVT::f32 || 8298 Op.getValueType() == MVT::f64) && 8299 "Invalid floating point type as target of conversion"); 8300 assert(Subtarget.hasFPCVT() && 8301 "Int to FP conversions with direct moves require FPCVT"); 8302 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8303 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8304 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8305 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8306 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8307 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8308 return convertIntToFP(Op, Mov, DAG, Subtarget); 8309 } 8310 8311 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8312 8313 EVT VecVT = Vec.getValueType(); 8314 assert(VecVT.isVector() && "Expected a vector type."); 8315 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8316 8317 EVT EltVT = VecVT.getVectorElementType(); 8318 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8319 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8320 8321 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8322 SmallVector<SDValue, 16> Ops(NumConcat); 8323 Ops[0] = Vec; 8324 SDValue UndefVec = DAG.getUNDEF(VecVT); 8325 for (unsigned i = 1; i < NumConcat; ++i) 8326 Ops[i] = UndefVec; 8327 8328 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8329 } 8330 8331 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8332 const SDLoc &dl) const { 8333 bool IsStrict = Op->isStrictFPOpcode(); 8334 unsigned Opc = Op.getOpcode(); 8335 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8336 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8337 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8338 "Unexpected conversion type"); 8339 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8340 "Supports conversions to v2f64/v4f32 only."); 8341 8342 // TODO: Any other flags to propagate? 8343 SDNodeFlags Flags; 8344 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8345 8346 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8347 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8348 8349 SDValue Wide = widenVec(DAG, Src, dl); 8350 EVT WideVT = Wide.getValueType(); 8351 unsigned WideNumElts = WideVT.getVectorNumElements(); 8352 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8353 8354 SmallVector<int, 16> ShuffV; 8355 for (unsigned i = 0; i < WideNumElts; ++i) 8356 ShuffV.push_back(i + WideNumElts); 8357 8358 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8359 int SaveElts = FourEltRes ? 4 : 2; 8360 if (Subtarget.isLittleEndian()) 8361 for (int i = 0; i < SaveElts; i++) 8362 ShuffV[i * Stride] = i; 8363 else 8364 for (int i = 1; i <= SaveElts; i++) 8365 ShuffV[i * Stride - 1] = i - 1; 8366 8367 SDValue ShuffleSrc2 = 8368 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8369 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8370 8371 SDValue Extend; 8372 if (SignedConv) { 8373 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8374 EVT ExtVT = Src.getValueType(); 8375 if (Subtarget.hasP9Altivec()) 8376 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8377 IntermediateVT.getVectorNumElements()); 8378 8379 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8380 DAG.getValueType(ExtVT)); 8381 } else 8382 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8383 8384 if (IsStrict) 8385 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8386 {Op.getOperand(0), Extend}, Flags); 8387 8388 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8389 } 8390 8391 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8392 SelectionDAG &DAG) const { 8393 SDLoc dl(Op); 8394 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8395 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8396 bool IsStrict = Op->isStrictFPOpcode(); 8397 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8398 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8399 8400 // TODO: Any other flags to propagate? 8401 SDNodeFlags Flags; 8402 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8403 8404 EVT InVT = Src.getValueType(); 8405 EVT OutVT = Op.getValueType(); 8406 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8407 isOperationCustom(Op.getOpcode(), InVT)) 8408 return LowerINT_TO_FPVector(Op, DAG, dl); 8409 8410 // Conversions to f128 are legal. 8411 if (Op.getValueType() == MVT::f128) 8412 return Subtarget.hasP9Vector() ? Op : SDValue(); 8413 8414 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8415 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8416 return SDValue(); 8417 8418 if (Src.getValueType() == MVT::i1) { 8419 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8420 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8421 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8422 if (IsStrict) 8423 return DAG.getMergeValues({Sel, Chain}, dl); 8424 else 8425 return Sel; 8426 } 8427 8428 // If we have direct moves, we can do all the conversion, skip the store/load 8429 // however, without FPCVT we can't do most conversions. 8430 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8431 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8432 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8433 8434 assert((IsSigned || Subtarget.hasFPCVT()) && 8435 "UINT_TO_FP is supported only with FPCVT"); 8436 8437 if (Src.getValueType() == MVT::i64) { 8438 SDValue SINT = Src; 8439 // When converting to single-precision, we actually need to convert 8440 // to double-precision first and then round to single-precision. 8441 // To avoid double-rounding effects during that operation, we have 8442 // to prepare the input operand. Bits that might be truncated when 8443 // converting to double-precision are replaced by a bit that won't 8444 // be lost at this stage, but is below the single-precision rounding 8445 // position. 8446 // 8447 // However, if -enable-unsafe-fp-math is in effect, accept double 8448 // rounding to avoid the extra overhead. 8449 if (Op.getValueType() == MVT::f32 && 8450 !Subtarget.hasFPCVT() && 8451 !DAG.getTarget().Options.UnsafeFPMath) { 8452 8453 // Twiddle input to make sure the low 11 bits are zero. (If this 8454 // is the case, we are guaranteed the value will fit into the 53 bit 8455 // mantissa of an IEEE double-precision value without rounding.) 8456 // If any of those low 11 bits were not zero originally, make sure 8457 // bit 12 (value 2048) is set instead, so that the final rounding 8458 // to single-precision gets the correct result. 8459 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8460 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8461 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8462 Round, DAG.getConstant(2047, dl, MVT::i64)); 8463 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8464 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8465 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8466 8467 // However, we cannot use that value unconditionally: if the magnitude 8468 // of the input value is small, the bit-twiddling we did above might 8469 // end up visibly changing the output. Fortunately, in that case, we 8470 // don't need to twiddle bits since the original input will convert 8471 // exactly to double-precision floating-point already. Therefore, 8472 // construct a conditional to use the original value if the top 11 8473 // bits are all sign-bit copies, and use the rounded value computed 8474 // above otherwise. 8475 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8476 SINT, DAG.getConstant(53, dl, MVT::i32)); 8477 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8478 Cond, DAG.getConstant(1, dl, MVT::i64)); 8479 Cond = DAG.getSetCC( 8480 dl, 8481 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8482 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8483 8484 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8485 } 8486 8487 ReuseLoadInfo RLI; 8488 SDValue Bits; 8489 8490 MachineFunction &MF = DAG.getMachineFunction(); 8491 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8492 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8493 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8494 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8495 } else if (Subtarget.hasLFIWAX() && 8496 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8497 MachineMemOperand *MMO = 8498 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8499 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8500 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8501 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8502 DAG.getVTList(MVT::f64, MVT::Other), 8503 Ops, MVT::i32, MMO); 8504 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8505 } else if (Subtarget.hasFPCVT() && 8506 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8507 MachineMemOperand *MMO = 8508 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8509 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8510 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8511 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8512 DAG.getVTList(MVT::f64, MVT::Other), 8513 Ops, MVT::i32, MMO); 8514 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8515 } else if (((Subtarget.hasLFIWAX() && 8516 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8517 (Subtarget.hasFPCVT() && 8518 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8519 SINT.getOperand(0).getValueType() == MVT::i32) { 8520 MachineFrameInfo &MFI = MF.getFrameInfo(); 8521 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8522 8523 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8524 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8525 8526 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8527 MachinePointerInfo::getFixedStack( 8528 DAG.getMachineFunction(), FrameIdx)); 8529 Chain = Store; 8530 8531 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8532 "Expected an i32 store"); 8533 8534 RLI.Ptr = FIdx; 8535 RLI.Chain = Chain; 8536 RLI.MPI = 8537 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8538 RLI.Alignment = Align(4); 8539 8540 MachineMemOperand *MMO = 8541 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8542 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8543 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8544 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8545 PPCISD::LFIWZX : PPCISD::LFIWAX, 8546 dl, DAG.getVTList(MVT::f64, MVT::Other), 8547 Ops, MVT::i32, MMO); 8548 Chain = Bits.getValue(1); 8549 } else 8550 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8551 8552 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8553 if (IsStrict) 8554 Chain = FP.getValue(1); 8555 8556 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8557 if (IsStrict) 8558 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8559 DAG.getVTList(MVT::f32, MVT::Other), 8560 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8561 else 8562 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8563 DAG.getIntPtrConstant(0, dl)); 8564 } 8565 return FP; 8566 } 8567 8568 assert(Src.getValueType() == MVT::i32 && 8569 "Unhandled INT_TO_FP type in custom expander!"); 8570 // Since we only generate this in 64-bit mode, we can take advantage of 8571 // 64-bit registers. In particular, sign extend the input value into the 8572 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8573 // then lfd it and fcfid it. 8574 MachineFunction &MF = DAG.getMachineFunction(); 8575 MachineFrameInfo &MFI = MF.getFrameInfo(); 8576 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8577 8578 SDValue Ld; 8579 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8580 ReuseLoadInfo RLI; 8581 bool ReusingLoad; 8582 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8583 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8584 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8585 8586 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8587 MachinePointerInfo::getFixedStack( 8588 DAG.getMachineFunction(), FrameIdx)); 8589 Chain = Store; 8590 8591 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8592 "Expected an i32 store"); 8593 8594 RLI.Ptr = FIdx; 8595 RLI.Chain = Chain; 8596 RLI.MPI = 8597 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8598 RLI.Alignment = Align(4); 8599 } 8600 8601 MachineMemOperand *MMO = 8602 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8603 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8604 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8605 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8606 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8607 MVT::i32, MMO); 8608 Chain = Ld.getValue(1); 8609 if (ReusingLoad) 8610 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8611 } else { 8612 assert(Subtarget.isPPC64() && 8613 "i32->FP without LFIWAX supported only on PPC64"); 8614 8615 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8616 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8617 8618 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8619 8620 // STD the extended value into the stack slot. 8621 SDValue Store = DAG.getStore( 8622 Chain, dl, Ext64, FIdx, 8623 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8624 Chain = Store; 8625 8626 // Load the value as a double. 8627 Ld = DAG.getLoad( 8628 MVT::f64, dl, Chain, FIdx, 8629 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8630 Chain = Ld.getValue(1); 8631 } 8632 8633 // FCFID it and return it. 8634 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8635 if (IsStrict) 8636 Chain = FP.getValue(1); 8637 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8638 if (IsStrict) 8639 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8640 DAG.getVTList(MVT::f32, MVT::Other), 8641 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8642 else 8643 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8644 DAG.getIntPtrConstant(0, dl)); 8645 } 8646 return FP; 8647 } 8648 8649 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8650 SelectionDAG &DAG) const { 8651 SDLoc dl(Op); 8652 /* 8653 The rounding mode is in bits 30:31 of FPSR, and has the following 8654 settings: 8655 00 Round to nearest 8656 01 Round to 0 8657 10 Round to +inf 8658 11 Round to -inf 8659 8660 FLT_ROUNDS, on the other hand, expects the following: 8661 -1 Undefined 8662 0 Round to 0 8663 1 Round to nearest 8664 2 Round to +inf 8665 3 Round to -inf 8666 8667 To perform the conversion, we do: 8668 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8669 */ 8670 8671 MachineFunction &MF = DAG.getMachineFunction(); 8672 EVT VT = Op.getValueType(); 8673 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8674 8675 // Save FP Control Word to register 8676 SDValue Chain = Op.getOperand(0); 8677 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8678 Chain = MFFS.getValue(1); 8679 8680 SDValue CWD; 8681 if (isTypeLegal(MVT::i64)) { 8682 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8683 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8684 } else { 8685 // Save FP register to stack slot 8686 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8687 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8688 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8689 8690 // Load FP Control Word from low 32 bits of stack slot. 8691 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8692 "Stack slot adjustment is valid only on big endian subtargets!"); 8693 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8694 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8695 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8696 Chain = CWD.getValue(1); 8697 } 8698 8699 // Transform as necessary 8700 SDValue CWD1 = 8701 DAG.getNode(ISD::AND, dl, MVT::i32, 8702 CWD, DAG.getConstant(3, dl, MVT::i32)); 8703 SDValue CWD2 = 8704 DAG.getNode(ISD::SRL, dl, MVT::i32, 8705 DAG.getNode(ISD::AND, dl, MVT::i32, 8706 DAG.getNode(ISD::XOR, dl, MVT::i32, 8707 CWD, DAG.getConstant(3, dl, MVT::i32)), 8708 DAG.getConstant(3, dl, MVT::i32)), 8709 DAG.getConstant(1, dl, MVT::i32)); 8710 8711 SDValue RetVal = 8712 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8713 8714 RetVal = 8715 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8716 dl, VT, RetVal); 8717 8718 return DAG.getMergeValues({RetVal, Chain}, dl); 8719 } 8720 8721 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8722 EVT VT = Op.getValueType(); 8723 unsigned BitWidth = VT.getSizeInBits(); 8724 SDLoc dl(Op); 8725 assert(Op.getNumOperands() == 3 && 8726 VT == Op.getOperand(1).getValueType() && 8727 "Unexpected SHL!"); 8728 8729 // Expand into a bunch of logical ops. Note that these ops 8730 // depend on the PPC behavior for oversized shift amounts. 8731 SDValue Lo = Op.getOperand(0); 8732 SDValue Hi = Op.getOperand(1); 8733 SDValue Amt = Op.getOperand(2); 8734 EVT AmtVT = Amt.getValueType(); 8735 8736 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8737 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8738 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8739 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8740 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8741 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8742 DAG.getConstant(-BitWidth, dl, AmtVT)); 8743 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8744 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8745 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8746 SDValue OutOps[] = { OutLo, OutHi }; 8747 return DAG.getMergeValues(OutOps, dl); 8748 } 8749 8750 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8751 EVT VT = Op.getValueType(); 8752 SDLoc dl(Op); 8753 unsigned BitWidth = VT.getSizeInBits(); 8754 assert(Op.getNumOperands() == 3 && 8755 VT == Op.getOperand(1).getValueType() && 8756 "Unexpected SRL!"); 8757 8758 // Expand into a bunch of logical ops. Note that these ops 8759 // depend on the PPC behavior for oversized shift amounts. 8760 SDValue Lo = Op.getOperand(0); 8761 SDValue Hi = Op.getOperand(1); 8762 SDValue Amt = Op.getOperand(2); 8763 EVT AmtVT = Amt.getValueType(); 8764 8765 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8766 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8767 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8768 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8769 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8770 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8771 DAG.getConstant(-BitWidth, dl, AmtVT)); 8772 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8773 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8774 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8775 SDValue OutOps[] = { OutLo, OutHi }; 8776 return DAG.getMergeValues(OutOps, dl); 8777 } 8778 8779 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8780 SDLoc dl(Op); 8781 EVT VT = Op.getValueType(); 8782 unsigned BitWidth = VT.getSizeInBits(); 8783 assert(Op.getNumOperands() == 3 && 8784 VT == Op.getOperand(1).getValueType() && 8785 "Unexpected SRA!"); 8786 8787 // Expand into a bunch of logical ops, followed by a select_cc. 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::SRA, dl, VT, Hi, Tmp5); 8801 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8802 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8803 Tmp4, Tmp6, ISD::SETLE); 8804 SDValue OutOps[] = { OutLo, OutHi }; 8805 return DAG.getMergeValues(OutOps, dl); 8806 } 8807 8808 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8809 SelectionDAG &DAG) const { 8810 SDLoc dl(Op); 8811 EVT VT = Op.getValueType(); 8812 unsigned BitWidth = VT.getSizeInBits(); 8813 8814 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8815 SDValue X = Op.getOperand(0); 8816 SDValue Y = Op.getOperand(1); 8817 SDValue Z = Op.getOperand(2); 8818 EVT AmtVT = Z.getValueType(); 8819 8820 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8821 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8822 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8823 // on PowerPC shift by BW being well defined. 8824 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8825 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8826 SDValue SubZ = 8827 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8828 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8829 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8830 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8831 } 8832 8833 //===----------------------------------------------------------------------===// 8834 // Vector related lowering. 8835 // 8836 8837 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8838 /// element size of SplatSize. Cast the result to VT. 8839 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8840 SelectionDAG &DAG, const SDLoc &dl) { 8841 static const MVT VTys[] = { // canonical VT to use for each size. 8842 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8843 }; 8844 8845 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8846 8847 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8848 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8849 SplatSize = 1; 8850 Val = 0xFF; 8851 } 8852 8853 EVT CanonicalVT = VTys[SplatSize-1]; 8854 8855 // Build a canonical splat for this value. 8856 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8857 } 8858 8859 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8860 /// specified intrinsic ID. 8861 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8862 const SDLoc &dl, EVT DestVT = MVT::Other) { 8863 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8864 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8865 DAG.getConstant(IID, dl, MVT::i32), Op); 8866 } 8867 8868 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8869 /// specified intrinsic ID. 8870 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8871 SelectionDAG &DAG, const SDLoc &dl, 8872 EVT DestVT = MVT::Other) { 8873 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8874 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8875 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8876 } 8877 8878 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8879 /// specified intrinsic ID. 8880 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8881 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8882 EVT DestVT = MVT::Other) { 8883 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8884 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8885 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8886 } 8887 8888 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8889 /// amount. The result has the specified value type. 8890 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8891 SelectionDAG &DAG, const SDLoc &dl) { 8892 // Force LHS/RHS to be the right type. 8893 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8894 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8895 8896 int Ops[16]; 8897 for (unsigned i = 0; i != 16; ++i) 8898 Ops[i] = i + Amt; 8899 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8900 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8901 } 8902 8903 /// Do we have an efficient pattern in a .td file for this node? 8904 /// 8905 /// \param V - pointer to the BuildVectorSDNode being matched 8906 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8907 /// 8908 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8909 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8910 /// the opposite is true (expansion is beneficial) are: 8911 /// - The node builds a vector out of integers that are not 32 or 64-bits 8912 /// - The node builds a vector out of constants 8913 /// - The node is a "load-and-splat" 8914 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8915 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8916 bool HasDirectMove, 8917 bool HasP8Vector) { 8918 EVT VecVT = V->getValueType(0); 8919 bool RightType = VecVT == MVT::v2f64 || 8920 (HasP8Vector && VecVT == MVT::v4f32) || 8921 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8922 if (!RightType) 8923 return false; 8924 8925 bool IsSplat = true; 8926 bool IsLoad = false; 8927 SDValue Op0 = V->getOperand(0); 8928 8929 // This function is called in a block that confirms the node is not a constant 8930 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8931 // different constants. 8932 if (V->isConstant()) 8933 return false; 8934 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8935 if (V->getOperand(i).isUndef()) 8936 return false; 8937 // We want to expand nodes that represent load-and-splat even if the 8938 // loaded value is a floating point truncation or conversion to int. 8939 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8940 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8941 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8942 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8943 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8944 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8945 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8946 IsLoad = true; 8947 // If the operands are different or the input is not a load and has more 8948 // uses than just this BV node, then it isn't a splat. 8949 if (V->getOperand(i) != Op0 || 8950 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8951 IsSplat = false; 8952 } 8953 return !(IsSplat && IsLoad); 8954 } 8955 8956 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8957 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8958 8959 SDLoc dl(Op); 8960 SDValue Op0 = Op->getOperand(0); 8961 8962 if ((Op.getValueType() != MVT::f128) || 8963 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8964 (Op0.getOperand(0).getValueType() != MVT::i64) || 8965 (Op0.getOperand(1).getValueType() != MVT::i64)) 8966 return SDValue(); 8967 8968 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8969 Op0.getOperand(1)); 8970 } 8971 8972 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 8973 const SDValue *InputLoad = &Op; 8974 if (InputLoad->getOpcode() == ISD::BITCAST) 8975 InputLoad = &InputLoad->getOperand(0); 8976 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 8977 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 8978 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 8979 InputLoad = &InputLoad->getOperand(0); 8980 } 8981 if (InputLoad->getOpcode() != ISD::LOAD) 8982 return nullptr; 8983 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8984 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8985 } 8986 8987 // Convert the argument APFloat to a single precision APFloat if there is no 8988 // loss in information during the conversion to single precision APFloat and the 8989 // resulting number is not a denormal number. Return true if successful. 8990 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 8991 APFloat APFloatToConvert = ArgAPFloat; 8992 bool LosesInfo = true; 8993 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8994 &LosesInfo); 8995 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 8996 if (Success) 8997 ArgAPFloat = APFloatToConvert; 8998 return Success; 8999 } 9000 9001 // Bitcast the argument APInt to a double and convert it to a single precision 9002 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9003 // argument if there is no loss in information during the conversion from 9004 // double to single precision APFloat and the resulting number is not a denormal 9005 // number. Return true if successful. 9006 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9007 double DpValue = ArgAPInt.bitsToDouble(); 9008 APFloat APFloatDp(DpValue); 9009 bool Success = convertToNonDenormSingle(APFloatDp); 9010 if (Success) 9011 ArgAPInt = APFloatDp.bitcastToAPInt(); 9012 return Success; 9013 } 9014 9015 // Nondestructive check for convertTonNonDenormSingle. 9016 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 9017 // Only convert if it loses info, since XXSPLTIDP should 9018 // handle the other case. 9019 APFloat APFloatToConvert = ArgAPFloat; 9020 bool LosesInfo = true; 9021 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9022 &LosesInfo); 9023 9024 return (!LosesInfo && !APFloatToConvert.isDenormal()); 9025 } 9026 9027 // If this is a case we can't handle, return null and let the default 9028 // expansion code take care of it. If we CAN select this case, and if it 9029 // selects to a single instruction, return Op. Otherwise, if we can codegen 9030 // this case more efficiently than a constant pool load, lower it to the 9031 // sequence of ops that should be used. 9032 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9033 SelectionDAG &DAG) const { 9034 SDLoc dl(Op); 9035 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9036 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9037 9038 // Check if this is a splat of a constant value. 9039 APInt APSplatBits, APSplatUndef; 9040 unsigned SplatBitSize; 9041 bool HasAnyUndefs; 9042 bool BVNIsConstantSplat = 9043 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9044 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9045 9046 // If it is a splat of a double, check if we can shrink it to a 32 bit 9047 // non-denormal float which when converted back to double gives us the same 9048 // double. This is to exploit the XXSPLTIDP instruction. 9049 // If we lose precision, we use XXSPLTI32DX. 9050 if (BVNIsConstantSplat && (SplatBitSize == 64) && 9051 Subtarget.hasPrefixInstrs()) { 9052 // Check the type first to short-circuit so we don't modify APSplatBits if 9053 // this block isn't executed. 9054 if ((Op->getValueType(0) == MVT::v2f64) && 9055 convertToNonDenormSingle(APSplatBits)) { 9056 SDValue SplatNode = DAG.getNode( 9057 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9058 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9059 return DAG.getBitcast(Op.getValueType(), SplatNode); 9060 } else { 9061 // We may lose precision, so we have to use XXSPLTI32DX. 9062 9063 uint32_t Hi = 9064 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 9065 uint32_t Lo = 9066 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 9067 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 9068 9069 if (!Hi || !Lo) 9070 // If either load is 0, then we should generate XXLXOR to set to 0. 9071 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 9072 9073 if (Hi) 9074 SplatNode = DAG.getNode( 9075 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9076 DAG.getTargetConstant(0, dl, MVT::i32), 9077 DAG.getTargetConstant(Hi, dl, MVT::i32)); 9078 9079 if (Lo) 9080 SplatNode = 9081 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9082 DAG.getTargetConstant(1, dl, MVT::i32), 9083 DAG.getTargetConstant(Lo, dl, MVT::i32)); 9084 9085 return DAG.getBitcast(Op.getValueType(), SplatNode); 9086 } 9087 } 9088 9089 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9090 9091 bool IsPermutedLoad = false; 9092 const SDValue *InputLoad = 9093 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9094 // Handle load-and-splat patterns as we have instructions that will do this 9095 // in one go. 9096 if (InputLoad && DAG.isSplatValue(Op, true)) { 9097 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9098 9099 // We have handling for 4 and 8 byte elements. 9100 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9101 9102 // Checking for a single use of this load, we have to check for vector 9103 // width (128 bits) / ElementSize uses (since each operand of the 9104 // BUILD_VECTOR is a separate use of the value. 9105 unsigned NumUsesOfInputLD = 128 / ElementSize; 9106 for (SDValue BVInOp : Op->ops()) 9107 if (BVInOp.isUndef()) 9108 NumUsesOfInputLD--; 9109 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9110 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9111 ((Subtarget.hasVSX() && ElementSize == 64) || 9112 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9113 SDValue Ops[] = { 9114 LD->getChain(), // Chain 9115 LD->getBasePtr(), // Ptr 9116 DAG.getValueType(Op.getValueType()) // VT 9117 }; 9118 SDValue LdSplt = DAG.getMemIntrinsicNode( 9119 PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 9120 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9121 // Replace all uses of the output chain of the original load with the 9122 // output chain of the new load. 9123 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9124 LdSplt.getValue(1)); 9125 return LdSplt; 9126 } 9127 } 9128 9129 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9130 // 32-bits can be lowered to VSX instructions under certain conditions. 9131 // Without VSX, there is no pattern more efficient than expanding the node. 9132 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9133 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9134 Subtarget.hasP8Vector())) 9135 return Op; 9136 return SDValue(); 9137 } 9138 9139 uint64_t SplatBits = APSplatBits.getZExtValue(); 9140 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9141 unsigned SplatSize = SplatBitSize / 8; 9142 9143 // First, handle single instruction cases. 9144 9145 // All zeros? 9146 if (SplatBits == 0) { 9147 // Canonicalize all zero vectors to be v4i32. 9148 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9149 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9150 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9151 } 9152 return Op; 9153 } 9154 9155 // We have XXSPLTIW for constant splats four bytes wide. 9156 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9157 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9158 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9159 // turned into a 4-byte splat of 0xABABABAB. 9160 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9161 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9162 Op.getValueType(), DAG, dl); 9163 9164 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9165 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9166 dl); 9167 9168 // We have XXSPLTIB for constant splats one byte wide. 9169 if (Subtarget.hasP9Vector() && SplatSize == 1) 9170 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9171 dl); 9172 9173 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9174 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9175 (32-SplatBitSize)); 9176 if (SextVal >= -16 && SextVal <= 15) 9177 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9178 dl); 9179 9180 // Two instruction sequences. 9181 9182 // If this value is in the range [-32,30] and is even, use: 9183 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9184 // If this value is in the range [17,31] and is odd, use: 9185 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9186 // If this value is in the range [-31,-17] and is odd, use: 9187 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9188 // Note the last two are three-instruction sequences. 9189 if (SextVal >= -32 && SextVal <= 31) { 9190 // To avoid having these optimizations undone by constant folding, 9191 // we convert to a pseudo that will be expanded later into one of 9192 // the above forms. 9193 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9194 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9195 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9196 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9197 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9198 if (VT == Op.getValueType()) 9199 return RetVal; 9200 else 9201 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9202 } 9203 9204 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9205 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9206 // for fneg/fabs. 9207 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9208 // Make -1 and vspltisw -1: 9209 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9210 9211 // Make the VSLW intrinsic, computing 0x8000_0000. 9212 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9213 OnesV, DAG, dl); 9214 9215 // xor by OnesV to invert it. 9216 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9217 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9218 } 9219 9220 // Check to see if this is a wide variety of vsplti*, binop self cases. 9221 static const signed char SplatCsts[] = { 9222 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9223 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9224 }; 9225 9226 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9227 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9228 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9229 int i = SplatCsts[idx]; 9230 9231 // Figure out what shift amount will be used by altivec if shifted by i in 9232 // this splat size. 9233 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9234 9235 // vsplti + shl self. 9236 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9237 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9238 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9239 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9240 Intrinsic::ppc_altivec_vslw 9241 }; 9242 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9243 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9244 } 9245 9246 // vsplti + srl self. 9247 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9248 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9249 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9250 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9251 Intrinsic::ppc_altivec_vsrw 9252 }; 9253 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9254 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9255 } 9256 9257 // vsplti + rol self. 9258 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9259 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9260 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9261 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9262 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9263 Intrinsic::ppc_altivec_vrlw 9264 }; 9265 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9266 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9267 } 9268 9269 // t = vsplti c, result = vsldoi t, t, 1 9270 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9271 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9272 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9273 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9274 } 9275 // t = vsplti c, result = vsldoi t, t, 2 9276 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9277 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9278 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9279 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9280 } 9281 // t = vsplti c, result = vsldoi t, t, 3 9282 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9283 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9284 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9285 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9286 } 9287 } 9288 9289 return SDValue(); 9290 } 9291 9292 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9293 /// the specified operations to build the shuffle. 9294 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9295 SDValue RHS, SelectionDAG &DAG, 9296 const SDLoc &dl) { 9297 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9298 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9299 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9300 9301 enum { 9302 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9303 OP_VMRGHW, 9304 OP_VMRGLW, 9305 OP_VSPLTISW0, 9306 OP_VSPLTISW1, 9307 OP_VSPLTISW2, 9308 OP_VSPLTISW3, 9309 OP_VSLDOI4, 9310 OP_VSLDOI8, 9311 OP_VSLDOI12 9312 }; 9313 9314 if (OpNum == OP_COPY) { 9315 if (LHSID == (1*9+2)*9+3) return LHS; 9316 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9317 return RHS; 9318 } 9319 9320 SDValue OpLHS, OpRHS; 9321 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9322 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9323 9324 int ShufIdxs[16]; 9325 switch (OpNum) { 9326 default: llvm_unreachable("Unknown i32 permute!"); 9327 case OP_VMRGHW: 9328 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9329 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9330 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9331 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9332 break; 9333 case OP_VMRGLW: 9334 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9335 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9336 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9337 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9338 break; 9339 case OP_VSPLTISW0: 9340 for (unsigned i = 0; i != 16; ++i) 9341 ShufIdxs[i] = (i&3)+0; 9342 break; 9343 case OP_VSPLTISW1: 9344 for (unsigned i = 0; i != 16; ++i) 9345 ShufIdxs[i] = (i&3)+4; 9346 break; 9347 case OP_VSPLTISW2: 9348 for (unsigned i = 0; i != 16; ++i) 9349 ShufIdxs[i] = (i&3)+8; 9350 break; 9351 case OP_VSPLTISW3: 9352 for (unsigned i = 0; i != 16; ++i) 9353 ShufIdxs[i] = (i&3)+12; 9354 break; 9355 case OP_VSLDOI4: 9356 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9357 case OP_VSLDOI8: 9358 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9359 case OP_VSLDOI12: 9360 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9361 } 9362 EVT VT = OpLHS.getValueType(); 9363 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9364 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9365 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9366 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9367 } 9368 9369 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9370 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9371 /// SDValue. 9372 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9373 SelectionDAG &DAG) const { 9374 const unsigned BytesInVector = 16; 9375 bool IsLE = Subtarget.isLittleEndian(); 9376 SDLoc dl(N); 9377 SDValue V1 = N->getOperand(0); 9378 SDValue V2 = N->getOperand(1); 9379 unsigned ShiftElts = 0, InsertAtByte = 0; 9380 bool Swap = false; 9381 9382 // Shifts required to get the byte we want at element 7. 9383 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9384 0, 15, 14, 13, 12, 11, 10, 9}; 9385 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9386 1, 2, 3, 4, 5, 6, 7, 8}; 9387 9388 ArrayRef<int> Mask = N->getMask(); 9389 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9390 9391 // For each mask element, find out if we're just inserting something 9392 // from V2 into V1 or vice versa. 9393 // Possible permutations inserting an element from V2 into V1: 9394 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9395 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9396 // ... 9397 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9398 // Inserting from V1 into V2 will be similar, except mask range will be 9399 // [16,31]. 9400 9401 bool FoundCandidate = false; 9402 // If both vector operands for the shuffle are the same vector, the mask 9403 // will contain only elements from the first one and the second one will be 9404 // undef. 9405 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9406 // Go through the mask of half-words to find an element that's being moved 9407 // from one vector to the other. 9408 for (unsigned i = 0; i < BytesInVector; ++i) { 9409 unsigned CurrentElement = Mask[i]; 9410 // If 2nd operand is undefined, we should only look for element 7 in the 9411 // Mask. 9412 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9413 continue; 9414 9415 bool OtherElementsInOrder = true; 9416 // Examine the other elements in the Mask to see if they're in original 9417 // order. 9418 for (unsigned j = 0; j < BytesInVector; ++j) { 9419 if (j == i) 9420 continue; 9421 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9422 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9423 // in which we always assume we're always picking from the 1st operand. 9424 int MaskOffset = 9425 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9426 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9427 OtherElementsInOrder = false; 9428 break; 9429 } 9430 } 9431 // If other elements are in original order, we record the number of shifts 9432 // we need to get the element we want into element 7. Also record which byte 9433 // in the vector we should insert into. 9434 if (OtherElementsInOrder) { 9435 // If 2nd operand is undefined, we assume no shifts and no swapping. 9436 if (V2.isUndef()) { 9437 ShiftElts = 0; 9438 Swap = false; 9439 } else { 9440 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9441 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9442 : BigEndianShifts[CurrentElement & 0xF]; 9443 Swap = CurrentElement < BytesInVector; 9444 } 9445 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9446 FoundCandidate = true; 9447 break; 9448 } 9449 } 9450 9451 if (!FoundCandidate) 9452 return SDValue(); 9453 9454 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9455 // optionally with VECSHL if shift is required. 9456 if (Swap) 9457 std::swap(V1, V2); 9458 if (V2.isUndef()) 9459 V2 = V1; 9460 if (ShiftElts) { 9461 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9462 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9463 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9464 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9465 } 9466 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9467 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9468 } 9469 9470 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9471 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9472 /// SDValue. 9473 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9474 SelectionDAG &DAG) const { 9475 const unsigned NumHalfWords = 8; 9476 const unsigned BytesInVector = NumHalfWords * 2; 9477 // Check that the shuffle is on half-words. 9478 if (!isNByteElemShuffleMask(N, 2, 1)) 9479 return SDValue(); 9480 9481 bool IsLE = Subtarget.isLittleEndian(); 9482 SDLoc dl(N); 9483 SDValue V1 = N->getOperand(0); 9484 SDValue V2 = N->getOperand(1); 9485 unsigned ShiftElts = 0, InsertAtByte = 0; 9486 bool Swap = false; 9487 9488 // Shifts required to get the half-word we want at element 3. 9489 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9490 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9491 9492 uint32_t Mask = 0; 9493 uint32_t OriginalOrderLow = 0x1234567; 9494 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9495 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9496 // 32-bit space, only need 4-bit nibbles per element. 9497 for (unsigned i = 0; i < NumHalfWords; ++i) { 9498 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9499 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9500 } 9501 9502 // For each mask element, find out if we're just inserting something 9503 // from V2 into V1 or vice versa. Possible permutations inserting an element 9504 // from V2 into V1: 9505 // X, 1, 2, 3, 4, 5, 6, 7 9506 // 0, X, 2, 3, 4, 5, 6, 7 9507 // 0, 1, X, 3, 4, 5, 6, 7 9508 // 0, 1, 2, X, 4, 5, 6, 7 9509 // 0, 1, 2, 3, X, 5, 6, 7 9510 // 0, 1, 2, 3, 4, X, 6, 7 9511 // 0, 1, 2, 3, 4, 5, X, 7 9512 // 0, 1, 2, 3, 4, 5, 6, X 9513 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9514 9515 bool FoundCandidate = false; 9516 // Go through the mask of half-words to find an element that's being moved 9517 // from one vector to the other. 9518 for (unsigned i = 0; i < NumHalfWords; ++i) { 9519 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9520 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9521 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9522 uint32_t TargetOrder = 0x0; 9523 9524 // If both vector operands for the shuffle are the same vector, the mask 9525 // will contain only elements from the first one and the second one will be 9526 // undef. 9527 if (V2.isUndef()) { 9528 ShiftElts = 0; 9529 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9530 TargetOrder = OriginalOrderLow; 9531 Swap = false; 9532 // Skip if not the correct element or mask of other elements don't equal 9533 // to our expected order. 9534 if (MaskOneElt == VINSERTHSrcElem && 9535 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9536 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9537 FoundCandidate = true; 9538 break; 9539 } 9540 } else { // If both operands are defined. 9541 // Target order is [8,15] if the current mask is between [0,7]. 9542 TargetOrder = 9543 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9544 // Skip if mask of other elements don't equal our expected order. 9545 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9546 // We only need the last 3 bits for the number of shifts. 9547 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9548 : BigEndianShifts[MaskOneElt & 0x7]; 9549 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9550 Swap = MaskOneElt < NumHalfWords; 9551 FoundCandidate = true; 9552 break; 9553 } 9554 } 9555 } 9556 9557 if (!FoundCandidate) 9558 return SDValue(); 9559 9560 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9561 // optionally with VECSHL if shift is required. 9562 if (Swap) 9563 std::swap(V1, V2); 9564 if (V2.isUndef()) 9565 V2 = V1; 9566 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9567 if (ShiftElts) { 9568 // Double ShiftElts because we're left shifting on v16i8 type. 9569 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9570 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9571 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9572 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9573 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9574 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9575 } 9576 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9577 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9578 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9579 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9580 } 9581 9582 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9583 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9584 /// return the default SDValue. 9585 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9586 SelectionDAG &DAG) const { 9587 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9588 // to v16i8. Peek through the bitcasts to get the actual operands. 9589 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9590 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9591 9592 auto ShuffleMask = SVN->getMask(); 9593 SDValue VecShuffle(SVN, 0); 9594 SDLoc DL(SVN); 9595 9596 // Check that we have a four byte shuffle. 9597 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9598 return SDValue(); 9599 9600 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9601 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9602 std::swap(LHS, RHS); 9603 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9604 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9605 } 9606 9607 // Ensure that the RHS is a vector of constants. 9608 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9609 if (!BVN) 9610 return SDValue(); 9611 9612 // Check if RHS is a splat of 4-bytes (or smaller). 9613 APInt APSplatValue, APSplatUndef; 9614 unsigned SplatBitSize; 9615 bool HasAnyUndefs; 9616 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9617 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9618 SplatBitSize > 32) 9619 return SDValue(); 9620 9621 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9622 // The instruction splats a constant C into two words of the source vector 9623 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9624 // Thus we check that the shuffle mask is the equivalent of 9625 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9626 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9627 // within each word are consecutive, so we only need to check the first byte. 9628 SDValue Index; 9629 bool IsLE = Subtarget.isLittleEndian(); 9630 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9631 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9632 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9633 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9634 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9635 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9636 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9637 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9638 else 9639 return SDValue(); 9640 9641 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9642 // for XXSPLTI32DX. 9643 unsigned SplatVal = APSplatValue.getZExtValue(); 9644 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9645 SplatVal |= (SplatVal << SplatBitSize); 9646 9647 SDValue SplatNode = DAG.getNode( 9648 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9649 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9650 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9651 } 9652 9653 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9654 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9655 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9656 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9657 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9658 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9659 assert(Op.getValueType() == MVT::v1i128 && 9660 "Only set v1i128 as custom, other type shouldn't reach here!"); 9661 SDLoc dl(Op); 9662 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9663 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9664 unsigned SHLAmt = N1.getConstantOperandVal(0); 9665 if (SHLAmt % 8 == 0) { 9666 SmallVector<int, 16> Mask(16, 0); 9667 std::iota(Mask.begin(), Mask.end(), 0); 9668 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9669 if (SDValue Shuffle = 9670 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9671 DAG.getUNDEF(MVT::v16i8), Mask)) 9672 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9673 } 9674 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9675 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9676 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9677 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9678 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9679 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9680 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9681 } 9682 9683 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9684 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9685 /// return the code it can be lowered into. Worst case, it can always be 9686 /// lowered into a vperm. 9687 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9688 SelectionDAG &DAG) const { 9689 SDLoc dl(Op); 9690 SDValue V1 = Op.getOperand(0); 9691 SDValue V2 = Op.getOperand(1); 9692 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9693 9694 // Any nodes that were combined in the target-independent combiner prior 9695 // to vector legalization will not be sent to the target combine. Try to 9696 // combine it here. 9697 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9698 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9699 return NewShuffle; 9700 Op = NewShuffle; 9701 SVOp = cast<ShuffleVectorSDNode>(Op); 9702 V1 = Op.getOperand(0); 9703 V2 = Op.getOperand(1); 9704 } 9705 EVT VT = Op.getValueType(); 9706 bool isLittleEndian = Subtarget.isLittleEndian(); 9707 9708 unsigned ShiftElts, InsertAtByte; 9709 bool Swap = false; 9710 9711 // If this is a load-and-splat, we can do that with a single instruction 9712 // in some cases. However if the load has multiple uses, we don't want to 9713 // combine it because that will just produce multiple loads. 9714 bool IsPermutedLoad = false; 9715 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9716 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9717 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9718 InputLoad->hasOneUse()) { 9719 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9720 int SplatIdx = 9721 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9722 9723 // The splat index for permuted loads will be in the left half of the vector 9724 // which is strictly wider than the loaded value by 8 bytes. So we need to 9725 // adjust the splat index to point to the correct address in memory. 9726 if (IsPermutedLoad) { 9727 assert((isLittleEndian || IsFourByte) && 9728 "Unexpected size for permuted load on big endian target"); 9729 SplatIdx += IsFourByte ? 2 : 1; 9730 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9731 "Splat of a value outside of the loaded memory"); 9732 } 9733 9734 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9735 // For 4-byte load-and-splat, we need Power9. 9736 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9737 uint64_t Offset = 0; 9738 if (IsFourByte) 9739 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9740 else 9741 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9742 9743 // If the width of the load is the same as the width of the splat, 9744 // loading with an offset would load the wrong memory. 9745 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9746 Offset = 0; 9747 9748 SDValue BasePtr = LD->getBasePtr(); 9749 if (Offset != 0) 9750 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9751 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9752 SDValue Ops[] = { 9753 LD->getChain(), // Chain 9754 BasePtr, // BasePtr 9755 DAG.getValueType(Op.getValueType()) // VT 9756 }; 9757 SDVTList VTL = 9758 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9759 SDValue LdSplt = 9760 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9761 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9762 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9763 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9764 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9765 return LdSplt; 9766 } 9767 } 9768 if (Subtarget.hasP9Vector() && 9769 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9770 isLittleEndian)) { 9771 if (Swap) 9772 std::swap(V1, V2); 9773 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9774 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9775 if (ShiftElts) { 9776 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9777 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9778 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9779 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9780 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9781 } 9782 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9783 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9784 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9785 } 9786 9787 if (Subtarget.hasPrefixInstrs()) { 9788 SDValue SplatInsertNode; 9789 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9790 return SplatInsertNode; 9791 } 9792 9793 if (Subtarget.hasP9Altivec()) { 9794 SDValue NewISDNode; 9795 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9796 return NewISDNode; 9797 9798 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9799 return NewISDNode; 9800 } 9801 9802 if (Subtarget.hasVSX() && 9803 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9804 if (Swap) 9805 std::swap(V1, V2); 9806 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9807 SDValue Conv2 = 9808 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9809 9810 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9811 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9812 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9813 } 9814 9815 if (Subtarget.hasVSX() && 9816 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9817 if (Swap) 9818 std::swap(V1, V2); 9819 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9820 SDValue Conv2 = 9821 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9822 9823 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9824 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9825 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9826 } 9827 9828 if (Subtarget.hasP9Vector()) { 9829 if (PPC::isXXBRHShuffleMask(SVOp)) { 9830 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9831 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9832 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9833 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9834 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9835 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9836 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9837 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9838 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9839 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9840 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9841 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9842 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9843 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9844 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9845 } 9846 } 9847 9848 if (Subtarget.hasVSX()) { 9849 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9850 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9851 9852 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9853 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9854 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9855 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9856 } 9857 9858 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9859 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9860 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9861 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9862 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9863 } 9864 } 9865 9866 // Cases that are handled by instructions that take permute immediates 9867 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9868 // selected by the instruction selector. 9869 if (V2.isUndef()) { 9870 if (PPC::isSplatShuffleMask(SVOp, 1) || 9871 PPC::isSplatShuffleMask(SVOp, 2) || 9872 PPC::isSplatShuffleMask(SVOp, 4) || 9873 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9874 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9875 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9876 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9877 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9878 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9879 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9880 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9881 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9882 (Subtarget.hasP8Altivec() && ( 9883 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9884 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9885 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9886 return Op; 9887 } 9888 } 9889 9890 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9891 // and produce a fixed permutation. If any of these match, do not lower to 9892 // VPERM. 9893 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9894 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9895 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9896 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9897 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9898 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9899 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9900 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9901 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9902 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9903 (Subtarget.hasP8Altivec() && ( 9904 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9905 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9906 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9907 return Op; 9908 9909 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9910 // perfect shuffle table to emit an optimal matching sequence. 9911 ArrayRef<int> PermMask = SVOp->getMask(); 9912 9913 unsigned PFIndexes[4]; 9914 bool isFourElementShuffle = true; 9915 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9916 unsigned EltNo = 8; // Start out undef. 9917 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9918 if (PermMask[i*4+j] < 0) 9919 continue; // Undef, ignore it. 9920 9921 unsigned ByteSource = PermMask[i*4+j]; 9922 if ((ByteSource & 3) != j) { 9923 isFourElementShuffle = false; 9924 break; 9925 } 9926 9927 if (EltNo == 8) { 9928 EltNo = ByteSource/4; 9929 } else if (EltNo != ByteSource/4) { 9930 isFourElementShuffle = false; 9931 break; 9932 } 9933 } 9934 PFIndexes[i] = EltNo; 9935 } 9936 9937 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9938 // perfect shuffle vector to determine if it is cost effective to do this as 9939 // discrete instructions, or whether we should use a vperm. 9940 // For now, we skip this for little endian until such time as we have a 9941 // little-endian perfect shuffle table. 9942 if (isFourElementShuffle && !isLittleEndian) { 9943 // Compute the index in the perfect shuffle table. 9944 unsigned PFTableIndex = 9945 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9946 9947 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9948 unsigned Cost = (PFEntry >> 30); 9949 9950 // Determining when to avoid vperm is tricky. Many things affect the cost 9951 // of vperm, particularly how many times the perm mask needs to be computed. 9952 // For example, if the perm mask can be hoisted out of a loop or is already 9953 // used (perhaps because there are multiple permutes with the same shuffle 9954 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9955 // the loop requires an extra register. 9956 // 9957 // As a compromise, we only emit discrete instructions if the shuffle can be 9958 // generated in 3 or fewer operations. When we have loop information 9959 // available, if this block is within a loop, we should avoid using vperm 9960 // for 3-operation perms and use a constant pool load instead. 9961 if (Cost < 3) 9962 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9963 } 9964 9965 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9966 // vector that will get spilled to the constant pool. 9967 if (V2.isUndef()) V2 = V1; 9968 9969 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9970 // that it is in input element units, not in bytes. Convert now. 9971 9972 // For little endian, the order of the input vectors is reversed, and 9973 // the permutation mask is complemented with respect to 31. This is 9974 // necessary to produce proper semantics with the big-endian-biased vperm 9975 // instruction. 9976 EVT EltVT = V1.getValueType().getVectorElementType(); 9977 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9978 9979 SmallVector<SDValue, 16> ResultMask; 9980 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9981 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9982 9983 for (unsigned j = 0; j != BytesPerElement; ++j) 9984 if (isLittleEndian) 9985 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9986 dl, MVT::i32)); 9987 else 9988 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9989 MVT::i32)); 9990 } 9991 9992 ShufflesHandledWithVPERM++; 9993 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9994 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9995 LLVM_DEBUG(SVOp->dump()); 9996 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9997 LLVM_DEBUG(VPermMask.dump()); 9998 9999 if (isLittleEndian) 10000 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10001 V2, V1, VPermMask); 10002 else 10003 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10004 V1, V2, VPermMask); 10005 } 10006 10007 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10008 /// vector comparison. If it is, return true and fill in Opc/isDot with 10009 /// information about the intrinsic. 10010 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10011 bool &isDot, const PPCSubtarget &Subtarget) { 10012 unsigned IntrinsicID = 10013 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10014 CompareOpc = -1; 10015 isDot = false; 10016 switch (IntrinsicID) { 10017 default: 10018 return false; 10019 // Comparison predicates. 10020 case Intrinsic::ppc_altivec_vcmpbfp_p: 10021 CompareOpc = 966; 10022 isDot = true; 10023 break; 10024 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10025 CompareOpc = 198; 10026 isDot = true; 10027 break; 10028 case Intrinsic::ppc_altivec_vcmpequb_p: 10029 CompareOpc = 6; 10030 isDot = true; 10031 break; 10032 case Intrinsic::ppc_altivec_vcmpequh_p: 10033 CompareOpc = 70; 10034 isDot = true; 10035 break; 10036 case Intrinsic::ppc_altivec_vcmpequw_p: 10037 CompareOpc = 134; 10038 isDot = true; 10039 break; 10040 case Intrinsic::ppc_altivec_vcmpequd_p: 10041 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10042 CompareOpc = 199; 10043 isDot = true; 10044 } else 10045 return false; 10046 break; 10047 case Intrinsic::ppc_altivec_vcmpneb_p: 10048 case Intrinsic::ppc_altivec_vcmpneh_p: 10049 case Intrinsic::ppc_altivec_vcmpnew_p: 10050 case Intrinsic::ppc_altivec_vcmpnezb_p: 10051 case Intrinsic::ppc_altivec_vcmpnezh_p: 10052 case Intrinsic::ppc_altivec_vcmpnezw_p: 10053 if (Subtarget.hasP9Altivec()) { 10054 switch (IntrinsicID) { 10055 default: 10056 llvm_unreachable("Unknown comparison intrinsic."); 10057 case Intrinsic::ppc_altivec_vcmpneb_p: 10058 CompareOpc = 7; 10059 break; 10060 case Intrinsic::ppc_altivec_vcmpneh_p: 10061 CompareOpc = 71; 10062 break; 10063 case Intrinsic::ppc_altivec_vcmpnew_p: 10064 CompareOpc = 135; 10065 break; 10066 case Intrinsic::ppc_altivec_vcmpnezb_p: 10067 CompareOpc = 263; 10068 break; 10069 case Intrinsic::ppc_altivec_vcmpnezh_p: 10070 CompareOpc = 327; 10071 break; 10072 case Intrinsic::ppc_altivec_vcmpnezw_p: 10073 CompareOpc = 391; 10074 break; 10075 } 10076 isDot = true; 10077 } else 10078 return false; 10079 break; 10080 case Intrinsic::ppc_altivec_vcmpgefp_p: 10081 CompareOpc = 454; 10082 isDot = true; 10083 break; 10084 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10085 CompareOpc = 710; 10086 isDot = true; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10089 CompareOpc = 774; 10090 isDot = true; 10091 break; 10092 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10093 CompareOpc = 838; 10094 isDot = true; 10095 break; 10096 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10097 CompareOpc = 902; 10098 isDot = true; 10099 break; 10100 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10101 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10102 CompareOpc = 967; 10103 isDot = true; 10104 } else 10105 return false; 10106 break; 10107 case Intrinsic::ppc_altivec_vcmpgtub_p: 10108 CompareOpc = 518; 10109 isDot = true; 10110 break; 10111 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10112 CompareOpc = 582; 10113 isDot = true; 10114 break; 10115 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10116 CompareOpc = 646; 10117 isDot = true; 10118 break; 10119 case Intrinsic::ppc_altivec_vcmpgtud_p: 10120 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10121 CompareOpc = 711; 10122 isDot = true; 10123 } else 10124 return false; 10125 break; 10126 10127 case Intrinsic::ppc_altivec_vcmpequq: 10128 case Intrinsic::ppc_altivec_vcmpgtsq: 10129 case Intrinsic::ppc_altivec_vcmpgtuq: 10130 if (!Subtarget.isISA3_1()) 10131 return false; 10132 switch (IntrinsicID) { 10133 default: 10134 llvm_unreachable("Unknown comparison intrinsic."); 10135 case Intrinsic::ppc_altivec_vcmpequq: 10136 CompareOpc = 455; 10137 break; 10138 case Intrinsic::ppc_altivec_vcmpgtsq: 10139 CompareOpc = 903; 10140 break; 10141 case Intrinsic::ppc_altivec_vcmpgtuq: 10142 CompareOpc = 647; 10143 break; 10144 } 10145 break; 10146 10147 // VSX predicate comparisons use the same infrastructure 10148 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10149 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10150 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10151 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10152 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10153 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10154 if (Subtarget.hasVSX()) { 10155 switch (IntrinsicID) { 10156 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10157 CompareOpc = 99; 10158 break; 10159 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10160 CompareOpc = 115; 10161 break; 10162 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10163 CompareOpc = 107; 10164 break; 10165 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10166 CompareOpc = 67; 10167 break; 10168 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10169 CompareOpc = 83; 10170 break; 10171 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10172 CompareOpc = 75; 10173 break; 10174 } 10175 isDot = true; 10176 } else 10177 return false; 10178 break; 10179 10180 // Normal Comparisons. 10181 case Intrinsic::ppc_altivec_vcmpbfp: 10182 CompareOpc = 966; 10183 break; 10184 case Intrinsic::ppc_altivec_vcmpeqfp: 10185 CompareOpc = 198; 10186 break; 10187 case Intrinsic::ppc_altivec_vcmpequb: 10188 CompareOpc = 6; 10189 break; 10190 case Intrinsic::ppc_altivec_vcmpequh: 10191 CompareOpc = 70; 10192 break; 10193 case Intrinsic::ppc_altivec_vcmpequw: 10194 CompareOpc = 134; 10195 break; 10196 case Intrinsic::ppc_altivec_vcmpequd: 10197 if (Subtarget.hasP8Altivec()) 10198 CompareOpc = 199; 10199 else 10200 return false; 10201 break; 10202 case Intrinsic::ppc_altivec_vcmpneb: 10203 case Intrinsic::ppc_altivec_vcmpneh: 10204 case Intrinsic::ppc_altivec_vcmpnew: 10205 case Intrinsic::ppc_altivec_vcmpnezb: 10206 case Intrinsic::ppc_altivec_vcmpnezh: 10207 case Intrinsic::ppc_altivec_vcmpnezw: 10208 if (Subtarget.hasP9Altivec()) 10209 switch (IntrinsicID) { 10210 default: 10211 llvm_unreachable("Unknown comparison intrinsic."); 10212 case Intrinsic::ppc_altivec_vcmpneb: 10213 CompareOpc = 7; 10214 break; 10215 case Intrinsic::ppc_altivec_vcmpneh: 10216 CompareOpc = 71; 10217 break; 10218 case Intrinsic::ppc_altivec_vcmpnew: 10219 CompareOpc = 135; 10220 break; 10221 case Intrinsic::ppc_altivec_vcmpnezb: 10222 CompareOpc = 263; 10223 break; 10224 case Intrinsic::ppc_altivec_vcmpnezh: 10225 CompareOpc = 327; 10226 break; 10227 case Intrinsic::ppc_altivec_vcmpnezw: 10228 CompareOpc = 391; 10229 break; 10230 } 10231 else 10232 return false; 10233 break; 10234 case Intrinsic::ppc_altivec_vcmpgefp: 10235 CompareOpc = 454; 10236 break; 10237 case Intrinsic::ppc_altivec_vcmpgtfp: 10238 CompareOpc = 710; 10239 break; 10240 case Intrinsic::ppc_altivec_vcmpgtsb: 10241 CompareOpc = 774; 10242 break; 10243 case Intrinsic::ppc_altivec_vcmpgtsh: 10244 CompareOpc = 838; 10245 break; 10246 case Intrinsic::ppc_altivec_vcmpgtsw: 10247 CompareOpc = 902; 10248 break; 10249 case Intrinsic::ppc_altivec_vcmpgtsd: 10250 if (Subtarget.hasP8Altivec()) 10251 CompareOpc = 967; 10252 else 10253 return false; 10254 break; 10255 case Intrinsic::ppc_altivec_vcmpgtub: 10256 CompareOpc = 518; 10257 break; 10258 case Intrinsic::ppc_altivec_vcmpgtuh: 10259 CompareOpc = 582; 10260 break; 10261 case Intrinsic::ppc_altivec_vcmpgtuw: 10262 CompareOpc = 646; 10263 break; 10264 case Intrinsic::ppc_altivec_vcmpgtud: 10265 if (Subtarget.hasP8Altivec()) 10266 CompareOpc = 711; 10267 else 10268 return false; 10269 break; 10270 case Intrinsic::ppc_altivec_vcmpequq_p: 10271 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10272 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10273 if (!Subtarget.isISA3_1()) 10274 return false; 10275 switch (IntrinsicID) { 10276 default: 10277 llvm_unreachable("Unknown comparison intrinsic."); 10278 case Intrinsic::ppc_altivec_vcmpequq_p: 10279 CompareOpc = 455; 10280 break; 10281 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10282 CompareOpc = 903; 10283 break; 10284 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10285 CompareOpc = 647; 10286 break; 10287 } 10288 isDot = true; 10289 break; 10290 } 10291 return true; 10292 } 10293 10294 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10295 /// lower, do it, otherwise return null. 10296 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10297 SelectionDAG &DAG) const { 10298 unsigned IntrinsicID = 10299 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10300 10301 SDLoc dl(Op); 10302 10303 switch (IntrinsicID) { 10304 case Intrinsic::thread_pointer: 10305 // Reads the thread pointer register, used for __builtin_thread_pointer. 10306 if (Subtarget.isPPC64()) 10307 return DAG.getRegister(PPC::X13, MVT::i64); 10308 return DAG.getRegister(PPC::R2, MVT::i32); 10309 10310 case Intrinsic::ppc_mma_disassemble_acc: 10311 case Intrinsic::ppc_vsx_disassemble_pair: { 10312 int NumVecs = 2; 10313 SDValue WideVec = Op.getOperand(1); 10314 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10315 NumVecs = 4; 10316 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10317 } 10318 SmallVector<SDValue, 4> RetOps; 10319 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10320 SDValue Extract = DAG.getNode( 10321 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10322 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10323 : VecNo, 10324 dl, getPointerTy(DAG.getDataLayout()))); 10325 RetOps.push_back(Extract); 10326 } 10327 return DAG.getMergeValues(RetOps, dl); 10328 } 10329 } 10330 10331 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10332 // opcode number of the comparison. 10333 int CompareOpc; 10334 bool isDot; 10335 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10336 return SDValue(); // Don't custom lower most intrinsics. 10337 10338 // If this is a non-dot comparison, make the VCMP node and we are done. 10339 if (!isDot) { 10340 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10341 Op.getOperand(1), Op.getOperand(2), 10342 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10343 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10344 } 10345 10346 // Create the PPCISD altivec 'dot' comparison node. 10347 SDValue Ops[] = { 10348 Op.getOperand(2), // LHS 10349 Op.getOperand(3), // RHS 10350 DAG.getConstant(CompareOpc, dl, MVT::i32) 10351 }; 10352 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10353 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10354 10355 // Now that we have the comparison, emit a copy from the CR to a GPR. 10356 // This is flagged to the above dot comparison. 10357 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10358 DAG.getRegister(PPC::CR6, MVT::i32), 10359 CompNode.getValue(1)); 10360 10361 // Unpack the result based on how the target uses it. 10362 unsigned BitNo; // Bit # of CR6. 10363 bool InvertBit; // Invert result? 10364 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10365 default: // Can't happen, don't crash on invalid number though. 10366 case 0: // Return the value of the EQ bit of CR6. 10367 BitNo = 0; InvertBit = false; 10368 break; 10369 case 1: // Return the inverted value of the EQ bit of CR6. 10370 BitNo = 0; InvertBit = true; 10371 break; 10372 case 2: // Return the value of the LT bit of CR6. 10373 BitNo = 2; InvertBit = false; 10374 break; 10375 case 3: // Return the inverted value of the LT bit of CR6. 10376 BitNo = 2; InvertBit = true; 10377 break; 10378 } 10379 10380 // Shift the bit into the low position. 10381 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10382 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10383 // Isolate the bit. 10384 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10385 DAG.getConstant(1, dl, MVT::i32)); 10386 10387 // If we are supposed to, toggle the bit. 10388 if (InvertBit) 10389 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10390 DAG.getConstant(1, dl, MVT::i32)); 10391 return Flags; 10392 } 10393 10394 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10395 SelectionDAG &DAG) const { 10396 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10397 // the beginning of the argument list. 10398 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10399 SDLoc DL(Op); 10400 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10401 case Intrinsic::ppc_cfence: { 10402 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10403 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10404 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10405 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10406 Op.getOperand(ArgStart + 1)), 10407 Op.getOperand(0)), 10408 0); 10409 } 10410 default: 10411 break; 10412 } 10413 return SDValue(); 10414 } 10415 10416 // Lower scalar BSWAP64 to xxbrd. 10417 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10418 SDLoc dl(Op); 10419 if (!Subtarget.isPPC64()) 10420 return Op; 10421 // MTVSRDD 10422 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10423 Op.getOperand(0)); 10424 // XXBRD 10425 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10426 // MFVSRD 10427 int VectorIndex = 0; 10428 if (Subtarget.isLittleEndian()) 10429 VectorIndex = 1; 10430 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10431 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10432 return Op; 10433 } 10434 10435 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10436 // compared to a value that is atomically loaded (atomic loads zero-extend). 10437 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10438 SelectionDAG &DAG) const { 10439 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10440 "Expecting an atomic compare-and-swap here."); 10441 SDLoc dl(Op); 10442 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10443 EVT MemVT = AtomicNode->getMemoryVT(); 10444 if (MemVT.getSizeInBits() >= 32) 10445 return Op; 10446 10447 SDValue CmpOp = Op.getOperand(2); 10448 // If this is already correctly zero-extended, leave it alone. 10449 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10450 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10451 return Op; 10452 10453 // Clear the high bits of the compare operand. 10454 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10455 SDValue NewCmpOp = 10456 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10457 DAG.getConstant(MaskVal, dl, MVT::i32)); 10458 10459 // Replace the existing compare operand with the properly zero-extended one. 10460 SmallVector<SDValue, 4> Ops; 10461 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10462 Ops.push_back(AtomicNode->getOperand(i)); 10463 Ops[2] = NewCmpOp; 10464 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10465 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10466 auto NodeTy = 10467 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10468 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10469 } 10470 10471 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10472 SelectionDAG &DAG) const { 10473 SDLoc dl(Op); 10474 // Create a stack slot that is 16-byte aligned. 10475 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10476 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10477 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10478 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10479 10480 // Store the input value into Value#0 of the stack slot. 10481 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10482 MachinePointerInfo()); 10483 // Load it out. 10484 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10485 } 10486 10487 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10488 SelectionDAG &DAG) const { 10489 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10490 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10491 10492 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10493 10494 EVT VT = Op.getValueType(); 10495 SDLoc dl(Op); 10496 SDValue V1 = Op.getOperand(0); 10497 SDValue V2 = Op.getOperand(1); 10498 SDValue V3 = Op.getOperand(2); 10499 10500 if (VT == MVT::v2f64 && C) 10501 return Op; 10502 10503 if (Subtarget.isISA3_1()) { 10504 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64()) 10505 return SDValue(); 10506 // On P10, we have legal lowering for constant and variable indices for 10507 // integer vectors. 10508 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10509 VT == MVT::v2i64) 10510 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10511 // For f32 and f64 vectors, we have legal lowering for variable indices. 10512 // For f32 we also have legal lowering when the element is loaded from 10513 // memory. 10514 if (VT == MVT::v4f32 || VT == MVT::v2f64) { 10515 if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2))) 10516 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10517 return Op; 10518 } 10519 } 10520 10521 // Before P10, we have legal lowering for constant indices but not for 10522 // variable ones. 10523 if (!C) 10524 return SDValue(); 10525 10526 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10527 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10528 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10529 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10530 unsigned InsertAtElement = C->getZExtValue(); 10531 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10532 if (Subtarget.isLittleEndian()) { 10533 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10534 } 10535 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10536 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10537 } 10538 return Op; 10539 } 10540 10541 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10542 SelectionDAG &DAG) const { 10543 SDLoc dl(Op); 10544 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10545 SDValue LoadChain = LN->getChain(); 10546 SDValue BasePtr = LN->getBasePtr(); 10547 EVT VT = Op.getValueType(); 10548 10549 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10550 return Op; 10551 10552 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10553 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10554 // 2 or 4 vsx registers. 10555 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10556 "Type unsupported without MMA"); 10557 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10558 "Type unsupported without paired vector support"); 10559 Align Alignment = LN->getAlign(); 10560 SmallVector<SDValue, 4> Loads; 10561 SmallVector<SDValue, 4> LoadChains; 10562 unsigned NumVecs = VT.getSizeInBits() / 128; 10563 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10564 SDValue Load = 10565 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10566 LN->getPointerInfo().getWithOffset(Idx * 16), 10567 commonAlignment(Alignment, Idx * 16), 10568 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10569 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10570 DAG.getConstant(16, dl, BasePtr.getValueType())); 10571 Loads.push_back(Load); 10572 LoadChains.push_back(Load.getValue(1)); 10573 } 10574 if (Subtarget.isLittleEndian()) { 10575 std::reverse(Loads.begin(), Loads.end()); 10576 std::reverse(LoadChains.begin(), LoadChains.end()); 10577 } 10578 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10579 SDValue Value = 10580 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10581 dl, VT, Loads); 10582 SDValue RetOps[] = {Value, TF}; 10583 return DAG.getMergeValues(RetOps, dl); 10584 } 10585 10586 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10587 SelectionDAG &DAG) const { 10588 SDLoc dl(Op); 10589 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10590 SDValue StoreChain = SN->getChain(); 10591 SDValue BasePtr = SN->getBasePtr(); 10592 SDValue Value = SN->getValue(); 10593 EVT StoreVT = Value.getValueType(); 10594 10595 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10596 return Op; 10597 10598 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10599 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10600 // underlying registers individually. 10601 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10602 "Type unsupported without MMA"); 10603 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10604 "Type unsupported without paired vector support"); 10605 Align Alignment = SN->getAlign(); 10606 SmallVector<SDValue, 4> Stores; 10607 unsigned NumVecs = 2; 10608 if (StoreVT == MVT::v512i1) { 10609 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10610 NumVecs = 4; 10611 } 10612 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10613 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10614 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10615 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 10616 SDValue Store = 10617 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10618 SN->getPointerInfo().getWithOffset(Idx * 16), 10619 commonAlignment(Alignment, Idx * 16), 10620 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10621 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10622 DAG.getConstant(16, dl, BasePtr.getValueType())); 10623 Stores.push_back(Store); 10624 } 10625 SDValue TF = DAG.getTokenFactor(dl, Stores); 10626 return TF; 10627 } 10628 10629 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10630 SDLoc dl(Op); 10631 if (Op.getValueType() == MVT::v4i32) { 10632 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10633 10634 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10635 // +16 as shift amt. 10636 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10637 SDValue RHSSwap = // = vrlw RHS, 16 10638 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10639 10640 // Shrinkify inputs to v8i16. 10641 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10642 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10643 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10644 10645 // Low parts multiplied together, generating 32-bit results (we ignore the 10646 // top parts). 10647 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10648 LHS, RHS, DAG, dl, MVT::v4i32); 10649 10650 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10651 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10652 // Shift the high parts up 16 bits. 10653 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10654 Neg16, DAG, dl); 10655 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10656 } else if (Op.getValueType() == MVT::v16i8) { 10657 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10658 bool isLittleEndian = Subtarget.isLittleEndian(); 10659 10660 // Multiply the even 8-bit parts, producing 16-bit sums. 10661 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10662 LHS, RHS, DAG, dl, MVT::v8i16); 10663 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10664 10665 // Multiply the odd 8-bit parts, producing 16-bit sums. 10666 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10667 LHS, RHS, DAG, dl, MVT::v8i16); 10668 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10669 10670 // Merge the results together. Because vmuleub and vmuloub are 10671 // instructions with a big-endian bias, we must reverse the 10672 // element numbering and reverse the meaning of "odd" and "even" 10673 // when generating little endian code. 10674 int Ops[16]; 10675 for (unsigned i = 0; i != 8; ++i) { 10676 if (isLittleEndian) { 10677 Ops[i*2 ] = 2*i; 10678 Ops[i*2+1] = 2*i+16; 10679 } else { 10680 Ops[i*2 ] = 2*i+1; 10681 Ops[i*2+1] = 2*i+1+16; 10682 } 10683 } 10684 if (isLittleEndian) 10685 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10686 else 10687 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10688 } else { 10689 llvm_unreachable("Unknown mul to lower!"); 10690 } 10691 } 10692 10693 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10694 bool IsStrict = Op->isStrictFPOpcode(); 10695 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10696 !Subtarget.hasP9Vector()) 10697 return SDValue(); 10698 10699 return Op; 10700 } 10701 10702 // Custom lowering for fpext vf32 to v2f64 10703 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10704 10705 assert(Op.getOpcode() == ISD::FP_EXTEND && 10706 "Should only be called for ISD::FP_EXTEND"); 10707 10708 // FIXME: handle extends from half precision float vectors on P9. 10709 // We only want to custom lower an extend from v2f32 to v2f64. 10710 if (Op.getValueType() != MVT::v2f64 || 10711 Op.getOperand(0).getValueType() != MVT::v2f32) 10712 return SDValue(); 10713 10714 SDLoc dl(Op); 10715 SDValue Op0 = Op.getOperand(0); 10716 10717 switch (Op0.getOpcode()) { 10718 default: 10719 return SDValue(); 10720 case ISD::EXTRACT_SUBVECTOR: { 10721 assert(Op0.getNumOperands() == 2 && 10722 isa<ConstantSDNode>(Op0->getOperand(1)) && 10723 "Node should have 2 operands with second one being a constant!"); 10724 10725 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10726 return SDValue(); 10727 10728 // Custom lower is only done for high or low doubleword. 10729 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10730 if (Idx % 2 != 0) 10731 return SDValue(); 10732 10733 // Since input is v4f32, at this point Idx is either 0 or 2. 10734 // Shift to get the doubleword position we want. 10735 int DWord = Idx >> 1; 10736 10737 // High and low word positions are different on little endian. 10738 if (Subtarget.isLittleEndian()) 10739 DWord ^= 0x1; 10740 10741 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10742 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10743 } 10744 case ISD::FADD: 10745 case ISD::FMUL: 10746 case ISD::FSUB: { 10747 SDValue NewLoad[2]; 10748 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10749 // Ensure both input are loads. 10750 SDValue LdOp = Op0.getOperand(i); 10751 if (LdOp.getOpcode() != ISD::LOAD) 10752 return SDValue(); 10753 // Generate new load node. 10754 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10755 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10756 NewLoad[i] = DAG.getMemIntrinsicNode( 10757 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10758 LD->getMemoryVT(), LD->getMemOperand()); 10759 } 10760 SDValue NewOp = 10761 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10762 NewLoad[1], Op0.getNode()->getFlags()); 10763 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10764 DAG.getConstant(0, dl, MVT::i32)); 10765 } 10766 case ISD::LOAD: { 10767 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10768 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10769 SDValue NewLd = DAG.getMemIntrinsicNode( 10770 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10771 LD->getMemoryVT(), LD->getMemOperand()); 10772 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10773 DAG.getConstant(0, dl, MVT::i32)); 10774 } 10775 } 10776 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10777 } 10778 10779 /// LowerOperation - Provide custom lowering hooks for some operations. 10780 /// 10781 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10782 switch (Op.getOpcode()) { 10783 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10784 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10785 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10786 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10787 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10788 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10789 case ISD::STRICT_FSETCC: 10790 case ISD::STRICT_FSETCCS: 10791 case ISD::SETCC: return LowerSETCC(Op, DAG); 10792 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10793 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10794 10795 case ISD::INLINEASM: 10796 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG); 10797 // Variable argument lowering. 10798 case ISD::VASTART: return LowerVASTART(Op, DAG); 10799 case ISD::VAARG: return LowerVAARG(Op, DAG); 10800 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10801 10802 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10803 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10804 case ISD::GET_DYNAMIC_AREA_OFFSET: 10805 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10806 10807 // Exception handling lowering. 10808 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10809 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10810 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10811 10812 case ISD::LOAD: return LowerLOAD(Op, DAG); 10813 case ISD::STORE: return LowerSTORE(Op, DAG); 10814 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10815 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10816 case ISD::STRICT_FP_TO_UINT: 10817 case ISD::STRICT_FP_TO_SINT: 10818 case ISD::FP_TO_UINT: 10819 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10820 case ISD::STRICT_UINT_TO_FP: 10821 case ISD::STRICT_SINT_TO_FP: 10822 case ISD::UINT_TO_FP: 10823 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10824 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10825 10826 // Lower 64-bit shifts. 10827 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10828 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10829 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10830 10831 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10832 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10833 10834 // Vector-related lowering. 10835 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10836 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10837 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10838 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10839 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10840 case ISD::MUL: return LowerMUL(Op, DAG); 10841 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10842 case ISD::STRICT_FP_ROUND: 10843 case ISD::FP_ROUND: 10844 return LowerFP_ROUND(Op, DAG); 10845 case ISD::ROTL: return LowerROTL(Op, DAG); 10846 10847 // For counter-based loop handling. 10848 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10849 10850 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10851 10852 // Frame & Return address. 10853 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10854 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10855 10856 case ISD::INTRINSIC_VOID: 10857 return LowerINTRINSIC_VOID(Op, DAG); 10858 case ISD::BSWAP: 10859 return LowerBSWAP(Op, DAG); 10860 case ISD::ATOMIC_CMP_SWAP: 10861 return LowerATOMIC_CMP_SWAP(Op, DAG); 10862 } 10863 } 10864 10865 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10866 SmallVectorImpl<SDValue>&Results, 10867 SelectionDAG &DAG) const { 10868 SDLoc dl(N); 10869 switch (N->getOpcode()) { 10870 default: 10871 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10872 case ISD::READCYCLECOUNTER: { 10873 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10874 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10875 10876 Results.push_back( 10877 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10878 Results.push_back(RTB.getValue(2)); 10879 break; 10880 } 10881 case ISD::INTRINSIC_W_CHAIN: { 10882 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10883 Intrinsic::loop_decrement) 10884 break; 10885 10886 assert(N->getValueType(0) == MVT::i1 && 10887 "Unexpected result type for CTR decrement intrinsic"); 10888 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10889 N->getValueType(0)); 10890 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10891 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10892 N->getOperand(1)); 10893 10894 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10895 Results.push_back(NewInt.getValue(1)); 10896 break; 10897 } 10898 case ISD::VAARG: { 10899 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10900 return; 10901 10902 EVT VT = N->getValueType(0); 10903 10904 if (VT == MVT::i64) { 10905 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10906 10907 Results.push_back(NewNode); 10908 Results.push_back(NewNode.getValue(1)); 10909 } 10910 return; 10911 } 10912 case ISD::STRICT_FP_TO_SINT: 10913 case ISD::STRICT_FP_TO_UINT: 10914 case ISD::FP_TO_SINT: 10915 case ISD::FP_TO_UINT: 10916 // LowerFP_TO_INT() can only handle f32 and f64. 10917 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10918 MVT::ppcf128) 10919 return; 10920 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10921 return; 10922 case ISD::TRUNCATE: { 10923 if (!N->getValueType(0).isVector()) 10924 return; 10925 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10926 if (Lowered) 10927 Results.push_back(Lowered); 10928 return; 10929 } 10930 case ISD::FSHL: 10931 case ISD::FSHR: 10932 // Don't handle funnel shifts here. 10933 return; 10934 case ISD::BITCAST: 10935 // Don't handle bitcast here. 10936 return; 10937 case ISD::FP_EXTEND: 10938 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10939 if (Lowered) 10940 Results.push_back(Lowered); 10941 return; 10942 } 10943 } 10944 10945 //===----------------------------------------------------------------------===// 10946 // Other Lowering Code 10947 //===----------------------------------------------------------------------===// 10948 10949 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) { 10950 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10951 Function *Func = Intrinsic::getDeclaration(M, Id); 10952 return Builder.CreateCall(Func, {}); 10953 } 10954 10955 // The mappings for emitLeading/TrailingFence is taken from 10956 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10957 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10958 Instruction *Inst, 10959 AtomicOrdering Ord) const { 10960 if (Ord == AtomicOrdering::SequentiallyConsistent) 10961 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10962 if (isReleaseOrStronger(Ord)) 10963 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10964 return nullptr; 10965 } 10966 10967 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10968 Instruction *Inst, 10969 AtomicOrdering Ord) const { 10970 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10971 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10972 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10973 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10974 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10975 return Builder.CreateCall( 10976 Intrinsic::getDeclaration( 10977 Builder.GetInsertBlock()->getParent()->getParent(), 10978 Intrinsic::ppc_cfence, {Inst->getType()}), 10979 {Inst}); 10980 // FIXME: Can use isync for rmw operation. 10981 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10982 } 10983 return nullptr; 10984 } 10985 10986 MachineBasicBlock * 10987 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10988 unsigned AtomicSize, 10989 unsigned BinOpcode, 10990 unsigned CmpOpcode, 10991 unsigned CmpPred) const { 10992 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10993 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10994 10995 auto LoadMnemonic = PPC::LDARX; 10996 auto StoreMnemonic = PPC::STDCX; 10997 switch (AtomicSize) { 10998 default: 10999 llvm_unreachable("Unexpected size of atomic entity"); 11000 case 1: 11001 LoadMnemonic = PPC::LBARX; 11002 StoreMnemonic = PPC::STBCX; 11003 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11004 break; 11005 case 2: 11006 LoadMnemonic = PPC::LHARX; 11007 StoreMnemonic = PPC::STHCX; 11008 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11009 break; 11010 case 4: 11011 LoadMnemonic = PPC::LWARX; 11012 StoreMnemonic = PPC::STWCX; 11013 break; 11014 case 8: 11015 LoadMnemonic = PPC::LDARX; 11016 StoreMnemonic = PPC::STDCX; 11017 break; 11018 } 11019 11020 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11021 MachineFunction *F = BB->getParent(); 11022 MachineFunction::iterator It = ++BB->getIterator(); 11023 11024 Register dest = MI.getOperand(0).getReg(); 11025 Register ptrA = MI.getOperand(1).getReg(); 11026 Register ptrB = MI.getOperand(2).getReg(); 11027 Register incr = MI.getOperand(3).getReg(); 11028 DebugLoc dl = MI.getDebugLoc(); 11029 11030 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11031 MachineBasicBlock *loop2MBB = 11032 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11033 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11034 F->insert(It, loopMBB); 11035 if (CmpOpcode) 11036 F->insert(It, loop2MBB); 11037 F->insert(It, exitMBB); 11038 exitMBB->splice(exitMBB->begin(), BB, 11039 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11040 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11041 11042 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11043 Register TmpReg = (!BinOpcode) ? incr : 11044 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11045 : &PPC::GPRCRegClass); 11046 11047 // thisMBB: 11048 // ... 11049 // fallthrough --> loopMBB 11050 BB->addSuccessor(loopMBB); 11051 11052 // loopMBB: 11053 // l[wd]arx dest, ptr 11054 // add r0, dest, incr 11055 // st[wd]cx. r0, ptr 11056 // bne- loopMBB 11057 // fallthrough --> exitMBB 11058 11059 // For max/min... 11060 // loopMBB: 11061 // l[wd]arx dest, ptr 11062 // cmpl?[wd] incr, dest 11063 // bgt exitMBB 11064 // loop2MBB: 11065 // st[wd]cx. dest, ptr 11066 // bne- loopMBB 11067 // fallthrough --> exitMBB 11068 11069 BB = loopMBB; 11070 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11071 .addReg(ptrA).addReg(ptrB); 11072 if (BinOpcode) 11073 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11074 if (CmpOpcode) { 11075 // Signed comparisons of byte or halfword values must be sign-extended. 11076 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11077 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11078 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11079 ExtReg).addReg(dest); 11080 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11081 .addReg(incr).addReg(ExtReg); 11082 } else 11083 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11084 .addReg(incr).addReg(dest); 11085 11086 BuildMI(BB, dl, TII->get(PPC::BCC)) 11087 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11088 BB->addSuccessor(loop2MBB); 11089 BB->addSuccessor(exitMBB); 11090 BB = loop2MBB; 11091 } 11092 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11093 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11094 BuildMI(BB, dl, TII->get(PPC::BCC)) 11095 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11096 BB->addSuccessor(loopMBB); 11097 BB->addSuccessor(exitMBB); 11098 11099 // exitMBB: 11100 // ... 11101 BB = exitMBB; 11102 return BB; 11103 } 11104 11105 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 11106 switch(MI.getOpcode()) { 11107 default: 11108 return false; 11109 case PPC::COPY: 11110 return TII->isSignExtended(MI); 11111 case PPC::LHA: 11112 case PPC::LHA8: 11113 case PPC::LHAU: 11114 case PPC::LHAU8: 11115 case PPC::LHAUX: 11116 case PPC::LHAUX8: 11117 case PPC::LHAX: 11118 case PPC::LHAX8: 11119 case PPC::LWA: 11120 case PPC::LWAUX: 11121 case PPC::LWAX: 11122 case PPC::LWAX_32: 11123 case PPC::LWA_32: 11124 case PPC::PLHA: 11125 case PPC::PLHA8: 11126 case PPC::PLHA8pc: 11127 case PPC::PLHApc: 11128 case PPC::PLWA: 11129 case PPC::PLWA8: 11130 case PPC::PLWA8pc: 11131 case PPC::PLWApc: 11132 case PPC::EXTSB: 11133 case PPC::EXTSB8: 11134 case PPC::EXTSB8_32_64: 11135 case PPC::EXTSB8_rec: 11136 case PPC::EXTSB_rec: 11137 case PPC::EXTSH: 11138 case PPC::EXTSH8: 11139 case PPC::EXTSH8_32_64: 11140 case PPC::EXTSH8_rec: 11141 case PPC::EXTSH_rec: 11142 case PPC::EXTSW: 11143 case PPC::EXTSWSLI: 11144 case PPC::EXTSWSLI_32_64: 11145 case PPC::EXTSWSLI_32_64_rec: 11146 case PPC::EXTSWSLI_rec: 11147 case PPC::EXTSW_32: 11148 case PPC::EXTSW_32_64: 11149 case PPC::EXTSW_32_64_rec: 11150 case PPC::EXTSW_rec: 11151 case PPC::SRAW: 11152 case PPC::SRAWI: 11153 case PPC::SRAWI_rec: 11154 case PPC::SRAW_rec: 11155 return true; 11156 } 11157 return false; 11158 } 11159 11160 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11161 MachineInstr &MI, MachineBasicBlock *BB, 11162 bool is8bit, // operation 11163 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11164 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11165 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 11166 11167 // If this is a signed comparison and the value being compared is not known 11168 // to be sign extended, sign extend it here. 11169 DebugLoc dl = MI.getDebugLoc(); 11170 MachineFunction *F = BB->getParent(); 11171 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11172 Register incr = MI.getOperand(3).getReg(); 11173 bool IsSignExtended = Register::isVirtualRegister(incr) && 11174 isSignExtended(*RegInfo.getVRegDef(incr), TII); 11175 11176 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11177 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11178 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11179 .addReg(MI.getOperand(3).getReg()); 11180 MI.getOperand(3).setReg(ValueReg); 11181 } 11182 // If we support part-word atomic mnemonics, just use them 11183 if (Subtarget.hasPartwordAtomics()) 11184 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11185 CmpPred); 11186 11187 // In 64 bit mode we have to use 64 bits for addresses, even though the 11188 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11189 // registers without caring whether they're 32 or 64, but here we're 11190 // doing actual arithmetic on the addresses. 11191 bool is64bit = Subtarget.isPPC64(); 11192 bool isLittleEndian = Subtarget.isLittleEndian(); 11193 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11194 11195 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11196 MachineFunction::iterator It = ++BB->getIterator(); 11197 11198 Register dest = MI.getOperand(0).getReg(); 11199 Register ptrA = MI.getOperand(1).getReg(); 11200 Register ptrB = MI.getOperand(2).getReg(); 11201 11202 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11203 MachineBasicBlock *loop2MBB = 11204 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11205 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11206 F->insert(It, loopMBB); 11207 if (CmpOpcode) 11208 F->insert(It, loop2MBB); 11209 F->insert(It, exitMBB); 11210 exitMBB->splice(exitMBB->begin(), BB, 11211 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11212 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11213 11214 const TargetRegisterClass *RC = 11215 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11216 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11217 11218 Register PtrReg = RegInfo.createVirtualRegister(RC); 11219 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11220 Register ShiftReg = 11221 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11222 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11223 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11224 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11225 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11226 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11227 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11228 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11229 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11230 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC); 11231 Register Ptr1Reg; 11232 Register TmpReg = 11233 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11234 11235 // thisMBB: 11236 // ... 11237 // fallthrough --> loopMBB 11238 BB->addSuccessor(loopMBB); 11239 11240 // The 4-byte load must be aligned, while a char or short may be 11241 // anywhere in the word. Hence all this nasty bookkeeping code. 11242 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11243 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11244 // xori shift, shift1, 24 [16] 11245 // rlwinm ptr, ptr1, 0, 0, 29 11246 // slw incr2, incr, shift 11247 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11248 // slw mask, mask2, shift 11249 // loopMBB: 11250 // lwarx tmpDest, ptr 11251 // add tmp, tmpDest, incr2 11252 // andc tmp2, tmpDest, mask 11253 // and tmp3, tmp, mask 11254 // or tmp4, tmp3, tmp2 11255 // stwcx. tmp4, ptr 11256 // bne- loopMBB 11257 // fallthrough --> exitMBB 11258 // srw SrwDest, tmpDest, shift 11259 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31 11260 if (ptrA != ZeroReg) { 11261 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11262 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11263 .addReg(ptrA) 11264 .addReg(ptrB); 11265 } else { 11266 Ptr1Reg = ptrB; 11267 } 11268 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11269 // mode. 11270 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11271 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11272 .addImm(3) 11273 .addImm(27) 11274 .addImm(is8bit ? 28 : 27); 11275 if (!isLittleEndian) 11276 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11277 .addReg(Shift1Reg) 11278 .addImm(is8bit ? 24 : 16); 11279 if (is64bit) 11280 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11281 .addReg(Ptr1Reg) 11282 .addImm(0) 11283 .addImm(61); 11284 else 11285 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11286 .addReg(Ptr1Reg) 11287 .addImm(0) 11288 .addImm(0) 11289 .addImm(29); 11290 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11291 if (is8bit) 11292 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11293 else { 11294 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11295 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11296 .addReg(Mask3Reg) 11297 .addImm(65535); 11298 } 11299 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11300 .addReg(Mask2Reg) 11301 .addReg(ShiftReg); 11302 11303 BB = loopMBB; 11304 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11305 .addReg(ZeroReg) 11306 .addReg(PtrReg); 11307 if (BinOpcode) 11308 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11309 .addReg(Incr2Reg) 11310 .addReg(TmpDestReg); 11311 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11312 .addReg(TmpDestReg) 11313 .addReg(MaskReg); 11314 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11315 if (CmpOpcode) { 11316 // For unsigned comparisons, we can directly compare the shifted values. 11317 // For signed comparisons we shift and sign extend. 11318 Register SReg = RegInfo.createVirtualRegister(GPRC); 11319 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11320 .addReg(TmpDestReg) 11321 .addReg(MaskReg); 11322 unsigned ValueReg = SReg; 11323 unsigned CmpReg = Incr2Reg; 11324 if (CmpOpcode == PPC::CMPW) { 11325 ValueReg = RegInfo.createVirtualRegister(GPRC); 11326 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11327 .addReg(SReg) 11328 .addReg(ShiftReg); 11329 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11330 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11331 .addReg(ValueReg); 11332 ValueReg = ValueSReg; 11333 CmpReg = incr; 11334 } 11335 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11336 .addReg(CmpReg) 11337 .addReg(ValueReg); 11338 BuildMI(BB, dl, TII->get(PPC::BCC)) 11339 .addImm(CmpPred) 11340 .addReg(PPC::CR0) 11341 .addMBB(exitMBB); 11342 BB->addSuccessor(loop2MBB); 11343 BB->addSuccessor(exitMBB); 11344 BB = loop2MBB; 11345 } 11346 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11347 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11348 .addReg(Tmp4Reg) 11349 .addReg(ZeroReg) 11350 .addReg(PtrReg); 11351 BuildMI(BB, dl, TII->get(PPC::BCC)) 11352 .addImm(PPC::PRED_NE) 11353 .addReg(PPC::CR0) 11354 .addMBB(loopMBB); 11355 BB->addSuccessor(loopMBB); 11356 BB->addSuccessor(exitMBB); 11357 11358 // exitMBB: 11359 // ... 11360 BB = exitMBB; 11361 // Since the shift amount is not a constant, we need to clear 11362 // the upper bits with a separate RLWINM. 11363 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest) 11364 .addReg(SrwDestReg) 11365 .addImm(0) 11366 .addImm(is8bit ? 24 : 16) 11367 .addImm(31); 11368 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg) 11369 .addReg(TmpDestReg) 11370 .addReg(ShiftReg); 11371 return BB; 11372 } 11373 11374 llvm::MachineBasicBlock * 11375 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11376 MachineBasicBlock *MBB) const { 11377 DebugLoc DL = MI.getDebugLoc(); 11378 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11379 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11380 11381 MachineFunction *MF = MBB->getParent(); 11382 MachineRegisterInfo &MRI = MF->getRegInfo(); 11383 11384 const BasicBlock *BB = MBB->getBasicBlock(); 11385 MachineFunction::iterator I = ++MBB->getIterator(); 11386 11387 Register DstReg = MI.getOperand(0).getReg(); 11388 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11389 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11390 Register mainDstReg = MRI.createVirtualRegister(RC); 11391 Register restoreDstReg = MRI.createVirtualRegister(RC); 11392 11393 MVT PVT = getPointerTy(MF->getDataLayout()); 11394 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11395 "Invalid Pointer Size!"); 11396 // For v = setjmp(buf), we generate 11397 // 11398 // thisMBB: 11399 // SjLjSetup mainMBB 11400 // bl mainMBB 11401 // v_restore = 1 11402 // b sinkMBB 11403 // 11404 // mainMBB: 11405 // buf[LabelOffset] = LR 11406 // v_main = 0 11407 // 11408 // sinkMBB: 11409 // v = phi(main, restore) 11410 // 11411 11412 MachineBasicBlock *thisMBB = MBB; 11413 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11414 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11415 MF->insert(I, mainMBB); 11416 MF->insert(I, sinkMBB); 11417 11418 MachineInstrBuilder MIB; 11419 11420 // Transfer the remainder of BB and its successor edges to sinkMBB. 11421 sinkMBB->splice(sinkMBB->begin(), MBB, 11422 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11423 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11424 11425 // Note that the structure of the jmp_buf used here is not compatible 11426 // with that used by libc, and is not designed to be. Specifically, it 11427 // stores only those 'reserved' registers that LLVM does not otherwise 11428 // understand how to spill. Also, by convention, by the time this 11429 // intrinsic is called, Clang has already stored the frame address in the 11430 // first slot of the buffer and stack address in the third. Following the 11431 // X86 target code, we'll store the jump address in the second slot. We also 11432 // need to save the TOC pointer (R2) to handle jumps between shared 11433 // libraries, and that will be stored in the fourth slot. The thread 11434 // identifier (R13) is not affected. 11435 11436 // thisMBB: 11437 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11438 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11439 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11440 11441 // Prepare IP either in reg. 11442 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11443 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11444 Register BufReg = MI.getOperand(1).getReg(); 11445 11446 if (Subtarget.is64BitELFABI()) { 11447 setUsesTOCBasePtr(*MBB->getParent()); 11448 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11449 .addReg(PPC::X2) 11450 .addImm(TOCOffset) 11451 .addReg(BufReg) 11452 .cloneMemRefs(MI); 11453 } 11454 11455 // Naked functions never have a base pointer, and so we use r1. For all 11456 // other functions, this decision must be delayed until during PEI. 11457 unsigned BaseReg; 11458 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11459 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11460 else 11461 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11462 11463 MIB = BuildMI(*thisMBB, MI, DL, 11464 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11465 .addReg(BaseReg) 11466 .addImm(BPOffset) 11467 .addReg(BufReg) 11468 .cloneMemRefs(MI); 11469 11470 // Setup 11471 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11472 MIB.addRegMask(TRI->getNoPreservedMask()); 11473 11474 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11475 11476 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11477 .addMBB(mainMBB); 11478 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11479 11480 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11481 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11482 11483 // mainMBB: 11484 // mainDstReg = 0 11485 MIB = 11486 BuildMI(mainMBB, DL, 11487 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11488 11489 // Store IP 11490 if (Subtarget.isPPC64()) { 11491 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11492 .addReg(LabelReg) 11493 .addImm(LabelOffset) 11494 .addReg(BufReg); 11495 } else { 11496 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11497 .addReg(LabelReg) 11498 .addImm(LabelOffset) 11499 .addReg(BufReg); 11500 } 11501 MIB.cloneMemRefs(MI); 11502 11503 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11504 mainMBB->addSuccessor(sinkMBB); 11505 11506 // sinkMBB: 11507 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11508 TII->get(PPC::PHI), DstReg) 11509 .addReg(mainDstReg).addMBB(mainMBB) 11510 .addReg(restoreDstReg).addMBB(thisMBB); 11511 11512 MI.eraseFromParent(); 11513 return sinkMBB; 11514 } 11515 11516 MachineBasicBlock * 11517 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11518 MachineBasicBlock *MBB) const { 11519 DebugLoc DL = MI.getDebugLoc(); 11520 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11521 11522 MachineFunction *MF = MBB->getParent(); 11523 MachineRegisterInfo &MRI = MF->getRegInfo(); 11524 11525 MVT PVT = getPointerTy(MF->getDataLayout()); 11526 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11527 "Invalid Pointer Size!"); 11528 11529 const TargetRegisterClass *RC = 11530 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11531 Register Tmp = MRI.createVirtualRegister(RC); 11532 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11533 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11534 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11535 unsigned BP = 11536 (PVT == MVT::i64) 11537 ? PPC::X30 11538 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11539 : PPC::R30); 11540 11541 MachineInstrBuilder MIB; 11542 11543 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11544 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11545 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11546 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11547 11548 Register BufReg = MI.getOperand(0).getReg(); 11549 11550 // Reload FP (the jumped-to function may not have had a 11551 // frame pointer, and if so, then its r31 will be restored 11552 // as necessary). 11553 if (PVT == MVT::i64) { 11554 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11555 .addImm(0) 11556 .addReg(BufReg); 11557 } else { 11558 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11559 .addImm(0) 11560 .addReg(BufReg); 11561 } 11562 MIB.cloneMemRefs(MI); 11563 11564 // Reload IP 11565 if (PVT == MVT::i64) { 11566 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11567 .addImm(LabelOffset) 11568 .addReg(BufReg); 11569 } else { 11570 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11571 .addImm(LabelOffset) 11572 .addReg(BufReg); 11573 } 11574 MIB.cloneMemRefs(MI); 11575 11576 // Reload SP 11577 if (PVT == MVT::i64) { 11578 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11579 .addImm(SPOffset) 11580 .addReg(BufReg); 11581 } else { 11582 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11583 .addImm(SPOffset) 11584 .addReg(BufReg); 11585 } 11586 MIB.cloneMemRefs(MI); 11587 11588 // Reload BP 11589 if (PVT == MVT::i64) { 11590 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11591 .addImm(BPOffset) 11592 .addReg(BufReg); 11593 } else { 11594 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11595 .addImm(BPOffset) 11596 .addReg(BufReg); 11597 } 11598 MIB.cloneMemRefs(MI); 11599 11600 // Reload TOC 11601 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11602 setUsesTOCBasePtr(*MBB->getParent()); 11603 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11604 .addImm(TOCOffset) 11605 .addReg(BufReg) 11606 .cloneMemRefs(MI); 11607 } 11608 11609 // Jump 11610 BuildMI(*MBB, MI, DL, 11611 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11612 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11613 11614 MI.eraseFromParent(); 11615 return MBB; 11616 } 11617 11618 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11619 // If the function specifically requests inline stack probes, emit them. 11620 if (MF.getFunction().hasFnAttribute("probe-stack")) 11621 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11622 "inline-asm"; 11623 return false; 11624 } 11625 11626 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11627 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11628 unsigned StackAlign = TFI->getStackAlignment(); 11629 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11630 "Unexpected stack alignment"); 11631 // The default stack probe size is 4096 if the function has no 11632 // stack-probe-size attribute. 11633 unsigned StackProbeSize = 4096; 11634 const Function &Fn = MF.getFunction(); 11635 if (Fn.hasFnAttribute("stack-probe-size")) 11636 Fn.getFnAttribute("stack-probe-size") 11637 .getValueAsString() 11638 .getAsInteger(0, StackProbeSize); 11639 // Round down to the stack alignment. 11640 StackProbeSize &= ~(StackAlign - 1); 11641 return StackProbeSize ? StackProbeSize : StackAlign; 11642 } 11643 11644 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11645 // into three phases. In the first phase, it uses pseudo instruction 11646 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11647 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11648 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11649 // MaxCallFrameSize so that it can calculate correct data area pointer. 11650 MachineBasicBlock * 11651 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11652 MachineBasicBlock *MBB) const { 11653 const bool isPPC64 = Subtarget.isPPC64(); 11654 MachineFunction *MF = MBB->getParent(); 11655 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11656 DebugLoc DL = MI.getDebugLoc(); 11657 const unsigned ProbeSize = getStackProbeSize(*MF); 11658 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11659 MachineRegisterInfo &MRI = MF->getRegInfo(); 11660 // The CFG of probing stack looks as 11661 // +-----+ 11662 // | MBB | 11663 // +--+--+ 11664 // | 11665 // +----v----+ 11666 // +--->+ TestMBB +---+ 11667 // | +----+----+ | 11668 // | | | 11669 // | +-----v----+ | 11670 // +---+ BlockMBB | | 11671 // +----------+ | 11672 // | 11673 // +---------+ | 11674 // | TailMBB +<--+ 11675 // +---------+ 11676 // In MBB, calculate previous frame pointer and final stack pointer. 11677 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11678 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11679 // TailMBB is spliced via \p MI. 11680 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11681 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11682 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11683 11684 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11685 MF->insert(MBBIter, TestMBB); 11686 MF->insert(MBBIter, BlockMBB); 11687 MF->insert(MBBIter, TailMBB); 11688 11689 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11690 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11691 11692 Register DstReg = MI.getOperand(0).getReg(); 11693 Register NegSizeReg = MI.getOperand(1).getReg(); 11694 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11695 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11696 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11697 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11698 11699 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11700 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11701 // NegSize. 11702 unsigned ProbeOpc; 11703 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11704 ProbeOpc = 11705 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11706 else 11707 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11708 // and NegSizeReg will be allocated in the same phyreg to avoid 11709 // redundant copy when NegSizeReg has only one use which is current MI and 11710 // will be replaced by PREPARE_PROBED_ALLOCA then. 11711 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11712 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11713 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11714 .addDef(ActualNegSizeReg) 11715 .addReg(NegSizeReg) 11716 .add(MI.getOperand(2)) 11717 .add(MI.getOperand(3)); 11718 11719 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11720 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11721 FinalStackPtr) 11722 .addReg(SPReg) 11723 .addReg(ActualNegSizeReg); 11724 11725 // Materialize a scratch register for update. 11726 int64_t NegProbeSize = -(int64_t)ProbeSize; 11727 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11728 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11729 if (!isInt<16>(NegProbeSize)) { 11730 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11731 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11732 .addImm(NegProbeSize >> 16); 11733 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11734 ScratchReg) 11735 .addReg(TempReg) 11736 .addImm(NegProbeSize & 0xFFFF); 11737 } else 11738 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11739 .addImm(NegProbeSize); 11740 11741 { 11742 // Probing leading residual part. 11743 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11744 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11745 .addReg(ActualNegSizeReg) 11746 .addReg(ScratchReg); 11747 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11748 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11749 .addReg(Div) 11750 .addReg(ScratchReg); 11751 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11752 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11753 .addReg(Mul) 11754 .addReg(ActualNegSizeReg); 11755 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11756 .addReg(FramePointer) 11757 .addReg(SPReg) 11758 .addReg(NegMod); 11759 } 11760 11761 { 11762 // Remaining part should be multiple of ProbeSize. 11763 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11764 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11765 .addReg(SPReg) 11766 .addReg(FinalStackPtr); 11767 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11768 .addImm(PPC::PRED_EQ) 11769 .addReg(CmpResult) 11770 .addMBB(TailMBB); 11771 TestMBB->addSuccessor(BlockMBB); 11772 TestMBB->addSuccessor(TailMBB); 11773 } 11774 11775 { 11776 // Touch the block. 11777 // |P...|P...|P... 11778 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11779 .addReg(FramePointer) 11780 .addReg(SPReg) 11781 .addReg(ScratchReg); 11782 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11783 BlockMBB->addSuccessor(TestMBB); 11784 } 11785 11786 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11787 // DYNAREAOFFSET pseudo instruction to get the future result. 11788 Register MaxCallFrameSizeReg = 11789 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11790 BuildMI(TailMBB, DL, 11791 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11792 MaxCallFrameSizeReg) 11793 .add(MI.getOperand(2)) 11794 .add(MI.getOperand(3)); 11795 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11796 .addReg(SPReg) 11797 .addReg(MaxCallFrameSizeReg); 11798 11799 // Splice instructions after MI to TailMBB. 11800 TailMBB->splice(TailMBB->end(), MBB, 11801 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11802 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11803 MBB->addSuccessor(TestMBB); 11804 11805 // Delete the pseudo instruction. 11806 MI.eraseFromParent(); 11807 11808 ++NumDynamicAllocaProbed; 11809 return TailMBB; 11810 } 11811 11812 MachineBasicBlock * 11813 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11814 MachineBasicBlock *BB) const { 11815 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11816 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11817 if (Subtarget.is64BitELFABI() && 11818 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11819 !Subtarget.isUsingPCRelativeCalls()) { 11820 // Call lowering should have added an r2 operand to indicate a dependence 11821 // on the TOC base pointer value. It can't however, because there is no 11822 // way to mark the dependence as implicit there, and so the stackmap code 11823 // will confuse it with a regular operand. Instead, add the dependence 11824 // here. 11825 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11826 } 11827 11828 return emitPatchPoint(MI, BB); 11829 } 11830 11831 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11832 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11833 return emitEHSjLjSetJmp(MI, BB); 11834 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11835 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11836 return emitEHSjLjLongJmp(MI, BB); 11837 } 11838 11839 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11840 11841 // To "insert" these instructions we actually have to insert their 11842 // control-flow patterns. 11843 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11844 MachineFunction::iterator It = ++BB->getIterator(); 11845 11846 MachineFunction *F = BB->getParent(); 11847 11848 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11849 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11850 MI.getOpcode() == PPC::SELECT_I8) { 11851 SmallVector<MachineOperand, 2> Cond; 11852 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11853 MI.getOpcode() == PPC::SELECT_CC_I8) 11854 Cond.push_back(MI.getOperand(4)); 11855 else 11856 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11857 Cond.push_back(MI.getOperand(1)); 11858 11859 DebugLoc dl = MI.getDebugLoc(); 11860 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11861 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11862 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11863 MI.getOpcode() == PPC::SELECT_CC_F8 || 11864 MI.getOpcode() == PPC::SELECT_CC_F16 || 11865 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11866 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11867 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11868 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11869 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11870 MI.getOpcode() == PPC::SELECT_CC_SPE || 11871 MI.getOpcode() == PPC::SELECT_F4 || 11872 MI.getOpcode() == PPC::SELECT_F8 || 11873 MI.getOpcode() == PPC::SELECT_F16 || 11874 MI.getOpcode() == PPC::SELECT_SPE || 11875 MI.getOpcode() == PPC::SELECT_SPE4 || 11876 MI.getOpcode() == PPC::SELECT_VRRC || 11877 MI.getOpcode() == PPC::SELECT_VSFRC || 11878 MI.getOpcode() == PPC::SELECT_VSSRC || 11879 MI.getOpcode() == PPC::SELECT_VSRC) { 11880 // The incoming instruction knows the destination vreg to set, the 11881 // condition code register to branch on, the true/false values to 11882 // select between, and a branch opcode to use. 11883 11884 // thisMBB: 11885 // ... 11886 // TrueVal = ... 11887 // cmpTY ccX, r1, r2 11888 // bCC copy1MBB 11889 // fallthrough --> copy0MBB 11890 MachineBasicBlock *thisMBB = BB; 11891 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11892 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11893 DebugLoc dl = MI.getDebugLoc(); 11894 F->insert(It, copy0MBB); 11895 F->insert(It, sinkMBB); 11896 11897 // Transfer the remainder of BB and its successor edges to sinkMBB. 11898 sinkMBB->splice(sinkMBB->begin(), BB, 11899 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11900 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11901 11902 // Next, add the true and fallthrough blocks as its successors. 11903 BB->addSuccessor(copy0MBB); 11904 BB->addSuccessor(sinkMBB); 11905 11906 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11907 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11908 MI.getOpcode() == PPC::SELECT_F16 || 11909 MI.getOpcode() == PPC::SELECT_SPE4 || 11910 MI.getOpcode() == PPC::SELECT_SPE || 11911 MI.getOpcode() == PPC::SELECT_VRRC || 11912 MI.getOpcode() == PPC::SELECT_VSFRC || 11913 MI.getOpcode() == PPC::SELECT_VSSRC || 11914 MI.getOpcode() == PPC::SELECT_VSRC) { 11915 BuildMI(BB, dl, TII->get(PPC::BC)) 11916 .addReg(MI.getOperand(1).getReg()) 11917 .addMBB(sinkMBB); 11918 } else { 11919 unsigned SelectPred = MI.getOperand(4).getImm(); 11920 BuildMI(BB, dl, TII->get(PPC::BCC)) 11921 .addImm(SelectPred) 11922 .addReg(MI.getOperand(1).getReg()) 11923 .addMBB(sinkMBB); 11924 } 11925 11926 // copy0MBB: 11927 // %FalseValue = ... 11928 // # fallthrough to sinkMBB 11929 BB = copy0MBB; 11930 11931 // Update machine-CFG edges 11932 BB->addSuccessor(sinkMBB); 11933 11934 // sinkMBB: 11935 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11936 // ... 11937 BB = sinkMBB; 11938 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11939 .addReg(MI.getOperand(3).getReg()) 11940 .addMBB(copy0MBB) 11941 .addReg(MI.getOperand(2).getReg()) 11942 .addMBB(thisMBB); 11943 } else if (MI.getOpcode() == PPC::ReadTB) { 11944 // To read the 64-bit time-base register on a 32-bit target, we read the 11945 // two halves. Should the counter have wrapped while it was being read, we 11946 // need to try again. 11947 // ... 11948 // readLoop: 11949 // mfspr Rx,TBU # load from TBU 11950 // mfspr Ry,TB # load from TB 11951 // mfspr Rz,TBU # load from TBU 11952 // cmpw crX,Rx,Rz # check if 'old'='new' 11953 // bne readLoop # branch if they're not equal 11954 // ... 11955 11956 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11957 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11958 DebugLoc dl = MI.getDebugLoc(); 11959 F->insert(It, readMBB); 11960 F->insert(It, sinkMBB); 11961 11962 // Transfer the remainder of BB and its successor edges to sinkMBB. 11963 sinkMBB->splice(sinkMBB->begin(), BB, 11964 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11965 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11966 11967 BB->addSuccessor(readMBB); 11968 BB = readMBB; 11969 11970 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11971 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11972 Register LoReg = MI.getOperand(0).getReg(); 11973 Register HiReg = MI.getOperand(1).getReg(); 11974 11975 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11976 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11977 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11978 11979 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11980 11981 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11982 .addReg(HiReg) 11983 .addReg(ReadAgainReg); 11984 BuildMI(BB, dl, TII->get(PPC::BCC)) 11985 .addImm(PPC::PRED_NE) 11986 .addReg(CmpReg) 11987 .addMBB(readMBB); 11988 11989 BB->addSuccessor(readMBB); 11990 BB->addSuccessor(sinkMBB); 11991 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11992 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11993 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11994 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11995 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11996 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11997 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11998 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11999 12000 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12001 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12002 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12003 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12004 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12005 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12006 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12007 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12008 12009 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12010 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12011 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12012 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12013 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12014 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12015 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12016 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12017 12018 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12019 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12020 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12021 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12022 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12023 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12024 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12025 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12026 12027 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12028 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12029 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12030 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12031 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12032 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12033 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12034 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12035 12036 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12037 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12038 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12039 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12040 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12041 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12042 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12043 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12044 12045 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12046 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12047 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12048 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12049 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12050 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12051 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12052 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12053 12054 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12055 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12056 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12057 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12058 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12059 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12060 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12061 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12062 12063 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12064 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12065 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12066 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12067 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12068 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12069 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12070 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12071 12072 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12073 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12074 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12075 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12076 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12077 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12078 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12079 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12080 12081 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12082 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12083 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12084 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12085 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12086 BB = EmitAtomicBinary(MI, BB, 4, 0); 12087 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12088 BB = EmitAtomicBinary(MI, BB, 8, 0); 12089 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12090 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12091 (Subtarget.hasPartwordAtomics() && 12092 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12093 (Subtarget.hasPartwordAtomics() && 12094 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12095 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12096 12097 auto LoadMnemonic = PPC::LDARX; 12098 auto StoreMnemonic = PPC::STDCX; 12099 switch (MI.getOpcode()) { 12100 default: 12101 llvm_unreachable("Compare and swap of unknown size"); 12102 case PPC::ATOMIC_CMP_SWAP_I8: 12103 LoadMnemonic = PPC::LBARX; 12104 StoreMnemonic = PPC::STBCX; 12105 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12106 break; 12107 case PPC::ATOMIC_CMP_SWAP_I16: 12108 LoadMnemonic = PPC::LHARX; 12109 StoreMnemonic = PPC::STHCX; 12110 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12111 break; 12112 case PPC::ATOMIC_CMP_SWAP_I32: 12113 LoadMnemonic = PPC::LWARX; 12114 StoreMnemonic = PPC::STWCX; 12115 break; 12116 case PPC::ATOMIC_CMP_SWAP_I64: 12117 LoadMnemonic = PPC::LDARX; 12118 StoreMnemonic = PPC::STDCX; 12119 break; 12120 } 12121 Register dest = MI.getOperand(0).getReg(); 12122 Register ptrA = MI.getOperand(1).getReg(); 12123 Register ptrB = MI.getOperand(2).getReg(); 12124 Register oldval = MI.getOperand(3).getReg(); 12125 Register newval = MI.getOperand(4).getReg(); 12126 DebugLoc dl = MI.getDebugLoc(); 12127 12128 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12129 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12130 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12131 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12132 F->insert(It, loop1MBB); 12133 F->insert(It, loop2MBB); 12134 F->insert(It, midMBB); 12135 F->insert(It, exitMBB); 12136 exitMBB->splice(exitMBB->begin(), BB, 12137 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12138 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12139 12140 // thisMBB: 12141 // ... 12142 // fallthrough --> loopMBB 12143 BB->addSuccessor(loop1MBB); 12144 12145 // loop1MBB: 12146 // l[bhwd]arx dest, ptr 12147 // cmp[wd] dest, oldval 12148 // bne- midMBB 12149 // loop2MBB: 12150 // st[bhwd]cx. newval, ptr 12151 // bne- loopMBB 12152 // b exitBB 12153 // midMBB: 12154 // st[bhwd]cx. dest, ptr 12155 // exitBB: 12156 BB = loop1MBB; 12157 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12158 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12159 .addReg(oldval) 12160 .addReg(dest); 12161 BuildMI(BB, dl, TII->get(PPC::BCC)) 12162 .addImm(PPC::PRED_NE) 12163 .addReg(PPC::CR0) 12164 .addMBB(midMBB); 12165 BB->addSuccessor(loop2MBB); 12166 BB->addSuccessor(midMBB); 12167 12168 BB = loop2MBB; 12169 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12170 .addReg(newval) 12171 .addReg(ptrA) 12172 .addReg(ptrB); 12173 BuildMI(BB, dl, TII->get(PPC::BCC)) 12174 .addImm(PPC::PRED_NE) 12175 .addReg(PPC::CR0) 12176 .addMBB(loop1MBB); 12177 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12178 BB->addSuccessor(loop1MBB); 12179 BB->addSuccessor(exitMBB); 12180 12181 BB = midMBB; 12182 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12183 .addReg(dest) 12184 .addReg(ptrA) 12185 .addReg(ptrB); 12186 BB->addSuccessor(exitMBB); 12187 12188 // exitMBB: 12189 // ... 12190 BB = exitMBB; 12191 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12192 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12193 // We must use 64-bit registers for addresses when targeting 64-bit, 12194 // since we're actually doing arithmetic on them. Other registers 12195 // can be 32-bit. 12196 bool is64bit = Subtarget.isPPC64(); 12197 bool isLittleEndian = Subtarget.isLittleEndian(); 12198 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12199 12200 Register dest = MI.getOperand(0).getReg(); 12201 Register ptrA = MI.getOperand(1).getReg(); 12202 Register ptrB = MI.getOperand(2).getReg(); 12203 Register oldval = MI.getOperand(3).getReg(); 12204 Register newval = MI.getOperand(4).getReg(); 12205 DebugLoc dl = MI.getDebugLoc(); 12206 12207 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12208 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12209 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12210 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12211 F->insert(It, loop1MBB); 12212 F->insert(It, loop2MBB); 12213 F->insert(It, midMBB); 12214 F->insert(It, exitMBB); 12215 exitMBB->splice(exitMBB->begin(), BB, 12216 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12217 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12218 12219 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12220 const TargetRegisterClass *RC = 12221 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12222 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12223 12224 Register PtrReg = RegInfo.createVirtualRegister(RC); 12225 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12226 Register ShiftReg = 12227 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12228 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12229 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12230 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12231 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12232 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12233 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12234 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12235 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12236 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12237 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12238 Register Ptr1Reg; 12239 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12240 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12241 // thisMBB: 12242 // ... 12243 // fallthrough --> loopMBB 12244 BB->addSuccessor(loop1MBB); 12245 12246 // The 4-byte load must be aligned, while a char or short may be 12247 // anywhere in the word. Hence all this nasty bookkeeping code. 12248 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12249 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12250 // xori shift, shift1, 24 [16] 12251 // rlwinm ptr, ptr1, 0, 0, 29 12252 // slw newval2, newval, shift 12253 // slw oldval2, oldval,shift 12254 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12255 // slw mask, mask2, shift 12256 // and newval3, newval2, mask 12257 // and oldval3, oldval2, mask 12258 // loop1MBB: 12259 // lwarx tmpDest, ptr 12260 // and tmp, tmpDest, mask 12261 // cmpw tmp, oldval3 12262 // bne- midMBB 12263 // loop2MBB: 12264 // andc tmp2, tmpDest, mask 12265 // or tmp4, tmp2, newval3 12266 // stwcx. tmp4, ptr 12267 // bne- loop1MBB 12268 // b exitBB 12269 // midMBB: 12270 // stwcx. tmpDest, ptr 12271 // exitBB: 12272 // srw dest, tmpDest, shift 12273 if (ptrA != ZeroReg) { 12274 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12275 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12276 .addReg(ptrA) 12277 .addReg(ptrB); 12278 } else { 12279 Ptr1Reg = ptrB; 12280 } 12281 12282 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12283 // mode. 12284 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12285 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12286 .addImm(3) 12287 .addImm(27) 12288 .addImm(is8bit ? 28 : 27); 12289 if (!isLittleEndian) 12290 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12291 .addReg(Shift1Reg) 12292 .addImm(is8bit ? 24 : 16); 12293 if (is64bit) 12294 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12295 .addReg(Ptr1Reg) 12296 .addImm(0) 12297 .addImm(61); 12298 else 12299 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12300 .addReg(Ptr1Reg) 12301 .addImm(0) 12302 .addImm(0) 12303 .addImm(29); 12304 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12305 .addReg(newval) 12306 .addReg(ShiftReg); 12307 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12308 .addReg(oldval) 12309 .addReg(ShiftReg); 12310 if (is8bit) 12311 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12312 else { 12313 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12314 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12315 .addReg(Mask3Reg) 12316 .addImm(65535); 12317 } 12318 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12319 .addReg(Mask2Reg) 12320 .addReg(ShiftReg); 12321 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12322 .addReg(NewVal2Reg) 12323 .addReg(MaskReg); 12324 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12325 .addReg(OldVal2Reg) 12326 .addReg(MaskReg); 12327 12328 BB = loop1MBB; 12329 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12330 .addReg(ZeroReg) 12331 .addReg(PtrReg); 12332 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12333 .addReg(TmpDestReg) 12334 .addReg(MaskReg); 12335 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12336 .addReg(TmpReg) 12337 .addReg(OldVal3Reg); 12338 BuildMI(BB, dl, TII->get(PPC::BCC)) 12339 .addImm(PPC::PRED_NE) 12340 .addReg(PPC::CR0) 12341 .addMBB(midMBB); 12342 BB->addSuccessor(loop2MBB); 12343 BB->addSuccessor(midMBB); 12344 12345 BB = loop2MBB; 12346 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12347 .addReg(TmpDestReg) 12348 .addReg(MaskReg); 12349 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12350 .addReg(Tmp2Reg) 12351 .addReg(NewVal3Reg); 12352 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12353 .addReg(Tmp4Reg) 12354 .addReg(ZeroReg) 12355 .addReg(PtrReg); 12356 BuildMI(BB, dl, TII->get(PPC::BCC)) 12357 .addImm(PPC::PRED_NE) 12358 .addReg(PPC::CR0) 12359 .addMBB(loop1MBB); 12360 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12361 BB->addSuccessor(loop1MBB); 12362 BB->addSuccessor(exitMBB); 12363 12364 BB = midMBB; 12365 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12366 .addReg(TmpDestReg) 12367 .addReg(ZeroReg) 12368 .addReg(PtrReg); 12369 BB->addSuccessor(exitMBB); 12370 12371 // exitMBB: 12372 // ... 12373 BB = exitMBB; 12374 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12375 .addReg(TmpReg) 12376 .addReg(ShiftReg); 12377 } else if (MI.getOpcode() == PPC::FADDrtz) { 12378 // This pseudo performs an FADD with rounding mode temporarily forced 12379 // to round-to-zero. We emit this via custom inserter since the FPSCR 12380 // is not modeled at the SelectionDAG level. 12381 Register Dest = MI.getOperand(0).getReg(); 12382 Register Src1 = MI.getOperand(1).getReg(); 12383 Register Src2 = MI.getOperand(2).getReg(); 12384 DebugLoc dl = MI.getDebugLoc(); 12385 12386 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12387 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12388 12389 // Save FPSCR value. 12390 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12391 12392 // Set rounding mode to round-to-zero. 12393 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12394 .addImm(31) 12395 .addReg(PPC::RM, RegState::ImplicitDefine); 12396 12397 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12398 .addImm(30) 12399 .addReg(PPC::RM, RegState::ImplicitDefine); 12400 12401 // Perform addition. 12402 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12403 .addReg(Src1) 12404 .addReg(Src2); 12405 if (MI.getFlag(MachineInstr::NoFPExcept)) 12406 MIB.setMIFlag(MachineInstr::NoFPExcept); 12407 12408 // Restore FPSCR value. 12409 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12410 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12411 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12412 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12413 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12414 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12415 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12416 ? PPC::ANDI8_rec 12417 : PPC::ANDI_rec; 12418 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12419 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12420 12421 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12422 Register Dest = RegInfo.createVirtualRegister( 12423 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12424 12425 DebugLoc Dl = MI.getDebugLoc(); 12426 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12427 .addReg(MI.getOperand(1).getReg()) 12428 .addImm(1); 12429 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12430 MI.getOperand(0).getReg()) 12431 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12432 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12433 DebugLoc Dl = MI.getDebugLoc(); 12434 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12435 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12436 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12437 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12438 MI.getOperand(0).getReg()) 12439 .addReg(CRReg); 12440 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12441 DebugLoc Dl = MI.getDebugLoc(); 12442 unsigned Imm = MI.getOperand(1).getImm(); 12443 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12444 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12445 MI.getOperand(0).getReg()) 12446 .addReg(PPC::CR0EQ); 12447 } else if (MI.getOpcode() == PPC::SETRNDi) { 12448 DebugLoc dl = MI.getDebugLoc(); 12449 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12450 12451 // Save FPSCR value. 12452 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12453 12454 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12455 // the following settings: 12456 // 00 Round to nearest 12457 // 01 Round to 0 12458 // 10 Round to +inf 12459 // 11 Round to -inf 12460 12461 // When the operand is immediate, using the two least significant bits of 12462 // the immediate to set the bits 62:63 of FPSCR. 12463 unsigned Mode = MI.getOperand(1).getImm(); 12464 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12465 .addImm(31) 12466 .addReg(PPC::RM, RegState::ImplicitDefine); 12467 12468 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12469 .addImm(30) 12470 .addReg(PPC::RM, RegState::ImplicitDefine); 12471 } else if (MI.getOpcode() == PPC::SETRND) { 12472 DebugLoc dl = MI.getDebugLoc(); 12473 12474 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12475 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12476 // If the target doesn't have DirectMove, we should use stack to do the 12477 // conversion, because the target doesn't have the instructions like mtvsrd 12478 // or mfvsrd to do this conversion directly. 12479 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12480 if (Subtarget.hasDirectMove()) { 12481 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12482 .addReg(SrcReg); 12483 } else { 12484 // Use stack to do the register copy. 12485 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12486 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12487 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12488 if (RC == &PPC::F8RCRegClass) { 12489 // Copy register from F8RCRegClass to G8RCRegclass. 12490 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12491 "Unsupported RegClass."); 12492 12493 StoreOp = PPC::STFD; 12494 LoadOp = PPC::LD; 12495 } else { 12496 // Copy register from G8RCRegClass to F8RCRegclass. 12497 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12498 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12499 "Unsupported RegClass."); 12500 } 12501 12502 MachineFrameInfo &MFI = F->getFrameInfo(); 12503 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12504 12505 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12506 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12507 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12508 MFI.getObjectAlign(FrameIdx)); 12509 12510 // Store the SrcReg into the stack. 12511 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12512 .addReg(SrcReg) 12513 .addImm(0) 12514 .addFrameIndex(FrameIdx) 12515 .addMemOperand(MMOStore); 12516 12517 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12518 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12519 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12520 MFI.getObjectAlign(FrameIdx)); 12521 12522 // Load from the stack where SrcReg is stored, and save to DestReg, 12523 // so we have done the RegClass conversion from RegClass::SrcReg to 12524 // RegClass::DestReg. 12525 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12526 .addImm(0) 12527 .addFrameIndex(FrameIdx) 12528 .addMemOperand(MMOLoad); 12529 } 12530 }; 12531 12532 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12533 12534 // Save FPSCR value. 12535 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12536 12537 // When the operand is gprc register, use two least significant bits of the 12538 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12539 // 12540 // copy OldFPSCRTmpReg, OldFPSCRReg 12541 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12542 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12543 // copy NewFPSCRReg, NewFPSCRTmpReg 12544 // mtfsf 255, NewFPSCRReg 12545 MachineOperand SrcOp = MI.getOperand(1); 12546 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12547 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12548 12549 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12550 12551 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12552 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12553 12554 // The first operand of INSERT_SUBREG should be a register which has 12555 // subregisters, we only care about its RegClass, so we should use an 12556 // IMPLICIT_DEF register. 12557 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12558 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12559 .addReg(ImDefReg) 12560 .add(SrcOp) 12561 .addImm(1); 12562 12563 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12564 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12565 .addReg(OldFPSCRTmpReg) 12566 .addReg(ExtSrcReg) 12567 .addImm(0) 12568 .addImm(62); 12569 12570 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12571 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12572 12573 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12574 // bits of FPSCR. 12575 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12576 .addImm(255) 12577 .addReg(NewFPSCRReg) 12578 .addImm(0) 12579 .addImm(0); 12580 } else if (MI.getOpcode() == PPC::SETFLM) { 12581 DebugLoc Dl = MI.getDebugLoc(); 12582 12583 // Result of setflm is previous FPSCR content, so we need to save it first. 12584 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12585 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12586 12587 // Put bits in 32:63 to FPSCR. 12588 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12589 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12590 .addImm(255) 12591 .addReg(NewFPSCRReg) 12592 .addImm(0) 12593 .addImm(0); 12594 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12595 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12596 return emitProbedAlloca(MI, BB); 12597 } else { 12598 llvm_unreachable("Unexpected instr type to insert"); 12599 } 12600 12601 MI.eraseFromParent(); // The pseudo instruction is gone now. 12602 return BB; 12603 } 12604 12605 //===----------------------------------------------------------------------===// 12606 // Target Optimization Hooks 12607 //===----------------------------------------------------------------------===// 12608 12609 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12610 // For the estimates, convergence is quadratic, so we essentially double the 12611 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12612 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12613 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12614 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12615 if (VT.getScalarType() == MVT::f64) 12616 RefinementSteps++; 12617 return RefinementSteps; 12618 } 12619 12620 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12621 const DenormalMode &Mode) const { 12622 // We only have VSX Vector Test for software Square Root. 12623 EVT VT = Op.getValueType(); 12624 if (!isTypeLegal(MVT::i1) || 12625 (VT != MVT::f64 && 12626 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12627 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 12628 12629 SDLoc DL(Op); 12630 // The output register of FTSQRT is CR field. 12631 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12632 // ftsqrt BF,FRB 12633 // Let e_b be the unbiased exponent of the double-precision 12634 // floating-point operand in register FRB. 12635 // fe_flag is set to 1 if either of the following conditions occurs. 12636 // - The double-precision floating-point operand in register FRB is a zero, 12637 // a NaN, or an infinity, or a negative value. 12638 // - e_b is less than or equal to -970. 12639 // Otherwise fe_flag is set to 0. 12640 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 12641 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 12642 // exponent is less than -970) 12643 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 12644 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 12645 FTSQRT, SRIdxVal), 12646 0); 12647 } 12648 12649 SDValue 12650 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 12651 SelectionDAG &DAG) const { 12652 // We only have VSX Vector Square Root. 12653 EVT VT = Op.getValueType(); 12654 if (VT != MVT::f64 && 12655 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 12656 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 12657 12658 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 12659 } 12660 12661 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12662 int Enabled, int &RefinementSteps, 12663 bool &UseOneConstNR, 12664 bool Reciprocal) const { 12665 EVT VT = Operand.getValueType(); 12666 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12667 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12668 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12669 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12670 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12671 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12672 12673 // The Newton-Raphson computation with a single constant does not provide 12674 // enough accuracy on some CPUs. 12675 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12676 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12677 } 12678 return SDValue(); 12679 } 12680 12681 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12682 int Enabled, 12683 int &RefinementSteps) const { 12684 EVT VT = Operand.getValueType(); 12685 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12686 (VT == MVT::f64 && Subtarget.hasFRE()) || 12687 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12688 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12689 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12690 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12691 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12692 } 12693 return SDValue(); 12694 } 12695 12696 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12697 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12698 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12699 // enabled for division), this functionality is redundant with the default 12700 // combiner logic (once the division -> reciprocal/multiply transformation 12701 // has taken place). As a result, this matters more for older cores than for 12702 // newer ones. 12703 12704 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12705 // reciprocal if there are two or more FDIVs (for embedded cores with only 12706 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12707 switch (Subtarget.getCPUDirective()) { 12708 default: 12709 return 3; 12710 case PPC::DIR_440: 12711 case PPC::DIR_A2: 12712 case PPC::DIR_E500: 12713 case PPC::DIR_E500mc: 12714 case PPC::DIR_E5500: 12715 return 2; 12716 } 12717 } 12718 12719 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12720 // collapsed, and so we need to look through chains of them. 12721 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12722 int64_t& Offset, SelectionDAG &DAG) { 12723 if (DAG.isBaseWithConstantOffset(Loc)) { 12724 Base = Loc.getOperand(0); 12725 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12726 12727 // The base might itself be a base plus an offset, and if so, accumulate 12728 // that as well. 12729 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12730 } 12731 } 12732 12733 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12734 unsigned Bytes, int Dist, 12735 SelectionDAG &DAG) { 12736 if (VT.getSizeInBits() / 8 != Bytes) 12737 return false; 12738 12739 SDValue BaseLoc = Base->getBasePtr(); 12740 if (Loc.getOpcode() == ISD::FrameIndex) { 12741 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12742 return false; 12743 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12744 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12745 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12746 int FS = MFI.getObjectSize(FI); 12747 int BFS = MFI.getObjectSize(BFI); 12748 if (FS != BFS || FS != (int)Bytes) return false; 12749 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12750 } 12751 12752 SDValue Base1 = Loc, Base2 = BaseLoc; 12753 int64_t Offset1 = 0, Offset2 = 0; 12754 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12755 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12756 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12757 return true; 12758 12759 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12760 const GlobalValue *GV1 = nullptr; 12761 const GlobalValue *GV2 = nullptr; 12762 Offset1 = 0; 12763 Offset2 = 0; 12764 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12765 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12766 if (isGA1 && isGA2 && GV1 == GV2) 12767 return Offset1 == (Offset2 + Dist*Bytes); 12768 return false; 12769 } 12770 12771 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12772 // not enforce equality of the chain operands. 12773 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12774 unsigned Bytes, int Dist, 12775 SelectionDAG &DAG) { 12776 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12777 EVT VT = LS->getMemoryVT(); 12778 SDValue Loc = LS->getBasePtr(); 12779 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12780 } 12781 12782 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12783 EVT VT; 12784 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12785 default: return false; 12786 case Intrinsic::ppc_altivec_lvx: 12787 case Intrinsic::ppc_altivec_lvxl: 12788 case Intrinsic::ppc_vsx_lxvw4x: 12789 case Intrinsic::ppc_vsx_lxvw4x_be: 12790 VT = MVT::v4i32; 12791 break; 12792 case Intrinsic::ppc_vsx_lxvd2x: 12793 case Intrinsic::ppc_vsx_lxvd2x_be: 12794 VT = MVT::v2f64; 12795 break; 12796 case Intrinsic::ppc_altivec_lvebx: 12797 VT = MVT::i8; 12798 break; 12799 case Intrinsic::ppc_altivec_lvehx: 12800 VT = MVT::i16; 12801 break; 12802 case Intrinsic::ppc_altivec_lvewx: 12803 VT = MVT::i32; 12804 break; 12805 } 12806 12807 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12808 } 12809 12810 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12811 EVT VT; 12812 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12813 default: return false; 12814 case Intrinsic::ppc_altivec_stvx: 12815 case Intrinsic::ppc_altivec_stvxl: 12816 case Intrinsic::ppc_vsx_stxvw4x: 12817 VT = MVT::v4i32; 12818 break; 12819 case Intrinsic::ppc_vsx_stxvd2x: 12820 VT = MVT::v2f64; 12821 break; 12822 case Intrinsic::ppc_vsx_stxvw4x_be: 12823 VT = MVT::v4i32; 12824 break; 12825 case Intrinsic::ppc_vsx_stxvd2x_be: 12826 VT = MVT::v2f64; 12827 break; 12828 case Intrinsic::ppc_altivec_stvebx: 12829 VT = MVT::i8; 12830 break; 12831 case Intrinsic::ppc_altivec_stvehx: 12832 VT = MVT::i16; 12833 break; 12834 case Intrinsic::ppc_altivec_stvewx: 12835 VT = MVT::i32; 12836 break; 12837 } 12838 12839 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12840 } 12841 12842 return false; 12843 } 12844 12845 // Return true is there is a nearyby consecutive load to the one provided 12846 // (regardless of alignment). We search up and down the chain, looking though 12847 // token factors and other loads (but nothing else). As a result, a true result 12848 // indicates that it is safe to create a new consecutive load adjacent to the 12849 // load provided. 12850 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12851 SDValue Chain = LD->getChain(); 12852 EVT VT = LD->getMemoryVT(); 12853 12854 SmallSet<SDNode *, 16> LoadRoots; 12855 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12856 SmallSet<SDNode *, 16> Visited; 12857 12858 // First, search up the chain, branching to follow all token-factor operands. 12859 // If we find a consecutive load, then we're done, otherwise, record all 12860 // nodes just above the top-level loads and token factors. 12861 while (!Queue.empty()) { 12862 SDNode *ChainNext = Queue.pop_back_val(); 12863 if (!Visited.insert(ChainNext).second) 12864 continue; 12865 12866 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12867 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12868 return true; 12869 12870 if (!Visited.count(ChainLD->getChain().getNode())) 12871 Queue.push_back(ChainLD->getChain().getNode()); 12872 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12873 for (const SDUse &O : ChainNext->ops()) 12874 if (!Visited.count(O.getNode())) 12875 Queue.push_back(O.getNode()); 12876 } else 12877 LoadRoots.insert(ChainNext); 12878 } 12879 12880 // Second, search down the chain, starting from the top-level nodes recorded 12881 // in the first phase. These top-level nodes are the nodes just above all 12882 // loads and token factors. Starting with their uses, recursively look though 12883 // all loads (just the chain uses) and token factors to find a consecutive 12884 // load. 12885 Visited.clear(); 12886 Queue.clear(); 12887 12888 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12889 IE = LoadRoots.end(); I != IE; ++I) { 12890 Queue.push_back(*I); 12891 12892 while (!Queue.empty()) { 12893 SDNode *LoadRoot = Queue.pop_back_val(); 12894 if (!Visited.insert(LoadRoot).second) 12895 continue; 12896 12897 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12898 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12899 return true; 12900 12901 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12902 UE = LoadRoot->use_end(); UI != UE; ++UI) 12903 if (((isa<MemSDNode>(*UI) && 12904 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12905 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12906 Queue.push_back(*UI); 12907 } 12908 } 12909 12910 return false; 12911 } 12912 12913 /// This function is called when we have proved that a SETCC node can be replaced 12914 /// by subtraction (and other supporting instructions) so that the result of 12915 /// comparison is kept in a GPR instead of CR. This function is purely for 12916 /// codegen purposes and has some flags to guide the codegen process. 12917 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12918 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12919 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12920 12921 // Zero extend the operands to the largest legal integer. Originally, they 12922 // must be of a strictly smaller size. 12923 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12924 DAG.getConstant(Size, DL, MVT::i32)); 12925 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12926 DAG.getConstant(Size, DL, MVT::i32)); 12927 12928 // Swap if needed. Depends on the condition code. 12929 if (Swap) 12930 std::swap(Op0, Op1); 12931 12932 // Subtract extended integers. 12933 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12934 12935 // Move the sign bit to the least significant position and zero out the rest. 12936 // Now the least significant bit carries the result of original comparison. 12937 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12938 DAG.getConstant(Size - 1, DL, MVT::i32)); 12939 auto Final = Shifted; 12940 12941 // Complement the result if needed. Based on the condition code. 12942 if (Complement) 12943 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12944 DAG.getConstant(1, DL, MVT::i64)); 12945 12946 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12947 } 12948 12949 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12950 DAGCombinerInfo &DCI) const { 12951 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12952 12953 SelectionDAG &DAG = DCI.DAG; 12954 SDLoc DL(N); 12955 12956 // Size of integers being compared has a critical role in the following 12957 // analysis, so we prefer to do this when all types are legal. 12958 if (!DCI.isAfterLegalizeDAG()) 12959 return SDValue(); 12960 12961 // If all users of SETCC extend its value to a legal integer type 12962 // then we replace SETCC with a subtraction 12963 for (SDNode::use_iterator UI = N->use_begin(), 12964 UE = N->use_end(); UI != UE; ++UI) { 12965 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12966 return SDValue(); 12967 } 12968 12969 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12970 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12971 12972 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12973 12974 if (OpSize < Size) { 12975 switch (CC) { 12976 default: break; 12977 case ISD::SETULT: 12978 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12979 case ISD::SETULE: 12980 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12981 case ISD::SETUGT: 12982 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12983 case ISD::SETUGE: 12984 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12985 } 12986 } 12987 12988 return SDValue(); 12989 } 12990 12991 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12992 DAGCombinerInfo &DCI) const { 12993 SelectionDAG &DAG = DCI.DAG; 12994 SDLoc dl(N); 12995 12996 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12997 // If we're tracking CR bits, we need to be careful that we don't have: 12998 // trunc(binary-ops(zext(x), zext(y))) 12999 // or 13000 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13001 // such that we're unnecessarily moving things into GPRs when it would be 13002 // better to keep them in CR bits. 13003 13004 // Note that trunc here can be an actual i1 trunc, or can be the effective 13005 // truncation that comes from a setcc or select_cc. 13006 if (N->getOpcode() == ISD::TRUNCATE && 13007 N->getValueType(0) != MVT::i1) 13008 return SDValue(); 13009 13010 if (N->getOperand(0).getValueType() != MVT::i32 && 13011 N->getOperand(0).getValueType() != MVT::i64) 13012 return SDValue(); 13013 13014 if (N->getOpcode() == ISD::SETCC || 13015 N->getOpcode() == ISD::SELECT_CC) { 13016 // If we're looking at a comparison, then we need to make sure that the 13017 // high bits (all except for the first) don't matter the result. 13018 ISD::CondCode CC = 13019 cast<CondCodeSDNode>(N->getOperand( 13020 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13021 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13022 13023 if (ISD::isSignedIntSetCC(CC)) { 13024 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13025 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13026 return SDValue(); 13027 } else if (ISD::isUnsignedIntSetCC(CC)) { 13028 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13029 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13030 !DAG.MaskedValueIsZero(N->getOperand(1), 13031 APInt::getHighBitsSet(OpBits, OpBits-1))) 13032 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13033 : SDValue()); 13034 } else { 13035 // This is neither a signed nor an unsigned comparison, just make sure 13036 // that the high bits are equal. 13037 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13038 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13039 13040 // We don't really care about what is known about the first bit (if 13041 // anything), so pretend that it is known zero for both to ensure they can 13042 // be compared as constants. 13043 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13044 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13045 13046 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13047 Op1Known.getConstant() != Op2Known.getConstant()) 13048 return SDValue(); 13049 } 13050 } 13051 13052 // We now know that the higher-order bits are irrelevant, we just need to 13053 // make sure that all of the intermediate operations are bit operations, and 13054 // all inputs are extensions. 13055 if (N->getOperand(0).getOpcode() != ISD::AND && 13056 N->getOperand(0).getOpcode() != ISD::OR && 13057 N->getOperand(0).getOpcode() != ISD::XOR && 13058 N->getOperand(0).getOpcode() != ISD::SELECT && 13059 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13060 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13061 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13062 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13063 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13064 return SDValue(); 13065 13066 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13067 N->getOperand(1).getOpcode() != ISD::AND && 13068 N->getOperand(1).getOpcode() != ISD::OR && 13069 N->getOperand(1).getOpcode() != ISD::XOR && 13070 N->getOperand(1).getOpcode() != ISD::SELECT && 13071 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13072 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13073 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13074 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13075 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13076 return SDValue(); 13077 13078 SmallVector<SDValue, 4> Inputs; 13079 SmallVector<SDValue, 8> BinOps, PromOps; 13080 SmallPtrSet<SDNode *, 16> Visited; 13081 13082 for (unsigned i = 0; i < 2; ++i) { 13083 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13084 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13085 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13086 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13087 isa<ConstantSDNode>(N->getOperand(i))) 13088 Inputs.push_back(N->getOperand(i)); 13089 else 13090 BinOps.push_back(N->getOperand(i)); 13091 13092 if (N->getOpcode() == ISD::TRUNCATE) 13093 break; 13094 } 13095 13096 // Visit all inputs, collect all binary operations (and, or, xor and 13097 // select) that are all fed by extensions. 13098 while (!BinOps.empty()) { 13099 SDValue BinOp = BinOps.pop_back_val(); 13100 13101 if (!Visited.insert(BinOp.getNode()).second) 13102 continue; 13103 13104 PromOps.push_back(BinOp); 13105 13106 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13107 // The condition of the select is not promoted. 13108 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13109 continue; 13110 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13111 continue; 13112 13113 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13114 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13115 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13116 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13117 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13118 Inputs.push_back(BinOp.getOperand(i)); 13119 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13120 BinOp.getOperand(i).getOpcode() == ISD::OR || 13121 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13122 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13123 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13124 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13125 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13126 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13127 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13128 BinOps.push_back(BinOp.getOperand(i)); 13129 } else { 13130 // We have an input that is not an extension or another binary 13131 // operation; we'll abort this transformation. 13132 return SDValue(); 13133 } 13134 } 13135 } 13136 13137 // Make sure that this is a self-contained cluster of operations (which 13138 // is not quite the same thing as saying that everything has only one 13139 // use). 13140 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13141 if (isa<ConstantSDNode>(Inputs[i])) 13142 continue; 13143 13144 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13145 UE = Inputs[i].getNode()->use_end(); 13146 UI != UE; ++UI) { 13147 SDNode *User = *UI; 13148 if (User != N && !Visited.count(User)) 13149 return SDValue(); 13150 13151 // Make sure that we're not going to promote the non-output-value 13152 // operand(s) or SELECT or SELECT_CC. 13153 // FIXME: Although we could sometimes handle this, and it does occur in 13154 // practice that one of the condition inputs to the select is also one of 13155 // the outputs, we currently can't deal with this. 13156 if (User->getOpcode() == ISD::SELECT) { 13157 if (User->getOperand(0) == Inputs[i]) 13158 return SDValue(); 13159 } else if (User->getOpcode() == ISD::SELECT_CC) { 13160 if (User->getOperand(0) == Inputs[i] || 13161 User->getOperand(1) == Inputs[i]) 13162 return SDValue(); 13163 } 13164 } 13165 } 13166 13167 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13168 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13169 UE = PromOps[i].getNode()->use_end(); 13170 UI != UE; ++UI) { 13171 SDNode *User = *UI; 13172 if (User != N && !Visited.count(User)) 13173 return SDValue(); 13174 13175 // Make sure that we're not going to promote the non-output-value 13176 // operand(s) or SELECT or SELECT_CC. 13177 // FIXME: Although we could sometimes handle this, and it does occur in 13178 // practice that one of the condition inputs to the select is also one of 13179 // the outputs, we currently can't deal with this. 13180 if (User->getOpcode() == ISD::SELECT) { 13181 if (User->getOperand(0) == PromOps[i]) 13182 return SDValue(); 13183 } else if (User->getOpcode() == ISD::SELECT_CC) { 13184 if (User->getOperand(0) == PromOps[i] || 13185 User->getOperand(1) == PromOps[i]) 13186 return SDValue(); 13187 } 13188 } 13189 } 13190 13191 // Replace all inputs with the extension operand. 13192 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13193 // Constants may have users outside the cluster of to-be-promoted nodes, 13194 // and so we need to replace those as we do the promotions. 13195 if (isa<ConstantSDNode>(Inputs[i])) 13196 continue; 13197 else 13198 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13199 } 13200 13201 std::list<HandleSDNode> PromOpHandles; 13202 for (auto &PromOp : PromOps) 13203 PromOpHandles.emplace_back(PromOp); 13204 13205 // Replace all operations (these are all the same, but have a different 13206 // (i1) return type). DAG.getNode will validate that the types of 13207 // a binary operator match, so go through the list in reverse so that 13208 // we've likely promoted both operands first. Any intermediate truncations or 13209 // extensions disappear. 13210 while (!PromOpHandles.empty()) { 13211 SDValue PromOp = PromOpHandles.back().getValue(); 13212 PromOpHandles.pop_back(); 13213 13214 if (PromOp.getOpcode() == ISD::TRUNCATE || 13215 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13216 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13217 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13218 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13219 PromOp.getOperand(0).getValueType() != MVT::i1) { 13220 // The operand is not yet ready (see comment below). 13221 PromOpHandles.emplace_front(PromOp); 13222 continue; 13223 } 13224 13225 SDValue RepValue = PromOp.getOperand(0); 13226 if (isa<ConstantSDNode>(RepValue)) 13227 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13228 13229 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13230 continue; 13231 } 13232 13233 unsigned C; 13234 switch (PromOp.getOpcode()) { 13235 default: C = 0; break; 13236 case ISD::SELECT: C = 1; break; 13237 case ISD::SELECT_CC: C = 2; break; 13238 } 13239 13240 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13241 PromOp.getOperand(C).getValueType() != MVT::i1) || 13242 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13243 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13244 // The to-be-promoted operands of this node have not yet been 13245 // promoted (this should be rare because we're going through the 13246 // list backward, but if one of the operands has several users in 13247 // this cluster of to-be-promoted nodes, it is possible). 13248 PromOpHandles.emplace_front(PromOp); 13249 continue; 13250 } 13251 13252 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13253 PromOp.getNode()->op_end()); 13254 13255 // If there are any constant inputs, make sure they're replaced now. 13256 for (unsigned i = 0; i < 2; ++i) 13257 if (isa<ConstantSDNode>(Ops[C+i])) 13258 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13259 13260 DAG.ReplaceAllUsesOfValueWith(PromOp, 13261 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13262 } 13263 13264 // Now we're left with the initial truncation itself. 13265 if (N->getOpcode() == ISD::TRUNCATE) 13266 return N->getOperand(0); 13267 13268 // Otherwise, this is a comparison. The operands to be compared have just 13269 // changed type (to i1), but everything else is the same. 13270 return SDValue(N, 0); 13271 } 13272 13273 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13274 DAGCombinerInfo &DCI) const { 13275 SelectionDAG &DAG = DCI.DAG; 13276 SDLoc dl(N); 13277 13278 // If we're tracking CR bits, we need to be careful that we don't have: 13279 // zext(binary-ops(trunc(x), trunc(y))) 13280 // or 13281 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13282 // such that we're unnecessarily moving things into CR bits that can more 13283 // efficiently stay in GPRs. Note that if we're not certain that the high 13284 // bits are set as required by the final extension, we still may need to do 13285 // some masking to get the proper behavior. 13286 13287 // This same functionality is important on PPC64 when dealing with 13288 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13289 // the return values of functions. Because it is so similar, it is handled 13290 // here as well. 13291 13292 if (N->getValueType(0) != MVT::i32 && 13293 N->getValueType(0) != MVT::i64) 13294 return SDValue(); 13295 13296 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13297 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13298 return SDValue(); 13299 13300 if (N->getOperand(0).getOpcode() != ISD::AND && 13301 N->getOperand(0).getOpcode() != ISD::OR && 13302 N->getOperand(0).getOpcode() != ISD::XOR && 13303 N->getOperand(0).getOpcode() != ISD::SELECT && 13304 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13305 return SDValue(); 13306 13307 SmallVector<SDValue, 4> Inputs; 13308 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13309 SmallPtrSet<SDNode *, 16> Visited; 13310 13311 // Visit all inputs, collect all binary operations (and, or, xor and 13312 // select) that are all fed by truncations. 13313 while (!BinOps.empty()) { 13314 SDValue BinOp = BinOps.pop_back_val(); 13315 13316 if (!Visited.insert(BinOp.getNode()).second) 13317 continue; 13318 13319 PromOps.push_back(BinOp); 13320 13321 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13322 // The condition of the select is not promoted. 13323 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13324 continue; 13325 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13326 continue; 13327 13328 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13329 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13330 Inputs.push_back(BinOp.getOperand(i)); 13331 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13332 BinOp.getOperand(i).getOpcode() == ISD::OR || 13333 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13334 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13335 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13336 BinOps.push_back(BinOp.getOperand(i)); 13337 } else { 13338 // We have an input that is not a truncation or another binary 13339 // operation; we'll abort this transformation. 13340 return SDValue(); 13341 } 13342 } 13343 } 13344 13345 // The operands of a select that must be truncated when the select is 13346 // promoted because the operand is actually part of the to-be-promoted set. 13347 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13348 13349 // Make sure that this is a self-contained cluster of operations (which 13350 // is not quite the same thing as saying that everything has only one 13351 // use). 13352 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13353 if (isa<ConstantSDNode>(Inputs[i])) 13354 continue; 13355 13356 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13357 UE = Inputs[i].getNode()->use_end(); 13358 UI != UE; ++UI) { 13359 SDNode *User = *UI; 13360 if (User != N && !Visited.count(User)) 13361 return SDValue(); 13362 13363 // If we're going to promote the non-output-value operand(s) or SELECT or 13364 // SELECT_CC, record them for truncation. 13365 if (User->getOpcode() == ISD::SELECT) { 13366 if (User->getOperand(0) == Inputs[i]) 13367 SelectTruncOp[0].insert(std::make_pair(User, 13368 User->getOperand(0).getValueType())); 13369 } else if (User->getOpcode() == ISD::SELECT_CC) { 13370 if (User->getOperand(0) == Inputs[i]) 13371 SelectTruncOp[0].insert(std::make_pair(User, 13372 User->getOperand(0).getValueType())); 13373 if (User->getOperand(1) == Inputs[i]) 13374 SelectTruncOp[1].insert(std::make_pair(User, 13375 User->getOperand(1).getValueType())); 13376 } 13377 } 13378 } 13379 13380 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13381 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13382 UE = PromOps[i].getNode()->use_end(); 13383 UI != UE; ++UI) { 13384 SDNode *User = *UI; 13385 if (User != N && !Visited.count(User)) 13386 return SDValue(); 13387 13388 // If we're going to promote the non-output-value operand(s) or SELECT or 13389 // SELECT_CC, record them for truncation. 13390 if (User->getOpcode() == ISD::SELECT) { 13391 if (User->getOperand(0) == PromOps[i]) 13392 SelectTruncOp[0].insert(std::make_pair(User, 13393 User->getOperand(0).getValueType())); 13394 } else if (User->getOpcode() == ISD::SELECT_CC) { 13395 if (User->getOperand(0) == PromOps[i]) 13396 SelectTruncOp[0].insert(std::make_pair(User, 13397 User->getOperand(0).getValueType())); 13398 if (User->getOperand(1) == PromOps[i]) 13399 SelectTruncOp[1].insert(std::make_pair(User, 13400 User->getOperand(1).getValueType())); 13401 } 13402 } 13403 } 13404 13405 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13406 bool ReallyNeedsExt = false; 13407 if (N->getOpcode() != ISD::ANY_EXTEND) { 13408 // If all of the inputs are not already sign/zero extended, then 13409 // we'll still need to do that at the end. 13410 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13411 if (isa<ConstantSDNode>(Inputs[i])) 13412 continue; 13413 13414 unsigned OpBits = 13415 Inputs[i].getOperand(0).getValueSizeInBits(); 13416 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13417 13418 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13419 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13420 APInt::getHighBitsSet(OpBits, 13421 OpBits-PromBits))) || 13422 (N->getOpcode() == ISD::SIGN_EXTEND && 13423 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13424 (OpBits-(PromBits-1)))) { 13425 ReallyNeedsExt = true; 13426 break; 13427 } 13428 } 13429 } 13430 13431 // Replace all inputs, either with the truncation operand, or a 13432 // truncation or extension to the final output type. 13433 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13434 // Constant inputs need to be replaced with the to-be-promoted nodes that 13435 // use them because they might have users outside of the cluster of 13436 // promoted nodes. 13437 if (isa<ConstantSDNode>(Inputs[i])) 13438 continue; 13439 13440 SDValue InSrc = Inputs[i].getOperand(0); 13441 if (Inputs[i].getValueType() == N->getValueType(0)) 13442 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13443 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13444 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13445 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13446 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13447 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13448 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13449 else 13450 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13451 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13452 } 13453 13454 std::list<HandleSDNode> PromOpHandles; 13455 for (auto &PromOp : PromOps) 13456 PromOpHandles.emplace_back(PromOp); 13457 13458 // Replace all operations (these are all the same, but have a different 13459 // (promoted) return type). DAG.getNode will validate that the types of 13460 // a binary operator match, so go through the list in reverse so that 13461 // we've likely promoted both operands first. 13462 while (!PromOpHandles.empty()) { 13463 SDValue PromOp = PromOpHandles.back().getValue(); 13464 PromOpHandles.pop_back(); 13465 13466 unsigned C; 13467 switch (PromOp.getOpcode()) { 13468 default: C = 0; break; 13469 case ISD::SELECT: C = 1; break; 13470 case ISD::SELECT_CC: C = 2; break; 13471 } 13472 13473 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13474 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13475 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13476 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13477 // The to-be-promoted operands of this node have not yet been 13478 // promoted (this should be rare because we're going through the 13479 // list backward, but if one of the operands has several users in 13480 // this cluster of to-be-promoted nodes, it is possible). 13481 PromOpHandles.emplace_front(PromOp); 13482 continue; 13483 } 13484 13485 // For SELECT and SELECT_CC nodes, we do a similar check for any 13486 // to-be-promoted comparison inputs. 13487 if (PromOp.getOpcode() == ISD::SELECT || 13488 PromOp.getOpcode() == ISD::SELECT_CC) { 13489 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13490 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13491 (SelectTruncOp[1].count(PromOp.getNode()) && 13492 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13493 PromOpHandles.emplace_front(PromOp); 13494 continue; 13495 } 13496 } 13497 13498 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13499 PromOp.getNode()->op_end()); 13500 13501 // If this node has constant inputs, then they'll need to be promoted here. 13502 for (unsigned i = 0; i < 2; ++i) { 13503 if (!isa<ConstantSDNode>(Ops[C+i])) 13504 continue; 13505 if (Ops[C+i].getValueType() == N->getValueType(0)) 13506 continue; 13507 13508 if (N->getOpcode() == ISD::SIGN_EXTEND) 13509 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13510 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13511 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13512 else 13513 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13514 } 13515 13516 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13517 // truncate them again to the original value type. 13518 if (PromOp.getOpcode() == ISD::SELECT || 13519 PromOp.getOpcode() == ISD::SELECT_CC) { 13520 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13521 if (SI0 != SelectTruncOp[0].end()) 13522 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13523 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13524 if (SI1 != SelectTruncOp[1].end()) 13525 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13526 } 13527 13528 DAG.ReplaceAllUsesOfValueWith(PromOp, 13529 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13530 } 13531 13532 // Now we're left with the initial extension itself. 13533 if (!ReallyNeedsExt) 13534 return N->getOperand(0); 13535 13536 // To zero extend, just mask off everything except for the first bit (in the 13537 // i1 case). 13538 if (N->getOpcode() == ISD::ZERO_EXTEND) 13539 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13540 DAG.getConstant(APInt::getLowBitsSet( 13541 N->getValueSizeInBits(0), PromBits), 13542 dl, N->getValueType(0))); 13543 13544 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13545 "Invalid extension type"); 13546 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13547 SDValue ShiftCst = 13548 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13549 return DAG.getNode( 13550 ISD::SRA, dl, N->getValueType(0), 13551 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13552 ShiftCst); 13553 } 13554 13555 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13556 DAGCombinerInfo &DCI) const { 13557 assert(N->getOpcode() == ISD::SETCC && 13558 "Should be called with a SETCC node"); 13559 13560 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13561 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13562 SDValue LHS = N->getOperand(0); 13563 SDValue RHS = N->getOperand(1); 13564 13565 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13566 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13567 LHS.hasOneUse()) 13568 std::swap(LHS, RHS); 13569 13570 // x == 0-y --> x+y == 0 13571 // x != 0-y --> x+y != 0 13572 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13573 RHS.hasOneUse()) { 13574 SDLoc DL(N); 13575 SelectionDAG &DAG = DCI.DAG; 13576 EVT VT = N->getValueType(0); 13577 EVT OpVT = LHS.getValueType(); 13578 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13579 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13580 } 13581 } 13582 13583 return DAGCombineTruncBoolExt(N, DCI); 13584 } 13585 13586 // Is this an extending load from an f32 to an f64? 13587 static bool isFPExtLoad(SDValue Op) { 13588 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13589 return LD->getExtensionType() == ISD::EXTLOAD && 13590 Op.getValueType() == MVT::f64; 13591 return false; 13592 } 13593 13594 /// Reduces the number of fp-to-int conversion when building a vector. 13595 /// 13596 /// If this vector is built out of floating to integer conversions, 13597 /// transform it to a vector built out of floating point values followed by a 13598 /// single floating to integer conversion of the vector. 13599 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13600 /// becomes (fptosi (build_vector ($A, $B, ...))) 13601 SDValue PPCTargetLowering:: 13602 combineElementTruncationToVectorTruncation(SDNode *N, 13603 DAGCombinerInfo &DCI) const { 13604 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13605 "Should be called with a BUILD_VECTOR node"); 13606 13607 SelectionDAG &DAG = DCI.DAG; 13608 SDLoc dl(N); 13609 13610 SDValue FirstInput = N->getOperand(0); 13611 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13612 "The input operand must be an fp-to-int conversion."); 13613 13614 // This combine happens after legalization so the fp_to_[su]i nodes are 13615 // already converted to PPCSISD nodes. 13616 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13617 if (FirstConversion == PPCISD::FCTIDZ || 13618 FirstConversion == PPCISD::FCTIDUZ || 13619 FirstConversion == PPCISD::FCTIWZ || 13620 FirstConversion == PPCISD::FCTIWUZ) { 13621 bool IsSplat = true; 13622 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13623 FirstConversion == PPCISD::FCTIWUZ; 13624 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13625 SmallVector<SDValue, 4> Ops; 13626 EVT TargetVT = N->getValueType(0); 13627 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13628 SDValue NextOp = N->getOperand(i); 13629 if (NextOp.getOpcode() != PPCISD::MFVSR) 13630 return SDValue(); 13631 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13632 if (NextConversion != FirstConversion) 13633 return SDValue(); 13634 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13635 // This is not valid if the input was originally double precision. It is 13636 // also not profitable to do unless this is an extending load in which 13637 // case doing this combine will allow us to combine consecutive loads. 13638 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13639 return SDValue(); 13640 if (N->getOperand(i) != FirstInput) 13641 IsSplat = false; 13642 } 13643 13644 // If this is a splat, we leave it as-is since there will be only a single 13645 // fp-to-int conversion followed by a splat of the integer. This is better 13646 // for 32-bit and smaller ints and neutral for 64-bit ints. 13647 if (IsSplat) 13648 return SDValue(); 13649 13650 // Now that we know we have the right type of node, get its operands 13651 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13652 SDValue In = N->getOperand(i).getOperand(0); 13653 if (Is32Bit) { 13654 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13655 // here, we know that all inputs are extending loads so this is safe). 13656 if (In.isUndef()) 13657 Ops.push_back(DAG.getUNDEF(SrcVT)); 13658 else { 13659 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13660 MVT::f32, In.getOperand(0), 13661 DAG.getIntPtrConstant(1, dl)); 13662 Ops.push_back(Trunc); 13663 } 13664 } else 13665 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13666 } 13667 13668 unsigned Opcode; 13669 if (FirstConversion == PPCISD::FCTIDZ || 13670 FirstConversion == PPCISD::FCTIWZ) 13671 Opcode = ISD::FP_TO_SINT; 13672 else 13673 Opcode = ISD::FP_TO_UINT; 13674 13675 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13676 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13677 return DAG.getNode(Opcode, dl, TargetVT, BV); 13678 } 13679 return SDValue(); 13680 } 13681 13682 /// Reduce the number of loads when building a vector. 13683 /// 13684 /// Building a vector out of multiple loads can be converted to a load 13685 /// of the vector type if the loads are consecutive. If the loads are 13686 /// consecutive but in descending order, a shuffle is added at the end 13687 /// to reorder the vector. 13688 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13689 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13690 "Should be called with a BUILD_VECTOR node"); 13691 13692 SDLoc dl(N); 13693 13694 // Return early for non byte-sized type, as they can't be consecutive. 13695 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13696 return SDValue(); 13697 13698 bool InputsAreConsecutiveLoads = true; 13699 bool InputsAreReverseConsecutive = true; 13700 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13701 SDValue FirstInput = N->getOperand(0); 13702 bool IsRoundOfExtLoad = false; 13703 13704 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13705 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13706 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13707 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13708 } 13709 // Not a build vector of (possibly fp_rounded) loads. 13710 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13711 N->getNumOperands() == 1) 13712 return SDValue(); 13713 13714 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13715 // If any inputs are fp_round(extload), they all must be. 13716 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13717 return SDValue(); 13718 13719 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13720 N->getOperand(i); 13721 if (NextInput.getOpcode() != ISD::LOAD) 13722 return SDValue(); 13723 13724 SDValue PreviousInput = 13725 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13726 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13727 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13728 13729 // If any inputs are fp_round(extload), they all must be. 13730 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13731 return SDValue(); 13732 13733 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13734 InputsAreConsecutiveLoads = false; 13735 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13736 InputsAreReverseConsecutive = false; 13737 13738 // Exit early if the loads are neither consecutive nor reverse consecutive. 13739 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13740 return SDValue(); 13741 } 13742 13743 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13744 "The loads cannot be both consecutive and reverse consecutive."); 13745 13746 SDValue FirstLoadOp = 13747 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13748 SDValue LastLoadOp = 13749 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13750 N->getOperand(N->getNumOperands()-1); 13751 13752 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13753 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13754 if (InputsAreConsecutiveLoads) { 13755 assert(LD1 && "Input needs to be a LoadSDNode."); 13756 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13757 LD1->getBasePtr(), LD1->getPointerInfo(), 13758 LD1->getAlignment()); 13759 } 13760 if (InputsAreReverseConsecutive) { 13761 assert(LDL && "Input needs to be a LoadSDNode."); 13762 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13763 LDL->getBasePtr(), LDL->getPointerInfo(), 13764 LDL->getAlignment()); 13765 SmallVector<int, 16> Ops; 13766 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13767 Ops.push_back(i); 13768 13769 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13770 DAG.getUNDEF(N->getValueType(0)), Ops); 13771 } 13772 return SDValue(); 13773 } 13774 13775 // This function adds the required vector_shuffle needed to get 13776 // the elements of the vector extract in the correct position 13777 // as specified by the CorrectElems encoding. 13778 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13779 SDValue Input, uint64_t Elems, 13780 uint64_t CorrectElems) { 13781 SDLoc dl(N); 13782 13783 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13784 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13785 13786 // Knowing the element indices being extracted from the original 13787 // vector and the order in which they're being inserted, just put 13788 // them at element indices required for the instruction. 13789 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13790 if (DAG.getDataLayout().isLittleEndian()) 13791 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13792 else 13793 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13794 CorrectElems = CorrectElems >> 8; 13795 Elems = Elems >> 8; 13796 } 13797 13798 SDValue Shuffle = 13799 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13800 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13801 13802 EVT VT = N->getValueType(0); 13803 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13804 13805 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13806 Input.getValueType().getVectorElementType(), 13807 VT.getVectorNumElements()); 13808 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13809 DAG.getValueType(ExtVT)); 13810 } 13811 13812 // Look for build vector patterns where input operands come from sign 13813 // extended vector_extract elements of specific indices. If the correct indices 13814 // aren't used, add a vector shuffle to fix up the indices and create 13815 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13816 // during instruction selection. 13817 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13818 // This array encodes the indices that the vector sign extend instructions 13819 // extract from when extending from one type to another for both BE and LE. 13820 // The right nibble of each byte corresponds to the LE incides. 13821 // and the left nibble of each byte corresponds to the BE incides. 13822 // For example: 0x3074B8FC byte->word 13823 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13824 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13825 // For example: 0x000070F8 byte->double word 13826 // For LE: the allowed indices are: 0x0,0x8 13827 // For BE: the allowed indices are: 0x7,0xF 13828 uint64_t TargetElems[] = { 13829 0x3074B8FC, // b->w 13830 0x000070F8, // b->d 13831 0x10325476, // h->w 13832 0x00003074, // h->d 13833 0x00001032, // w->d 13834 }; 13835 13836 uint64_t Elems = 0; 13837 int Index; 13838 SDValue Input; 13839 13840 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13841 if (!Op) 13842 return false; 13843 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13844 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13845 return false; 13846 13847 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13848 // of the right width. 13849 SDValue Extract = Op.getOperand(0); 13850 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13851 Extract = Extract.getOperand(0); 13852 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13853 return false; 13854 13855 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13856 if (!ExtOp) 13857 return false; 13858 13859 Index = ExtOp->getZExtValue(); 13860 if (Input && Input != Extract.getOperand(0)) 13861 return false; 13862 13863 if (!Input) 13864 Input = Extract.getOperand(0); 13865 13866 Elems = Elems << 8; 13867 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13868 Elems |= Index; 13869 13870 return true; 13871 }; 13872 13873 // If the build vector operands aren't sign extended vector extracts, 13874 // of the same input vector, then return. 13875 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13876 if (!isSExtOfVecExtract(N->getOperand(i))) { 13877 return SDValue(); 13878 } 13879 } 13880 13881 // If the vector extract indicies are not correct, add the appropriate 13882 // vector_shuffle. 13883 int TgtElemArrayIdx; 13884 int InputSize = Input.getValueType().getScalarSizeInBits(); 13885 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13886 if (InputSize + OutputSize == 40) 13887 TgtElemArrayIdx = 0; 13888 else if (InputSize + OutputSize == 72) 13889 TgtElemArrayIdx = 1; 13890 else if (InputSize + OutputSize == 48) 13891 TgtElemArrayIdx = 2; 13892 else if (InputSize + OutputSize == 80) 13893 TgtElemArrayIdx = 3; 13894 else if (InputSize + OutputSize == 96) 13895 TgtElemArrayIdx = 4; 13896 else 13897 return SDValue(); 13898 13899 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13900 CorrectElems = DAG.getDataLayout().isLittleEndian() 13901 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13902 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13903 if (Elems != CorrectElems) { 13904 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13905 } 13906 13907 // Regular lowering will catch cases where a shuffle is not needed. 13908 return SDValue(); 13909 } 13910 13911 // Look for the pattern of a load from a narrow width to i128, feeding 13912 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13913 // (LXVRZX). This node represents a zero extending load that will be matched 13914 // to the Load VSX Vector Rightmost instructions. 13915 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13916 SDLoc DL(N); 13917 13918 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13919 if (N->getValueType(0) != MVT::v1i128) 13920 return SDValue(); 13921 13922 SDValue Operand = N->getOperand(0); 13923 // Proceed with the transformation if the operand to the BUILD_VECTOR 13924 // is a load instruction. 13925 if (Operand.getOpcode() != ISD::LOAD) 13926 return SDValue(); 13927 13928 auto *LD = cast<LoadSDNode>(Operand); 13929 EVT MemoryType = LD->getMemoryVT(); 13930 13931 // This transformation is only valid if the we are loading either a byte, 13932 // halfword, word, or doubleword. 13933 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13934 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13935 13936 // Ensure that the load from the narrow width is being zero extended to i128. 13937 if (!ValidLDType || 13938 (LD->getExtensionType() != ISD::ZEXTLOAD && 13939 LD->getExtensionType() != ISD::EXTLOAD)) 13940 return SDValue(); 13941 13942 SDValue LoadOps[] = { 13943 LD->getChain(), LD->getBasePtr(), 13944 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13945 13946 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13947 DAG.getVTList(MVT::v1i128, MVT::Other), 13948 LoadOps, MemoryType, LD->getMemOperand()); 13949 } 13950 13951 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13952 DAGCombinerInfo &DCI) const { 13953 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13954 "Should be called with a BUILD_VECTOR node"); 13955 13956 SelectionDAG &DAG = DCI.DAG; 13957 SDLoc dl(N); 13958 13959 if (!Subtarget.hasVSX()) 13960 return SDValue(); 13961 13962 // The target independent DAG combiner will leave a build_vector of 13963 // float-to-int conversions intact. We can generate MUCH better code for 13964 // a float-to-int conversion of a vector of floats. 13965 SDValue FirstInput = N->getOperand(0); 13966 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13967 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13968 if (Reduced) 13969 return Reduced; 13970 } 13971 13972 // If we're building a vector out of consecutive loads, just load that 13973 // vector type. 13974 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13975 if (Reduced) 13976 return Reduced; 13977 13978 // If we're building a vector out of extended elements from another vector 13979 // we have P9 vector integer extend instructions. The code assumes legal 13980 // input types (i.e. it can't handle things like v4i16) so do not run before 13981 // legalization. 13982 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13983 Reduced = combineBVOfVecSExt(N, DAG); 13984 if (Reduced) 13985 return Reduced; 13986 } 13987 13988 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13989 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13990 // is a load from <valid narrow width> to i128. 13991 if (Subtarget.isISA3_1()) { 13992 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13993 if (BVOfZLoad) 13994 return BVOfZLoad; 13995 } 13996 13997 if (N->getValueType(0) != MVT::v2f64) 13998 return SDValue(); 13999 14000 // Looking for: 14001 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14002 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14003 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14004 return SDValue(); 14005 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14006 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14007 return SDValue(); 14008 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14009 return SDValue(); 14010 14011 SDValue Ext1 = FirstInput.getOperand(0); 14012 SDValue Ext2 = N->getOperand(1).getOperand(0); 14013 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14014 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14015 return SDValue(); 14016 14017 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14018 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14019 if (!Ext1Op || !Ext2Op) 14020 return SDValue(); 14021 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14022 Ext1.getOperand(0) != Ext2.getOperand(0)) 14023 return SDValue(); 14024 14025 int FirstElem = Ext1Op->getZExtValue(); 14026 int SecondElem = Ext2Op->getZExtValue(); 14027 int SubvecIdx; 14028 if (FirstElem == 0 && SecondElem == 1) 14029 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14030 else if (FirstElem == 2 && SecondElem == 3) 14031 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14032 else 14033 return SDValue(); 14034 14035 SDValue SrcVec = Ext1.getOperand(0); 14036 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14037 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14038 return DAG.getNode(NodeType, dl, MVT::v2f64, 14039 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14040 } 14041 14042 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14043 DAGCombinerInfo &DCI) const { 14044 assert((N->getOpcode() == ISD::SINT_TO_FP || 14045 N->getOpcode() == ISD::UINT_TO_FP) && 14046 "Need an int -> FP conversion node here"); 14047 14048 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14049 return SDValue(); 14050 14051 SelectionDAG &DAG = DCI.DAG; 14052 SDLoc dl(N); 14053 SDValue Op(N, 0); 14054 14055 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14056 // from the hardware. 14057 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14058 return SDValue(); 14059 if (!Op.getOperand(0).getValueType().isSimple()) 14060 return SDValue(); 14061 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14062 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14063 return SDValue(); 14064 14065 SDValue FirstOperand(Op.getOperand(0)); 14066 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14067 (FirstOperand.getValueType() == MVT::i8 || 14068 FirstOperand.getValueType() == MVT::i16); 14069 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14070 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14071 bool DstDouble = Op.getValueType() == MVT::f64; 14072 unsigned ConvOp = Signed ? 14073 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14074 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14075 SDValue WidthConst = 14076 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14077 dl, false); 14078 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14079 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14080 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14081 DAG.getVTList(MVT::f64, MVT::Other), 14082 Ops, MVT::i8, LDN->getMemOperand()); 14083 14084 // For signed conversion, we need to sign-extend the value in the VSR 14085 if (Signed) { 14086 SDValue ExtOps[] = { Ld, WidthConst }; 14087 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14088 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14089 } else 14090 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14091 } 14092 14093 14094 // For i32 intermediate values, unfortunately, the conversion functions 14095 // leave the upper 32 bits of the value are undefined. Within the set of 14096 // scalar instructions, we have no method for zero- or sign-extending the 14097 // value. Thus, we cannot handle i32 intermediate values here. 14098 if (Op.getOperand(0).getValueType() == MVT::i32) 14099 return SDValue(); 14100 14101 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14102 "UINT_TO_FP is supported only with FPCVT"); 14103 14104 // If we have FCFIDS, then use it when converting to single-precision. 14105 // Otherwise, convert to double-precision and then round. 14106 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14107 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14108 : PPCISD::FCFIDS) 14109 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14110 : PPCISD::FCFID); 14111 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14112 ? MVT::f32 14113 : MVT::f64; 14114 14115 // If we're converting from a float, to an int, and back to a float again, 14116 // then we don't need the store/load pair at all. 14117 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14118 Subtarget.hasFPCVT()) || 14119 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14120 SDValue Src = Op.getOperand(0).getOperand(0); 14121 if (Src.getValueType() == MVT::f32) { 14122 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14123 DCI.AddToWorklist(Src.getNode()); 14124 } else if (Src.getValueType() != MVT::f64) { 14125 // Make sure that we don't pick up a ppc_fp128 source value. 14126 return SDValue(); 14127 } 14128 14129 unsigned FCTOp = 14130 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14131 PPCISD::FCTIDUZ; 14132 14133 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14134 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14135 14136 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14137 FP = DAG.getNode(ISD::FP_ROUND, dl, 14138 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14139 DCI.AddToWorklist(FP.getNode()); 14140 } 14141 14142 return FP; 14143 } 14144 14145 return SDValue(); 14146 } 14147 14148 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14149 // builtins) into loads with swaps. 14150 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14151 DAGCombinerInfo &DCI) const { 14152 SelectionDAG &DAG = DCI.DAG; 14153 SDLoc dl(N); 14154 SDValue Chain; 14155 SDValue Base; 14156 MachineMemOperand *MMO; 14157 14158 switch (N->getOpcode()) { 14159 default: 14160 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14161 case ISD::LOAD: { 14162 LoadSDNode *LD = cast<LoadSDNode>(N); 14163 Chain = LD->getChain(); 14164 Base = LD->getBasePtr(); 14165 MMO = LD->getMemOperand(); 14166 // If the MMO suggests this isn't a load of a full vector, leave 14167 // things alone. For a built-in, we have to make the change for 14168 // correctness, so if there is a size problem that will be a bug. 14169 if (MMO->getSize() < 16) 14170 return SDValue(); 14171 break; 14172 } 14173 case ISD::INTRINSIC_W_CHAIN: { 14174 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14175 Chain = Intrin->getChain(); 14176 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14177 // us what we want. Get operand 2 instead. 14178 Base = Intrin->getOperand(2); 14179 MMO = Intrin->getMemOperand(); 14180 break; 14181 } 14182 } 14183 14184 MVT VecTy = N->getValueType(0).getSimpleVT(); 14185 14186 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14187 // aligned and the type is a vector with elements up to 4 bytes 14188 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14189 VecTy.getScalarSizeInBits() <= 32) { 14190 return SDValue(); 14191 } 14192 14193 SDValue LoadOps[] = { Chain, Base }; 14194 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14195 DAG.getVTList(MVT::v2f64, MVT::Other), 14196 LoadOps, MVT::v2f64, MMO); 14197 14198 DCI.AddToWorklist(Load.getNode()); 14199 Chain = Load.getValue(1); 14200 SDValue Swap = DAG.getNode( 14201 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14202 DCI.AddToWorklist(Swap.getNode()); 14203 14204 // Add a bitcast if the resulting load type doesn't match v2f64. 14205 if (VecTy != MVT::v2f64) { 14206 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14207 DCI.AddToWorklist(N.getNode()); 14208 // Package {bitcast value, swap's chain} to match Load's shape. 14209 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14210 N, Swap.getValue(1)); 14211 } 14212 14213 return Swap; 14214 } 14215 14216 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14217 // builtins) into stores with swaps. 14218 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14219 DAGCombinerInfo &DCI) const { 14220 SelectionDAG &DAG = DCI.DAG; 14221 SDLoc dl(N); 14222 SDValue Chain; 14223 SDValue Base; 14224 unsigned SrcOpnd; 14225 MachineMemOperand *MMO; 14226 14227 switch (N->getOpcode()) { 14228 default: 14229 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14230 case ISD::STORE: { 14231 StoreSDNode *ST = cast<StoreSDNode>(N); 14232 Chain = ST->getChain(); 14233 Base = ST->getBasePtr(); 14234 MMO = ST->getMemOperand(); 14235 SrcOpnd = 1; 14236 // If the MMO suggests this isn't a store of a full vector, leave 14237 // things alone. For a built-in, we have to make the change for 14238 // correctness, so if there is a size problem that will be a bug. 14239 if (MMO->getSize() < 16) 14240 return SDValue(); 14241 break; 14242 } 14243 case ISD::INTRINSIC_VOID: { 14244 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14245 Chain = Intrin->getChain(); 14246 // Intrin->getBasePtr() oddly does not get what we want. 14247 Base = Intrin->getOperand(3); 14248 MMO = Intrin->getMemOperand(); 14249 SrcOpnd = 2; 14250 break; 14251 } 14252 } 14253 14254 SDValue Src = N->getOperand(SrcOpnd); 14255 MVT VecTy = Src.getValueType().getSimpleVT(); 14256 14257 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14258 // aligned and the type is a vector with elements up to 4 bytes 14259 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14260 VecTy.getScalarSizeInBits() <= 32) { 14261 return SDValue(); 14262 } 14263 14264 // All stores are done as v2f64 and possible bit cast. 14265 if (VecTy != MVT::v2f64) { 14266 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14267 DCI.AddToWorklist(Src.getNode()); 14268 } 14269 14270 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14271 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14272 DCI.AddToWorklist(Swap.getNode()); 14273 Chain = Swap.getValue(1); 14274 SDValue StoreOps[] = { Chain, Swap, Base }; 14275 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14276 DAG.getVTList(MVT::Other), 14277 StoreOps, VecTy, MMO); 14278 DCI.AddToWorklist(Store.getNode()); 14279 return Store; 14280 } 14281 14282 // Handle DAG combine for STORE (FP_TO_INT F). 14283 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14284 DAGCombinerInfo &DCI) const { 14285 14286 SelectionDAG &DAG = DCI.DAG; 14287 SDLoc dl(N); 14288 unsigned Opcode = N->getOperand(1).getOpcode(); 14289 14290 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14291 && "Not a FP_TO_INT Instruction!"); 14292 14293 SDValue Val = N->getOperand(1).getOperand(0); 14294 EVT Op1VT = N->getOperand(1).getValueType(); 14295 EVT ResVT = Val.getValueType(); 14296 14297 if (!isTypeLegal(ResVT)) 14298 return SDValue(); 14299 14300 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14301 bool ValidTypeForStoreFltAsInt = 14302 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14303 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14304 14305 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14306 return SDValue(); 14307 14308 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14309 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14310 return SDValue(); 14311 14312 // Extend f32 values to f64 14313 if (ResVT.getScalarSizeInBits() == 32) { 14314 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14315 DCI.AddToWorklist(Val.getNode()); 14316 } 14317 14318 // Set signed or unsigned conversion opcode. 14319 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14320 PPCISD::FP_TO_SINT_IN_VSR : 14321 PPCISD::FP_TO_UINT_IN_VSR; 14322 14323 Val = DAG.getNode(ConvOpcode, 14324 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14325 DCI.AddToWorklist(Val.getNode()); 14326 14327 // Set number of bytes being converted. 14328 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14329 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14330 DAG.getIntPtrConstant(ByteSize, dl, false), 14331 DAG.getValueType(Op1VT) }; 14332 14333 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14334 DAG.getVTList(MVT::Other), Ops, 14335 cast<StoreSDNode>(N)->getMemoryVT(), 14336 cast<StoreSDNode>(N)->getMemOperand()); 14337 14338 DCI.AddToWorklist(Val.getNode()); 14339 return Val; 14340 } 14341 14342 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14343 // Check that the source of the element keeps flipping 14344 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14345 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14346 for (int i = 1, e = Mask.size(); i < e; i++) { 14347 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14348 return false; 14349 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14350 return false; 14351 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14352 } 14353 return true; 14354 } 14355 14356 static bool isSplatBV(SDValue Op) { 14357 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14358 return false; 14359 SDValue FirstOp; 14360 14361 // Find first non-undef input. 14362 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14363 FirstOp = Op.getOperand(i); 14364 if (!FirstOp.isUndef()) 14365 break; 14366 } 14367 14368 // All inputs are undef or the same as the first non-undef input. 14369 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14370 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14371 return false; 14372 return true; 14373 } 14374 14375 static SDValue isScalarToVec(SDValue Op) { 14376 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14377 return Op; 14378 if (Op.getOpcode() != ISD::BITCAST) 14379 return SDValue(); 14380 Op = Op.getOperand(0); 14381 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14382 return Op; 14383 return SDValue(); 14384 } 14385 14386 // Fix up the shuffle mask to account for the fact that the result of 14387 // scalar_to_vector is not in lane zero. This just takes all values in 14388 // the ranges specified by the min/max indices and adds the number of 14389 // elements required to ensure each element comes from the respective 14390 // position in the valid lane. 14391 // On little endian, that's just the corresponding element in the other 14392 // half of the vector. On big endian, it is in the same half but right 14393 // justified rather than left justified in that half. 14394 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14395 int LHSMaxIdx, int RHSMinIdx, 14396 int RHSMaxIdx, int HalfVec, 14397 unsigned ValidLaneWidth, 14398 const PPCSubtarget &Subtarget) { 14399 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14400 int Idx = ShuffV[i]; 14401 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14402 ShuffV[i] += 14403 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14404 } 14405 } 14406 14407 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14408 // the original is: 14409 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14410 // In such a case, just change the shuffle mask to extract the element 14411 // from the permuted index. 14412 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14413 const PPCSubtarget &Subtarget) { 14414 SDLoc dl(OrigSToV); 14415 EVT VT = OrigSToV.getValueType(); 14416 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14417 "Expecting a SCALAR_TO_VECTOR here"); 14418 SDValue Input = OrigSToV.getOperand(0); 14419 14420 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14421 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14422 SDValue OrigVector = Input.getOperand(0); 14423 14424 // Can't handle non-const element indices or different vector types 14425 // for the input to the extract and the output of the scalar_to_vector. 14426 if (Idx && VT == OrigVector.getValueType()) { 14427 unsigned NumElts = VT.getVectorNumElements(); 14428 assert( 14429 NumElts > 1 && 14430 "Cannot produce a permuted scalar_to_vector for one element vector"); 14431 SmallVector<int, 16> NewMask(NumElts, -1); 14432 unsigned ResultInElt = NumElts / 2; 14433 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14434 NewMask[ResultInElt] = Idx->getZExtValue(); 14435 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14436 } 14437 } 14438 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14439 OrigSToV.getOperand(0)); 14440 } 14441 14442 // On little endian subtargets, combine shuffles such as: 14443 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14444 // into: 14445 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14446 // because the latter can be matched to a single instruction merge. 14447 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14448 // to put the value into element zero. Adjust the shuffle mask so that the 14449 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14450 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 14451 // nodes with elements smaller than doubleword because all the ways 14452 // of getting scalar data into a vector register put the value in the 14453 // rightmost element of the left half of the vector. 14454 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14455 SelectionDAG &DAG) const { 14456 SDValue LHS = SVN->getOperand(0); 14457 SDValue RHS = SVN->getOperand(1); 14458 auto Mask = SVN->getMask(); 14459 int NumElts = LHS.getValueType().getVectorNumElements(); 14460 SDValue Res(SVN, 0); 14461 SDLoc dl(SVN); 14462 bool IsLittleEndian = Subtarget.isLittleEndian(); 14463 14464 // On little endian targets, do these combines on all VSX targets since 14465 // canonical shuffles match efficient permutes. On big endian targets, 14466 // this is only useful for targets with direct moves. 14467 if (!Subtarget.hasDirectMove() && !(IsLittleEndian && Subtarget.hasVSX())) 14468 return Res; 14469 14470 // If this is not a shuffle of a shuffle and the first element comes from 14471 // the second vector, canonicalize to the commuted form. This will make it 14472 // more likely to match one of the single instruction patterns. 14473 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14474 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14475 std::swap(LHS, RHS); 14476 Res = DAG.getCommutedVectorShuffle(*SVN); 14477 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14478 } 14479 14480 // Adjust the shuffle mask if either input vector comes from a 14481 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14482 // form (to prevent the need for a swap). 14483 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14484 SDValue SToVLHS = isScalarToVec(LHS); 14485 SDValue SToVRHS = isScalarToVec(RHS); 14486 if (SToVLHS || SToVRHS) { 14487 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14488 : SToVRHS.getValueType().getVectorNumElements(); 14489 int NumEltsOut = ShuffV.size(); 14490 unsigned InElemSizeInBits = 14491 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() 14492 : SToVRHS.getValueType().getScalarSizeInBits(); 14493 unsigned OutElemSizeInBits = SToVLHS 14494 ? LHS.getValueType().getScalarSizeInBits() 14495 : RHS.getValueType().getScalarSizeInBits(); 14496 14497 // The width of the "valid lane" (i.e. the lane that contains the value that 14498 // is vectorized) needs to be expressed in terms of the number of elements 14499 // of the shuffle. It is thereby the ratio of the values before and after 14500 // any bitcast. 14501 unsigned ValidLaneWidth = InElemSizeInBits / OutElemSizeInBits; 14502 14503 // Initially assume that neither input is permuted. These will be adjusted 14504 // accordingly if either input is. 14505 int LHSMaxIdx = -1; 14506 int RHSMinIdx = -1; 14507 int RHSMaxIdx = -1; 14508 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14509 14510 // Get the permuted scalar to vector nodes for the source(s) that come from 14511 // ISD::SCALAR_TO_VECTOR. 14512 // On big endian systems, this only makes sense for element sizes smaller 14513 // than 64 bits since for 64-bit elements, all instructions already put 14514 // the value into element zero. 14515 if (SToVLHS) { 14516 if (!IsLittleEndian && InElemSizeInBits >= 64) 14517 return Res; 14518 // Set up the values for the shuffle vector fixup. 14519 LHSMaxIdx = NumEltsOut / NumEltsIn; 14520 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 14521 if (SToVLHS.getValueType() != LHS.getValueType()) 14522 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14523 LHS = SToVLHS; 14524 } 14525 if (SToVRHS) { 14526 if (!IsLittleEndian && InElemSizeInBits >= 64) 14527 return Res; 14528 RHSMinIdx = NumEltsOut; 14529 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14530 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 14531 if (SToVRHS.getValueType() != RHS.getValueType()) 14532 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14533 RHS = SToVRHS; 14534 } 14535 14536 // Fix up the shuffle mask to reflect where the desired element actually is. 14537 // The minimum and maximum indices that correspond to element zero for both 14538 // the LHS and RHS are computed and will control which shuffle mask entries 14539 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14540 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 14541 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14542 HalfVec, ValidLaneWidth, Subtarget); 14543 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14544 14545 // We may have simplified away the shuffle. We won't be able to do anything 14546 // further with it here. 14547 if (!isa<ShuffleVectorSDNode>(Res)) 14548 return Res; 14549 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14550 } 14551 14552 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 14553 // The common case after we commuted the shuffle is that the RHS is a splat 14554 // and we have elements coming in from the splat at indices that are not 14555 // conducive to using a merge. 14556 // Example: 14557 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14558 if (!isSplatBV(TheSplat)) 14559 return Res; 14560 14561 // We are looking for a mask such that all even elements are from 14562 // one vector and all odd elements from the other. 14563 if (!isAlternatingShuffMask(Mask, NumElts)) 14564 return Res; 14565 14566 // Adjust the mask so we are pulling in the same index from the splat 14567 // as the index from the interesting vector in consecutive elements. 14568 if (IsLittleEndian) { 14569 // Example (even elements from first vector): 14570 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14571 if (Mask[0] < NumElts) 14572 for (int i = 1, e = Mask.size(); i < e; i += 2) 14573 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14574 // Example (odd elements from first vector): 14575 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14576 else 14577 for (int i = 0, e = Mask.size(); i < e; i += 2) 14578 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14579 } else { 14580 // Example (even elements from first vector): 14581 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 14582 if (Mask[0] < NumElts) 14583 for (int i = 0, e = Mask.size(); i < e; i += 2) 14584 ShuffV[i] = ShuffV[i + 1] - NumElts; 14585 // Example (odd elements from first vector): 14586 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 14587 else 14588 for (int i = 1, e = Mask.size(); i < e; i += 2) 14589 ShuffV[i] = ShuffV[i - 1] - NumElts; 14590 } 14591 14592 // If the RHS has undefs, we need to remove them since we may have created 14593 // a shuffle that adds those instead of the splat value. 14594 SDValue SplatVal = 14595 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 14596 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 14597 14598 if (IsLittleEndian) 14599 RHS = TheSplat; 14600 else 14601 LHS = TheSplat; 14602 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14603 } 14604 14605 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14606 LSBaseSDNode *LSBase, 14607 DAGCombinerInfo &DCI) const { 14608 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14609 "Not a reverse memop pattern!"); 14610 14611 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14612 auto Mask = SVN->getMask(); 14613 int i = 0; 14614 auto I = Mask.rbegin(); 14615 auto E = Mask.rend(); 14616 14617 for (; I != E; ++I) { 14618 if (*I != i) 14619 return false; 14620 i++; 14621 } 14622 return true; 14623 }; 14624 14625 SelectionDAG &DAG = DCI.DAG; 14626 EVT VT = SVN->getValueType(0); 14627 14628 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14629 return SDValue(); 14630 14631 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14632 // See comment in PPCVSXSwapRemoval.cpp. 14633 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14634 if (!Subtarget.hasP9Vector()) 14635 return SDValue(); 14636 14637 if(!IsElementReverse(SVN)) 14638 return SDValue(); 14639 14640 if (LSBase->getOpcode() == ISD::LOAD) { 14641 // If the load return value 0 has more than one user except the 14642 // shufflevector instruction, it is not profitable to replace the 14643 // shufflevector with a reverse load. 14644 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end(); 14645 UI != UE; ++UI) 14646 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE) 14647 return SDValue(); 14648 14649 SDLoc dl(LSBase); 14650 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14651 return DAG.getMemIntrinsicNode( 14652 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14653 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14654 } 14655 14656 if (LSBase->getOpcode() == ISD::STORE) { 14657 // If there are other uses of the shuffle, the swap cannot be avoided. 14658 // Forcing the use of an X-Form (since swapped stores only have 14659 // X-Forms) without removing the swap is unprofitable. 14660 if (!SVN->hasOneUse()) 14661 return SDValue(); 14662 14663 SDLoc dl(LSBase); 14664 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14665 LSBase->getBasePtr()}; 14666 return DAG.getMemIntrinsicNode( 14667 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14668 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14669 } 14670 14671 llvm_unreachable("Expected a load or store node here"); 14672 } 14673 14674 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14675 DAGCombinerInfo &DCI) const { 14676 SelectionDAG &DAG = DCI.DAG; 14677 SDLoc dl(N); 14678 switch (N->getOpcode()) { 14679 default: break; 14680 case ISD::ADD: 14681 return combineADD(N, DCI); 14682 case ISD::SHL: 14683 return combineSHL(N, DCI); 14684 case ISD::SRA: 14685 return combineSRA(N, DCI); 14686 case ISD::SRL: 14687 return combineSRL(N, DCI); 14688 case ISD::MUL: 14689 return combineMUL(N, DCI); 14690 case ISD::FMA: 14691 case PPCISD::FNMSUB: 14692 return combineFMALike(N, DCI); 14693 case PPCISD::SHL: 14694 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14695 return N->getOperand(0); 14696 break; 14697 case PPCISD::SRL: 14698 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14699 return N->getOperand(0); 14700 break; 14701 case PPCISD::SRA: 14702 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14703 if (C->isNullValue() || // 0 >>s V -> 0. 14704 C->isAllOnesValue()) // -1 >>s V -> -1. 14705 return N->getOperand(0); 14706 } 14707 break; 14708 case ISD::SIGN_EXTEND: 14709 case ISD::ZERO_EXTEND: 14710 case ISD::ANY_EXTEND: 14711 return DAGCombineExtBoolTrunc(N, DCI); 14712 case ISD::TRUNCATE: 14713 return combineTRUNCATE(N, DCI); 14714 case ISD::SETCC: 14715 if (SDValue CSCC = combineSetCC(N, DCI)) 14716 return CSCC; 14717 LLVM_FALLTHROUGH; 14718 case ISD::SELECT_CC: 14719 return DAGCombineTruncBoolExt(N, DCI); 14720 case ISD::SINT_TO_FP: 14721 case ISD::UINT_TO_FP: 14722 return combineFPToIntToFP(N, DCI); 14723 case ISD::VECTOR_SHUFFLE: 14724 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14725 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14726 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14727 } 14728 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14729 case ISD::STORE: { 14730 14731 EVT Op1VT = N->getOperand(1).getValueType(); 14732 unsigned Opcode = N->getOperand(1).getOpcode(); 14733 14734 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14735 SDValue Val= combineStoreFPToInt(N, DCI); 14736 if (Val) 14737 return Val; 14738 } 14739 14740 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14741 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14742 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14743 if (Val) 14744 return Val; 14745 } 14746 14747 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14748 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14749 N->getOperand(1).getNode()->hasOneUse() && 14750 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14751 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14752 14753 // STBRX can only handle simple types and it makes no sense to store less 14754 // two bytes in byte-reversed order. 14755 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14756 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14757 break; 14758 14759 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14760 // Do an any-extend to 32-bits if this is a half-word input. 14761 if (BSwapOp.getValueType() == MVT::i16) 14762 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14763 14764 // If the type of BSWAP operand is wider than stored memory width 14765 // it need to be shifted to the right side before STBRX. 14766 if (Op1VT.bitsGT(mVT)) { 14767 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14768 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14769 DAG.getConstant(Shift, dl, MVT::i32)); 14770 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14771 if (Op1VT == MVT::i64) 14772 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14773 } 14774 14775 SDValue Ops[] = { 14776 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14777 }; 14778 return 14779 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14780 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14781 cast<StoreSDNode>(N)->getMemOperand()); 14782 } 14783 14784 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14785 // So it can increase the chance of CSE constant construction. 14786 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14787 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14788 // Need to sign-extended to 64-bits to handle negative values. 14789 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14790 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14791 MemVT.getSizeInBits()); 14792 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14793 14794 // DAG.getTruncStore() can't be used here because it doesn't accept 14795 // the general (base + offset) addressing mode. 14796 // So we use UpdateNodeOperands and setTruncatingStore instead. 14797 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14798 N->getOperand(3)); 14799 cast<StoreSDNode>(N)->setTruncatingStore(true); 14800 return SDValue(N, 0); 14801 } 14802 14803 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14804 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14805 if (Op1VT.isSimple()) { 14806 MVT StoreVT = Op1VT.getSimpleVT(); 14807 if (Subtarget.needsSwapsForVSXMemOps() && 14808 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14809 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14810 return expandVSXStoreForLE(N, DCI); 14811 } 14812 break; 14813 } 14814 case ISD::LOAD: { 14815 LoadSDNode *LD = cast<LoadSDNode>(N); 14816 EVT VT = LD->getValueType(0); 14817 14818 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14819 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14820 if (VT.isSimple()) { 14821 MVT LoadVT = VT.getSimpleVT(); 14822 if (Subtarget.needsSwapsForVSXMemOps() && 14823 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14824 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14825 return expandVSXLoadForLE(N, DCI); 14826 } 14827 14828 // We sometimes end up with a 64-bit integer load, from which we extract 14829 // two single-precision floating-point numbers. This happens with 14830 // std::complex<float>, and other similar structures, because of the way we 14831 // canonicalize structure copies. However, if we lack direct moves, 14832 // then the final bitcasts from the extracted integer values to the 14833 // floating-point numbers turn into store/load pairs. Even with direct moves, 14834 // just loading the two floating-point numbers is likely better. 14835 auto ReplaceTwoFloatLoad = [&]() { 14836 if (VT != MVT::i64) 14837 return false; 14838 14839 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14840 LD->isVolatile()) 14841 return false; 14842 14843 // We're looking for a sequence like this: 14844 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14845 // t16: i64 = srl t13, Constant:i32<32> 14846 // t17: i32 = truncate t16 14847 // t18: f32 = bitcast t17 14848 // t19: i32 = truncate t13 14849 // t20: f32 = bitcast t19 14850 14851 if (!LD->hasNUsesOfValue(2, 0)) 14852 return false; 14853 14854 auto UI = LD->use_begin(); 14855 while (UI.getUse().getResNo() != 0) ++UI; 14856 SDNode *Trunc = *UI++; 14857 while (UI.getUse().getResNo() != 0) ++UI; 14858 SDNode *RightShift = *UI; 14859 if (Trunc->getOpcode() != ISD::TRUNCATE) 14860 std::swap(Trunc, RightShift); 14861 14862 if (Trunc->getOpcode() != ISD::TRUNCATE || 14863 Trunc->getValueType(0) != MVT::i32 || 14864 !Trunc->hasOneUse()) 14865 return false; 14866 if (RightShift->getOpcode() != ISD::SRL || 14867 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14868 RightShift->getConstantOperandVal(1) != 32 || 14869 !RightShift->hasOneUse()) 14870 return false; 14871 14872 SDNode *Trunc2 = *RightShift->use_begin(); 14873 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14874 Trunc2->getValueType(0) != MVT::i32 || 14875 !Trunc2->hasOneUse()) 14876 return false; 14877 14878 SDNode *Bitcast = *Trunc->use_begin(); 14879 SDNode *Bitcast2 = *Trunc2->use_begin(); 14880 14881 if (Bitcast->getOpcode() != ISD::BITCAST || 14882 Bitcast->getValueType(0) != MVT::f32) 14883 return false; 14884 if (Bitcast2->getOpcode() != ISD::BITCAST || 14885 Bitcast2->getValueType(0) != MVT::f32) 14886 return false; 14887 14888 if (Subtarget.isLittleEndian()) 14889 std::swap(Bitcast, Bitcast2); 14890 14891 // Bitcast has the second float (in memory-layout order) and Bitcast2 14892 // has the first one. 14893 14894 SDValue BasePtr = LD->getBasePtr(); 14895 if (LD->isIndexed()) { 14896 assert(LD->getAddressingMode() == ISD::PRE_INC && 14897 "Non-pre-inc AM on PPC?"); 14898 BasePtr = 14899 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14900 LD->getOffset()); 14901 } 14902 14903 auto MMOFlags = 14904 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14905 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14906 LD->getPointerInfo(), LD->getAlignment(), 14907 MMOFlags, LD->getAAInfo()); 14908 SDValue AddPtr = 14909 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14910 BasePtr, DAG.getIntPtrConstant(4, dl)); 14911 SDValue FloatLoad2 = DAG.getLoad( 14912 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14913 LD->getPointerInfo().getWithOffset(4), 14914 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14915 14916 if (LD->isIndexed()) { 14917 // Note that DAGCombine should re-form any pre-increment load(s) from 14918 // what is produced here if that makes sense. 14919 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14920 } 14921 14922 DCI.CombineTo(Bitcast2, FloatLoad); 14923 DCI.CombineTo(Bitcast, FloatLoad2); 14924 14925 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14926 SDValue(FloatLoad2.getNode(), 1)); 14927 return true; 14928 }; 14929 14930 if (ReplaceTwoFloatLoad()) 14931 return SDValue(N, 0); 14932 14933 EVT MemVT = LD->getMemoryVT(); 14934 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14935 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14936 if (LD->isUnindexed() && VT.isVector() && 14937 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14938 // P8 and later hardware should just use LOAD. 14939 !Subtarget.hasP8Vector() && 14940 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14941 VT == MVT::v4f32))) && 14942 LD->getAlign() < ABIAlignment) { 14943 // This is a type-legal unaligned Altivec load. 14944 SDValue Chain = LD->getChain(); 14945 SDValue Ptr = LD->getBasePtr(); 14946 bool isLittleEndian = Subtarget.isLittleEndian(); 14947 14948 // This implements the loading of unaligned vectors as described in 14949 // the venerable Apple Velocity Engine overview. Specifically: 14950 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14951 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14952 // 14953 // The general idea is to expand a sequence of one or more unaligned 14954 // loads into an alignment-based permutation-control instruction (lvsl 14955 // or lvsr), a series of regular vector loads (which always truncate 14956 // their input address to an aligned address), and a series of 14957 // permutations. The results of these permutations are the requested 14958 // loaded values. The trick is that the last "extra" load is not taken 14959 // from the address you might suspect (sizeof(vector) bytes after the 14960 // last requested load), but rather sizeof(vector) - 1 bytes after the 14961 // last requested vector. The point of this is to avoid a page fault if 14962 // the base address happened to be aligned. This works because if the 14963 // base address is aligned, then adding less than a full vector length 14964 // will cause the last vector in the sequence to be (re)loaded. 14965 // Otherwise, the next vector will be fetched as you might suspect was 14966 // necessary. 14967 14968 // We might be able to reuse the permutation generation from 14969 // a different base address offset from this one by an aligned amount. 14970 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14971 // optimization later. 14972 Intrinsic::ID Intr, IntrLD, IntrPerm; 14973 MVT PermCntlTy, PermTy, LDTy; 14974 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14975 : Intrinsic::ppc_altivec_lvsl; 14976 IntrLD = Intrinsic::ppc_altivec_lvx; 14977 IntrPerm = Intrinsic::ppc_altivec_vperm; 14978 PermCntlTy = MVT::v16i8; 14979 PermTy = MVT::v4i32; 14980 LDTy = MVT::v4i32; 14981 14982 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14983 14984 // Create the new MMO for the new base load. It is like the original MMO, 14985 // but represents an area in memory almost twice the vector size centered 14986 // on the original address. If the address is unaligned, we might start 14987 // reading up to (sizeof(vector)-1) bytes below the address of the 14988 // original unaligned load. 14989 MachineFunction &MF = DAG.getMachineFunction(); 14990 MachineMemOperand *BaseMMO = 14991 MF.getMachineMemOperand(LD->getMemOperand(), 14992 -(long)MemVT.getStoreSize()+1, 14993 2*MemVT.getStoreSize()-1); 14994 14995 // Create the new base load. 14996 SDValue LDXIntID = 14997 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14998 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14999 SDValue BaseLoad = 15000 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15001 DAG.getVTList(PermTy, MVT::Other), 15002 BaseLoadOps, LDTy, BaseMMO); 15003 15004 // Note that the value of IncOffset (which is provided to the next 15005 // load's pointer info offset value, and thus used to calculate the 15006 // alignment), and the value of IncValue (which is actually used to 15007 // increment the pointer value) are different! This is because we 15008 // require the next load to appear to be aligned, even though it 15009 // is actually offset from the base pointer by a lesser amount. 15010 int IncOffset = VT.getSizeInBits() / 8; 15011 int IncValue = IncOffset; 15012 15013 // Walk (both up and down) the chain looking for another load at the real 15014 // (aligned) offset (the alignment of the other load does not matter in 15015 // this case). If found, then do not use the offset reduction trick, as 15016 // that will prevent the loads from being later combined (as they would 15017 // otherwise be duplicates). 15018 if (!findConsecutiveLoad(LD, DAG)) 15019 --IncValue; 15020 15021 SDValue Increment = 15022 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15023 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15024 15025 MachineMemOperand *ExtraMMO = 15026 MF.getMachineMemOperand(LD->getMemOperand(), 15027 1, 2*MemVT.getStoreSize()-1); 15028 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15029 SDValue ExtraLoad = 15030 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15031 DAG.getVTList(PermTy, MVT::Other), 15032 ExtraLoadOps, LDTy, ExtraMMO); 15033 15034 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15035 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15036 15037 // Because vperm has a big-endian bias, we must reverse the order 15038 // of the input vectors and complement the permute control vector 15039 // when generating little endian code. We have already handled the 15040 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15041 // and ExtraLoad here. 15042 SDValue Perm; 15043 if (isLittleEndian) 15044 Perm = BuildIntrinsicOp(IntrPerm, 15045 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15046 else 15047 Perm = BuildIntrinsicOp(IntrPerm, 15048 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15049 15050 if (VT != PermTy) 15051 Perm = Subtarget.hasAltivec() 15052 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15053 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15054 DAG.getTargetConstant(1, dl, MVT::i64)); 15055 // second argument is 1 because this rounding 15056 // is always exact. 15057 15058 // The output of the permutation is our loaded result, the TokenFactor is 15059 // our new chain. 15060 DCI.CombineTo(N, Perm, TF); 15061 return SDValue(N, 0); 15062 } 15063 } 15064 break; 15065 case ISD::INTRINSIC_WO_CHAIN: { 15066 bool isLittleEndian = Subtarget.isLittleEndian(); 15067 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15068 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15069 : Intrinsic::ppc_altivec_lvsl); 15070 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15071 SDValue Add = N->getOperand(1); 15072 15073 int Bits = 4 /* 16 byte alignment */; 15074 15075 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15076 APInt::getAllOnesValue(Bits /* alignment */) 15077 .zext(Add.getScalarValueSizeInBits()))) { 15078 SDNode *BasePtr = Add->getOperand(0).getNode(); 15079 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15080 UE = BasePtr->use_end(); 15081 UI != UE; ++UI) { 15082 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15083 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 15084 IID) { 15085 // We've found another LVSL/LVSR, and this address is an aligned 15086 // multiple of that one. The results will be the same, so use the 15087 // one we've just found instead. 15088 15089 return SDValue(*UI, 0); 15090 } 15091 } 15092 } 15093 15094 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15095 SDNode *BasePtr = Add->getOperand(0).getNode(); 15096 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15097 UE = BasePtr->use_end(); UI != UE; ++UI) { 15098 if (UI->getOpcode() == ISD::ADD && 15099 isa<ConstantSDNode>(UI->getOperand(1)) && 15100 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15101 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 15102 (1ULL << Bits) == 0) { 15103 SDNode *OtherAdd = *UI; 15104 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 15105 VE = OtherAdd->use_end(); VI != VE; ++VI) { 15106 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15107 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 15108 return SDValue(*VI, 0); 15109 } 15110 } 15111 } 15112 } 15113 } 15114 } 15115 15116 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15117 // Expose the vabsduw/h/b opportunity for down stream 15118 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15119 (IID == Intrinsic::ppc_altivec_vmaxsw || 15120 IID == Intrinsic::ppc_altivec_vmaxsh || 15121 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15122 SDValue V1 = N->getOperand(1); 15123 SDValue V2 = N->getOperand(2); 15124 if ((V1.getSimpleValueType() == MVT::v4i32 || 15125 V1.getSimpleValueType() == MVT::v8i16 || 15126 V1.getSimpleValueType() == MVT::v16i8) && 15127 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15128 // (0-a, a) 15129 if (V1.getOpcode() == ISD::SUB && 15130 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15131 V1.getOperand(1) == V2) { 15132 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15133 } 15134 // (a, 0-a) 15135 if (V2.getOpcode() == ISD::SUB && 15136 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15137 V2.getOperand(1) == V1) { 15138 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15139 } 15140 // (x-y, y-x) 15141 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15142 V1.getOperand(0) == V2.getOperand(1) && 15143 V1.getOperand(1) == V2.getOperand(0)) { 15144 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15145 } 15146 } 15147 } 15148 } 15149 15150 break; 15151 case ISD::INTRINSIC_W_CHAIN: 15152 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15153 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15154 if (Subtarget.needsSwapsForVSXMemOps()) { 15155 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15156 default: 15157 break; 15158 case Intrinsic::ppc_vsx_lxvw4x: 15159 case Intrinsic::ppc_vsx_lxvd2x: 15160 return expandVSXLoadForLE(N, DCI); 15161 } 15162 } 15163 break; 15164 case ISD::INTRINSIC_VOID: 15165 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15166 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15167 if (Subtarget.needsSwapsForVSXMemOps()) { 15168 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15169 default: 15170 break; 15171 case Intrinsic::ppc_vsx_stxvw4x: 15172 case Intrinsic::ppc_vsx_stxvd2x: 15173 return expandVSXStoreForLE(N, DCI); 15174 } 15175 } 15176 break; 15177 case ISD::BSWAP: 15178 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15179 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 15180 N->getOperand(0).hasOneUse() && 15181 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15182 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 15183 N->getValueType(0) == MVT::i64))) { 15184 SDValue Load = N->getOperand(0); 15185 LoadSDNode *LD = cast<LoadSDNode>(Load); 15186 // Create the byte-swapping load. 15187 SDValue Ops[] = { 15188 LD->getChain(), // Chain 15189 LD->getBasePtr(), // Ptr 15190 DAG.getValueType(N->getValueType(0)) // VT 15191 }; 15192 SDValue BSLoad = 15193 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15194 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15195 MVT::i64 : MVT::i32, MVT::Other), 15196 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15197 15198 // If this is an i16 load, insert the truncate. 15199 SDValue ResVal = BSLoad; 15200 if (N->getValueType(0) == MVT::i16) 15201 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15202 15203 // First, combine the bswap away. This makes the value produced by the 15204 // load dead. 15205 DCI.CombineTo(N, ResVal); 15206 15207 // Next, combine the load away, we give it a bogus result value but a real 15208 // chain result. The result value is dead because the bswap is dead. 15209 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15210 15211 // Return N so it doesn't get rechecked! 15212 return SDValue(N, 0); 15213 } 15214 break; 15215 case PPCISD::VCMP: 15216 // If a VCMP_rec node already exists with exactly the same operands as this 15217 // node, use its result instead of this node (VCMP_rec computes both a CR6 15218 // and a normal output). 15219 // 15220 if (!N->getOperand(0).hasOneUse() && 15221 !N->getOperand(1).hasOneUse() && 15222 !N->getOperand(2).hasOneUse()) { 15223 15224 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15225 SDNode *VCMPrecNode = nullptr; 15226 15227 SDNode *LHSN = N->getOperand(0).getNode(); 15228 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15229 UI != E; ++UI) 15230 if (UI->getOpcode() == PPCISD::VCMP_rec && 15231 UI->getOperand(1) == N->getOperand(1) && 15232 UI->getOperand(2) == N->getOperand(2) && 15233 UI->getOperand(0) == N->getOperand(0)) { 15234 VCMPrecNode = *UI; 15235 break; 15236 } 15237 15238 // If there is no VCMP_rec node, or if the flag value has a single use, 15239 // don't transform this. 15240 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15241 break; 15242 15243 // Look at the (necessarily single) use of the flag value. If it has a 15244 // chain, this transformation is more complex. Note that multiple things 15245 // could use the value result, which we should ignore. 15246 SDNode *FlagUser = nullptr; 15247 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15248 FlagUser == nullptr; ++UI) { 15249 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15250 SDNode *User = *UI; 15251 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15252 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15253 FlagUser = User; 15254 break; 15255 } 15256 } 15257 } 15258 15259 // If the user is a MFOCRF instruction, we know this is safe. 15260 // Otherwise we give up for right now. 15261 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15262 return SDValue(VCMPrecNode, 0); 15263 } 15264 break; 15265 case ISD::BRCOND: { 15266 SDValue Cond = N->getOperand(1); 15267 SDValue Target = N->getOperand(2); 15268 15269 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15270 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15271 Intrinsic::loop_decrement) { 15272 15273 // We now need to make the intrinsic dead (it cannot be instruction 15274 // selected). 15275 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15276 assert(Cond.getNode()->hasOneUse() && 15277 "Counter decrement has more than one use"); 15278 15279 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15280 N->getOperand(0), Target); 15281 } 15282 } 15283 break; 15284 case ISD::BR_CC: { 15285 // If this is a branch on an altivec predicate comparison, lower this so 15286 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15287 // lowering is done pre-legalize, because the legalizer lowers the predicate 15288 // compare down to code that is difficult to reassemble. 15289 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15290 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15291 15292 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15293 // value. If so, pass-through the AND to get to the intrinsic. 15294 if (LHS.getOpcode() == ISD::AND && 15295 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15296 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15297 Intrinsic::loop_decrement && 15298 isa<ConstantSDNode>(LHS.getOperand(1)) && 15299 !isNullConstant(LHS.getOperand(1))) 15300 LHS = LHS.getOperand(0); 15301 15302 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15303 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15304 Intrinsic::loop_decrement && 15305 isa<ConstantSDNode>(RHS)) { 15306 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15307 "Counter decrement comparison is not EQ or NE"); 15308 15309 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15310 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15311 (CC == ISD::SETNE && !Val); 15312 15313 // We now need to make the intrinsic dead (it cannot be instruction 15314 // selected). 15315 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15316 assert(LHS.getNode()->hasOneUse() && 15317 "Counter decrement has more than one use"); 15318 15319 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15320 N->getOperand(0), N->getOperand(4)); 15321 } 15322 15323 int CompareOpc; 15324 bool isDot; 15325 15326 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15327 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15328 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15329 assert(isDot && "Can't compare against a vector result!"); 15330 15331 // If this is a comparison against something other than 0/1, then we know 15332 // that the condition is never/always true. 15333 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15334 if (Val != 0 && Val != 1) { 15335 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15336 return N->getOperand(0); 15337 // Always !=, turn it into an unconditional branch. 15338 return DAG.getNode(ISD::BR, dl, MVT::Other, 15339 N->getOperand(0), N->getOperand(4)); 15340 } 15341 15342 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15343 15344 // Create the PPCISD altivec 'dot' comparison node. 15345 SDValue Ops[] = { 15346 LHS.getOperand(2), // LHS of compare 15347 LHS.getOperand(3), // RHS of compare 15348 DAG.getConstant(CompareOpc, dl, MVT::i32) 15349 }; 15350 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15351 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15352 15353 // Unpack the result based on how the target uses it. 15354 PPC::Predicate CompOpc; 15355 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15356 default: // Can't happen, don't crash on invalid number though. 15357 case 0: // Branch on the value of the EQ bit of CR6. 15358 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15359 break; 15360 case 1: // Branch on the inverted value of the EQ bit of CR6. 15361 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15362 break; 15363 case 2: // Branch on the value of the LT bit of CR6. 15364 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15365 break; 15366 case 3: // Branch on the inverted value of the LT bit of CR6. 15367 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15368 break; 15369 } 15370 15371 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15372 DAG.getConstant(CompOpc, dl, MVT::i32), 15373 DAG.getRegister(PPC::CR6, MVT::i32), 15374 N->getOperand(4), CompNode.getValue(1)); 15375 } 15376 break; 15377 } 15378 case ISD::BUILD_VECTOR: 15379 return DAGCombineBuildVector(N, DCI); 15380 case ISD::ABS: 15381 return combineABS(N, DCI); 15382 case ISD::VSELECT: 15383 return combineVSelect(N, DCI); 15384 } 15385 15386 return SDValue(); 15387 } 15388 15389 SDValue 15390 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15391 SelectionDAG &DAG, 15392 SmallVectorImpl<SDNode *> &Created) const { 15393 // fold (sdiv X, pow2) 15394 EVT VT = N->getValueType(0); 15395 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15396 return SDValue(); 15397 if ((VT != MVT::i32 && VT != MVT::i64) || 15398 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15399 return SDValue(); 15400 15401 SDLoc DL(N); 15402 SDValue N0 = N->getOperand(0); 15403 15404 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15405 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15406 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15407 15408 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15409 Created.push_back(Op.getNode()); 15410 15411 if (IsNegPow2) { 15412 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15413 Created.push_back(Op.getNode()); 15414 } 15415 15416 return Op; 15417 } 15418 15419 //===----------------------------------------------------------------------===// 15420 // Inline Assembly Support 15421 //===----------------------------------------------------------------------===// 15422 15423 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15424 KnownBits &Known, 15425 const APInt &DemandedElts, 15426 const SelectionDAG &DAG, 15427 unsigned Depth) const { 15428 Known.resetAll(); 15429 switch (Op.getOpcode()) { 15430 default: break; 15431 case PPCISD::LBRX: { 15432 // lhbrx is known to have the top bits cleared out. 15433 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15434 Known.Zero = 0xFFFF0000; 15435 break; 15436 } 15437 case ISD::INTRINSIC_WO_CHAIN: { 15438 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15439 default: break; 15440 case Intrinsic::ppc_altivec_vcmpbfp_p: 15441 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15442 case Intrinsic::ppc_altivec_vcmpequb_p: 15443 case Intrinsic::ppc_altivec_vcmpequh_p: 15444 case Intrinsic::ppc_altivec_vcmpequw_p: 15445 case Intrinsic::ppc_altivec_vcmpequd_p: 15446 case Intrinsic::ppc_altivec_vcmpequq_p: 15447 case Intrinsic::ppc_altivec_vcmpgefp_p: 15448 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15449 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15450 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15451 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15452 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15453 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15454 case Intrinsic::ppc_altivec_vcmpgtub_p: 15455 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15456 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15457 case Intrinsic::ppc_altivec_vcmpgtud_p: 15458 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15459 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15460 break; 15461 } 15462 } 15463 } 15464 } 15465 15466 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15467 switch (Subtarget.getCPUDirective()) { 15468 default: break; 15469 case PPC::DIR_970: 15470 case PPC::DIR_PWR4: 15471 case PPC::DIR_PWR5: 15472 case PPC::DIR_PWR5X: 15473 case PPC::DIR_PWR6: 15474 case PPC::DIR_PWR6X: 15475 case PPC::DIR_PWR7: 15476 case PPC::DIR_PWR8: 15477 case PPC::DIR_PWR9: 15478 case PPC::DIR_PWR10: 15479 case PPC::DIR_PWR_FUTURE: { 15480 if (!ML) 15481 break; 15482 15483 if (!DisableInnermostLoopAlign32) { 15484 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15485 // so that we can decrease cache misses and branch-prediction misses. 15486 // Actual alignment of the loop will depend on the hotness check and other 15487 // logic in alignBlocks. 15488 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15489 return Align(32); 15490 } 15491 15492 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15493 15494 // For small loops (between 5 and 8 instructions), align to a 32-byte 15495 // boundary so that the entire loop fits in one instruction-cache line. 15496 uint64_t LoopSize = 0; 15497 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15498 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15499 LoopSize += TII->getInstSizeInBytes(*J); 15500 if (LoopSize > 32) 15501 break; 15502 } 15503 15504 if (LoopSize > 16 && LoopSize <= 32) 15505 return Align(32); 15506 15507 break; 15508 } 15509 } 15510 15511 return TargetLowering::getPrefLoopAlignment(ML); 15512 } 15513 15514 /// getConstraintType - Given a constraint, return the type of 15515 /// constraint it is for this target. 15516 PPCTargetLowering::ConstraintType 15517 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15518 if (Constraint.size() == 1) { 15519 switch (Constraint[0]) { 15520 default: break; 15521 case 'b': 15522 case 'r': 15523 case 'f': 15524 case 'd': 15525 case 'v': 15526 case 'y': 15527 return C_RegisterClass; 15528 case 'Z': 15529 // FIXME: While Z does indicate a memory constraint, it specifically 15530 // indicates an r+r address (used in conjunction with the 'y' modifier 15531 // in the replacement string). Currently, we're forcing the base 15532 // register to be r0 in the asm printer (which is interpreted as zero) 15533 // and forming the complete address in the second register. This is 15534 // suboptimal. 15535 return C_Memory; 15536 } 15537 } else if (Constraint == "wc") { // individual CR bits. 15538 return C_RegisterClass; 15539 } else if (Constraint == "wa" || Constraint == "wd" || 15540 Constraint == "wf" || Constraint == "ws" || 15541 Constraint == "wi" || Constraint == "ww") { 15542 return C_RegisterClass; // VSX registers. 15543 } 15544 return TargetLowering::getConstraintType(Constraint); 15545 } 15546 15547 /// Examine constraint type and operand type and determine a weight value. 15548 /// This object must already have been set up with the operand type 15549 /// and the current alternative constraint selected. 15550 TargetLowering::ConstraintWeight 15551 PPCTargetLowering::getSingleConstraintMatchWeight( 15552 AsmOperandInfo &info, const char *constraint) const { 15553 ConstraintWeight weight = CW_Invalid; 15554 Value *CallOperandVal = info.CallOperandVal; 15555 // If we don't have a value, we can't do a match, 15556 // but allow it at the lowest weight. 15557 if (!CallOperandVal) 15558 return CW_Default; 15559 Type *type = CallOperandVal->getType(); 15560 15561 // Look at the constraint type. 15562 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15563 return CW_Register; // an individual CR bit. 15564 else if ((StringRef(constraint) == "wa" || 15565 StringRef(constraint) == "wd" || 15566 StringRef(constraint) == "wf") && 15567 type->isVectorTy()) 15568 return CW_Register; 15569 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15570 return CW_Register; // just hold 64-bit integers data. 15571 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15572 return CW_Register; 15573 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15574 return CW_Register; 15575 15576 switch (*constraint) { 15577 default: 15578 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15579 break; 15580 case 'b': 15581 if (type->isIntegerTy()) 15582 weight = CW_Register; 15583 break; 15584 case 'f': 15585 if (type->isFloatTy()) 15586 weight = CW_Register; 15587 break; 15588 case 'd': 15589 if (type->isDoubleTy()) 15590 weight = CW_Register; 15591 break; 15592 case 'v': 15593 if (type->isVectorTy()) 15594 weight = CW_Register; 15595 break; 15596 case 'y': 15597 weight = CW_Register; 15598 break; 15599 case 'Z': 15600 weight = CW_Memory; 15601 break; 15602 } 15603 return weight; 15604 } 15605 15606 std::pair<unsigned, const TargetRegisterClass *> 15607 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15608 StringRef Constraint, 15609 MVT VT) const { 15610 if (Constraint.size() == 1) { 15611 // GCC RS6000 Constraint Letters 15612 switch (Constraint[0]) { 15613 case 'b': // R1-R31 15614 if (VT == MVT::i64 && Subtarget.isPPC64()) 15615 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15616 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15617 case 'r': // R0-R31 15618 if (VT == MVT::i64 && Subtarget.isPPC64()) 15619 return std::make_pair(0U, &PPC::G8RCRegClass); 15620 return std::make_pair(0U, &PPC::GPRCRegClass); 15621 // 'd' and 'f' constraints are both defined to be "the floating point 15622 // registers", where one is for 32-bit and the other for 64-bit. We don't 15623 // really care overly much here so just give them all the same reg classes. 15624 case 'd': 15625 case 'f': 15626 if (Subtarget.hasSPE()) { 15627 if (VT == MVT::f32 || VT == MVT::i32) 15628 return std::make_pair(0U, &PPC::GPRCRegClass); 15629 if (VT == MVT::f64 || VT == MVT::i64) 15630 return std::make_pair(0U, &PPC::SPERCRegClass); 15631 } else { 15632 if (VT == MVT::f32 || VT == MVT::i32) 15633 return std::make_pair(0U, &PPC::F4RCRegClass); 15634 if (VT == MVT::f64 || VT == MVT::i64) 15635 return std::make_pair(0U, &PPC::F8RCRegClass); 15636 } 15637 break; 15638 case 'v': 15639 if (Subtarget.hasAltivec()) 15640 return std::make_pair(0U, &PPC::VRRCRegClass); 15641 break; 15642 case 'y': // crrc 15643 return std::make_pair(0U, &PPC::CRRCRegClass); 15644 } 15645 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15646 // An individual CR bit. 15647 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15648 } else if ((Constraint == "wa" || Constraint == "wd" || 15649 Constraint == "wf" || Constraint == "wi") && 15650 Subtarget.hasVSX()) { 15651 // A VSX register for either a scalar (FP) or vector. There is no 15652 // support for single precision scalars on subtargets prior to Power8. 15653 if (VT.isVector()) 15654 return std::make_pair(0U, &PPC::VSRCRegClass); 15655 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15656 return std::make_pair(0U, &PPC::VSSRCRegClass); 15657 return std::make_pair(0U, &PPC::VSFRCRegClass); 15658 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15659 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15660 return std::make_pair(0U, &PPC::VSSRCRegClass); 15661 else 15662 return std::make_pair(0U, &PPC::VSFRCRegClass); 15663 } else if (Constraint == "lr") { 15664 if (VT == MVT::i64) 15665 return std::make_pair(0U, &PPC::LR8RCRegClass); 15666 else 15667 return std::make_pair(0U, &PPC::LRRCRegClass); 15668 } 15669 15670 // Handle special cases of physical registers that are not properly handled 15671 // by the base class. 15672 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 15673 // If we name a VSX register, we can't defer to the base class because it 15674 // will not recognize the correct register (their names will be VSL{0-31} 15675 // and V{0-31} so they won't match). So we match them here. 15676 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15677 int VSNum = atoi(Constraint.data() + 3); 15678 assert(VSNum >= 0 && VSNum <= 63 && 15679 "Attempted to access a vsr out of range"); 15680 if (VSNum < 32) 15681 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15682 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15683 } 15684 15685 // For float registers, we can't defer to the base class as it will match 15686 // the SPILLTOVSRRC class. 15687 if (Constraint.size() > 3 && Constraint[1] == 'f') { 15688 int RegNum = atoi(Constraint.data() + 2); 15689 if (RegNum > 31 || RegNum < 0) 15690 report_fatal_error("Invalid floating point register number"); 15691 if (VT == MVT::f32 || VT == MVT::i32) 15692 return Subtarget.hasSPE() 15693 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 15694 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 15695 if (VT == MVT::f64 || VT == MVT::i64) 15696 return Subtarget.hasSPE() 15697 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 15698 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 15699 } 15700 } 15701 15702 std::pair<unsigned, const TargetRegisterClass *> R = 15703 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15704 15705 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15706 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15707 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15708 // register. 15709 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15710 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15711 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15712 PPC::GPRCRegClass.contains(R.first)) 15713 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15714 PPC::sub_32, &PPC::G8RCRegClass), 15715 &PPC::G8RCRegClass); 15716 15717 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15718 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15719 R.first = PPC::CR0; 15720 R.second = &PPC::CRRCRegClass; 15721 } 15722 // FIXME: This warning should ideally be emitted in the front end. 15723 const auto &TM = getTargetMachine(); 15724 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 15725 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 15726 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 15727 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 15728 errs() << "warning: vector registers 20 to 32 are reserved in the " 15729 "default AIX AltiVec ABI and cannot be used\n"; 15730 } 15731 15732 return R; 15733 } 15734 15735 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15736 /// vector. If it is invalid, don't add anything to Ops. 15737 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15738 std::string &Constraint, 15739 std::vector<SDValue>&Ops, 15740 SelectionDAG &DAG) const { 15741 SDValue Result; 15742 15743 // Only support length 1 constraints. 15744 if (Constraint.length() > 1) return; 15745 15746 char Letter = Constraint[0]; 15747 switch (Letter) { 15748 default: break; 15749 case 'I': 15750 case 'J': 15751 case 'K': 15752 case 'L': 15753 case 'M': 15754 case 'N': 15755 case 'O': 15756 case 'P': { 15757 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15758 if (!CST) return; // Must be an immediate to match. 15759 SDLoc dl(Op); 15760 int64_t Value = CST->getSExtValue(); 15761 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15762 // numbers are printed as such. 15763 switch (Letter) { 15764 default: llvm_unreachable("Unknown constraint letter!"); 15765 case 'I': // "I" is a signed 16-bit constant. 15766 if (isInt<16>(Value)) 15767 Result = DAG.getTargetConstant(Value, dl, TCVT); 15768 break; 15769 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15770 if (isShiftedUInt<16, 16>(Value)) 15771 Result = DAG.getTargetConstant(Value, dl, TCVT); 15772 break; 15773 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15774 if (isShiftedInt<16, 16>(Value)) 15775 Result = DAG.getTargetConstant(Value, dl, TCVT); 15776 break; 15777 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15778 if (isUInt<16>(Value)) 15779 Result = DAG.getTargetConstant(Value, dl, TCVT); 15780 break; 15781 case 'M': // "M" is a constant that is greater than 31. 15782 if (Value > 31) 15783 Result = DAG.getTargetConstant(Value, dl, TCVT); 15784 break; 15785 case 'N': // "N" is a positive constant that is an exact power of two. 15786 if (Value > 0 && isPowerOf2_64(Value)) 15787 Result = DAG.getTargetConstant(Value, dl, TCVT); 15788 break; 15789 case 'O': // "O" is the constant zero. 15790 if (Value == 0) 15791 Result = DAG.getTargetConstant(Value, dl, TCVT); 15792 break; 15793 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15794 if (isInt<16>(-Value)) 15795 Result = DAG.getTargetConstant(Value, dl, TCVT); 15796 break; 15797 } 15798 break; 15799 } 15800 } 15801 15802 if (Result.getNode()) { 15803 Ops.push_back(Result); 15804 return; 15805 } 15806 15807 // Handle standard constraint letters. 15808 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15809 } 15810 15811 // isLegalAddressingMode - Return true if the addressing mode represented 15812 // by AM is legal for this target, for a load/store of the specified type. 15813 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15814 const AddrMode &AM, Type *Ty, 15815 unsigned AS, 15816 Instruction *I) const { 15817 // Vector type r+i form is supported since power9 as DQ form. We don't check 15818 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15819 // imm form is preferred and the offset can be adjusted to use imm form later 15820 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15821 // max offset to check legal addressing mode, we should be a little aggressive 15822 // to contain other offsets for that LSRUse. 15823 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15824 return false; 15825 15826 // PPC allows a sign-extended 16-bit immediate field. 15827 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15828 return false; 15829 15830 // No global is ever allowed as a base. 15831 if (AM.BaseGV) 15832 return false; 15833 15834 // PPC only support r+r, 15835 switch (AM.Scale) { 15836 case 0: // "r+i" or just "i", depending on HasBaseReg. 15837 break; 15838 case 1: 15839 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15840 return false; 15841 // Otherwise we have r+r or r+i. 15842 break; 15843 case 2: 15844 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15845 return false; 15846 // Allow 2*r as r+r. 15847 break; 15848 default: 15849 // No other scales are supported. 15850 return false; 15851 } 15852 15853 return true; 15854 } 15855 15856 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15857 SelectionDAG &DAG) const { 15858 MachineFunction &MF = DAG.getMachineFunction(); 15859 MachineFrameInfo &MFI = MF.getFrameInfo(); 15860 MFI.setReturnAddressIsTaken(true); 15861 15862 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15863 return SDValue(); 15864 15865 SDLoc dl(Op); 15866 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15867 15868 // Make sure the function does not optimize away the store of the RA to 15869 // the stack. 15870 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15871 FuncInfo->setLRStoreRequired(); 15872 bool isPPC64 = Subtarget.isPPC64(); 15873 auto PtrVT = getPointerTy(MF.getDataLayout()); 15874 15875 if (Depth > 0) { 15876 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15877 SDValue Offset = 15878 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15879 isPPC64 ? MVT::i64 : MVT::i32); 15880 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15881 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15882 MachinePointerInfo()); 15883 } 15884 15885 // Just load the return address off the stack. 15886 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15887 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15888 MachinePointerInfo()); 15889 } 15890 15891 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15892 SelectionDAG &DAG) const { 15893 SDLoc dl(Op); 15894 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15895 15896 MachineFunction &MF = DAG.getMachineFunction(); 15897 MachineFrameInfo &MFI = MF.getFrameInfo(); 15898 MFI.setFrameAddressIsTaken(true); 15899 15900 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15901 bool isPPC64 = PtrVT == MVT::i64; 15902 15903 // Naked functions never have a frame pointer, and so we use r1. For all 15904 // other functions, this decision must be delayed until during PEI. 15905 unsigned FrameReg; 15906 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15907 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15908 else 15909 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15910 15911 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15912 PtrVT); 15913 while (Depth--) 15914 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15915 FrameAddr, MachinePointerInfo()); 15916 return FrameAddr; 15917 } 15918 15919 // FIXME? Maybe this could be a TableGen attribute on some registers and 15920 // this table could be generated automatically from RegInfo. 15921 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15922 const MachineFunction &MF) const { 15923 bool isPPC64 = Subtarget.isPPC64(); 15924 15925 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15926 if (!is64Bit && VT != LLT::scalar(32)) 15927 report_fatal_error("Invalid register global variable type"); 15928 15929 Register Reg = StringSwitch<Register>(RegName) 15930 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15931 .Case("r2", isPPC64 ? Register() : PPC::R2) 15932 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15933 .Default(Register()); 15934 15935 if (Reg) 15936 return Reg; 15937 report_fatal_error("Invalid register name global variable"); 15938 } 15939 15940 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15941 // 32-bit SVR4 ABI access everything as got-indirect. 15942 if (Subtarget.is32BitELFABI()) 15943 return true; 15944 15945 // AIX accesses everything indirectly through the TOC, which is similar to 15946 // the GOT. 15947 if (Subtarget.isAIXABI()) 15948 return true; 15949 15950 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15951 // If it is small or large code model, module locals are accessed 15952 // indirectly by loading their address from .toc/.got. 15953 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15954 return true; 15955 15956 // JumpTable and BlockAddress are accessed as got-indirect. 15957 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15958 return true; 15959 15960 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15961 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15962 15963 return false; 15964 } 15965 15966 bool 15967 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15968 // The PowerPC target isn't yet aware of offsets. 15969 return false; 15970 } 15971 15972 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15973 const CallInst &I, 15974 MachineFunction &MF, 15975 unsigned Intrinsic) const { 15976 switch (Intrinsic) { 15977 case Intrinsic::ppc_altivec_lvx: 15978 case Intrinsic::ppc_altivec_lvxl: 15979 case Intrinsic::ppc_altivec_lvebx: 15980 case Intrinsic::ppc_altivec_lvehx: 15981 case Intrinsic::ppc_altivec_lvewx: 15982 case Intrinsic::ppc_vsx_lxvd2x: 15983 case Intrinsic::ppc_vsx_lxvw4x: 15984 case Intrinsic::ppc_vsx_lxvd2x_be: 15985 case Intrinsic::ppc_vsx_lxvw4x_be: 15986 case Intrinsic::ppc_vsx_lxvl: 15987 case Intrinsic::ppc_vsx_lxvll: { 15988 EVT VT; 15989 switch (Intrinsic) { 15990 case Intrinsic::ppc_altivec_lvebx: 15991 VT = MVT::i8; 15992 break; 15993 case Intrinsic::ppc_altivec_lvehx: 15994 VT = MVT::i16; 15995 break; 15996 case Intrinsic::ppc_altivec_lvewx: 15997 VT = MVT::i32; 15998 break; 15999 case Intrinsic::ppc_vsx_lxvd2x: 16000 case Intrinsic::ppc_vsx_lxvd2x_be: 16001 VT = MVT::v2f64; 16002 break; 16003 default: 16004 VT = MVT::v4i32; 16005 break; 16006 } 16007 16008 Info.opc = ISD::INTRINSIC_W_CHAIN; 16009 Info.memVT = VT; 16010 Info.ptrVal = I.getArgOperand(0); 16011 Info.offset = -VT.getStoreSize()+1; 16012 Info.size = 2*VT.getStoreSize()-1; 16013 Info.align = Align(1); 16014 Info.flags = MachineMemOperand::MOLoad; 16015 return true; 16016 } 16017 case Intrinsic::ppc_altivec_stvx: 16018 case Intrinsic::ppc_altivec_stvxl: 16019 case Intrinsic::ppc_altivec_stvebx: 16020 case Intrinsic::ppc_altivec_stvehx: 16021 case Intrinsic::ppc_altivec_stvewx: 16022 case Intrinsic::ppc_vsx_stxvd2x: 16023 case Intrinsic::ppc_vsx_stxvw4x: 16024 case Intrinsic::ppc_vsx_stxvd2x_be: 16025 case Intrinsic::ppc_vsx_stxvw4x_be: 16026 case Intrinsic::ppc_vsx_stxvl: 16027 case Intrinsic::ppc_vsx_stxvll: { 16028 EVT VT; 16029 switch (Intrinsic) { 16030 case Intrinsic::ppc_altivec_stvebx: 16031 VT = MVT::i8; 16032 break; 16033 case Intrinsic::ppc_altivec_stvehx: 16034 VT = MVT::i16; 16035 break; 16036 case Intrinsic::ppc_altivec_stvewx: 16037 VT = MVT::i32; 16038 break; 16039 case Intrinsic::ppc_vsx_stxvd2x: 16040 case Intrinsic::ppc_vsx_stxvd2x_be: 16041 VT = MVT::v2f64; 16042 break; 16043 default: 16044 VT = MVT::v4i32; 16045 break; 16046 } 16047 16048 Info.opc = ISD::INTRINSIC_VOID; 16049 Info.memVT = VT; 16050 Info.ptrVal = I.getArgOperand(1); 16051 Info.offset = -VT.getStoreSize()+1; 16052 Info.size = 2*VT.getStoreSize()-1; 16053 Info.align = Align(1); 16054 Info.flags = MachineMemOperand::MOStore; 16055 return true; 16056 } 16057 default: 16058 break; 16059 } 16060 16061 return false; 16062 } 16063 16064 /// It returns EVT::Other if the type should be determined using generic 16065 /// target-independent logic. 16066 EVT PPCTargetLowering::getOptimalMemOpType( 16067 const MemOp &Op, const AttributeList &FuncAttributes) const { 16068 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16069 // We should use Altivec/VSX loads and stores when available. For unaligned 16070 // addresses, unaligned VSX loads are only fast starting with the P8. 16071 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16072 (Op.isAligned(Align(16)) || 16073 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16074 return MVT::v4i32; 16075 } 16076 16077 if (Subtarget.isPPC64()) { 16078 return MVT::i64; 16079 } 16080 16081 return MVT::i32; 16082 } 16083 16084 /// Returns true if it is beneficial to convert a load of a constant 16085 /// to just the constant itself. 16086 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16087 Type *Ty) const { 16088 assert(Ty->isIntegerTy()); 16089 16090 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16091 return !(BitSize == 0 || BitSize > 64); 16092 } 16093 16094 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16095 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16096 return false; 16097 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16098 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16099 return NumBits1 == 64 && NumBits2 == 32; 16100 } 16101 16102 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16103 if (!VT1.isInteger() || !VT2.isInteger()) 16104 return false; 16105 unsigned NumBits1 = VT1.getSizeInBits(); 16106 unsigned NumBits2 = VT2.getSizeInBits(); 16107 return NumBits1 == 64 && NumBits2 == 32; 16108 } 16109 16110 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16111 // Generally speaking, zexts are not free, but they are free when they can be 16112 // folded with other operations. 16113 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16114 EVT MemVT = LD->getMemoryVT(); 16115 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16116 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16117 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16118 LD->getExtensionType() == ISD::ZEXTLOAD)) 16119 return true; 16120 } 16121 16122 // FIXME: Add other cases... 16123 // - 32-bit shifts with a zext to i64 16124 // - zext after ctlz, bswap, etc. 16125 // - zext after and by a constant mask 16126 16127 return TargetLowering::isZExtFree(Val, VT2); 16128 } 16129 16130 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16131 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16132 "invalid fpext types"); 16133 // Extending to float128 is not free. 16134 if (DestVT == MVT::f128) 16135 return false; 16136 return true; 16137 } 16138 16139 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16140 return isInt<16>(Imm) || isUInt<16>(Imm); 16141 } 16142 16143 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16144 return isInt<16>(Imm) || isUInt<16>(Imm); 16145 } 16146 16147 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 16148 MachineMemOperand::Flags, 16149 bool *Fast) const { 16150 if (DisablePPCUnaligned) 16151 return false; 16152 16153 // PowerPC supports unaligned memory access for simple non-vector types. 16154 // Although accessing unaligned addresses is not as efficient as accessing 16155 // aligned addresses, it is generally more efficient than manual expansion, 16156 // and generally only traps for software emulation when crossing page 16157 // boundaries. 16158 16159 if (!VT.isSimple()) 16160 return false; 16161 16162 if (VT.isFloatingPoint() && !VT.isVector() && 16163 !Subtarget.allowsUnalignedFPAccess()) 16164 return false; 16165 16166 if (VT.getSimpleVT().isVector()) { 16167 if (Subtarget.hasVSX()) { 16168 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16169 VT != MVT::v4f32 && VT != MVT::v4i32) 16170 return false; 16171 } else { 16172 return false; 16173 } 16174 } 16175 16176 if (VT == MVT::ppcf128) 16177 return false; 16178 16179 if (Fast) 16180 *Fast = true; 16181 16182 return true; 16183 } 16184 16185 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16186 SDValue C) const { 16187 // Check integral scalar types. 16188 if (!VT.isScalarInteger()) 16189 return false; 16190 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16191 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16192 return false; 16193 // This transformation will generate >= 2 operations. But the following 16194 // cases will generate <= 2 instructions during ISEL. So exclude them. 16195 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16196 // HW instruction, ie. MULLI 16197 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16198 // instruction is needed than case 1, ie. MULLI and RLDICR 16199 int64_t Imm = ConstNode->getSExtValue(); 16200 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16201 Imm >>= Shift; 16202 if (isInt<16>(Imm)) 16203 return false; 16204 uint64_t UImm = static_cast<uint64_t>(Imm); 16205 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16206 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16207 return true; 16208 } 16209 return false; 16210 } 16211 16212 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16213 EVT VT) const { 16214 return isFMAFasterThanFMulAndFAdd( 16215 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16216 } 16217 16218 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16219 Type *Ty) const { 16220 switch (Ty->getScalarType()->getTypeID()) { 16221 case Type::FloatTyID: 16222 case Type::DoubleTyID: 16223 return true; 16224 case Type::FP128TyID: 16225 return Subtarget.hasP9Vector(); 16226 default: 16227 return false; 16228 } 16229 } 16230 16231 // FIXME: add more patterns which are not profitable to hoist. 16232 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16233 if (!I->hasOneUse()) 16234 return true; 16235 16236 Instruction *User = I->user_back(); 16237 assert(User && "A single use instruction with no uses."); 16238 16239 switch (I->getOpcode()) { 16240 case Instruction::FMul: { 16241 // Don't break FMA, PowerPC prefers FMA. 16242 if (User->getOpcode() != Instruction::FSub && 16243 User->getOpcode() != Instruction::FAdd) 16244 return true; 16245 16246 const TargetOptions &Options = getTargetMachine().Options; 16247 const Function *F = I->getFunction(); 16248 const DataLayout &DL = F->getParent()->getDataLayout(); 16249 Type *Ty = User->getOperand(0)->getType(); 16250 16251 return !( 16252 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16253 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16254 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16255 } 16256 case Instruction::Load: { 16257 // Don't break "store (load float*)" pattern, this pattern will be combined 16258 // to "store (load int32)" in later InstCombine pass. See function 16259 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16260 // cycles than loading a 32 bit integer. 16261 LoadInst *LI = cast<LoadInst>(I); 16262 // For the loads that combineLoadToOperationType does nothing, like 16263 // ordered load, it should be profitable to hoist them. 16264 // For swifterror load, it can only be used for pointer to pointer type, so 16265 // later type check should get rid of this case. 16266 if (!LI->isUnordered()) 16267 return true; 16268 16269 if (User->getOpcode() != Instruction::Store) 16270 return true; 16271 16272 if (I->getType()->getTypeID() != Type::FloatTyID) 16273 return true; 16274 16275 return false; 16276 } 16277 default: 16278 return true; 16279 } 16280 return true; 16281 } 16282 16283 const MCPhysReg * 16284 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16285 // LR is a callee-save register, but we must treat it as clobbered by any call 16286 // site. Hence we include LR in the scratch registers, which are in turn added 16287 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16288 // to CTR, which is used by any indirect call. 16289 static const MCPhysReg ScratchRegs[] = { 16290 PPC::X12, PPC::LR8, PPC::CTR8, 0 16291 }; 16292 16293 return ScratchRegs; 16294 } 16295 16296 Register PPCTargetLowering::getExceptionPointerRegister( 16297 const Constant *PersonalityFn) const { 16298 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16299 } 16300 16301 Register PPCTargetLowering::getExceptionSelectorRegister( 16302 const Constant *PersonalityFn) const { 16303 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16304 } 16305 16306 bool 16307 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16308 EVT VT , unsigned DefinedValues) const { 16309 if (VT == MVT::v2i64) 16310 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16311 16312 if (Subtarget.hasVSX()) 16313 return true; 16314 16315 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16316 } 16317 16318 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16319 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16320 return TargetLowering::getSchedulingPreference(N); 16321 16322 return Sched::ILP; 16323 } 16324 16325 // Create a fast isel object. 16326 FastISel * 16327 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16328 const TargetLibraryInfo *LibInfo) const { 16329 return PPC::createFastISel(FuncInfo, LibInfo); 16330 } 16331 16332 // 'Inverted' means the FMA opcode after negating one multiplicand. 16333 // For example, (fma -a b c) = (fnmsub a b c) 16334 static unsigned invertFMAOpcode(unsigned Opc) { 16335 switch (Opc) { 16336 default: 16337 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16338 case ISD::FMA: 16339 return PPCISD::FNMSUB; 16340 case PPCISD::FNMSUB: 16341 return ISD::FMA; 16342 } 16343 } 16344 16345 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16346 bool LegalOps, bool OptForSize, 16347 NegatibleCost &Cost, 16348 unsigned Depth) const { 16349 if (Depth > SelectionDAG::MaxRecursionDepth) 16350 return SDValue(); 16351 16352 unsigned Opc = Op.getOpcode(); 16353 EVT VT = Op.getValueType(); 16354 SDNodeFlags Flags = Op.getNode()->getFlags(); 16355 16356 switch (Opc) { 16357 case PPCISD::FNMSUB: 16358 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16359 break; 16360 16361 const TargetOptions &Options = getTargetMachine().Options; 16362 SDValue N0 = Op.getOperand(0); 16363 SDValue N1 = Op.getOperand(1); 16364 SDValue N2 = Op.getOperand(2); 16365 SDLoc Loc(Op); 16366 16367 NegatibleCost N2Cost = NegatibleCost::Expensive; 16368 SDValue NegN2 = 16369 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16370 16371 if (!NegN2) 16372 return SDValue(); 16373 16374 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16375 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16376 // These transformations may change sign of zeroes. For example, 16377 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16378 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16379 // Try and choose the cheaper one to negate. 16380 NegatibleCost N0Cost = NegatibleCost::Expensive; 16381 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16382 N0Cost, Depth + 1); 16383 16384 NegatibleCost N1Cost = NegatibleCost::Expensive; 16385 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16386 N1Cost, Depth + 1); 16387 16388 if (NegN0 && N0Cost <= N1Cost) { 16389 Cost = std::min(N0Cost, N2Cost); 16390 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16391 } else if (NegN1) { 16392 Cost = std::min(N1Cost, N2Cost); 16393 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16394 } 16395 } 16396 16397 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16398 if (isOperationLegal(ISD::FMA, VT)) { 16399 Cost = N2Cost; 16400 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16401 } 16402 16403 break; 16404 } 16405 16406 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16407 Cost, Depth); 16408 } 16409 16410 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16411 bool PPCTargetLowering::useLoadStackGuardNode() const { 16412 if (!Subtarget.isTargetLinux()) 16413 return TargetLowering::useLoadStackGuardNode(); 16414 return true; 16415 } 16416 16417 // Override to disable global variable loading on Linux and insert AIX canary 16418 // word declaration. 16419 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16420 if (Subtarget.isAIXABI()) { 16421 M.getOrInsertGlobal(AIXSSPCanaryWordName, 16422 Type::getInt8PtrTy(M.getContext())); 16423 return; 16424 } 16425 if (!Subtarget.isTargetLinux()) 16426 return TargetLowering::insertSSPDeclarations(M); 16427 } 16428 16429 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const { 16430 if (Subtarget.isAIXABI()) 16431 return M.getGlobalVariable(AIXSSPCanaryWordName); 16432 return TargetLowering::getSDagStackGuard(M); 16433 } 16434 16435 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16436 bool ForCodeSize) const { 16437 if (!VT.isSimple() || !Subtarget.hasVSX()) 16438 return false; 16439 16440 switch(VT.getSimpleVT().SimpleTy) { 16441 default: 16442 // For FP types that are currently not supported by PPC backend, return 16443 // false. Examples: f16, f80. 16444 return false; 16445 case MVT::f32: 16446 case MVT::f64: 16447 if (Subtarget.hasPrefixInstrs()) { 16448 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 16449 return true; 16450 } 16451 LLVM_FALLTHROUGH; 16452 case MVT::ppcf128: 16453 return Imm.isPosZero(); 16454 } 16455 } 16456 16457 // For vector shift operation op, fold 16458 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16459 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16460 SelectionDAG &DAG) { 16461 SDValue N0 = N->getOperand(0); 16462 SDValue N1 = N->getOperand(1); 16463 EVT VT = N0.getValueType(); 16464 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16465 unsigned Opcode = N->getOpcode(); 16466 unsigned TargetOpcode; 16467 16468 switch (Opcode) { 16469 default: 16470 llvm_unreachable("Unexpected shift operation"); 16471 case ISD::SHL: 16472 TargetOpcode = PPCISD::SHL; 16473 break; 16474 case ISD::SRL: 16475 TargetOpcode = PPCISD::SRL; 16476 break; 16477 case ISD::SRA: 16478 TargetOpcode = PPCISD::SRA; 16479 break; 16480 } 16481 16482 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16483 N1->getOpcode() == ISD::AND) 16484 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16485 if (Mask->getZExtValue() == OpSizeInBits - 1) 16486 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16487 16488 return SDValue(); 16489 } 16490 16491 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16492 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16493 return Value; 16494 16495 SDValue N0 = N->getOperand(0); 16496 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16497 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16498 N0.getOpcode() != ISD::SIGN_EXTEND || 16499 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16500 N->getValueType(0) != MVT::i64) 16501 return SDValue(); 16502 16503 // We can't save an operation here if the value is already extended, and 16504 // the existing shift is easier to combine. 16505 SDValue ExtsSrc = N0.getOperand(0); 16506 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16507 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16508 return SDValue(); 16509 16510 SDLoc DL(N0); 16511 SDValue ShiftBy = SDValue(CN1, 0); 16512 // We want the shift amount to be i32 on the extswli, but the shift could 16513 // have an i64. 16514 if (ShiftBy.getValueType() == MVT::i64) 16515 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16516 16517 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16518 ShiftBy); 16519 } 16520 16521 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16522 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16523 return Value; 16524 16525 return SDValue(); 16526 } 16527 16528 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16529 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16530 return Value; 16531 16532 return SDValue(); 16533 } 16534 16535 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16536 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16537 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16538 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16539 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16540 const PPCSubtarget &Subtarget) { 16541 if (!Subtarget.isPPC64()) 16542 return SDValue(); 16543 16544 SDValue LHS = N->getOperand(0); 16545 SDValue RHS = N->getOperand(1); 16546 16547 auto isZextOfCompareWithConstant = [](SDValue Op) { 16548 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16549 Op.getValueType() != MVT::i64) 16550 return false; 16551 16552 SDValue Cmp = Op.getOperand(0); 16553 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16554 Cmp.getOperand(0).getValueType() != MVT::i64) 16555 return false; 16556 16557 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16558 int64_t NegConstant = 0 - Constant->getSExtValue(); 16559 // Due to the limitations of the addi instruction, 16560 // -C is required to be [-32768, 32767]. 16561 return isInt<16>(NegConstant); 16562 } 16563 16564 return false; 16565 }; 16566 16567 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16568 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16569 16570 // If there is a pattern, canonicalize a zext operand to the RHS. 16571 if (LHSHasPattern && !RHSHasPattern) 16572 std::swap(LHS, RHS); 16573 else if (!LHSHasPattern && !RHSHasPattern) 16574 return SDValue(); 16575 16576 SDLoc DL(N); 16577 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16578 SDValue Cmp = RHS.getOperand(0); 16579 SDValue Z = Cmp.getOperand(0); 16580 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1)); 16581 int64_t NegConstant = 0 - Constant->getSExtValue(); 16582 16583 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16584 default: break; 16585 case ISD::SETNE: { 16586 // when C == 0 16587 // --> addze X, (addic Z, -1).carry 16588 // / 16589 // add X, (zext(setne Z, C))-- 16590 // \ when -32768 <= -C <= 32767 && C != 0 16591 // --> addze X, (addic (addi Z, -C), -1).carry 16592 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16593 DAG.getConstant(NegConstant, DL, MVT::i64)); 16594 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16595 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16596 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16597 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16598 SDValue(Addc.getNode(), 1)); 16599 } 16600 case ISD::SETEQ: { 16601 // when C == 0 16602 // --> addze X, (subfic Z, 0).carry 16603 // / 16604 // add X, (zext(sete Z, C))-- 16605 // \ when -32768 <= -C <= 32767 && C != 0 16606 // --> addze X, (subfic (addi Z, -C), 0).carry 16607 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16608 DAG.getConstant(NegConstant, DL, MVT::i64)); 16609 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16610 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16611 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16612 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16613 SDValue(Subc.getNode(), 1)); 16614 } 16615 } 16616 16617 return SDValue(); 16618 } 16619 16620 // Transform 16621 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16622 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16623 // In this case both C1 and C2 must be known constants. 16624 // C1+C2 must fit into a 34 bit signed integer. 16625 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16626 const PPCSubtarget &Subtarget) { 16627 if (!Subtarget.isUsingPCRelativeCalls()) 16628 return SDValue(); 16629 16630 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16631 // If we find that node try to cast the Global Address and the Constant. 16632 SDValue LHS = N->getOperand(0); 16633 SDValue RHS = N->getOperand(1); 16634 16635 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16636 std::swap(LHS, RHS); 16637 16638 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16639 return SDValue(); 16640 16641 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16642 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16643 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16644 16645 // Check that both casts succeeded. 16646 if (!GSDN || !ConstNode) 16647 return SDValue(); 16648 16649 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16650 SDLoc DL(GSDN); 16651 16652 // The signed int offset needs to fit in 34 bits. 16653 if (!isInt<34>(NewOffset)) 16654 return SDValue(); 16655 16656 // The new global address is a copy of the old global address except 16657 // that it has the updated Offset. 16658 SDValue GA = 16659 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16660 NewOffset, GSDN->getTargetFlags()); 16661 SDValue MatPCRel = 16662 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16663 return MatPCRel; 16664 } 16665 16666 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16667 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16668 return Value; 16669 16670 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16671 return Value; 16672 16673 return SDValue(); 16674 } 16675 16676 // Detect TRUNCATE operations on bitcasts of float128 values. 16677 // What we are looking for here is the situtation where we extract a subset 16678 // of bits from a 128 bit float. 16679 // This can be of two forms: 16680 // 1) BITCAST of f128 feeding TRUNCATE 16681 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16682 // The reason this is required is because we do not have a legal i128 type 16683 // and so we want to prevent having to store the f128 and then reload part 16684 // of it. 16685 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16686 DAGCombinerInfo &DCI) const { 16687 // If we are using CRBits then try that first. 16688 if (Subtarget.useCRBits()) { 16689 // Check if CRBits did anything and return that if it did. 16690 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16691 return CRTruncValue; 16692 } 16693 16694 SDLoc dl(N); 16695 SDValue Op0 = N->getOperand(0); 16696 16697 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16698 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16699 EVT VT = N->getValueType(0); 16700 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16701 return SDValue(); 16702 SDValue Sub = Op0.getOperand(0); 16703 if (Sub.getOpcode() == ISD::SUB) { 16704 SDValue SubOp0 = Sub.getOperand(0); 16705 SDValue SubOp1 = Sub.getOperand(1); 16706 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16707 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16708 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16709 SubOp1.getOperand(0), 16710 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16711 } 16712 } 16713 } 16714 16715 // Looking for a truncate of i128 to i64. 16716 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16717 return SDValue(); 16718 16719 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16720 16721 // SRL feeding TRUNCATE. 16722 if (Op0.getOpcode() == ISD::SRL) { 16723 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16724 // The right shift has to be by 64 bits. 16725 if (!ConstNode || ConstNode->getZExtValue() != 64) 16726 return SDValue(); 16727 16728 // Switch the element number to extract. 16729 EltToExtract = EltToExtract ? 0 : 1; 16730 // Update Op0 past the SRL. 16731 Op0 = Op0.getOperand(0); 16732 } 16733 16734 // BITCAST feeding a TRUNCATE possibly via SRL. 16735 if (Op0.getOpcode() == ISD::BITCAST && 16736 Op0.getValueType() == MVT::i128 && 16737 Op0.getOperand(0).getValueType() == MVT::f128) { 16738 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16739 return DCI.DAG.getNode( 16740 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16741 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16742 } 16743 return SDValue(); 16744 } 16745 16746 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16747 SelectionDAG &DAG = DCI.DAG; 16748 16749 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16750 if (!ConstOpOrElement) 16751 return SDValue(); 16752 16753 // An imul is usually smaller than the alternative sequence for legal type. 16754 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16755 isOperationLegal(ISD::MUL, N->getValueType(0))) 16756 return SDValue(); 16757 16758 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16759 switch (this->Subtarget.getCPUDirective()) { 16760 default: 16761 // TODO: enhance the condition for subtarget before pwr8 16762 return false; 16763 case PPC::DIR_PWR8: 16764 // type mul add shl 16765 // scalar 4 1 1 16766 // vector 7 2 2 16767 return true; 16768 case PPC::DIR_PWR9: 16769 case PPC::DIR_PWR10: 16770 case PPC::DIR_PWR_FUTURE: 16771 // type mul add shl 16772 // scalar 5 2 2 16773 // vector 7 2 2 16774 16775 // The cycle RATIO of related operations are showed as a table above. 16776 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16777 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16778 // are 4, it is always profitable; but for 3 instrs patterns 16779 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16780 // So we should only do it for vector type. 16781 return IsAddOne && IsNeg ? VT.isVector() : true; 16782 } 16783 }; 16784 16785 EVT VT = N->getValueType(0); 16786 SDLoc DL(N); 16787 16788 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16789 bool IsNeg = MulAmt.isNegative(); 16790 APInt MulAmtAbs = MulAmt.abs(); 16791 16792 if ((MulAmtAbs - 1).isPowerOf2()) { 16793 // (mul x, 2^N + 1) => (add (shl x, N), x) 16794 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16795 16796 if (!IsProfitable(IsNeg, true, VT)) 16797 return SDValue(); 16798 16799 SDValue Op0 = N->getOperand(0); 16800 SDValue Op1 = 16801 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16802 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16803 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16804 16805 if (!IsNeg) 16806 return Res; 16807 16808 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16809 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16810 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16811 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16812 16813 if (!IsProfitable(IsNeg, false, VT)) 16814 return SDValue(); 16815 16816 SDValue Op0 = N->getOperand(0); 16817 SDValue Op1 = 16818 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16819 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16820 16821 if (!IsNeg) 16822 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16823 else 16824 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16825 16826 } else { 16827 return SDValue(); 16828 } 16829 } 16830 16831 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16832 // in combiner since we need to check SD flags and other subtarget features. 16833 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16834 DAGCombinerInfo &DCI) const { 16835 SDValue N0 = N->getOperand(0); 16836 SDValue N1 = N->getOperand(1); 16837 SDValue N2 = N->getOperand(2); 16838 SDNodeFlags Flags = N->getFlags(); 16839 EVT VT = N->getValueType(0); 16840 SelectionDAG &DAG = DCI.DAG; 16841 const TargetOptions &Options = getTargetMachine().Options; 16842 unsigned Opc = N->getOpcode(); 16843 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16844 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16845 SDLoc Loc(N); 16846 16847 if (!isOperationLegal(ISD::FMA, VT)) 16848 return SDValue(); 16849 16850 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16851 // since (fnmsub a b c)=-0 while c-ab=+0. 16852 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16853 return SDValue(); 16854 16855 // (fma (fneg a) b c) => (fnmsub a b c) 16856 // (fnmsub (fneg a) b c) => (fma a b c) 16857 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16858 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16859 16860 // (fma a (fneg b) c) => (fnmsub a b c) 16861 // (fnmsub a (fneg b) c) => (fma a b c) 16862 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16863 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16864 16865 return SDValue(); 16866 } 16867 16868 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16869 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16870 if (!Subtarget.is64BitELFABI()) 16871 return false; 16872 16873 // If not a tail call then no need to proceed. 16874 if (!CI->isTailCall()) 16875 return false; 16876 16877 // If sibling calls have been disabled and tail-calls aren't guaranteed 16878 // there is no reason to duplicate. 16879 auto &TM = getTargetMachine(); 16880 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16881 return false; 16882 16883 // Can't tail call a function called indirectly, or if it has variadic args. 16884 const Function *Callee = CI->getCalledFunction(); 16885 if (!Callee || Callee->isVarArg()) 16886 return false; 16887 16888 // Make sure the callee and caller calling conventions are eligible for tco. 16889 const Function *Caller = CI->getParent()->getParent(); 16890 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16891 CI->getCallingConv())) 16892 return false; 16893 16894 // If the function is local then we have a good chance at tail-calling it 16895 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16896 } 16897 16898 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16899 if (!Subtarget.hasVSX()) 16900 return false; 16901 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16902 return true; 16903 return VT == MVT::f32 || VT == MVT::f64 || 16904 VT == MVT::v4f32 || VT == MVT::v2f64; 16905 } 16906 16907 bool PPCTargetLowering:: 16908 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16909 const Value *Mask = AndI.getOperand(1); 16910 // If the mask is suitable for andi. or andis. we should sink the and. 16911 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16912 // Can't handle constants wider than 64-bits. 16913 if (CI->getBitWidth() > 64) 16914 return false; 16915 int64_t ConstVal = CI->getZExtValue(); 16916 return isUInt<16>(ConstVal) || 16917 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16918 } 16919 16920 // For non-constant masks, we can always use the record-form and. 16921 return true; 16922 } 16923 16924 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16925 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16926 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16927 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16928 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16929 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16930 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16931 assert(Subtarget.hasP9Altivec() && 16932 "Only combine this when P9 altivec supported!"); 16933 EVT VT = N->getValueType(0); 16934 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16935 return SDValue(); 16936 16937 SelectionDAG &DAG = DCI.DAG; 16938 SDLoc dl(N); 16939 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16940 // Even for signed integers, if it's known to be positive (as signed 16941 // integer) due to zero-extended inputs. 16942 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16943 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16944 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16945 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16946 (SubOpcd1 == ISD::ZERO_EXTEND || 16947 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16948 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16949 N->getOperand(0)->getOperand(0), 16950 N->getOperand(0)->getOperand(1), 16951 DAG.getTargetConstant(0, dl, MVT::i32)); 16952 } 16953 16954 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16955 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16956 N->getOperand(0).hasOneUse()) { 16957 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16958 N->getOperand(0)->getOperand(0), 16959 N->getOperand(0)->getOperand(1), 16960 DAG.getTargetConstant(1, dl, MVT::i32)); 16961 } 16962 } 16963 16964 return SDValue(); 16965 } 16966 16967 // For type v4i32/v8ii16/v16i8, transform 16968 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16969 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16970 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16971 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16972 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16973 DAGCombinerInfo &DCI) const { 16974 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16975 assert(Subtarget.hasP9Altivec() && 16976 "Only combine this when P9 altivec supported!"); 16977 16978 SelectionDAG &DAG = DCI.DAG; 16979 SDLoc dl(N); 16980 SDValue Cond = N->getOperand(0); 16981 SDValue TrueOpnd = N->getOperand(1); 16982 SDValue FalseOpnd = N->getOperand(2); 16983 EVT VT = N->getOperand(1).getValueType(); 16984 16985 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16986 FalseOpnd.getOpcode() != ISD::SUB) 16987 return SDValue(); 16988 16989 // ABSD only available for type v4i32/v8i16/v16i8 16990 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16991 return SDValue(); 16992 16993 // At least to save one more dependent computation 16994 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16995 return SDValue(); 16996 16997 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16998 16999 // Can only handle unsigned comparison here 17000 switch (CC) { 17001 default: 17002 return SDValue(); 17003 case ISD::SETUGT: 17004 case ISD::SETUGE: 17005 break; 17006 case ISD::SETULT: 17007 case ISD::SETULE: 17008 std::swap(TrueOpnd, FalseOpnd); 17009 break; 17010 } 17011 17012 SDValue CmpOpnd1 = Cond.getOperand(0); 17013 SDValue CmpOpnd2 = Cond.getOperand(1); 17014 17015 // SETCC CmpOpnd1 CmpOpnd2 cond 17016 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17017 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17018 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17019 TrueOpnd.getOperand(1) == CmpOpnd2 && 17020 FalseOpnd.getOperand(0) == CmpOpnd2 && 17021 FalseOpnd.getOperand(1) == CmpOpnd1) { 17022 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 17023 CmpOpnd1, CmpOpnd2, 17024 DAG.getTargetConstant(0, dl, MVT::i32)); 17025 } 17026 17027 return SDValue(); 17028 } 17029 17030 /// getAddrModeForFlags - Based on the set of address flags, select the most 17031 /// optimal instruction format to match by. 17032 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const { 17033 // This is not a node we should be handling here. 17034 if (Flags == PPC::MOF_None) 17035 return PPC::AM_None; 17036 // Unaligned D-Forms are tried first, followed by the aligned D-Forms. 17037 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm)) 17038 if ((Flags & FlagSet) == FlagSet) 17039 return PPC::AM_DForm; 17040 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm)) 17041 if ((Flags & FlagSet) == FlagSet) 17042 return PPC::AM_DSForm; 17043 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm)) 17044 if ((Flags & FlagSet) == FlagSet) 17045 return PPC::AM_DQForm; 17046 // If no other forms are selected, return an X-Form as it is the most 17047 // general addressing mode. 17048 return PPC::AM_XForm; 17049 } 17050 17051 /// Set alignment flags based on whether or not the Frame Index is aligned. 17052 /// Utilized when computing flags for address computation when selecting 17053 /// load and store instructions. 17054 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, 17055 SelectionDAG &DAG) { 17056 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR)); 17057 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N); 17058 if (!FI) 17059 return; 17060 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17061 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value(); 17062 // If this is (add $FI, $S16Imm), the alignment flags are already set 17063 // based on the immediate. We just need to clear the alignment flags 17064 // if the FI alignment is weaker. 17065 if ((FrameIndexAlign % 4) != 0) 17066 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4; 17067 if ((FrameIndexAlign % 16) != 0) 17068 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16; 17069 // If the address is a plain FrameIndex, set alignment flags based on 17070 // FI alignment. 17071 if (!IsAdd) { 17072 if ((FrameIndexAlign % 4) == 0) 17073 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17074 if ((FrameIndexAlign % 16) == 0) 17075 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17076 } 17077 } 17078 17079 /// Given a node, compute flags that are used for address computation when 17080 /// selecting load and store instructions. The flags computed are stored in 17081 /// FlagSet. This function takes into account whether the node is a constant, 17082 /// an ADD, OR, or a constant, and computes the address flags accordingly. 17083 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, 17084 SelectionDAG &DAG) { 17085 // Set the alignment flags for the node depending on if the node is 17086 // 4-byte or 16-byte aligned. 17087 auto SetAlignFlagsForImm = [&](uint64_t Imm) { 17088 if ((Imm & 0x3) == 0) 17089 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17090 if ((Imm & 0xf) == 0) 17091 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17092 }; 17093 17094 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 17095 // All 32-bit constants can be computed as LIS + Disp. 17096 const APInt &ConstImm = CN->getAPIntValue(); 17097 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants. 17098 FlagSet |= PPC::MOF_AddrIsSImm32; 17099 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17100 setAlignFlagsForFI(N, FlagSet, DAG); 17101 } 17102 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants. 17103 FlagSet |= PPC::MOF_RPlusSImm34; 17104 else // Let constant materialization handle large constants. 17105 FlagSet |= PPC::MOF_NotAddNorCst; 17106 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) { 17107 // This address can be represented as an addition of: 17108 // - Register + Imm16 (possibly a multiple of 4/16) 17109 // - Register + Imm34 17110 // - Register + PPCISD::Lo 17111 // - Register + Register 17112 // In any case, we won't have to match this as Base + Zero. 17113 SDValue RHS = N.getOperand(1); 17114 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) { 17115 const APInt &ConstImm = CN->getAPIntValue(); 17116 if (ConstImm.isSignedIntN(16)) { 17117 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates. 17118 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17119 setAlignFlagsForFI(N, FlagSet, DAG); 17120 } 17121 if (ConstImm.isSignedIntN(34)) 17122 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates. 17123 else 17124 FlagSet |= PPC::MOF_RPlusR; // Register. 17125 } else if (RHS.getOpcode() == PPCISD::Lo && 17126 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue()) 17127 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo. 17128 else 17129 FlagSet |= PPC::MOF_RPlusR; 17130 } else { // The address computation is not a constant or an addition. 17131 setAlignFlagsForFI(N, FlagSet, DAG); 17132 FlagSet |= PPC::MOF_NotAddNorCst; 17133 } 17134 } 17135 17136 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute 17137 /// the address flags of the load/store instruction that is to be matched. 17138 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N, 17139 SelectionDAG &DAG) const { 17140 unsigned FlagSet = PPC::MOF_None; 17141 17142 // Compute subtarget flags. 17143 if (!Subtarget.hasP9Vector()) 17144 FlagSet |= PPC::MOF_SubtargetBeforeP9; 17145 else { 17146 FlagSet |= PPC::MOF_SubtargetP9; 17147 if (Subtarget.hasPrefixInstrs()) 17148 FlagSet |= PPC::MOF_SubtargetP10; 17149 } 17150 if (Subtarget.hasSPE()) 17151 FlagSet |= PPC::MOF_SubtargetSPE; 17152 17153 // Mark this as something we don't want to handle here if it is atomic 17154 // or pre-increment instruction. 17155 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent)) 17156 if (LSB->isIndexed()) 17157 return PPC::MOF_None; 17158 17159 // Compute in-memory type flags. This is based on if there are scalars, 17160 // floats or vectors. 17161 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent); 17162 assert(MN && "Parent should be a MemSDNode!"); 17163 EVT MemVT = MN->getMemoryVT(); 17164 unsigned Size = MemVT.getSizeInBits(); 17165 if (MemVT.isScalarInteger()) { 17166 assert(Size <= 64 && "Not expecting scalar integers larger than 8 bytes!"); 17167 if (Size < 32) 17168 FlagSet |= PPC::MOF_SubWordInt; 17169 else if (Size == 32) 17170 FlagSet |= PPC::MOF_WordInt; 17171 else 17172 FlagSet |= PPC::MOF_DoubleWordInt; 17173 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors. 17174 if (Size == 128) 17175 FlagSet |= PPC::MOF_Vector; 17176 else if (Size == 256) 17177 FlagSet |= PPC::MOF_Vector256; 17178 else 17179 llvm_unreachable("Not expecting illegal vectors!"); 17180 } else { // Floating point type: can be scalar, f128 or vector types. 17181 if (Size == 32 || Size == 64) 17182 FlagSet |= PPC::MOF_ScalarFloat; 17183 else if (MemVT == MVT::f128 || MemVT.isVector()) 17184 FlagSet |= PPC::MOF_Vector; 17185 else 17186 llvm_unreachable("Not expecting illegal scalar floats!"); 17187 } 17188 17189 // Compute flags for address computation. 17190 computeFlagsForAddressComputation(N, FlagSet, DAG); 17191 17192 // Compute type extension flags. 17193 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) { 17194 switch (LN->getExtensionType()) { 17195 case ISD::SEXTLOAD: 17196 FlagSet |= PPC::MOF_SExt; 17197 break; 17198 case ISD::EXTLOAD: 17199 case ISD::ZEXTLOAD: 17200 FlagSet |= PPC::MOF_ZExt; 17201 break; 17202 case ISD::NON_EXTLOAD: 17203 FlagSet |= PPC::MOF_NoExt; 17204 break; 17205 } 17206 } else 17207 FlagSet |= PPC::MOF_NoExt; 17208 17209 // For integers, no extension is the same as zero extension. 17210 // We set the extension mode to zero extension so we don't have 17211 // to add separate entries in AddrModesMap for loads and stores. 17212 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) { 17213 FlagSet |= PPC::MOF_ZExt; 17214 FlagSet &= ~PPC::MOF_NoExt; 17215 } 17216 17217 // If we don't have prefixed instructions, 34-bit constants should be 17218 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms. 17219 bool IsNonP1034BitConst = 17220 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) & 17221 FlagSet) == PPC::MOF_RPlusSImm34; 17222 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR && 17223 IsNonP1034BitConst) 17224 FlagSet |= PPC::MOF_NotAddNorCst; 17225 17226 return FlagSet; 17227 } 17228 17229 /// SelectForceXFormMode - Given the specified address, force it to be 17230 /// represented as an indexed [r+r] operation (an XForm instruction). 17231 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp, 17232 SDValue &Base, 17233 SelectionDAG &DAG) const { 17234 17235 PPC::AddrMode Mode = PPC::AM_XForm; 17236 int16_t ForceXFormImm = 0; 17237 if (provablyDisjointOr(DAG, N) && 17238 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) { 17239 Disp = N.getOperand(0); 17240 Base = N.getOperand(1); 17241 return Mode; 17242 } 17243 17244 // If the address is the result of an add, we will utilize the fact that the 17245 // address calculation includes an implicit add. However, we can reduce 17246 // register pressure if we do not materialize a constant just for use as the 17247 // index register. We only get rid of the add if it is not an add of a 17248 // value and a 16-bit signed constant and both have a single use. 17249 if (N.getOpcode() == ISD::ADD && 17250 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) || 17251 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 17252 Disp = N.getOperand(0); 17253 Base = N.getOperand(1); 17254 return Mode; 17255 } 17256 17257 // Otherwise, use R0 as the base register. 17258 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17259 N.getValueType()); 17260 Base = N; 17261 17262 return Mode; 17263 } 17264 17265 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), 17266 /// compute the address flags of the node, get the optimal address mode based 17267 /// on the flags, and set the Base and Disp based on the address mode. 17268 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent, 17269 SDValue N, SDValue &Disp, 17270 SDValue &Base, 17271 SelectionDAG &DAG, 17272 MaybeAlign Align) const { 17273 SDLoc DL(Parent); 17274 17275 // Compute the address flags. 17276 unsigned Flags = computeMOFlags(Parent, N, DAG); 17277 17278 // Get the optimal address mode based on the Flags. 17279 PPC::AddrMode Mode = getAddrModeForFlags(Flags); 17280 17281 // Set Base and Disp accordingly depending on the address mode. 17282 switch (Mode) { 17283 case PPC::AM_DForm: 17284 case PPC::AM_DSForm: 17285 case PPC::AM_DQForm: { 17286 // This is a register plus a 16-bit immediate. The base will be the 17287 // register and the displacement will be the immediate unless it 17288 // isn't sufficiently aligned. 17289 if (Flags & PPC::MOF_RPlusSImm16) { 17290 SDValue Op0 = N.getOperand(0); 17291 SDValue Op1 = N.getOperand(1); 17292 int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue(); 17293 if (!Align || isAligned(*Align, Imm)) { 17294 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType()); 17295 Base = Op0; 17296 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) { 17297 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17298 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17299 } 17300 break; 17301 } 17302 } 17303 // This is a register plus the @lo relocation. The base is the register 17304 // and the displacement is the global address. 17305 else if (Flags & PPC::MOF_RPlusLo) { 17306 Disp = N.getOperand(1).getOperand(0); // The global address. 17307 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 17308 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 17309 Disp.getOpcode() == ISD::TargetConstantPool || 17310 Disp.getOpcode() == ISD::TargetJumpTable); 17311 Base = N.getOperand(0); 17312 break; 17313 } 17314 // This is a constant address at most 32 bits. The base will be 17315 // zero or load-immediate-shifted and the displacement will be 17316 // the low 16 bits of the address. 17317 else if (Flags & PPC::MOF_AddrIsSImm32) { 17318 auto *CN = cast<ConstantSDNode>(N); 17319 EVT CNType = CN->getValueType(0); 17320 uint64_t CNImm = CN->getZExtValue(); 17321 // If this address fits entirely in a 16-bit sext immediate field, codegen 17322 // this as "d, 0". 17323 int16_t Imm; 17324 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) { 17325 Disp = DAG.getTargetConstant(Imm, DL, CNType); 17326 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17327 CNType); 17328 break; 17329 } 17330 // Handle 32-bit sext immediate with LIS + Addr mode. 17331 if ((CNType == MVT::i32 || isInt<32>(CNImm)) && 17332 (!Align || isAligned(*Align, CNImm))) { 17333 int32_t Addr = (int32_t)CNImm; 17334 // Otherwise, break this down into LIS + Disp. 17335 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32); 17336 Base = 17337 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32); 17338 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8; 17339 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0); 17340 break; 17341 } 17342 } 17343 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable. 17344 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout())); 17345 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 17346 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 17347 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 17348 } else 17349 Base = N; 17350 break; 17351 } 17352 case PPC::AM_None: 17353 break; 17354 default: { // By default, X-Form is always available to be selected. 17355 // When a frame index is not aligned, we also match by XForm. 17356 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N); 17357 Base = FI ? N : N.getOperand(1); 17358 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17359 N.getValueType()) 17360 : N.getOperand(0); 17361 break; 17362 } 17363 } 17364 return Mode; 17365 } 17366 17367 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC, 17368 bool Return, 17369 bool IsVarArg) const { 17370 switch (CC) { 17371 case CallingConv::Cold: 17372 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS); 17373 default: 17374 return CC_PPC64_ELF_FIS; 17375 } 17376 } 17377