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 // FIXME: Remove this once the bug has been fixed! 134 extern cl::opt<bool> ANDIGlueBug; 135 136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 137 const PPCSubtarget &STI) 138 : TargetLowering(TM), Subtarget(STI) { 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 149 // EFPU2 APU only supports f32 150 if (!Subtarget.hasEFPU2()) 151 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 152 } else { 153 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 154 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 155 } 156 } 157 158 // Match BITREVERSE to customized fast code sequence in the td file. 159 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 160 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 161 162 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 163 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 164 165 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 166 for (MVT VT : MVT::integer_valuetypes()) { 167 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 168 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 169 } 170 171 if (Subtarget.isISA3_0()) { 172 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 173 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 174 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 175 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 176 } else { 177 // No extending loads from f16 or HW conversions back and forth. 178 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 179 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 180 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 181 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 182 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 183 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 184 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 185 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 186 } 187 188 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 189 190 // PowerPC has pre-inc load and store's. 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 195 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 200 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 201 if (!Subtarget.hasSPE()) { 202 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 203 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 204 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 205 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 206 } 207 208 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 209 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 210 for (MVT VT : ScalarIntVTs) { 211 setOperationAction(ISD::ADDC, VT, Legal); 212 setOperationAction(ISD::ADDE, VT, Legal); 213 setOperationAction(ISD::SUBC, VT, Legal); 214 setOperationAction(ISD::SUBE, VT, Legal); 215 } 216 217 if (Subtarget.useCRBits()) { 218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 219 220 if (isPPC64 || Subtarget.hasFPCVT()) { 221 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 222 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 223 isPPC64 ? MVT::i64 : MVT::i32); 224 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 225 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 226 isPPC64 ? MVT::i64 : MVT::i32); 227 228 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 229 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 230 isPPC64 ? MVT::i64 : MVT::i32); 231 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 232 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 233 isPPC64 ? MVT::i64 : MVT::i32); 234 235 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 236 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 237 isPPC64 ? MVT::i64 : MVT::i32); 238 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 239 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 240 isPPC64 ? MVT::i64 : MVT::i32); 241 242 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 243 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 244 isPPC64 ? MVT::i64 : MVT::i32); 245 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 246 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 247 isPPC64 ? MVT::i64 : MVT::i32); 248 } else { 249 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 250 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 251 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 252 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 253 } 254 255 // PowerPC does not support direct load/store of condition registers. 256 setOperationAction(ISD::LOAD, MVT::i1, Custom); 257 setOperationAction(ISD::STORE, MVT::i1, Custom); 258 259 // FIXME: Remove this once the ANDI glue bug is fixed: 260 if (ANDIGlueBug) 261 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 262 263 for (MVT VT : MVT::integer_valuetypes()) { 264 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 265 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 266 setTruncStoreAction(VT, MVT::i1, Expand); 267 } 268 269 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 270 } 271 272 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 273 // PPC (the libcall is not available). 274 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 275 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 276 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 277 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 278 279 // We do not currently implement these libm ops for PowerPC. 280 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 281 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 282 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 283 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 284 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 285 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 286 287 // PowerPC has no SREM/UREM instructions unless we are on P9 288 // On P9 we may use a hardware instruction to compute the remainder. 289 // When the result of both the remainder and the division is required it is 290 // more efficient to compute the remainder from the result of the division 291 // rather than use the remainder instruction. The instructions are legalized 292 // directly because the DivRemPairsPass performs the transformation at the IR 293 // level. 294 if (Subtarget.isISA3_0()) { 295 setOperationAction(ISD::SREM, MVT::i32, Legal); 296 setOperationAction(ISD::UREM, MVT::i32, Legal); 297 setOperationAction(ISD::SREM, MVT::i64, Legal); 298 setOperationAction(ISD::UREM, MVT::i64, Legal); 299 } else { 300 setOperationAction(ISD::SREM, MVT::i32, Expand); 301 setOperationAction(ISD::UREM, MVT::i32, Expand); 302 setOperationAction(ISD::SREM, MVT::i64, Expand); 303 setOperationAction(ISD::UREM, MVT::i64, Expand); 304 } 305 306 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 307 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 308 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 309 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 310 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 311 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 312 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 313 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 314 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 315 316 // Handle constrained floating-point operations of scalar. 317 // TODO: Handle SPE specific operation. 318 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 319 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 320 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 321 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 322 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 323 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 324 325 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 326 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 327 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 328 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 329 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 330 if (Subtarget.hasVSX()) { 331 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 332 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 333 } 334 335 if (Subtarget.hasFSQRT()) { 336 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 337 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 338 } 339 340 if (Subtarget.hasFPRND()) { 341 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 342 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 343 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 344 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 345 346 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 347 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 348 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 349 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 350 } 351 352 // We don't support sin/cos/sqrt/fmod/pow 353 setOperationAction(ISD::FSIN , MVT::f64, Expand); 354 setOperationAction(ISD::FCOS , MVT::f64, Expand); 355 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 356 setOperationAction(ISD::FREM , MVT::f64, Expand); 357 setOperationAction(ISD::FPOW , MVT::f64, Expand); 358 setOperationAction(ISD::FSIN , MVT::f32, Expand); 359 setOperationAction(ISD::FCOS , MVT::f32, Expand); 360 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 361 setOperationAction(ISD::FREM , MVT::f32, Expand); 362 setOperationAction(ISD::FPOW , MVT::f32, Expand); 363 if (Subtarget.hasSPE()) { 364 setOperationAction(ISD::FMA , MVT::f64, Expand); 365 setOperationAction(ISD::FMA , MVT::f32, Expand); 366 } else { 367 setOperationAction(ISD::FMA , MVT::f64, Legal); 368 setOperationAction(ISD::FMA , MVT::f32, Legal); 369 } 370 371 if (Subtarget.hasSPE()) 372 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 373 374 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 375 376 // If we're enabling GP optimizations, use hardware square root 377 if (!Subtarget.hasFSQRT() && 378 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 379 Subtarget.hasFRE())) 380 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 381 382 if (!Subtarget.hasFSQRT() && 383 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 384 Subtarget.hasFRES())) 385 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 386 387 if (Subtarget.hasFCPSGN()) { 388 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 389 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 390 } else { 391 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 392 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 393 } 394 395 if (Subtarget.hasFPRND()) { 396 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 397 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 398 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 399 setOperationAction(ISD::FROUND, MVT::f64, Legal); 400 401 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 402 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 403 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 404 setOperationAction(ISD::FROUND, MVT::f32, Legal); 405 } 406 407 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 408 // to speed up scalar BSWAP64. 409 // CTPOP or CTTZ were introduced in P8/P9 respectively 410 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 411 if (Subtarget.hasP9Vector()) 412 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 413 else 414 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 415 if (Subtarget.isISA3_0()) { 416 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 417 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 418 } else { 419 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 420 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 421 } 422 423 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 424 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 425 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 426 } else { 427 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 428 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 429 } 430 431 // PowerPC does not have ROTR 432 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 433 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 434 435 if (!Subtarget.useCRBits()) { 436 // PowerPC does not have Select 437 setOperationAction(ISD::SELECT, MVT::i32, Expand); 438 setOperationAction(ISD::SELECT, MVT::i64, Expand); 439 setOperationAction(ISD::SELECT, MVT::f32, Expand); 440 setOperationAction(ISD::SELECT, MVT::f64, Expand); 441 } 442 443 // PowerPC wants to turn select_cc of FP into fsel when possible. 444 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 445 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 446 447 // PowerPC wants to optimize integer setcc a bit 448 if (!Subtarget.useCRBits()) 449 setOperationAction(ISD::SETCC, MVT::i32, Custom); 450 451 if (Subtarget.hasFPU()) { 452 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 453 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 454 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 455 456 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 457 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 458 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 459 } 460 461 // PowerPC does not have BRCOND which requires SetCC 462 if (!Subtarget.useCRBits()) 463 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 464 465 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 466 467 if (Subtarget.hasSPE()) { 468 // SPE has built-in conversions 469 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 470 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 471 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 472 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 473 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 474 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 475 } else { 476 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 477 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 478 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 479 480 // PowerPC does not have [U|S]INT_TO_FP 481 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 482 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 483 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 484 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 485 } 486 487 if (Subtarget.hasDirectMove() && isPPC64) { 488 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 489 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 490 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 491 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 492 if (TM.Options.UnsafeFPMath) { 493 setOperationAction(ISD::LRINT, MVT::f64, Legal); 494 setOperationAction(ISD::LRINT, MVT::f32, Legal); 495 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 496 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 497 setOperationAction(ISD::LROUND, MVT::f64, Legal); 498 setOperationAction(ISD::LROUND, MVT::f32, Legal); 499 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 500 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 501 } 502 } else { 503 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 504 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 505 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 506 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 507 } 508 509 // We cannot sextinreg(i1). Expand to shifts. 510 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 511 512 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 513 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 514 // support continuation, user-level threading, and etc.. As a result, no 515 // other SjLj exception interfaces are implemented and please don't build 516 // your own exception handling based on them. 517 // LLVM/Clang supports zero-cost DWARF exception handling. 518 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 519 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 520 521 // We want to legalize GlobalAddress and ConstantPool nodes into the 522 // appropriate instructions to materialize the address. 523 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 524 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 525 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 526 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 527 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 528 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 529 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 530 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 531 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 532 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 533 534 // TRAP is legal. 535 setOperationAction(ISD::TRAP, MVT::Other, Legal); 536 537 // TRAMPOLINE is custom lowered. 538 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 539 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 540 541 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 542 setOperationAction(ISD::VASTART , MVT::Other, Custom); 543 544 if (Subtarget.is64BitELFABI()) { 545 // VAARG always uses double-word chunks, so promote anything smaller. 546 setOperationAction(ISD::VAARG, MVT::i1, Promote); 547 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 548 setOperationAction(ISD::VAARG, MVT::i8, Promote); 549 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 550 setOperationAction(ISD::VAARG, MVT::i16, Promote); 551 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 552 setOperationAction(ISD::VAARG, MVT::i32, Promote); 553 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 554 setOperationAction(ISD::VAARG, MVT::Other, Expand); 555 } else if (Subtarget.is32BitELFABI()) { 556 // VAARG is custom lowered with the 32-bit SVR4 ABI. 557 setOperationAction(ISD::VAARG, MVT::Other, Custom); 558 setOperationAction(ISD::VAARG, MVT::i64, Custom); 559 } else 560 setOperationAction(ISD::VAARG, MVT::Other, Expand); 561 562 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 563 if (Subtarget.is32BitELFABI()) 564 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 565 else 566 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 567 568 // Use the default implementation. 569 setOperationAction(ISD::VAEND , MVT::Other, Expand); 570 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 571 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 572 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 573 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 574 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 575 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 576 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 577 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 578 579 // We want to custom lower some of our intrinsics. 580 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 581 582 // To handle counter-based loop conditions. 583 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 584 585 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 586 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 587 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 588 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 589 590 // Comparisons that require checking two conditions. 591 if (Subtarget.hasSPE()) { 592 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 593 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 594 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 595 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 596 } 597 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 598 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 599 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 600 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 601 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 602 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 603 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 604 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 605 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 606 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 607 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 608 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 609 610 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 611 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 612 613 if (Subtarget.has64BitSupport()) { 614 // They also have instructions for converting between i64 and fp. 615 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 616 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 617 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 618 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 619 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 620 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 621 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 622 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 623 // This is just the low 32 bits of a (signed) fp->i64 conversion. 624 // We cannot do this with Promote because i64 is not a legal type. 625 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 626 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 627 628 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 629 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 630 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 631 } 632 } else { 633 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 634 if (Subtarget.hasSPE()) { 635 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 636 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 637 } else { 638 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 639 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 640 } 641 } 642 643 // With the instructions enabled under FPCVT, we can do everything. 644 if (Subtarget.hasFPCVT()) { 645 if (Subtarget.has64BitSupport()) { 646 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 647 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 648 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 649 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 650 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 651 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 652 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 653 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 654 } 655 656 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 657 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 658 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 659 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 660 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 661 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 662 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 663 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 664 } 665 666 if (Subtarget.use64BitRegs()) { 667 // 64-bit PowerPC implementations can support i64 types directly 668 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 669 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 670 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 671 // 64-bit PowerPC wants to expand i128 shifts itself. 672 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 673 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 674 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 675 } else { 676 // 32-bit PowerPC wants to expand i64 shifts itself. 677 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 678 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 679 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 680 } 681 682 // PowerPC has better expansions for funnel shifts than the generic 683 // TargetLowering::expandFunnelShift. 684 if (Subtarget.has64BitSupport()) { 685 setOperationAction(ISD::FSHL, MVT::i64, Custom); 686 setOperationAction(ISD::FSHR, MVT::i64, Custom); 687 } 688 setOperationAction(ISD::FSHL, MVT::i32, Custom); 689 setOperationAction(ISD::FSHR, MVT::i32, Custom); 690 691 if (Subtarget.hasVSX()) { 692 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 693 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 694 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 695 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 696 } 697 698 if (Subtarget.hasAltivec()) { 699 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 700 setOperationAction(ISD::SADDSAT, VT, Legal); 701 setOperationAction(ISD::SSUBSAT, VT, Legal); 702 setOperationAction(ISD::UADDSAT, VT, Legal); 703 setOperationAction(ISD::USUBSAT, VT, Legal); 704 } 705 // First set operation action for all vector types to expand. Then we 706 // will selectively turn on ones that can be effectively codegen'd. 707 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 708 // add/sub are legal for all supported vector VT's. 709 setOperationAction(ISD::ADD, VT, Legal); 710 setOperationAction(ISD::SUB, VT, Legal); 711 712 // For v2i64, these are only valid with P8Vector. This is corrected after 713 // the loop. 714 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 715 setOperationAction(ISD::SMAX, VT, Legal); 716 setOperationAction(ISD::SMIN, VT, Legal); 717 setOperationAction(ISD::UMAX, VT, Legal); 718 setOperationAction(ISD::UMIN, VT, Legal); 719 } 720 else { 721 setOperationAction(ISD::SMAX, VT, Expand); 722 setOperationAction(ISD::SMIN, VT, Expand); 723 setOperationAction(ISD::UMAX, VT, Expand); 724 setOperationAction(ISD::UMIN, VT, Expand); 725 } 726 727 if (Subtarget.hasVSX()) { 728 setOperationAction(ISD::FMAXNUM, VT, Legal); 729 setOperationAction(ISD::FMINNUM, VT, Legal); 730 } 731 732 // Vector instructions introduced in P8 733 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 734 setOperationAction(ISD::CTPOP, VT, Legal); 735 setOperationAction(ISD::CTLZ, VT, Legal); 736 } 737 else { 738 setOperationAction(ISD::CTPOP, VT, Expand); 739 setOperationAction(ISD::CTLZ, VT, Expand); 740 } 741 742 // Vector instructions introduced in P9 743 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 744 setOperationAction(ISD::CTTZ, VT, Legal); 745 else 746 setOperationAction(ISD::CTTZ, VT, Expand); 747 748 // We promote all shuffles to v16i8. 749 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 750 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 751 752 // We promote all non-typed operations to v4i32. 753 setOperationAction(ISD::AND , VT, Promote); 754 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 755 setOperationAction(ISD::OR , VT, Promote); 756 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 757 setOperationAction(ISD::XOR , VT, Promote); 758 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 759 setOperationAction(ISD::LOAD , VT, Promote); 760 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 761 setOperationAction(ISD::SELECT, VT, Promote); 762 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 763 setOperationAction(ISD::VSELECT, VT, Legal); 764 setOperationAction(ISD::SELECT_CC, VT, Promote); 765 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 766 setOperationAction(ISD::STORE, VT, Promote); 767 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 768 769 // No other operations are legal. 770 setOperationAction(ISD::MUL , VT, Expand); 771 setOperationAction(ISD::SDIV, VT, Expand); 772 setOperationAction(ISD::SREM, VT, Expand); 773 setOperationAction(ISD::UDIV, VT, Expand); 774 setOperationAction(ISD::UREM, VT, Expand); 775 setOperationAction(ISD::FDIV, VT, Expand); 776 setOperationAction(ISD::FREM, VT, Expand); 777 setOperationAction(ISD::FNEG, VT, Expand); 778 setOperationAction(ISD::FSQRT, VT, Expand); 779 setOperationAction(ISD::FLOG, VT, Expand); 780 setOperationAction(ISD::FLOG10, VT, Expand); 781 setOperationAction(ISD::FLOG2, VT, Expand); 782 setOperationAction(ISD::FEXP, VT, Expand); 783 setOperationAction(ISD::FEXP2, VT, Expand); 784 setOperationAction(ISD::FSIN, VT, Expand); 785 setOperationAction(ISD::FCOS, VT, Expand); 786 setOperationAction(ISD::FABS, VT, Expand); 787 setOperationAction(ISD::FFLOOR, VT, Expand); 788 setOperationAction(ISD::FCEIL, VT, Expand); 789 setOperationAction(ISD::FTRUNC, VT, Expand); 790 setOperationAction(ISD::FRINT, VT, Expand); 791 setOperationAction(ISD::FNEARBYINT, VT, Expand); 792 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 793 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 794 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 795 setOperationAction(ISD::MULHU, VT, Expand); 796 setOperationAction(ISD::MULHS, VT, Expand); 797 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 798 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 799 setOperationAction(ISD::UDIVREM, VT, Expand); 800 setOperationAction(ISD::SDIVREM, VT, Expand); 801 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 802 setOperationAction(ISD::FPOW, VT, Expand); 803 setOperationAction(ISD::BSWAP, VT, Expand); 804 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 805 setOperationAction(ISD::ROTL, VT, Expand); 806 setOperationAction(ISD::ROTR, VT, Expand); 807 808 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 809 setTruncStoreAction(VT, InnerVT, Expand); 810 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 811 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 812 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 813 } 814 } 815 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 816 if (!Subtarget.hasP8Vector()) { 817 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 818 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 819 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 820 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 821 } 822 823 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 824 // with merges, splats, etc. 825 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 826 827 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 828 // are cheap, so handle them before they get expanded to scalar. 829 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 830 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 831 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 832 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 833 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 834 835 setOperationAction(ISD::AND , MVT::v4i32, Legal); 836 setOperationAction(ISD::OR , MVT::v4i32, Legal); 837 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 838 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 839 setOperationAction(ISD::SELECT, MVT::v4i32, 840 Subtarget.useCRBits() ? Legal : Expand); 841 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 842 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 843 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 844 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 845 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 846 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 847 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 848 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 849 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 850 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 851 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 852 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 853 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 854 855 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 856 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 857 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 858 if (Subtarget.hasAltivec()) 859 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 860 setOperationAction(ISD::ROTL, VT, Legal); 861 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 862 if (Subtarget.hasP8Altivec()) 863 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 864 865 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 866 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 867 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 868 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 869 870 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 871 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 872 873 if (Subtarget.hasVSX()) { 874 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 875 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 876 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 877 } 878 879 if (Subtarget.hasP8Altivec()) 880 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 881 else 882 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 883 884 if (Subtarget.isISA3_1()) { 885 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 886 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 887 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 888 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 889 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 890 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 891 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 892 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 893 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 894 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 895 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 896 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 897 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 898 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 899 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 900 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 901 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 902 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 903 } 904 905 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 906 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 907 908 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 909 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 910 911 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 912 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 913 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 914 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 915 916 // Altivec does not contain unordered floating-point compare instructions 917 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 918 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 919 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 920 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 921 922 if (Subtarget.hasVSX()) { 923 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 924 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 925 if (Subtarget.hasP8Vector()) { 926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 928 } 929 if (Subtarget.hasDirectMove() && isPPC64) { 930 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 931 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 932 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 933 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 934 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 935 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 938 } 939 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 940 941 // The nearbyint variants are not allowed to raise the inexact exception 942 // so we can only code-gen them with unsafe math. 943 if (TM.Options.UnsafeFPMath) { 944 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 945 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 946 } 947 948 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 949 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 950 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 951 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 952 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 953 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 954 setOperationAction(ISD::FROUND, MVT::f64, Legal); 955 setOperationAction(ISD::FRINT, MVT::f64, Legal); 956 957 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 958 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 959 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 960 setOperationAction(ISD::FROUND, MVT::f32, Legal); 961 setOperationAction(ISD::FRINT, MVT::f32, Legal); 962 963 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 964 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 965 966 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 967 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 968 969 // Share the Altivec comparison restrictions. 970 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 971 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 972 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 973 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 974 975 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 976 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 977 978 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 979 980 if (Subtarget.hasP8Vector()) 981 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 982 983 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 984 985 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 986 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 987 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 988 989 if (Subtarget.hasP8Altivec()) { 990 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 991 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 992 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 993 994 // 128 bit shifts can be accomplished via 3 instructions for SHL and 995 // SRL, but not for SRA because of the instructions available: 996 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 997 // doing 998 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 999 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1000 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1001 1002 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1003 } 1004 else { 1005 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1006 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1007 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1008 1009 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1010 1011 // VSX v2i64 only supports non-arithmetic operations. 1012 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1013 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1014 } 1015 1016 if (Subtarget.isISA3_1()) 1017 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1018 else 1019 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1020 1021 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1022 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1023 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1024 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1025 1026 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1027 1028 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1029 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1030 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1031 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1032 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1033 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1034 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1035 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1036 1037 // Custom handling for partial vectors of integers converted to 1038 // floating point. We already have optimal handling for v2i32 through 1039 // the DAG combine, so those aren't necessary. 1040 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1041 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1042 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1043 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1044 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1045 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1046 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1047 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1048 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1049 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1050 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1051 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1052 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1053 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1054 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1055 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1056 1057 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1058 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1059 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1060 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1061 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1062 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1063 1064 if (Subtarget.hasDirectMove()) 1065 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1066 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1067 1068 // Handle constrained floating-point operations of vector. 1069 // The predictor is `hasVSX` because altivec instruction has 1070 // no exception but VSX vector instruction has. 1071 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1072 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1073 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1074 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1075 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1076 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1077 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1078 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1079 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1080 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1081 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1082 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1083 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1084 1085 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1086 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1087 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1088 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1089 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1090 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1091 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1092 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1093 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1094 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1095 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1096 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1097 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1098 1099 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1100 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1101 1102 for (MVT FPT : MVT::fp_valuetypes()) 1103 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1104 1105 // Expand the SELECT to SELECT_CC 1106 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1107 1108 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1109 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1110 1111 // No implementation for these ops for PowerPC. 1112 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1113 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1114 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1115 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1116 setOperationAction(ISD::FREM, MVT::f128, Expand); 1117 } 1118 1119 if (Subtarget.hasP8Altivec()) { 1120 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1121 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1122 } 1123 1124 if (Subtarget.hasP9Vector()) { 1125 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1126 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1127 1128 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1129 // SRL, but not for SRA because of the instructions available: 1130 // VS{RL} and VS{RL}O. 1131 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1132 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1133 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1134 1135 setOperationAction(ISD::FADD, MVT::f128, Legal); 1136 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1137 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1138 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1139 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1140 1141 setOperationAction(ISD::FMA, MVT::f128, Legal); 1142 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1143 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1144 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1145 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1146 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1147 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1148 1149 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1150 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1151 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1152 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1153 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1154 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1155 1156 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1157 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1158 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1159 1160 // Handle constrained floating-point operations of fp128 1161 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1162 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1163 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1164 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1165 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1166 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1167 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1168 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1169 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1170 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1171 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1172 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1173 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1174 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1175 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1176 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1177 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1178 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1179 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1180 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1181 } else if (Subtarget.hasVSX()) { 1182 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1183 setOperationAction(ISD::STORE, MVT::f128, Promote); 1184 1185 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1186 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1187 1188 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1189 // fp_to_uint and int_to_fp. 1190 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1191 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1192 1193 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1194 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1195 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1196 setOperationAction(ISD::FABS, MVT::f128, Expand); 1197 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1198 setOperationAction(ISD::FMA, MVT::f128, Expand); 1199 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1200 1201 // Expand the fp_extend if the target type is fp128. 1202 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1203 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1204 1205 // Expand the fp_round if the source type is fp128. 1206 for (MVT VT : {MVT::f32, MVT::f64}) { 1207 setOperationAction(ISD::FP_ROUND, VT, Custom); 1208 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1209 } 1210 1211 setOperationAction(ISD::SETCC, MVT::f128, Custom); 1212 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 1213 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 1214 setOperationAction(ISD::BR_CC, MVT::f128, Expand); 1215 1216 // Lower following f128 select_cc pattern: 1217 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE 1218 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1219 1220 // We need to handle f128 SELECT_CC with integer result type. 1221 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1222 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 1223 } 1224 1225 if (Subtarget.hasP9Altivec()) { 1226 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1227 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1228 1229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1236 } 1237 1238 if (Subtarget.isISA3_1()) 1239 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 1240 } 1241 1242 if (Subtarget.pairedVectorMemops()) { 1243 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1244 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1245 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1246 } 1247 if (Subtarget.hasMMA()) { 1248 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1249 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1250 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1251 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1252 } 1253 1254 if (Subtarget.has64BitSupport()) 1255 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1256 1257 if (Subtarget.isISA3_1()) 1258 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1259 1260 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1261 1262 if (!isPPC64) { 1263 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1264 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1265 } 1266 1267 setBooleanContents(ZeroOrOneBooleanContent); 1268 1269 if (Subtarget.hasAltivec()) { 1270 // Altivec instructions set fields to all zeros or all ones. 1271 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1272 } 1273 1274 if (!isPPC64) { 1275 // These libcalls are not available in 32-bit. 1276 setLibcallName(RTLIB::SHL_I128, nullptr); 1277 setLibcallName(RTLIB::SRL_I128, nullptr); 1278 setLibcallName(RTLIB::SRA_I128, nullptr); 1279 } 1280 1281 if (!isPPC64) 1282 setMaxAtomicSizeInBitsSupported(32); 1283 1284 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1285 1286 // We have target-specific dag combine patterns for the following nodes: 1287 setTargetDAGCombine(ISD::ADD); 1288 setTargetDAGCombine(ISD::SHL); 1289 setTargetDAGCombine(ISD::SRA); 1290 setTargetDAGCombine(ISD::SRL); 1291 setTargetDAGCombine(ISD::MUL); 1292 setTargetDAGCombine(ISD::FMA); 1293 setTargetDAGCombine(ISD::SINT_TO_FP); 1294 setTargetDAGCombine(ISD::BUILD_VECTOR); 1295 if (Subtarget.hasFPCVT()) 1296 setTargetDAGCombine(ISD::UINT_TO_FP); 1297 setTargetDAGCombine(ISD::LOAD); 1298 setTargetDAGCombine(ISD::STORE); 1299 setTargetDAGCombine(ISD::BR_CC); 1300 if (Subtarget.useCRBits()) 1301 setTargetDAGCombine(ISD::BRCOND); 1302 setTargetDAGCombine(ISD::BSWAP); 1303 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1304 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1305 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1306 1307 setTargetDAGCombine(ISD::SIGN_EXTEND); 1308 setTargetDAGCombine(ISD::ZERO_EXTEND); 1309 setTargetDAGCombine(ISD::ANY_EXTEND); 1310 1311 setTargetDAGCombine(ISD::TRUNCATE); 1312 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1313 1314 1315 if (Subtarget.useCRBits()) { 1316 setTargetDAGCombine(ISD::TRUNCATE); 1317 setTargetDAGCombine(ISD::SETCC); 1318 setTargetDAGCombine(ISD::SELECT_CC); 1319 } 1320 1321 if (Subtarget.hasP9Altivec()) { 1322 setTargetDAGCombine(ISD::ABS); 1323 setTargetDAGCombine(ISD::VSELECT); 1324 } 1325 1326 setLibcallName(RTLIB::LOG_F128, "logf128"); 1327 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1328 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1329 setLibcallName(RTLIB::EXP_F128, "expf128"); 1330 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1331 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1332 setLibcallName(RTLIB::COS_F128, "cosf128"); 1333 setLibcallName(RTLIB::POW_F128, "powf128"); 1334 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1335 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1336 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1337 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1338 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1339 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1340 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1341 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1342 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1343 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1344 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1345 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1346 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1347 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1348 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1349 1350 // With 32 condition bits, we don't need to sink (and duplicate) compares 1351 // aggressively in CodeGenPrep. 1352 if (Subtarget.useCRBits()) { 1353 setHasMultipleConditionRegisters(); 1354 setJumpIsExpensive(); 1355 } 1356 1357 setMinFunctionAlignment(Align(4)); 1358 1359 switch (Subtarget.getCPUDirective()) { 1360 default: break; 1361 case PPC::DIR_970: 1362 case PPC::DIR_A2: 1363 case PPC::DIR_E500: 1364 case PPC::DIR_E500mc: 1365 case PPC::DIR_E5500: 1366 case PPC::DIR_PWR4: 1367 case PPC::DIR_PWR5: 1368 case PPC::DIR_PWR5X: 1369 case PPC::DIR_PWR6: 1370 case PPC::DIR_PWR6X: 1371 case PPC::DIR_PWR7: 1372 case PPC::DIR_PWR8: 1373 case PPC::DIR_PWR9: 1374 case PPC::DIR_PWR10: 1375 case PPC::DIR_PWR_FUTURE: 1376 setPrefLoopAlignment(Align(16)); 1377 setPrefFunctionAlignment(Align(16)); 1378 break; 1379 } 1380 1381 if (Subtarget.enableMachineScheduler()) 1382 setSchedulingPreference(Sched::Source); 1383 else 1384 setSchedulingPreference(Sched::Hybrid); 1385 1386 computeRegisterProperties(STI.getRegisterInfo()); 1387 1388 // The Freescale cores do better with aggressive inlining of memcpy and 1389 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1390 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1391 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1392 MaxStoresPerMemset = 32; 1393 MaxStoresPerMemsetOptSize = 16; 1394 MaxStoresPerMemcpy = 32; 1395 MaxStoresPerMemcpyOptSize = 8; 1396 MaxStoresPerMemmove = 32; 1397 MaxStoresPerMemmoveOptSize = 8; 1398 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1399 // The A2 also benefits from (very) aggressive inlining of memcpy and 1400 // friends. The overhead of a the function call, even when warm, can be 1401 // over one hundred cycles. 1402 MaxStoresPerMemset = 128; 1403 MaxStoresPerMemcpy = 128; 1404 MaxStoresPerMemmove = 128; 1405 MaxLoadsPerMemcmp = 128; 1406 } else { 1407 MaxLoadsPerMemcmp = 8; 1408 MaxLoadsPerMemcmpOptSize = 4; 1409 } 1410 1411 IsStrictFPEnabled = true; 1412 1413 // Let the subtarget (CPU) decide if a predictable select is more expensive 1414 // than the corresponding branch. This information is used in CGP to decide 1415 // when to convert selects into branches. 1416 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1417 } 1418 1419 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1420 /// the desired ByVal argument alignment. 1421 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1422 if (MaxAlign == MaxMaxAlign) 1423 return; 1424 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1425 if (MaxMaxAlign >= 32 && 1426 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1427 MaxAlign = Align(32); 1428 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1429 MaxAlign < 16) 1430 MaxAlign = Align(16); 1431 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1432 Align EltAlign; 1433 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1434 if (EltAlign > MaxAlign) 1435 MaxAlign = EltAlign; 1436 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1437 for (auto *EltTy : STy->elements()) { 1438 Align EltAlign; 1439 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1440 if (EltAlign > MaxAlign) 1441 MaxAlign = EltAlign; 1442 if (MaxAlign == MaxMaxAlign) 1443 break; 1444 } 1445 } 1446 } 1447 1448 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1449 /// function arguments in the caller parameter area. 1450 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1451 const DataLayout &DL) const { 1452 // 16byte and wider vectors are passed on 16byte boundary. 1453 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1454 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1455 if (Subtarget.hasAltivec()) 1456 getMaxByValAlign(Ty, Alignment, Align(16)); 1457 return Alignment.value(); 1458 } 1459 1460 bool PPCTargetLowering::useSoftFloat() const { 1461 return Subtarget.useSoftFloat(); 1462 } 1463 1464 bool PPCTargetLowering::hasSPE() const { 1465 return Subtarget.hasSPE(); 1466 } 1467 1468 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1469 return VT.isScalarInteger(); 1470 } 1471 1472 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1473 switch ((PPCISD::NodeType)Opcode) { 1474 case PPCISD::FIRST_NUMBER: break; 1475 case PPCISD::FSEL: return "PPCISD::FSEL"; 1476 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1477 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1478 case PPCISD::FCFID: return "PPCISD::FCFID"; 1479 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1480 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1481 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1482 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1483 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1484 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1485 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1486 case PPCISD::FP_TO_UINT_IN_VSR: 1487 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1488 case PPCISD::FP_TO_SINT_IN_VSR: 1489 return "PPCISD::FP_TO_SINT_IN_VSR"; 1490 case PPCISD::FRE: return "PPCISD::FRE"; 1491 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1492 case PPCISD::FTSQRT: 1493 return "PPCISD::FTSQRT"; 1494 case PPCISD::FSQRT: 1495 return "PPCISD::FSQRT"; 1496 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1497 case PPCISD::VPERM: return "PPCISD::VPERM"; 1498 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1499 case PPCISD::XXSPLTI_SP_TO_DP: 1500 return "PPCISD::XXSPLTI_SP_TO_DP"; 1501 case PPCISD::XXSPLTI32DX: 1502 return "PPCISD::XXSPLTI32DX"; 1503 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1504 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1505 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1506 case PPCISD::CMPB: return "PPCISD::CMPB"; 1507 case PPCISD::Hi: return "PPCISD::Hi"; 1508 case PPCISD::Lo: return "PPCISD::Lo"; 1509 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1510 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1511 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1512 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1513 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1514 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1515 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1516 case PPCISD::SRL: return "PPCISD::SRL"; 1517 case PPCISD::SRA: return "PPCISD::SRA"; 1518 case PPCISD::SHL: return "PPCISD::SHL"; 1519 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1520 case PPCISD::CALL: return "PPCISD::CALL"; 1521 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1522 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1523 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1524 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1525 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1526 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1527 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1528 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1529 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1530 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1531 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1532 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1533 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1534 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1535 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1536 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1537 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1538 case PPCISD::ANDI_rec_1_EQ_BIT: 1539 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1540 case PPCISD::ANDI_rec_1_GT_BIT: 1541 return "PPCISD::ANDI_rec_1_GT_BIT"; 1542 case PPCISD::VCMP: return "PPCISD::VCMP"; 1543 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1544 case PPCISD::LBRX: return "PPCISD::LBRX"; 1545 case PPCISD::STBRX: return "PPCISD::STBRX"; 1546 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1547 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1548 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1549 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1550 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1551 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1552 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1553 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1554 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1555 case PPCISD::ST_VSR_SCAL_INT: 1556 return "PPCISD::ST_VSR_SCAL_INT"; 1557 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1558 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1559 case PPCISD::BDZ: return "PPCISD::BDZ"; 1560 case PPCISD::MFFS: return "PPCISD::MFFS"; 1561 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1562 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1563 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1564 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1565 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1566 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1567 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1568 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1569 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1570 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1571 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1572 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1573 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1574 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX"; 1575 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1576 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1577 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1578 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1579 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1580 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1581 case PPCISD::PADDI_DTPREL: 1582 return "PPCISD::PADDI_DTPREL"; 1583 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1584 case PPCISD::SC: return "PPCISD::SC"; 1585 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1586 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1587 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1588 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1589 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1590 case PPCISD::VABSD: return "PPCISD::VABSD"; 1591 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1592 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1593 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1594 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1595 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1596 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1597 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1598 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1599 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1600 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1601 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1602 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1603 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1604 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1605 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1606 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1607 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1608 case PPCISD::STRICT_FADDRTZ: 1609 return "PPCISD::STRICT_FADDRTZ"; 1610 case PPCISD::STRICT_FCTIDZ: 1611 return "PPCISD::STRICT_FCTIDZ"; 1612 case PPCISD::STRICT_FCTIWZ: 1613 return "PPCISD::STRICT_FCTIWZ"; 1614 case PPCISD::STRICT_FCTIDUZ: 1615 return "PPCISD::STRICT_FCTIDUZ"; 1616 case PPCISD::STRICT_FCTIWUZ: 1617 return "PPCISD::STRICT_FCTIWUZ"; 1618 case PPCISD::STRICT_FCFID: 1619 return "PPCISD::STRICT_FCFID"; 1620 case PPCISD::STRICT_FCFIDU: 1621 return "PPCISD::STRICT_FCFIDU"; 1622 case PPCISD::STRICT_FCFIDS: 1623 return "PPCISD::STRICT_FCFIDS"; 1624 case PPCISD::STRICT_FCFIDUS: 1625 return "PPCISD::STRICT_FCFIDUS"; 1626 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1627 } 1628 return nullptr; 1629 } 1630 1631 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1632 EVT VT) const { 1633 if (!VT.isVector()) 1634 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1635 1636 return VT.changeVectorElementTypeToInteger(); 1637 } 1638 1639 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1640 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1641 return true; 1642 } 1643 1644 //===----------------------------------------------------------------------===// 1645 // Node matching predicates, for use by the tblgen matching code. 1646 //===----------------------------------------------------------------------===// 1647 1648 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1649 static bool isFloatingPointZero(SDValue Op) { 1650 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1651 return CFP->getValueAPF().isZero(); 1652 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1653 // Maybe this has already been legalized into the constant pool? 1654 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1655 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1656 return CFP->getValueAPF().isZero(); 1657 } 1658 return false; 1659 } 1660 1661 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1662 /// true if Op is undef or if it matches the specified value. 1663 static bool isConstantOrUndef(int Op, int Val) { 1664 return Op < 0 || Op == Val; 1665 } 1666 1667 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1668 /// VPKUHUM instruction. 1669 /// The ShuffleKind distinguishes between big-endian operations with 1670 /// two different inputs (0), either-endian operations with two identical 1671 /// inputs (1), and little-endian operations with two different inputs (2). 1672 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1673 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1674 SelectionDAG &DAG) { 1675 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1676 if (ShuffleKind == 0) { 1677 if (IsLE) 1678 return false; 1679 for (unsigned i = 0; i != 16; ++i) 1680 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1681 return false; 1682 } else if (ShuffleKind == 2) { 1683 if (!IsLE) 1684 return false; 1685 for (unsigned i = 0; i != 16; ++i) 1686 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1687 return false; 1688 } else if (ShuffleKind == 1) { 1689 unsigned j = IsLE ? 0 : 1; 1690 for (unsigned i = 0; i != 8; ++i) 1691 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1692 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1693 return false; 1694 } 1695 return true; 1696 } 1697 1698 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1699 /// VPKUWUM instruction. 1700 /// The ShuffleKind distinguishes between big-endian operations with 1701 /// two different inputs (0), either-endian operations with two identical 1702 /// inputs (1), and little-endian operations with two different inputs (2). 1703 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1704 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1705 SelectionDAG &DAG) { 1706 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1707 if (ShuffleKind == 0) { 1708 if (IsLE) 1709 return false; 1710 for (unsigned i = 0; i != 16; i += 2) 1711 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1712 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1713 return false; 1714 } else if (ShuffleKind == 2) { 1715 if (!IsLE) 1716 return false; 1717 for (unsigned i = 0; i != 16; i += 2) 1718 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1719 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1720 return false; 1721 } else if (ShuffleKind == 1) { 1722 unsigned j = IsLE ? 0 : 2; 1723 for (unsigned i = 0; i != 8; i += 2) 1724 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1725 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1726 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1727 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1728 return false; 1729 } 1730 return true; 1731 } 1732 1733 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1734 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1735 /// current subtarget. 1736 /// 1737 /// The ShuffleKind distinguishes between big-endian operations with 1738 /// two different inputs (0), either-endian operations with two identical 1739 /// inputs (1), and little-endian operations with two different inputs (2). 1740 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1741 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1742 SelectionDAG &DAG) { 1743 const PPCSubtarget& Subtarget = 1744 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1745 if (!Subtarget.hasP8Vector()) 1746 return false; 1747 1748 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1749 if (ShuffleKind == 0) { 1750 if (IsLE) 1751 return false; 1752 for (unsigned i = 0; i != 16; i += 4) 1753 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1754 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1755 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1756 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1757 return false; 1758 } else if (ShuffleKind == 2) { 1759 if (!IsLE) 1760 return false; 1761 for (unsigned i = 0; i != 16; i += 4) 1762 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1763 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1764 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1765 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1766 return false; 1767 } else if (ShuffleKind == 1) { 1768 unsigned j = IsLE ? 0 : 4; 1769 for (unsigned i = 0; i != 8; i += 4) 1770 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1771 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1772 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1773 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1774 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1775 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1776 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1777 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1778 return false; 1779 } 1780 return true; 1781 } 1782 1783 /// isVMerge - Common function, used to match vmrg* shuffles. 1784 /// 1785 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1786 unsigned LHSStart, unsigned RHSStart) { 1787 if (N->getValueType(0) != MVT::v16i8) 1788 return false; 1789 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1790 "Unsupported merge size!"); 1791 1792 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1793 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1794 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1795 LHSStart+j+i*UnitSize) || 1796 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1797 RHSStart+j+i*UnitSize)) 1798 return false; 1799 } 1800 return true; 1801 } 1802 1803 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1804 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1805 /// The ShuffleKind distinguishes between big-endian merges with two 1806 /// different inputs (0), either-endian merges with two identical inputs (1), 1807 /// and little-endian merges with two different inputs (2). For the latter, 1808 /// the input operands are swapped (see PPCInstrAltivec.td). 1809 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1810 unsigned ShuffleKind, SelectionDAG &DAG) { 1811 if (DAG.getDataLayout().isLittleEndian()) { 1812 if (ShuffleKind == 1) // unary 1813 return isVMerge(N, UnitSize, 0, 0); 1814 else if (ShuffleKind == 2) // swapped 1815 return isVMerge(N, UnitSize, 0, 16); 1816 else 1817 return false; 1818 } else { 1819 if (ShuffleKind == 1) // unary 1820 return isVMerge(N, UnitSize, 8, 8); 1821 else if (ShuffleKind == 0) // normal 1822 return isVMerge(N, UnitSize, 8, 24); 1823 else 1824 return false; 1825 } 1826 } 1827 1828 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1829 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1830 /// The ShuffleKind distinguishes between big-endian merges with two 1831 /// different inputs (0), either-endian merges with two identical inputs (1), 1832 /// and little-endian merges with two different inputs (2). For the latter, 1833 /// the input operands are swapped (see PPCInstrAltivec.td). 1834 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1835 unsigned ShuffleKind, SelectionDAG &DAG) { 1836 if (DAG.getDataLayout().isLittleEndian()) { 1837 if (ShuffleKind == 1) // unary 1838 return isVMerge(N, UnitSize, 8, 8); 1839 else if (ShuffleKind == 2) // swapped 1840 return isVMerge(N, UnitSize, 8, 24); 1841 else 1842 return false; 1843 } else { 1844 if (ShuffleKind == 1) // unary 1845 return isVMerge(N, UnitSize, 0, 0); 1846 else if (ShuffleKind == 0) // normal 1847 return isVMerge(N, UnitSize, 0, 16); 1848 else 1849 return false; 1850 } 1851 } 1852 1853 /** 1854 * Common function used to match vmrgew and vmrgow shuffles 1855 * 1856 * The indexOffset determines whether to look for even or odd words in 1857 * the shuffle mask. This is based on the of the endianness of the target 1858 * machine. 1859 * - Little Endian: 1860 * - Use offset of 0 to check for odd elements 1861 * - Use offset of 4 to check for even elements 1862 * - Big Endian: 1863 * - Use offset of 0 to check for even elements 1864 * - Use offset of 4 to check for odd elements 1865 * A detailed description of the vector element ordering for little endian and 1866 * big endian can be found at 1867 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1868 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1869 * compiler differences mean to you 1870 * 1871 * The mask to the shuffle vector instruction specifies the indices of the 1872 * elements from the two input vectors to place in the result. The elements are 1873 * numbered in array-access order, starting with the first vector. These vectors 1874 * are always of type v16i8, thus each vector will contain 16 elements of size 1875 * 8. More info on the shuffle vector can be found in the 1876 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1877 * Language Reference. 1878 * 1879 * The RHSStartValue indicates whether the same input vectors are used (unary) 1880 * or two different input vectors are used, based on the following: 1881 * - If the instruction uses the same vector for both inputs, the range of the 1882 * indices will be 0 to 15. In this case, the RHSStart value passed should 1883 * be 0. 1884 * - If the instruction has two different vectors then the range of the 1885 * indices will be 0 to 31. In this case, the RHSStart value passed should 1886 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1887 * to 31 specify elements in the second vector). 1888 * 1889 * \param[in] N The shuffle vector SD Node to analyze 1890 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1891 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1892 * vector to the shuffle_vector instruction 1893 * \return true iff this shuffle vector represents an even or odd word merge 1894 */ 1895 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1896 unsigned RHSStartValue) { 1897 if (N->getValueType(0) != MVT::v16i8) 1898 return false; 1899 1900 for (unsigned i = 0; i < 2; ++i) 1901 for (unsigned j = 0; j < 4; ++j) 1902 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1903 i*RHSStartValue+j+IndexOffset) || 1904 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1905 i*RHSStartValue+j+IndexOffset+8)) 1906 return false; 1907 return true; 1908 } 1909 1910 /** 1911 * Determine if the specified shuffle mask is suitable for the vmrgew or 1912 * vmrgow instructions. 1913 * 1914 * \param[in] N The shuffle vector SD Node to analyze 1915 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1916 * \param[in] ShuffleKind Identify the type of merge: 1917 * - 0 = big-endian merge with two different inputs; 1918 * - 1 = either-endian merge with two identical inputs; 1919 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1920 * little-endian merges). 1921 * \param[in] DAG The current SelectionDAG 1922 * \return true iff this shuffle mask 1923 */ 1924 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1925 unsigned ShuffleKind, SelectionDAG &DAG) { 1926 if (DAG.getDataLayout().isLittleEndian()) { 1927 unsigned indexOffset = CheckEven ? 4 : 0; 1928 if (ShuffleKind == 1) // Unary 1929 return isVMerge(N, indexOffset, 0); 1930 else if (ShuffleKind == 2) // swapped 1931 return isVMerge(N, indexOffset, 16); 1932 else 1933 return false; 1934 } 1935 else { 1936 unsigned indexOffset = CheckEven ? 0 : 4; 1937 if (ShuffleKind == 1) // Unary 1938 return isVMerge(N, indexOffset, 0); 1939 else if (ShuffleKind == 0) // Normal 1940 return isVMerge(N, indexOffset, 16); 1941 else 1942 return false; 1943 } 1944 return false; 1945 } 1946 1947 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1948 /// amount, otherwise return -1. 1949 /// The ShuffleKind distinguishes between big-endian operations with two 1950 /// different inputs (0), either-endian operations with two identical inputs 1951 /// (1), and little-endian operations with two different inputs (2). For the 1952 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1953 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1954 SelectionDAG &DAG) { 1955 if (N->getValueType(0) != MVT::v16i8) 1956 return -1; 1957 1958 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1959 1960 // Find the first non-undef value in the shuffle mask. 1961 unsigned i; 1962 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1963 /*search*/; 1964 1965 if (i == 16) return -1; // all undef. 1966 1967 // Otherwise, check to see if the rest of the elements are consecutively 1968 // numbered from this value. 1969 unsigned ShiftAmt = SVOp->getMaskElt(i); 1970 if (ShiftAmt < i) return -1; 1971 1972 ShiftAmt -= i; 1973 bool isLE = DAG.getDataLayout().isLittleEndian(); 1974 1975 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1976 // Check the rest of the elements to see if they are consecutive. 1977 for (++i; i != 16; ++i) 1978 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1979 return -1; 1980 } else if (ShuffleKind == 1) { 1981 // Check the rest of the elements to see if they are consecutive. 1982 for (++i; i != 16; ++i) 1983 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1984 return -1; 1985 } else 1986 return -1; 1987 1988 if (isLE) 1989 ShiftAmt = 16 - ShiftAmt; 1990 1991 return ShiftAmt; 1992 } 1993 1994 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1995 /// specifies a splat of a single element that is suitable for input to 1996 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1997 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1998 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1999 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2000 2001 // The consecutive indices need to specify an element, not part of two 2002 // different elements. So abandon ship early if this isn't the case. 2003 if (N->getMaskElt(0) % EltSize != 0) 2004 return false; 2005 2006 // This is a splat operation if each element of the permute is the same, and 2007 // if the value doesn't reference the second vector. 2008 unsigned ElementBase = N->getMaskElt(0); 2009 2010 // FIXME: Handle UNDEF elements too! 2011 if (ElementBase >= 16) 2012 return false; 2013 2014 // Check that the indices are consecutive, in the case of a multi-byte element 2015 // splatted with a v16i8 mask. 2016 for (unsigned i = 1; i != EltSize; ++i) 2017 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2018 return false; 2019 2020 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2021 if (N->getMaskElt(i) < 0) continue; 2022 for (unsigned j = 0; j != EltSize; ++j) 2023 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2024 return false; 2025 } 2026 return true; 2027 } 2028 2029 /// Check that the mask is shuffling N byte elements. Within each N byte 2030 /// element of the mask, the indices could be either in increasing or 2031 /// decreasing order as long as they are consecutive. 2032 /// \param[in] N the shuffle vector SD Node to analyze 2033 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2034 /// Word/DoubleWord/QuadWord). 2035 /// \param[in] StepLen the delta indices number among the N byte element, if 2036 /// the mask is in increasing/decreasing order then it is 1/-1. 2037 /// \return true iff the mask is shuffling N byte elements. 2038 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2039 int StepLen) { 2040 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2041 "Unexpected element width."); 2042 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2043 2044 unsigned NumOfElem = 16 / Width; 2045 unsigned MaskVal[16]; // Width is never greater than 16 2046 for (unsigned i = 0; i < NumOfElem; ++i) { 2047 MaskVal[0] = N->getMaskElt(i * Width); 2048 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2049 return false; 2050 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2051 return false; 2052 } 2053 2054 for (unsigned int j = 1; j < Width; ++j) { 2055 MaskVal[j] = N->getMaskElt(i * Width + j); 2056 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2057 return false; 2058 } 2059 } 2060 } 2061 2062 return true; 2063 } 2064 2065 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2066 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2067 if (!isNByteElemShuffleMask(N, 4, 1)) 2068 return false; 2069 2070 // Now we look at mask elements 0,4,8,12 2071 unsigned M0 = N->getMaskElt(0) / 4; 2072 unsigned M1 = N->getMaskElt(4) / 4; 2073 unsigned M2 = N->getMaskElt(8) / 4; 2074 unsigned M3 = N->getMaskElt(12) / 4; 2075 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2076 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2077 2078 // Below, let H and L be arbitrary elements of the shuffle mask 2079 // where H is in the range [4,7] and L is in the range [0,3]. 2080 // H, 1, 2, 3 or L, 5, 6, 7 2081 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2082 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2083 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2084 InsertAtByte = IsLE ? 12 : 0; 2085 Swap = M0 < 4; 2086 return true; 2087 } 2088 // 0, H, 2, 3 or 4, L, 6, 7 2089 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2090 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2091 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2092 InsertAtByte = IsLE ? 8 : 4; 2093 Swap = M1 < 4; 2094 return true; 2095 } 2096 // 0, 1, H, 3 or 4, 5, L, 7 2097 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2098 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2099 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2100 InsertAtByte = IsLE ? 4 : 8; 2101 Swap = M2 < 4; 2102 return true; 2103 } 2104 // 0, 1, 2, H or 4, 5, 6, L 2105 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2106 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2107 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2108 InsertAtByte = IsLE ? 0 : 12; 2109 Swap = M3 < 4; 2110 return true; 2111 } 2112 2113 // If both vector operands for the shuffle are the same vector, the mask will 2114 // contain only elements from the first one and the second one will be undef. 2115 if (N->getOperand(1).isUndef()) { 2116 ShiftElts = 0; 2117 Swap = true; 2118 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2119 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2120 InsertAtByte = IsLE ? 12 : 0; 2121 return true; 2122 } 2123 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2124 InsertAtByte = IsLE ? 8 : 4; 2125 return true; 2126 } 2127 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2128 InsertAtByte = IsLE ? 4 : 8; 2129 return true; 2130 } 2131 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2132 InsertAtByte = IsLE ? 0 : 12; 2133 return true; 2134 } 2135 } 2136 2137 return false; 2138 } 2139 2140 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2141 bool &Swap, bool IsLE) { 2142 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2143 // Ensure each byte index of the word is consecutive. 2144 if (!isNByteElemShuffleMask(N, 4, 1)) 2145 return false; 2146 2147 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2148 unsigned M0 = N->getMaskElt(0) / 4; 2149 unsigned M1 = N->getMaskElt(4) / 4; 2150 unsigned M2 = N->getMaskElt(8) / 4; 2151 unsigned M3 = N->getMaskElt(12) / 4; 2152 2153 // If both vector operands for the shuffle are the same vector, the mask will 2154 // contain only elements from the first one and the second one will be undef. 2155 if (N->getOperand(1).isUndef()) { 2156 assert(M0 < 4 && "Indexing into an undef vector?"); 2157 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2158 return false; 2159 2160 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2161 Swap = false; 2162 return true; 2163 } 2164 2165 // Ensure each word index of the ShuffleVector Mask is consecutive. 2166 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2167 return false; 2168 2169 if (IsLE) { 2170 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2171 // Input vectors don't need to be swapped if the leading element 2172 // of the result is one of the 3 left elements of the second vector 2173 // (or if there is no shift to be done at all). 2174 Swap = false; 2175 ShiftElts = (8 - M0) % 8; 2176 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2177 // Input vectors need to be swapped if the leading element 2178 // of the result is one of the 3 left elements of the first vector 2179 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2180 Swap = true; 2181 ShiftElts = (4 - M0) % 4; 2182 } 2183 2184 return true; 2185 } else { // BE 2186 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2187 // Input vectors don't need to be swapped if the leading element 2188 // of the result is one of the 4 elements of the first vector. 2189 Swap = false; 2190 ShiftElts = M0; 2191 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2192 // Input vectors need to be swapped if the leading element 2193 // of the result is one of the 4 elements of the right vector. 2194 Swap = true; 2195 ShiftElts = M0 - 4; 2196 } 2197 2198 return true; 2199 } 2200 } 2201 2202 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2203 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2204 2205 if (!isNByteElemShuffleMask(N, Width, -1)) 2206 return false; 2207 2208 for (int i = 0; i < 16; i += Width) 2209 if (N->getMaskElt(i) != i + Width - 1) 2210 return false; 2211 2212 return true; 2213 } 2214 2215 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2216 return isXXBRShuffleMaskHelper(N, 2); 2217 } 2218 2219 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2220 return isXXBRShuffleMaskHelper(N, 4); 2221 } 2222 2223 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2224 return isXXBRShuffleMaskHelper(N, 8); 2225 } 2226 2227 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2228 return isXXBRShuffleMaskHelper(N, 16); 2229 } 2230 2231 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2232 /// if the inputs to the instruction should be swapped and set \p DM to the 2233 /// value for the immediate. 2234 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2235 /// AND element 0 of the result comes from the first input (LE) or second input 2236 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2237 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2238 /// mask. 2239 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2240 bool &Swap, bool IsLE) { 2241 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2242 2243 // Ensure each byte index of the double word is consecutive. 2244 if (!isNByteElemShuffleMask(N, 8, 1)) 2245 return false; 2246 2247 unsigned M0 = N->getMaskElt(0) / 8; 2248 unsigned M1 = N->getMaskElt(8) / 8; 2249 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2250 2251 // If both vector operands for the shuffle are the same vector, the mask will 2252 // contain only elements from the first one and the second one will be undef. 2253 if (N->getOperand(1).isUndef()) { 2254 if ((M0 | M1) < 2) { 2255 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2256 Swap = false; 2257 return true; 2258 } else 2259 return false; 2260 } 2261 2262 if (IsLE) { 2263 if (M0 > 1 && M1 < 2) { 2264 Swap = false; 2265 } else if (M0 < 2 && M1 > 1) { 2266 M0 = (M0 + 2) % 4; 2267 M1 = (M1 + 2) % 4; 2268 Swap = true; 2269 } else 2270 return false; 2271 2272 // Note: if control flow comes here that means Swap is already set above 2273 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2274 return true; 2275 } else { // BE 2276 if (M0 < 2 && M1 > 1) { 2277 Swap = false; 2278 } else if (M0 > 1 && M1 < 2) { 2279 M0 = (M0 + 2) % 4; 2280 M1 = (M1 + 2) % 4; 2281 Swap = true; 2282 } else 2283 return false; 2284 2285 // Note: if control flow comes here that means Swap is already set above 2286 DM = (M0 << 1) + (M1 & 1); 2287 return true; 2288 } 2289 } 2290 2291 2292 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2293 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2294 /// elements are counted from the left of the vector register). 2295 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2296 SelectionDAG &DAG) { 2297 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2298 assert(isSplatShuffleMask(SVOp, EltSize)); 2299 if (DAG.getDataLayout().isLittleEndian()) 2300 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2301 else 2302 return SVOp->getMaskElt(0) / EltSize; 2303 } 2304 2305 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2306 /// by using a vspltis[bhw] instruction of the specified element size, return 2307 /// the constant being splatted. The ByteSize field indicates the number of 2308 /// bytes of each element [124] -> [bhw]. 2309 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2310 SDValue OpVal(nullptr, 0); 2311 2312 // If ByteSize of the splat is bigger than the element size of the 2313 // build_vector, then we have a case where we are checking for a splat where 2314 // multiple elements of the buildvector are folded together into a single 2315 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2316 unsigned EltSize = 16/N->getNumOperands(); 2317 if (EltSize < ByteSize) { 2318 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2319 SDValue UniquedVals[4]; 2320 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2321 2322 // See if all of the elements in the buildvector agree across. 2323 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2324 if (N->getOperand(i).isUndef()) continue; 2325 // If the element isn't a constant, bail fully out. 2326 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2327 2328 if (!UniquedVals[i&(Multiple-1)].getNode()) 2329 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2330 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2331 return SDValue(); // no match. 2332 } 2333 2334 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2335 // either constant or undef values that are identical for each chunk. See 2336 // if these chunks can form into a larger vspltis*. 2337 2338 // Check to see if all of the leading entries are either 0 or -1. If 2339 // neither, then this won't fit into the immediate field. 2340 bool LeadingZero = true; 2341 bool LeadingOnes = true; 2342 for (unsigned i = 0; i != Multiple-1; ++i) { 2343 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2344 2345 LeadingZero &= isNullConstant(UniquedVals[i]); 2346 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2347 } 2348 // Finally, check the least significant entry. 2349 if (LeadingZero) { 2350 if (!UniquedVals[Multiple-1].getNode()) 2351 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2352 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2353 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2354 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2355 } 2356 if (LeadingOnes) { 2357 if (!UniquedVals[Multiple-1].getNode()) 2358 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2359 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2360 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2361 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2362 } 2363 2364 return SDValue(); 2365 } 2366 2367 // Check to see if this buildvec has a single non-undef value in its elements. 2368 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2369 if (N->getOperand(i).isUndef()) continue; 2370 if (!OpVal.getNode()) 2371 OpVal = N->getOperand(i); 2372 else if (OpVal != N->getOperand(i)) 2373 return SDValue(); 2374 } 2375 2376 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2377 2378 unsigned ValSizeInBytes = EltSize; 2379 uint64_t Value = 0; 2380 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2381 Value = CN->getZExtValue(); 2382 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2383 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2384 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2385 } 2386 2387 // If the splat value is larger than the element value, then we can never do 2388 // this splat. The only case that we could fit the replicated bits into our 2389 // immediate field for would be zero, and we prefer to use vxor for it. 2390 if (ValSizeInBytes < ByteSize) return SDValue(); 2391 2392 // If the element value is larger than the splat value, check if it consists 2393 // of a repeated bit pattern of size ByteSize. 2394 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2395 return SDValue(); 2396 2397 // Properly sign extend the value. 2398 int MaskVal = SignExtend32(Value, ByteSize * 8); 2399 2400 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2401 if (MaskVal == 0) return SDValue(); 2402 2403 // Finally, if this value fits in a 5 bit sext field, return it 2404 if (SignExtend32<5>(MaskVal) == MaskVal) 2405 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2406 return SDValue(); 2407 } 2408 2409 //===----------------------------------------------------------------------===// 2410 // Addressing Mode Selection 2411 //===----------------------------------------------------------------------===// 2412 2413 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2414 /// or 64-bit immediate, and if the value can be accurately represented as a 2415 /// sign extension from a 16-bit value. If so, this returns true and the 2416 /// immediate. 2417 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2418 if (!isa<ConstantSDNode>(N)) 2419 return false; 2420 2421 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2422 if (N->getValueType(0) == MVT::i32) 2423 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2424 else 2425 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2426 } 2427 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2428 return isIntS16Immediate(Op.getNode(), Imm); 2429 } 2430 2431 2432 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2433 /// be represented as an indexed [r+r] operation. 2434 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2435 SDValue &Index, 2436 SelectionDAG &DAG) const { 2437 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2438 UI != E; ++UI) { 2439 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2440 if (Memop->getMemoryVT() == MVT::f64) { 2441 Base = N.getOperand(0); 2442 Index = N.getOperand(1); 2443 return true; 2444 } 2445 } 2446 } 2447 return false; 2448 } 2449 2450 /// isIntS34Immediate - This method tests if value of node given can be 2451 /// accurately represented as a sign extension from a 34-bit value. If so, 2452 /// this returns true and the immediate. 2453 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2454 if (!isa<ConstantSDNode>(N)) 2455 return false; 2456 2457 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2458 return isInt<34>(Imm); 2459 } 2460 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2461 return isIntS34Immediate(Op.getNode(), Imm); 2462 } 2463 2464 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2465 /// can be represented as an indexed [r+r] operation. Returns false if it 2466 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2467 /// non-zero and N can be represented by a base register plus a signed 16-bit 2468 /// displacement, make a more precise judgement by checking (displacement % \p 2469 /// EncodingAlignment). 2470 bool PPCTargetLowering::SelectAddressRegReg( 2471 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2472 MaybeAlign EncodingAlignment) const { 2473 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2474 // a [pc+imm]. 2475 if (SelectAddressPCRel(N, Base)) 2476 return false; 2477 2478 int16_t Imm = 0; 2479 if (N.getOpcode() == ISD::ADD) { 2480 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2481 // SPE load/store can only handle 8-bit offsets. 2482 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2483 return true; 2484 if (isIntS16Immediate(N.getOperand(1), Imm) && 2485 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2486 return false; // r+i 2487 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2488 return false; // r+i 2489 2490 Base = N.getOperand(0); 2491 Index = N.getOperand(1); 2492 return true; 2493 } else if (N.getOpcode() == ISD::OR) { 2494 if (isIntS16Immediate(N.getOperand(1), Imm) && 2495 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2496 return false; // r+i can fold it if we can. 2497 2498 // If this is an or of disjoint bitfields, we can codegen this as an add 2499 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2500 // disjoint. 2501 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2502 2503 if (LHSKnown.Zero.getBoolValue()) { 2504 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2505 // If all of the bits are known zero on the LHS or RHS, the add won't 2506 // carry. 2507 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2508 Base = N.getOperand(0); 2509 Index = N.getOperand(1); 2510 return true; 2511 } 2512 } 2513 } 2514 2515 return false; 2516 } 2517 2518 // If we happen to be doing an i64 load or store into a stack slot that has 2519 // less than a 4-byte alignment, then the frame-index elimination may need to 2520 // use an indexed load or store instruction (because the offset may not be a 2521 // multiple of 4). The extra register needed to hold the offset comes from the 2522 // register scavenger, and it is possible that the scavenger will need to use 2523 // an emergency spill slot. As a result, we need to make sure that a spill slot 2524 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2525 // stack slot. 2526 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2527 // FIXME: This does not handle the LWA case. 2528 if (VT != MVT::i64) 2529 return; 2530 2531 // NOTE: We'll exclude negative FIs here, which come from argument 2532 // lowering, because there are no known test cases triggering this problem 2533 // using packed structures (or similar). We can remove this exclusion if 2534 // we find such a test case. The reason why this is so test-case driven is 2535 // because this entire 'fixup' is only to prevent crashes (from the 2536 // register scavenger) on not-really-valid inputs. For example, if we have: 2537 // %a = alloca i1 2538 // %b = bitcast i1* %a to i64* 2539 // store i64* a, i64 b 2540 // then the store should really be marked as 'align 1', but is not. If it 2541 // were marked as 'align 1' then the indexed form would have been 2542 // instruction-selected initially, and the problem this 'fixup' is preventing 2543 // won't happen regardless. 2544 if (FrameIdx < 0) 2545 return; 2546 2547 MachineFunction &MF = DAG.getMachineFunction(); 2548 MachineFrameInfo &MFI = MF.getFrameInfo(); 2549 2550 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2551 return; 2552 2553 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2554 FuncInfo->setHasNonRISpills(); 2555 } 2556 2557 /// Returns true if the address N can be represented by a base register plus 2558 /// a signed 16-bit displacement [r+imm], and if it is not better 2559 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2560 /// displacements that are multiples of that value. 2561 bool PPCTargetLowering::SelectAddressRegImm( 2562 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2563 MaybeAlign EncodingAlignment) const { 2564 // FIXME dl should come from parent load or store, not from address 2565 SDLoc dl(N); 2566 2567 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2568 // a [pc+imm]. 2569 if (SelectAddressPCRel(N, Base)) 2570 return false; 2571 2572 // If this can be more profitably realized as r+r, fail. 2573 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2574 return false; 2575 2576 if (N.getOpcode() == ISD::ADD) { 2577 int16_t imm = 0; 2578 if (isIntS16Immediate(N.getOperand(1), imm) && 2579 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2580 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2581 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2582 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2583 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2584 } else { 2585 Base = N.getOperand(0); 2586 } 2587 return true; // [r+i] 2588 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2589 // Match LOAD (ADD (X, Lo(G))). 2590 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2591 && "Cannot handle constant offsets yet!"); 2592 Disp = N.getOperand(1).getOperand(0); // The global address. 2593 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2594 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2595 Disp.getOpcode() == ISD::TargetConstantPool || 2596 Disp.getOpcode() == ISD::TargetJumpTable); 2597 Base = N.getOperand(0); 2598 return true; // [&g+r] 2599 } 2600 } else if (N.getOpcode() == ISD::OR) { 2601 int16_t imm = 0; 2602 if (isIntS16Immediate(N.getOperand(1), imm) && 2603 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2604 // If this is an or of disjoint bitfields, we can codegen this as an add 2605 // (for better address arithmetic) if the LHS and RHS of the OR are 2606 // provably disjoint. 2607 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2608 2609 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2610 // If all of the bits are known zero on the LHS or RHS, the add won't 2611 // carry. 2612 if (FrameIndexSDNode *FI = 2613 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2614 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2615 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2616 } else { 2617 Base = N.getOperand(0); 2618 } 2619 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2620 return true; 2621 } 2622 } 2623 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2624 // Loading from a constant address. 2625 2626 // If this address fits entirely in a 16-bit sext immediate field, codegen 2627 // this as "d, 0" 2628 int16_t Imm; 2629 if (isIntS16Immediate(CN, Imm) && 2630 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2631 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2632 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2633 CN->getValueType(0)); 2634 return true; 2635 } 2636 2637 // Handle 32-bit sext immediates with LIS + addr mode. 2638 if ((CN->getValueType(0) == MVT::i32 || 2639 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2640 (!EncodingAlignment || 2641 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2642 int Addr = (int)CN->getZExtValue(); 2643 2644 // Otherwise, break this down into an LIS + disp. 2645 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2646 2647 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2648 MVT::i32); 2649 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2650 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2651 return true; 2652 } 2653 } 2654 2655 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2656 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2657 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2658 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2659 } else 2660 Base = N; 2661 return true; // [r+0] 2662 } 2663 2664 /// Similar to the 16-bit case but for instructions that take a 34-bit 2665 /// displacement field (prefixed loads/stores). 2666 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2667 SDValue &Base, 2668 SelectionDAG &DAG) const { 2669 // Only on 64-bit targets. 2670 if (N.getValueType() != MVT::i64) 2671 return false; 2672 2673 SDLoc dl(N); 2674 int64_t Imm = 0; 2675 2676 if (N.getOpcode() == ISD::ADD) { 2677 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2678 return false; 2679 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2680 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2681 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2682 else 2683 Base = N.getOperand(0); 2684 return true; 2685 } 2686 2687 if (N.getOpcode() == ISD::OR) { 2688 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2689 return false; 2690 // If this is an or of disjoint bitfields, we can codegen this as an add 2691 // (for better address arithmetic) if the LHS and RHS of the OR are 2692 // provably disjoint. 2693 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2694 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2695 return false; 2696 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2697 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2698 else 2699 Base = N.getOperand(0); 2700 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2701 return true; 2702 } 2703 2704 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2705 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2706 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2707 return true; 2708 } 2709 2710 return false; 2711 } 2712 2713 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2714 /// represented as an indexed [r+r] operation. 2715 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2716 SDValue &Index, 2717 SelectionDAG &DAG) const { 2718 // Check to see if we can easily represent this as an [r+r] address. This 2719 // will fail if it thinks that the address is more profitably represented as 2720 // reg+imm, e.g. where imm = 0. 2721 if (SelectAddressRegReg(N, Base, Index, DAG)) 2722 return true; 2723 2724 // If the address is the result of an add, we will utilize the fact that the 2725 // address calculation includes an implicit add. However, we can reduce 2726 // register pressure if we do not materialize a constant just for use as the 2727 // index register. We only get rid of the add if it is not an add of a 2728 // value and a 16-bit signed constant and both have a single use. 2729 int16_t imm = 0; 2730 if (N.getOpcode() == ISD::ADD && 2731 (!isIntS16Immediate(N.getOperand(1), imm) || 2732 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2733 Base = N.getOperand(0); 2734 Index = N.getOperand(1); 2735 return true; 2736 } 2737 2738 // Otherwise, do it the hard way, using R0 as the base register. 2739 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2740 N.getValueType()); 2741 Index = N; 2742 return true; 2743 } 2744 2745 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2746 Ty *PCRelCand = dyn_cast<Ty>(N); 2747 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2748 } 2749 2750 /// Returns true if this address is a PC Relative address. 2751 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2752 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2753 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2754 // This is a materialize PC Relative node. Always select this as PC Relative. 2755 Base = N; 2756 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2757 return true; 2758 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2759 isValidPCRelNode<GlobalAddressSDNode>(N) || 2760 isValidPCRelNode<JumpTableSDNode>(N) || 2761 isValidPCRelNode<BlockAddressSDNode>(N)) 2762 return true; 2763 return false; 2764 } 2765 2766 /// Returns true if we should use a direct load into vector instruction 2767 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2768 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2769 2770 // If there are any other uses other than scalar to vector, then we should 2771 // keep it as a scalar load -> direct move pattern to prevent multiple 2772 // loads. 2773 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2774 if (!LD) 2775 return false; 2776 2777 EVT MemVT = LD->getMemoryVT(); 2778 if (!MemVT.isSimple()) 2779 return false; 2780 switch(MemVT.getSimpleVT().SimpleTy) { 2781 case MVT::i64: 2782 break; 2783 case MVT::i32: 2784 if (!ST.hasP8Vector()) 2785 return false; 2786 break; 2787 case MVT::i16: 2788 case MVT::i8: 2789 if (!ST.hasP9Vector()) 2790 return false; 2791 break; 2792 default: 2793 return false; 2794 } 2795 2796 SDValue LoadedVal(N, 0); 2797 if (!LoadedVal.hasOneUse()) 2798 return false; 2799 2800 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2801 UI != UE; ++UI) 2802 if (UI.getUse().get().getResNo() == 0 && 2803 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2804 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2805 return false; 2806 2807 return true; 2808 } 2809 2810 /// getPreIndexedAddressParts - returns true by value, base pointer and 2811 /// offset pointer and addressing mode by reference if the node's address 2812 /// can be legally represented as pre-indexed load / store address. 2813 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2814 SDValue &Offset, 2815 ISD::MemIndexedMode &AM, 2816 SelectionDAG &DAG) const { 2817 if (DisablePPCPreinc) return false; 2818 2819 bool isLoad = true; 2820 SDValue Ptr; 2821 EVT VT; 2822 unsigned Alignment; 2823 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2824 Ptr = LD->getBasePtr(); 2825 VT = LD->getMemoryVT(); 2826 Alignment = LD->getAlignment(); 2827 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2828 Ptr = ST->getBasePtr(); 2829 VT = ST->getMemoryVT(); 2830 Alignment = ST->getAlignment(); 2831 isLoad = false; 2832 } else 2833 return false; 2834 2835 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2836 // instructions because we can fold these into a more efficient instruction 2837 // instead, (such as LXSD). 2838 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2839 return false; 2840 } 2841 2842 // PowerPC doesn't have preinc load/store instructions for vectors 2843 if (VT.isVector()) 2844 return false; 2845 2846 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2847 // Common code will reject creating a pre-inc form if the base pointer 2848 // is a frame index, or if N is a store and the base pointer is either 2849 // the same as or a predecessor of the value being stored. Check for 2850 // those situations here, and try with swapped Base/Offset instead. 2851 bool Swap = false; 2852 2853 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2854 Swap = true; 2855 else if (!isLoad) { 2856 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2857 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2858 Swap = true; 2859 } 2860 2861 if (Swap) 2862 std::swap(Base, Offset); 2863 2864 AM = ISD::PRE_INC; 2865 return true; 2866 } 2867 2868 // LDU/STU can only handle immediates that are a multiple of 4. 2869 if (VT != MVT::i64) { 2870 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2871 return false; 2872 } else { 2873 // LDU/STU need an address with at least 4-byte alignment. 2874 if (Alignment < 4) 2875 return false; 2876 2877 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2878 return false; 2879 } 2880 2881 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2882 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2883 // sext i32 to i64 when addr mode is r+i. 2884 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2885 LD->getExtensionType() == ISD::SEXTLOAD && 2886 isa<ConstantSDNode>(Offset)) 2887 return false; 2888 } 2889 2890 AM = ISD::PRE_INC; 2891 return true; 2892 } 2893 2894 //===----------------------------------------------------------------------===// 2895 // LowerOperation implementation 2896 //===----------------------------------------------------------------------===// 2897 2898 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2899 /// and LoOpFlags to the target MO flags. 2900 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2901 unsigned &HiOpFlags, unsigned &LoOpFlags, 2902 const GlobalValue *GV = nullptr) { 2903 HiOpFlags = PPCII::MO_HA; 2904 LoOpFlags = PPCII::MO_LO; 2905 2906 // Don't use the pic base if not in PIC relocation model. 2907 if (IsPIC) { 2908 HiOpFlags |= PPCII::MO_PIC_FLAG; 2909 LoOpFlags |= PPCII::MO_PIC_FLAG; 2910 } 2911 } 2912 2913 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2914 SelectionDAG &DAG) { 2915 SDLoc DL(HiPart); 2916 EVT PtrVT = HiPart.getValueType(); 2917 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2918 2919 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2920 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2921 2922 // With PIC, the first instruction is actually "GR+hi(&G)". 2923 if (isPIC) 2924 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2925 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2926 2927 // Generate non-pic code that has direct accesses to the constant pool. 2928 // The address of the global is just (hi(&g)+lo(&g)). 2929 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2930 } 2931 2932 static void setUsesTOCBasePtr(MachineFunction &MF) { 2933 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2934 FuncInfo->setUsesTOCBasePtr(); 2935 } 2936 2937 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2938 setUsesTOCBasePtr(DAG.getMachineFunction()); 2939 } 2940 2941 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2942 SDValue GA) const { 2943 const bool Is64Bit = Subtarget.isPPC64(); 2944 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2945 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2946 : Subtarget.isAIXABI() 2947 ? DAG.getRegister(PPC::R2, VT) 2948 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2949 SDValue Ops[] = { GA, Reg }; 2950 return DAG.getMemIntrinsicNode( 2951 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2952 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2953 MachineMemOperand::MOLoad); 2954 } 2955 2956 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2957 SelectionDAG &DAG) const { 2958 EVT PtrVT = Op.getValueType(); 2959 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2960 const Constant *C = CP->getConstVal(); 2961 2962 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2963 // The actual address of the GlobalValue is stored in the TOC. 2964 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2965 if (Subtarget.isUsingPCRelativeCalls()) { 2966 SDLoc DL(CP); 2967 EVT Ty = getPointerTy(DAG.getDataLayout()); 2968 SDValue ConstPool = DAG.getTargetConstantPool( 2969 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2970 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2971 } 2972 setUsesTOCBasePtr(DAG); 2973 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2974 return getTOCEntry(DAG, SDLoc(CP), GA); 2975 } 2976 2977 unsigned MOHiFlag, MOLoFlag; 2978 bool IsPIC = isPositionIndependent(); 2979 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2980 2981 if (IsPIC && Subtarget.isSVR4ABI()) { 2982 SDValue GA = 2983 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2984 return getTOCEntry(DAG, SDLoc(CP), GA); 2985 } 2986 2987 SDValue CPIHi = 2988 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2989 SDValue CPILo = 2990 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2991 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2992 } 2993 2994 // For 64-bit PowerPC, prefer the more compact relative encodings. 2995 // This trades 32 bits per jump table entry for one or two instructions 2996 // on the jump site. 2997 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2998 if (isJumpTableRelative()) 2999 return MachineJumpTableInfo::EK_LabelDifference32; 3000 3001 return TargetLowering::getJumpTableEncoding(); 3002 } 3003 3004 bool PPCTargetLowering::isJumpTableRelative() const { 3005 if (UseAbsoluteJumpTables) 3006 return false; 3007 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3008 return true; 3009 return TargetLowering::isJumpTableRelative(); 3010 } 3011 3012 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3013 SelectionDAG &DAG) const { 3014 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3015 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3016 3017 switch (getTargetMachine().getCodeModel()) { 3018 case CodeModel::Small: 3019 case CodeModel::Medium: 3020 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3021 default: 3022 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3023 getPointerTy(DAG.getDataLayout())); 3024 } 3025 } 3026 3027 const MCExpr * 3028 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3029 unsigned JTI, 3030 MCContext &Ctx) const { 3031 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3032 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3033 3034 switch (getTargetMachine().getCodeModel()) { 3035 case CodeModel::Small: 3036 case CodeModel::Medium: 3037 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3038 default: 3039 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3040 } 3041 } 3042 3043 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3044 EVT PtrVT = Op.getValueType(); 3045 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3046 3047 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3048 if (Subtarget.isUsingPCRelativeCalls()) { 3049 SDLoc DL(JT); 3050 EVT Ty = getPointerTy(DAG.getDataLayout()); 3051 SDValue GA = 3052 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3053 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3054 return MatAddr; 3055 } 3056 3057 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3058 // The actual address of the GlobalValue is stored in the TOC. 3059 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3060 setUsesTOCBasePtr(DAG); 3061 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3062 return getTOCEntry(DAG, SDLoc(JT), GA); 3063 } 3064 3065 unsigned MOHiFlag, MOLoFlag; 3066 bool IsPIC = isPositionIndependent(); 3067 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3068 3069 if (IsPIC && Subtarget.isSVR4ABI()) { 3070 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3071 PPCII::MO_PIC_FLAG); 3072 return getTOCEntry(DAG, SDLoc(GA), GA); 3073 } 3074 3075 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3076 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3077 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3078 } 3079 3080 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3081 SelectionDAG &DAG) const { 3082 EVT PtrVT = Op.getValueType(); 3083 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3084 const BlockAddress *BA = BASDN->getBlockAddress(); 3085 3086 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3087 if (Subtarget.isUsingPCRelativeCalls()) { 3088 SDLoc DL(BASDN); 3089 EVT Ty = getPointerTy(DAG.getDataLayout()); 3090 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3091 PPCII::MO_PCREL_FLAG); 3092 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3093 return MatAddr; 3094 } 3095 3096 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3097 // The actual BlockAddress is stored in the TOC. 3098 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3099 setUsesTOCBasePtr(DAG); 3100 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3101 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3102 } 3103 3104 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3105 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3106 return getTOCEntry( 3107 DAG, SDLoc(BASDN), 3108 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3109 3110 unsigned MOHiFlag, MOLoFlag; 3111 bool IsPIC = isPositionIndependent(); 3112 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3113 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3114 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3115 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3116 } 3117 3118 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3119 SelectionDAG &DAG) const { 3120 if (Subtarget.isAIXABI()) 3121 return LowerGlobalTLSAddressAIX(Op, DAG); 3122 3123 return LowerGlobalTLSAddressLinux(Op, DAG); 3124 } 3125 3126 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3127 SelectionDAG &DAG) const { 3128 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3129 3130 if (DAG.getTarget().useEmulatedTLS()) 3131 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3132 3133 SDLoc dl(GA); 3134 const GlobalValue *GV = GA->getGlobal(); 3135 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3136 3137 // The general-dynamic model is the only access model supported for now, so 3138 // all the GlobalTLSAddress nodes are lowered with this model. 3139 // We need to generate two TOC entries, one for the variable offset, one for 3140 // the region handle. The global address for the TOC entry of the region 3141 // handle is created with the MO_TLSGD_FLAG flag so we can easily identify 3142 // this entry and add the right relocation. 3143 SDValue VariableOffsetTGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3144 SDValue RegionHandleTGA = 3145 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3146 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3147 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3148 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3149 RegionHandle); 3150 } 3151 3152 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3153 SelectionDAG &DAG) const { 3154 // FIXME: TLS addresses currently use medium model code sequences, 3155 // which is the most useful form. Eventually support for small and 3156 // large models could be added if users need it, at the cost of 3157 // additional complexity. 3158 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3159 if (DAG.getTarget().useEmulatedTLS()) 3160 return LowerToTLSEmulatedModel(GA, DAG); 3161 3162 SDLoc dl(GA); 3163 const GlobalValue *GV = GA->getGlobal(); 3164 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3165 bool is64bit = Subtarget.isPPC64(); 3166 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3167 PICLevel::Level picLevel = M->getPICLevel(); 3168 3169 const TargetMachine &TM = getTargetMachine(); 3170 TLSModel::Model Model = TM.getTLSModel(GV); 3171 3172 if (Model == TLSModel::LocalExec) { 3173 if (Subtarget.isUsingPCRelativeCalls()) { 3174 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3175 SDValue TGA = DAG.getTargetGlobalAddress( 3176 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3177 SDValue MatAddr = 3178 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3179 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3180 } 3181 3182 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3183 PPCII::MO_TPREL_HA); 3184 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3185 PPCII::MO_TPREL_LO); 3186 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3187 : DAG.getRegister(PPC::R2, MVT::i32); 3188 3189 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3190 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3191 } 3192 3193 if (Model == TLSModel::InitialExec) { 3194 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3195 SDValue TGA = DAG.getTargetGlobalAddress( 3196 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3197 SDValue TGATLS = DAG.getTargetGlobalAddress( 3198 GV, dl, PtrVT, 0, 3199 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3200 SDValue TPOffset; 3201 if (IsPCRel) { 3202 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3203 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3204 MachinePointerInfo()); 3205 } else { 3206 SDValue GOTPtr; 3207 if (is64bit) { 3208 setUsesTOCBasePtr(DAG); 3209 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3210 GOTPtr = 3211 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3212 } else { 3213 if (!TM.isPositionIndependent()) 3214 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3215 else if (picLevel == PICLevel::SmallPIC) 3216 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3217 else 3218 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3219 } 3220 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3221 } 3222 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3223 } 3224 3225 if (Model == TLSModel::GeneralDynamic) { 3226 if (Subtarget.isUsingPCRelativeCalls()) { 3227 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3228 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3229 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3230 } 3231 3232 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3233 SDValue GOTPtr; 3234 if (is64bit) { 3235 setUsesTOCBasePtr(DAG); 3236 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3237 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3238 GOTReg, TGA); 3239 } else { 3240 if (picLevel == PICLevel::SmallPIC) 3241 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3242 else 3243 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3244 } 3245 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3246 GOTPtr, TGA, TGA); 3247 } 3248 3249 if (Model == TLSModel::LocalDynamic) { 3250 if (Subtarget.isUsingPCRelativeCalls()) { 3251 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3252 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3253 SDValue MatPCRel = 3254 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3255 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3256 } 3257 3258 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3259 SDValue GOTPtr; 3260 if (is64bit) { 3261 setUsesTOCBasePtr(DAG); 3262 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3263 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3264 GOTReg, TGA); 3265 } else { 3266 if (picLevel == PICLevel::SmallPIC) 3267 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3268 else 3269 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3270 } 3271 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3272 PtrVT, GOTPtr, TGA, TGA); 3273 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3274 PtrVT, TLSAddr, TGA); 3275 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3276 } 3277 3278 llvm_unreachable("Unknown TLS model!"); 3279 } 3280 3281 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3282 SelectionDAG &DAG) const { 3283 EVT PtrVT = Op.getValueType(); 3284 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3285 SDLoc DL(GSDN); 3286 const GlobalValue *GV = GSDN->getGlobal(); 3287 3288 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3289 // The actual address of the GlobalValue is stored in the TOC. 3290 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3291 if (Subtarget.isUsingPCRelativeCalls()) { 3292 EVT Ty = getPointerTy(DAG.getDataLayout()); 3293 if (isAccessedAsGotIndirect(Op)) { 3294 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3295 PPCII::MO_PCREL_FLAG | 3296 PPCII::MO_GOT_FLAG); 3297 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3298 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3299 MachinePointerInfo()); 3300 return Load; 3301 } else { 3302 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3303 PPCII::MO_PCREL_FLAG); 3304 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3305 } 3306 } 3307 setUsesTOCBasePtr(DAG); 3308 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3309 return getTOCEntry(DAG, DL, GA); 3310 } 3311 3312 unsigned MOHiFlag, MOLoFlag; 3313 bool IsPIC = isPositionIndependent(); 3314 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3315 3316 if (IsPIC && Subtarget.isSVR4ABI()) { 3317 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3318 GSDN->getOffset(), 3319 PPCII::MO_PIC_FLAG); 3320 return getTOCEntry(DAG, DL, GA); 3321 } 3322 3323 SDValue GAHi = 3324 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3325 SDValue GALo = 3326 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3327 3328 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3329 } 3330 3331 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3332 bool IsStrict = Op->isStrictFPOpcode(); 3333 ISD::CondCode CC = 3334 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get(); 3335 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0); 3336 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1); 3337 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 3338 EVT LHSVT = LHS.getValueType(); 3339 SDLoc dl(Op); 3340 3341 // Soften the setcc with libcall if it is fp128. 3342 if (LHSVT == MVT::f128) { 3343 assert(!Subtarget.hasP9Vector() && 3344 "SETCC for f128 is already legal under Power9!"); 3345 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain, 3346 Op->getOpcode() == ISD::STRICT_FSETCCS); 3347 if (RHS.getNode()) 3348 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS, 3349 DAG.getCondCode(CC)); 3350 if (IsStrict) 3351 return DAG.getMergeValues({LHS, Chain}, dl); 3352 return LHS; 3353 } 3354 3355 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!"); 3356 3357 if (Op.getValueType() == MVT::v2i64) { 3358 // When the operands themselves are v2i64 values, we need to do something 3359 // special because VSX has no underlying comparison operations for these. 3360 if (LHS.getValueType() == MVT::v2i64) { 3361 // Equality can be handled by casting to the legal type for Altivec 3362 // comparisons, everything else needs to be expanded. 3363 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3364 return DAG.getNode( 3365 ISD::BITCAST, dl, MVT::v2i64, 3366 DAG.getSetCC(dl, MVT::v4i32, 3367 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS), 3368 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC)); 3369 } 3370 3371 return SDValue(); 3372 } 3373 3374 // We handle most of these in the usual way. 3375 return Op; 3376 } 3377 3378 // If we're comparing for equality to zero, expose the fact that this is 3379 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3380 // fold the new nodes. 3381 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3382 return V; 3383 3384 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 3385 // Leave comparisons against 0 and -1 alone for now, since they're usually 3386 // optimized. FIXME: revisit this when we can custom lower all setcc 3387 // optimizations. 3388 if (C->isAllOnesValue() || C->isNullValue()) 3389 return SDValue(); 3390 } 3391 3392 // If we have an integer seteq/setne, turn it into a compare against zero 3393 // by xor'ing the rhs with the lhs, which is faster than setting a 3394 // condition register, reading it back out, and masking the correct bit. The 3395 // normal approach here uses sub to do this instead of xor. Using xor exposes 3396 // the result to other bit-twiddling opportunities. 3397 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3398 EVT VT = Op.getValueType(); 3399 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS); 3400 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3401 } 3402 return SDValue(); 3403 } 3404 3405 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3406 SDNode *Node = Op.getNode(); 3407 EVT VT = Node->getValueType(0); 3408 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3409 SDValue InChain = Node->getOperand(0); 3410 SDValue VAListPtr = Node->getOperand(1); 3411 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3412 SDLoc dl(Node); 3413 3414 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3415 3416 // gpr_index 3417 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3418 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3419 InChain = GprIndex.getValue(1); 3420 3421 if (VT == MVT::i64) { 3422 // Check if GprIndex is even 3423 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3424 DAG.getConstant(1, dl, MVT::i32)); 3425 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3426 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3427 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3428 DAG.getConstant(1, dl, MVT::i32)); 3429 // Align GprIndex to be even if it isn't 3430 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3431 GprIndex); 3432 } 3433 3434 // fpr index is 1 byte after gpr 3435 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3436 DAG.getConstant(1, dl, MVT::i32)); 3437 3438 // fpr 3439 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3440 FprPtr, MachinePointerInfo(SV), MVT::i8); 3441 InChain = FprIndex.getValue(1); 3442 3443 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3444 DAG.getConstant(8, dl, MVT::i32)); 3445 3446 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3447 DAG.getConstant(4, dl, MVT::i32)); 3448 3449 // areas 3450 SDValue OverflowArea = 3451 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3452 InChain = OverflowArea.getValue(1); 3453 3454 SDValue RegSaveArea = 3455 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3456 InChain = RegSaveArea.getValue(1); 3457 3458 // select overflow_area if index > 8 3459 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3460 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3461 3462 // adjustment constant gpr_index * 4/8 3463 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3464 VT.isInteger() ? GprIndex : FprIndex, 3465 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3466 MVT::i32)); 3467 3468 // OurReg = RegSaveArea + RegConstant 3469 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3470 RegConstant); 3471 3472 // Floating types are 32 bytes into RegSaveArea 3473 if (VT.isFloatingPoint()) 3474 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3475 DAG.getConstant(32, dl, MVT::i32)); 3476 3477 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3478 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3479 VT.isInteger() ? GprIndex : FprIndex, 3480 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3481 MVT::i32)); 3482 3483 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3484 VT.isInteger() ? VAListPtr : FprPtr, 3485 MachinePointerInfo(SV), MVT::i8); 3486 3487 // determine if we should load from reg_save_area or overflow_area 3488 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3489 3490 // increase overflow_area by 4/8 if gpr/fpr > 8 3491 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3492 DAG.getConstant(VT.isInteger() ? 4 : 8, 3493 dl, MVT::i32)); 3494 3495 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3496 OverflowAreaPlusN); 3497 3498 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3499 MachinePointerInfo(), MVT::i32); 3500 3501 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3502 } 3503 3504 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3505 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3506 3507 // We have to copy the entire va_list struct: 3508 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3509 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3510 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3511 false, true, false, MachinePointerInfo(), 3512 MachinePointerInfo()); 3513 } 3514 3515 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3516 SelectionDAG &DAG) const { 3517 if (Subtarget.isAIXABI()) 3518 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3519 3520 return Op.getOperand(0); 3521 } 3522 3523 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3524 SelectionDAG &DAG) const { 3525 if (Subtarget.isAIXABI()) 3526 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3527 3528 SDValue Chain = Op.getOperand(0); 3529 SDValue Trmp = Op.getOperand(1); // trampoline 3530 SDValue FPtr = Op.getOperand(2); // nested function 3531 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3532 SDLoc dl(Op); 3533 3534 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3535 bool isPPC64 = (PtrVT == MVT::i64); 3536 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3537 3538 TargetLowering::ArgListTy Args; 3539 TargetLowering::ArgListEntry Entry; 3540 3541 Entry.Ty = IntPtrTy; 3542 Entry.Node = Trmp; Args.push_back(Entry); 3543 3544 // TrampSize == (isPPC64 ? 48 : 40); 3545 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3546 isPPC64 ? MVT::i64 : MVT::i32); 3547 Args.push_back(Entry); 3548 3549 Entry.Node = FPtr; Args.push_back(Entry); 3550 Entry.Node = Nest; Args.push_back(Entry); 3551 3552 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3553 TargetLowering::CallLoweringInfo CLI(DAG); 3554 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3555 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3556 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3557 3558 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3559 return CallResult.second; 3560 } 3561 3562 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3563 MachineFunction &MF = DAG.getMachineFunction(); 3564 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3565 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3566 3567 SDLoc dl(Op); 3568 3569 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3570 // vastart just stores the address of the VarArgsFrameIndex slot into the 3571 // memory location argument. 3572 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3573 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3574 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3575 MachinePointerInfo(SV)); 3576 } 3577 3578 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3579 // We suppose the given va_list is already allocated. 3580 // 3581 // typedef struct { 3582 // char gpr; /* index into the array of 8 GPRs 3583 // * stored in the register save area 3584 // * gpr=0 corresponds to r3, 3585 // * gpr=1 to r4, etc. 3586 // */ 3587 // char fpr; /* index into the array of 8 FPRs 3588 // * stored in the register save area 3589 // * fpr=0 corresponds to f1, 3590 // * fpr=1 to f2, etc. 3591 // */ 3592 // char *overflow_arg_area; 3593 // /* location on stack that holds 3594 // * the next overflow argument 3595 // */ 3596 // char *reg_save_area; 3597 // /* where r3:r10 and f1:f8 (if saved) 3598 // * are stored 3599 // */ 3600 // } va_list[1]; 3601 3602 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3603 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3604 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3605 PtrVT); 3606 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3607 PtrVT); 3608 3609 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3610 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3611 3612 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3613 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3614 3615 uint64_t FPROffset = 1; 3616 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3617 3618 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3619 3620 // Store first byte : number of int regs 3621 SDValue firstStore = 3622 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3623 MachinePointerInfo(SV), MVT::i8); 3624 uint64_t nextOffset = FPROffset; 3625 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3626 ConstFPROffset); 3627 3628 // Store second byte : number of float regs 3629 SDValue secondStore = 3630 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3631 MachinePointerInfo(SV, nextOffset), MVT::i8); 3632 nextOffset += StackOffset; 3633 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3634 3635 // Store second word : arguments given on stack 3636 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3637 MachinePointerInfo(SV, nextOffset)); 3638 nextOffset += FrameOffset; 3639 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3640 3641 // Store third word : arguments given in registers 3642 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3643 MachinePointerInfo(SV, nextOffset)); 3644 } 3645 3646 /// FPR - The set of FP registers that should be allocated for arguments 3647 /// on Darwin and AIX. 3648 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3649 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3650 PPC::F11, PPC::F12, PPC::F13}; 3651 3652 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3653 /// the stack. 3654 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3655 unsigned PtrByteSize) { 3656 unsigned ArgSize = ArgVT.getStoreSize(); 3657 if (Flags.isByVal()) 3658 ArgSize = Flags.getByValSize(); 3659 3660 // Round up to multiples of the pointer size, except for array members, 3661 // which are always packed. 3662 if (!Flags.isInConsecutiveRegs()) 3663 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3664 3665 return ArgSize; 3666 } 3667 3668 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3669 /// on the stack. 3670 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3671 ISD::ArgFlagsTy Flags, 3672 unsigned PtrByteSize) { 3673 Align Alignment(PtrByteSize); 3674 3675 // Altivec parameters are padded to a 16 byte boundary. 3676 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3677 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3678 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3679 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3680 Alignment = Align(16); 3681 3682 // ByVal parameters are aligned as requested. 3683 if (Flags.isByVal()) { 3684 auto BVAlign = Flags.getNonZeroByValAlign(); 3685 if (BVAlign > PtrByteSize) { 3686 if (BVAlign.value() % PtrByteSize != 0) 3687 llvm_unreachable( 3688 "ByVal alignment is not a multiple of the pointer size"); 3689 3690 Alignment = BVAlign; 3691 } 3692 } 3693 3694 // Array members are always packed to their original alignment. 3695 if (Flags.isInConsecutiveRegs()) { 3696 // If the array member was split into multiple registers, the first 3697 // needs to be aligned to the size of the full type. (Except for 3698 // ppcf128, which is only aligned as its f64 components.) 3699 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3700 Alignment = Align(OrigVT.getStoreSize()); 3701 else 3702 Alignment = Align(ArgVT.getStoreSize()); 3703 } 3704 3705 return Alignment; 3706 } 3707 3708 /// CalculateStackSlotUsed - Return whether this argument will use its 3709 /// stack slot (instead of being passed in registers). ArgOffset, 3710 /// AvailableFPRs, and AvailableVRs must hold the current argument 3711 /// position, and will be updated to account for this argument. 3712 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3713 unsigned PtrByteSize, unsigned LinkageSize, 3714 unsigned ParamAreaSize, unsigned &ArgOffset, 3715 unsigned &AvailableFPRs, 3716 unsigned &AvailableVRs) { 3717 bool UseMemory = false; 3718 3719 // Respect alignment of argument on the stack. 3720 Align Alignment = 3721 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3722 ArgOffset = alignTo(ArgOffset, Alignment); 3723 // If there's no space left in the argument save area, we must 3724 // use memory (this check also catches zero-sized arguments). 3725 if (ArgOffset >= LinkageSize + ParamAreaSize) 3726 UseMemory = true; 3727 3728 // Allocate argument on the stack. 3729 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3730 if (Flags.isInConsecutiveRegsLast()) 3731 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3732 // If we overran the argument save area, we must use memory 3733 // (this check catches arguments passed partially in memory) 3734 if (ArgOffset > LinkageSize + ParamAreaSize) 3735 UseMemory = true; 3736 3737 // However, if the argument is actually passed in an FPR or a VR, 3738 // we don't use memory after all. 3739 if (!Flags.isByVal()) { 3740 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3741 if (AvailableFPRs > 0) { 3742 --AvailableFPRs; 3743 return false; 3744 } 3745 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3746 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3747 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3748 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3749 if (AvailableVRs > 0) { 3750 --AvailableVRs; 3751 return false; 3752 } 3753 } 3754 3755 return UseMemory; 3756 } 3757 3758 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3759 /// ensure minimum alignment required for target. 3760 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3761 unsigned NumBytes) { 3762 return alignTo(NumBytes, Lowering->getStackAlign()); 3763 } 3764 3765 SDValue PPCTargetLowering::LowerFormalArguments( 3766 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3767 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3768 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3769 if (Subtarget.isAIXABI()) 3770 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3771 InVals); 3772 if (Subtarget.is64BitELFABI()) 3773 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3774 InVals); 3775 assert(Subtarget.is32BitELFABI()); 3776 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3777 InVals); 3778 } 3779 3780 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3781 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3782 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3783 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3784 3785 // 32-bit SVR4 ABI Stack Frame Layout: 3786 // +-----------------------------------+ 3787 // +--> | Back chain | 3788 // | +-----------------------------------+ 3789 // | | Floating-point register save area | 3790 // | +-----------------------------------+ 3791 // | | General register save area | 3792 // | +-----------------------------------+ 3793 // | | CR save word | 3794 // | +-----------------------------------+ 3795 // | | VRSAVE save word | 3796 // | +-----------------------------------+ 3797 // | | Alignment padding | 3798 // | +-----------------------------------+ 3799 // | | Vector register save area | 3800 // | +-----------------------------------+ 3801 // | | Local variable space | 3802 // | +-----------------------------------+ 3803 // | | Parameter list area | 3804 // | +-----------------------------------+ 3805 // | | LR save word | 3806 // | +-----------------------------------+ 3807 // SP--> +--- | Back chain | 3808 // +-----------------------------------+ 3809 // 3810 // Specifications: 3811 // System V Application Binary Interface PowerPC Processor Supplement 3812 // AltiVec Technology Programming Interface Manual 3813 3814 MachineFunction &MF = DAG.getMachineFunction(); 3815 MachineFrameInfo &MFI = MF.getFrameInfo(); 3816 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3817 3818 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3819 // Potential tail calls could cause overwriting of argument stack slots. 3820 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3821 (CallConv == CallingConv::Fast)); 3822 const Align PtrAlign(4); 3823 3824 // Assign locations to all of the incoming arguments. 3825 SmallVector<CCValAssign, 16> ArgLocs; 3826 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3827 *DAG.getContext()); 3828 3829 // Reserve space for the linkage area on the stack. 3830 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3831 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3832 if (useSoftFloat()) 3833 CCInfo.PreAnalyzeFormalArguments(Ins); 3834 3835 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3836 CCInfo.clearWasPPCF128(); 3837 3838 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3839 CCValAssign &VA = ArgLocs[i]; 3840 3841 // Arguments stored in registers. 3842 if (VA.isRegLoc()) { 3843 const TargetRegisterClass *RC; 3844 EVT ValVT = VA.getValVT(); 3845 3846 switch (ValVT.getSimpleVT().SimpleTy) { 3847 default: 3848 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3849 case MVT::i1: 3850 case MVT::i32: 3851 RC = &PPC::GPRCRegClass; 3852 break; 3853 case MVT::f32: 3854 if (Subtarget.hasP8Vector()) 3855 RC = &PPC::VSSRCRegClass; 3856 else if (Subtarget.hasSPE()) 3857 RC = &PPC::GPRCRegClass; 3858 else 3859 RC = &PPC::F4RCRegClass; 3860 break; 3861 case MVT::f64: 3862 if (Subtarget.hasVSX()) 3863 RC = &PPC::VSFRCRegClass; 3864 else if (Subtarget.hasSPE()) 3865 // SPE passes doubles in GPR pairs. 3866 RC = &PPC::GPRCRegClass; 3867 else 3868 RC = &PPC::F8RCRegClass; 3869 break; 3870 case MVT::v16i8: 3871 case MVT::v8i16: 3872 case MVT::v4i32: 3873 RC = &PPC::VRRCRegClass; 3874 break; 3875 case MVT::v4f32: 3876 RC = &PPC::VRRCRegClass; 3877 break; 3878 case MVT::v2f64: 3879 case MVT::v2i64: 3880 RC = &PPC::VRRCRegClass; 3881 break; 3882 } 3883 3884 SDValue ArgValue; 3885 // Transform the arguments stored in physical registers into 3886 // virtual ones. 3887 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3888 assert(i + 1 < e && "No second half of double precision argument"); 3889 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3890 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3891 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3892 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3893 if (!Subtarget.isLittleEndian()) 3894 std::swap (ArgValueLo, ArgValueHi); 3895 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3896 ArgValueHi); 3897 } else { 3898 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3899 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3900 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3901 if (ValVT == MVT::i1) 3902 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3903 } 3904 3905 InVals.push_back(ArgValue); 3906 } else { 3907 // Argument stored in memory. 3908 assert(VA.isMemLoc()); 3909 3910 // Get the extended size of the argument type in stack 3911 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3912 // Get the actual size of the argument type 3913 unsigned ObjSize = VA.getValVT().getStoreSize(); 3914 unsigned ArgOffset = VA.getLocMemOffset(); 3915 // Stack objects in PPC32 are right justified. 3916 ArgOffset += ArgSize - ObjSize; 3917 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3918 3919 // Create load nodes to retrieve arguments from the stack. 3920 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3921 InVals.push_back( 3922 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3923 } 3924 } 3925 3926 // Assign locations to all of the incoming aggregate by value arguments. 3927 // Aggregates passed by value are stored in the local variable space of the 3928 // caller's stack frame, right above the parameter list area. 3929 SmallVector<CCValAssign, 16> ByValArgLocs; 3930 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3931 ByValArgLocs, *DAG.getContext()); 3932 3933 // Reserve stack space for the allocations in CCInfo. 3934 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3935 3936 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3937 3938 // Area that is at least reserved in the caller of this function. 3939 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3940 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3941 3942 // Set the size that is at least reserved in caller of this function. Tail 3943 // call optimized function's reserved stack space needs to be aligned so that 3944 // taking the difference between two stack areas will result in an aligned 3945 // stack. 3946 MinReservedArea = 3947 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3948 FuncInfo->setMinReservedArea(MinReservedArea); 3949 3950 SmallVector<SDValue, 8> MemOps; 3951 3952 // If the function takes variable number of arguments, make a frame index for 3953 // the start of the first vararg value... for expansion of llvm.va_start. 3954 if (isVarArg) { 3955 static const MCPhysReg GPArgRegs[] = { 3956 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3957 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3958 }; 3959 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3960 3961 static const MCPhysReg FPArgRegs[] = { 3962 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3963 PPC::F8 3964 }; 3965 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3966 3967 if (useSoftFloat() || hasSPE()) 3968 NumFPArgRegs = 0; 3969 3970 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3971 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3972 3973 // Make room for NumGPArgRegs and NumFPArgRegs. 3974 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3975 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3976 3977 FuncInfo->setVarArgsStackOffset( 3978 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3979 CCInfo.getNextStackOffset(), true)); 3980 3981 FuncInfo->setVarArgsFrameIndex( 3982 MFI.CreateStackObject(Depth, Align(8), false)); 3983 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3984 3985 // The fixed integer arguments of a variadic function are stored to the 3986 // VarArgsFrameIndex on the stack so that they may be loaded by 3987 // dereferencing the result of va_next. 3988 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3989 // Get an existing live-in vreg, or add a new one. 3990 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3991 if (!VReg) 3992 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3993 3994 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3995 SDValue Store = 3996 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3997 MemOps.push_back(Store); 3998 // Increment the address by four for the next argument to store 3999 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4000 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4001 } 4002 4003 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 4004 // is set. 4005 // The double arguments are stored to the VarArgsFrameIndex 4006 // on the stack. 4007 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 4008 // Get an existing live-in vreg, or add a new one. 4009 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 4010 if (!VReg) 4011 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 4012 4013 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 4014 SDValue Store = 4015 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4016 MemOps.push_back(Store); 4017 // Increment the address by eight for the next argument to store 4018 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4019 PtrVT); 4020 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4021 } 4022 } 4023 4024 if (!MemOps.empty()) 4025 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4026 4027 return Chain; 4028 } 4029 4030 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4031 // value to MVT::i64 and then truncate to the correct register size. 4032 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4033 EVT ObjectVT, SelectionDAG &DAG, 4034 SDValue ArgVal, 4035 const SDLoc &dl) const { 4036 if (Flags.isSExt()) 4037 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4038 DAG.getValueType(ObjectVT)); 4039 else if (Flags.isZExt()) 4040 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4041 DAG.getValueType(ObjectVT)); 4042 4043 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4044 } 4045 4046 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4047 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4048 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4049 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4050 // TODO: add description of PPC stack frame format, or at least some docs. 4051 // 4052 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4053 bool isLittleEndian = Subtarget.isLittleEndian(); 4054 MachineFunction &MF = DAG.getMachineFunction(); 4055 MachineFrameInfo &MFI = MF.getFrameInfo(); 4056 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4057 4058 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4059 "fastcc not supported on varargs functions"); 4060 4061 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4062 // Potential tail calls could cause overwriting of argument stack slots. 4063 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4064 (CallConv == CallingConv::Fast)); 4065 unsigned PtrByteSize = 8; 4066 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4067 4068 static const MCPhysReg GPR[] = { 4069 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4070 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4071 }; 4072 static const MCPhysReg VR[] = { 4073 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4074 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4075 }; 4076 4077 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4078 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4079 const unsigned Num_VR_Regs = array_lengthof(VR); 4080 4081 // Do a first pass over the arguments to determine whether the ABI 4082 // guarantees that our caller has allocated the parameter save area 4083 // on its stack frame. In the ELFv1 ABI, this is always the case; 4084 // in the ELFv2 ABI, it is true if this is a vararg function or if 4085 // any parameter is located in a stack slot. 4086 4087 bool HasParameterArea = !isELFv2ABI || isVarArg; 4088 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4089 unsigned NumBytes = LinkageSize; 4090 unsigned AvailableFPRs = Num_FPR_Regs; 4091 unsigned AvailableVRs = Num_VR_Regs; 4092 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4093 if (Ins[i].Flags.isNest()) 4094 continue; 4095 4096 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4097 PtrByteSize, LinkageSize, ParamAreaSize, 4098 NumBytes, AvailableFPRs, AvailableVRs)) 4099 HasParameterArea = true; 4100 } 4101 4102 // Add DAG nodes to load the arguments or copy them out of registers. On 4103 // entry to a function on PPC, the arguments start after the linkage area, 4104 // although the first ones are often in registers. 4105 4106 unsigned ArgOffset = LinkageSize; 4107 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4108 SmallVector<SDValue, 8> MemOps; 4109 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4110 unsigned CurArgIdx = 0; 4111 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4112 SDValue ArgVal; 4113 bool needsLoad = false; 4114 EVT ObjectVT = Ins[ArgNo].VT; 4115 EVT OrigVT = Ins[ArgNo].ArgVT; 4116 unsigned ObjSize = ObjectVT.getStoreSize(); 4117 unsigned ArgSize = ObjSize; 4118 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4119 if (Ins[ArgNo].isOrigArg()) { 4120 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4121 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4122 } 4123 // We re-align the argument offset for each argument, except when using the 4124 // fast calling convention, when we need to make sure we do that only when 4125 // we'll actually use a stack slot. 4126 unsigned CurArgOffset; 4127 Align Alignment; 4128 auto ComputeArgOffset = [&]() { 4129 /* Respect alignment of argument on the stack. */ 4130 Alignment = 4131 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4132 ArgOffset = alignTo(ArgOffset, Alignment); 4133 CurArgOffset = ArgOffset; 4134 }; 4135 4136 if (CallConv != CallingConv::Fast) { 4137 ComputeArgOffset(); 4138 4139 /* Compute GPR index associated with argument offset. */ 4140 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4141 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4142 } 4143 4144 // FIXME the codegen can be much improved in some cases. 4145 // We do not have to keep everything in memory. 4146 if (Flags.isByVal()) { 4147 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4148 4149 if (CallConv == CallingConv::Fast) 4150 ComputeArgOffset(); 4151 4152 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4153 ObjSize = Flags.getByValSize(); 4154 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4155 // Empty aggregate parameters do not take up registers. Examples: 4156 // struct { } a; 4157 // union { } b; 4158 // int c[0]; 4159 // etc. However, we have to provide a place-holder in InVals, so 4160 // pretend we have an 8-byte item at the current address for that 4161 // purpose. 4162 if (!ObjSize) { 4163 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4164 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4165 InVals.push_back(FIN); 4166 continue; 4167 } 4168 4169 // Create a stack object covering all stack doublewords occupied 4170 // by the argument. If the argument is (fully or partially) on 4171 // the stack, or if the argument is fully in registers but the 4172 // caller has allocated the parameter save anyway, we can refer 4173 // directly to the caller's stack frame. Otherwise, create a 4174 // local copy in our own frame. 4175 int FI; 4176 if (HasParameterArea || 4177 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4178 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4179 else 4180 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4181 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4182 4183 // Handle aggregates smaller than 8 bytes. 4184 if (ObjSize < PtrByteSize) { 4185 // The value of the object is its address, which differs from the 4186 // address of the enclosing doubleword on big-endian systems. 4187 SDValue Arg = FIN; 4188 if (!isLittleEndian) { 4189 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4190 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4191 } 4192 InVals.push_back(Arg); 4193 4194 if (GPR_idx != Num_GPR_Regs) { 4195 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4196 FuncInfo->addLiveInAttr(VReg, Flags); 4197 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4198 SDValue Store; 4199 4200 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4201 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4202 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4203 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4204 MachinePointerInfo(&*FuncArg), ObjType); 4205 } else { 4206 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4207 // store the whole register as-is to the parameter save area 4208 // slot. 4209 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4210 MachinePointerInfo(&*FuncArg)); 4211 } 4212 4213 MemOps.push_back(Store); 4214 } 4215 // Whether we copied from a register or not, advance the offset 4216 // into the parameter save area by a full doubleword. 4217 ArgOffset += PtrByteSize; 4218 continue; 4219 } 4220 4221 // The value of the object is its address, which is the address of 4222 // its first stack doubleword. 4223 InVals.push_back(FIN); 4224 4225 // Store whatever pieces of the object are in registers to memory. 4226 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4227 if (GPR_idx == Num_GPR_Regs) 4228 break; 4229 4230 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4231 FuncInfo->addLiveInAttr(VReg, Flags); 4232 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4233 SDValue Addr = FIN; 4234 if (j) { 4235 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4236 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4237 } 4238 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4239 MachinePointerInfo(&*FuncArg, j)); 4240 MemOps.push_back(Store); 4241 ++GPR_idx; 4242 } 4243 ArgOffset += ArgSize; 4244 continue; 4245 } 4246 4247 switch (ObjectVT.getSimpleVT().SimpleTy) { 4248 default: llvm_unreachable("Unhandled argument type!"); 4249 case MVT::i1: 4250 case MVT::i32: 4251 case MVT::i64: 4252 if (Flags.isNest()) { 4253 // The 'nest' parameter, if any, is passed in R11. 4254 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4255 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4256 4257 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4258 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4259 4260 break; 4261 } 4262 4263 // These can be scalar arguments or elements of an integer array type 4264 // passed directly. Clang may use those instead of "byval" aggregate 4265 // types to avoid forcing arguments to memory unnecessarily. 4266 if (GPR_idx != Num_GPR_Regs) { 4267 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4268 FuncInfo->addLiveInAttr(VReg, Flags); 4269 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4270 4271 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4272 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4273 // value to MVT::i64 and then truncate to the correct register size. 4274 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4275 } else { 4276 if (CallConv == CallingConv::Fast) 4277 ComputeArgOffset(); 4278 4279 needsLoad = true; 4280 ArgSize = PtrByteSize; 4281 } 4282 if (CallConv != CallingConv::Fast || needsLoad) 4283 ArgOffset += 8; 4284 break; 4285 4286 case MVT::f32: 4287 case MVT::f64: 4288 // These can be scalar arguments or elements of a float array type 4289 // passed directly. The latter are used to implement ELFv2 homogenous 4290 // float aggregates. 4291 if (FPR_idx != Num_FPR_Regs) { 4292 unsigned VReg; 4293 4294 if (ObjectVT == MVT::f32) 4295 VReg = MF.addLiveIn(FPR[FPR_idx], 4296 Subtarget.hasP8Vector() 4297 ? &PPC::VSSRCRegClass 4298 : &PPC::F4RCRegClass); 4299 else 4300 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4301 ? &PPC::VSFRCRegClass 4302 : &PPC::F8RCRegClass); 4303 4304 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4305 ++FPR_idx; 4306 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4307 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4308 // once we support fp <-> gpr moves. 4309 4310 // This can only ever happen in the presence of f32 array types, 4311 // since otherwise we never run out of FPRs before running out 4312 // of GPRs. 4313 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4314 FuncInfo->addLiveInAttr(VReg, Flags); 4315 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4316 4317 if (ObjectVT == MVT::f32) { 4318 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4319 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4320 DAG.getConstant(32, dl, MVT::i32)); 4321 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4322 } 4323 4324 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4325 } else { 4326 if (CallConv == CallingConv::Fast) 4327 ComputeArgOffset(); 4328 4329 needsLoad = true; 4330 } 4331 4332 // When passing an array of floats, the array occupies consecutive 4333 // space in the argument area; only round up to the next doubleword 4334 // at the end of the array. Otherwise, each float takes 8 bytes. 4335 if (CallConv != CallingConv::Fast || needsLoad) { 4336 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4337 ArgOffset += ArgSize; 4338 if (Flags.isInConsecutiveRegsLast()) 4339 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4340 } 4341 break; 4342 case MVT::v4f32: 4343 case MVT::v4i32: 4344 case MVT::v8i16: 4345 case MVT::v16i8: 4346 case MVT::v2f64: 4347 case MVT::v2i64: 4348 case MVT::v1i128: 4349 case MVT::f128: 4350 // These can be scalar arguments or elements of a vector array type 4351 // passed directly. The latter are used to implement ELFv2 homogenous 4352 // vector aggregates. 4353 if (VR_idx != Num_VR_Regs) { 4354 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4355 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4356 ++VR_idx; 4357 } else { 4358 if (CallConv == CallingConv::Fast) 4359 ComputeArgOffset(); 4360 needsLoad = true; 4361 } 4362 if (CallConv != CallingConv::Fast || needsLoad) 4363 ArgOffset += 16; 4364 break; 4365 } 4366 4367 // We need to load the argument to a virtual register if we determined 4368 // above that we ran out of physical registers of the appropriate type. 4369 if (needsLoad) { 4370 if (ObjSize < ArgSize && !isLittleEndian) 4371 CurArgOffset += ArgSize - ObjSize; 4372 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4373 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4374 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4375 } 4376 4377 InVals.push_back(ArgVal); 4378 } 4379 4380 // Area that is at least reserved in the caller of this function. 4381 unsigned MinReservedArea; 4382 if (HasParameterArea) 4383 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4384 else 4385 MinReservedArea = LinkageSize; 4386 4387 // Set the size that is at least reserved in caller of this function. Tail 4388 // call optimized functions' reserved stack space needs to be aligned so that 4389 // taking the difference between two stack areas will result in an aligned 4390 // stack. 4391 MinReservedArea = 4392 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4393 FuncInfo->setMinReservedArea(MinReservedArea); 4394 4395 // If the function takes variable number of arguments, make a frame index for 4396 // the start of the first vararg value... for expansion of llvm.va_start. 4397 // On ELFv2ABI spec, it writes: 4398 // C programs that are intended to be *portable* across different compilers 4399 // and architectures must use the header file <stdarg.h> to deal with variable 4400 // argument lists. 4401 if (isVarArg && MFI.hasVAStart()) { 4402 int Depth = ArgOffset; 4403 4404 FuncInfo->setVarArgsFrameIndex( 4405 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4406 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4407 4408 // If this function is vararg, store any remaining integer argument regs 4409 // to their spots on the stack so that they may be loaded by dereferencing 4410 // the result of va_next. 4411 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4412 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4413 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4414 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4415 SDValue Store = 4416 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4417 MemOps.push_back(Store); 4418 // Increment the address by four for the next argument to store 4419 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4420 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4421 } 4422 } 4423 4424 if (!MemOps.empty()) 4425 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4426 4427 return Chain; 4428 } 4429 4430 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4431 /// adjusted to accommodate the arguments for the tailcall. 4432 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4433 unsigned ParamSize) { 4434 4435 if (!isTailCall) return 0; 4436 4437 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4438 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4439 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4440 // Remember only if the new adjustment is bigger. 4441 if (SPDiff < FI->getTailCallSPDelta()) 4442 FI->setTailCallSPDelta(SPDiff); 4443 4444 return SPDiff; 4445 } 4446 4447 static bool isFunctionGlobalAddress(SDValue Callee); 4448 4449 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4450 const TargetMachine &TM) { 4451 // It does not make sense to call callsShareTOCBase() with a caller that 4452 // is PC Relative since PC Relative callers do not have a TOC. 4453 #ifndef NDEBUG 4454 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4455 assert(!STICaller->isUsingPCRelativeCalls() && 4456 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4457 #endif 4458 4459 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4460 // don't have enough information to determine if the caller and callee share 4461 // the same TOC base, so we have to pessimistically assume they don't for 4462 // correctness. 4463 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4464 if (!G) 4465 return false; 4466 4467 const GlobalValue *GV = G->getGlobal(); 4468 4469 // If the callee is preemptable, then the static linker will use a plt-stub 4470 // which saves the toc to the stack, and needs a nop after the call 4471 // instruction to convert to a toc-restore. 4472 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4473 return false; 4474 4475 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4476 // We may need a TOC restore in the situation where the caller requires a 4477 // valid TOC but the callee is PC Relative and does not. 4478 const Function *F = dyn_cast<Function>(GV); 4479 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4480 4481 // If we have an Alias we can try to get the function from there. 4482 if (Alias) { 4483 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4484 F = dyn_cast<Function>(GlobalObj); 4485 } 4486 4487 // If we still have no valid function pointer we do not have enough 4488 // information to determine if the callee uses PC Relative calls so we must 4489 // assume that it does. 4490 if (!F) 4491 return false; 4492 4493 // If the callee uses PC Relative we cannot guarantee that the callee won't 4494 // clobber the TOC of the caller and so we must assume that the two 4495 // functions do not share a TOC base. 4496 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4497 if (STICallee->isUsingPCRelativeCalls()) 4498 return false; 4499 4500 // If the GV is not a strong definition then we need to assume it can be 4501 // replaced by another function at link time. The function that replaces 4502 // it may not share the same TOC as the caller since the callee may be 4503 // replaced by a PC Relative version of the same function. 4504 if (!GV->isStrongDefinitionForLinker()) 4505 return false; 4506 4507 // The medium and large code models are expected to provide a sufficiently 4508 // large TOC to provide all data addressing needs of a module with a 4509 // single TOC. 4510 if (CodeModel::Medium == TM.getCodeModel() || 4511 CodeModel::Large == TM.getCodeModel()) 4512 return true; 4513 4514 // Any explicitly-specified sections and section prefixes must also match. 4515 // Also, if we're using -ffunction-sections, then each function is always in 4516 // a different section (the same is true for COMDAT functions). 4517 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4518 GV->getSection() != Caller->getSection()) 4519 return false; 4520 if (const auto *F = dyn_cast<Function>(GV)) { 4521 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4522 return false; 4523 } 4524 4525 return true; 4526 } 4527 4528 static bool 4529 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4530 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4531 assert(Subtarget.is64BitELFABI()); 4532 4533 const unsigned PtrByteSize = 8; 4534 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4535 4536 static const MCPhysReg GPR[] = { 4537 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4538 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4539 }; 4540 static const MCPhysReg VR[] = { 4541 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4542 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4543 }; 4544 4545 const unsigned NumGPRs = array_lengthof(GPR); 4546 const unsigned NumFPRs = 13; 4547 const unsigned NumVRs = array_lengthof(VR); 4548 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4549 4550 unsigned NumBytes = LinkageSize; 4551 unsigned AvailableFPRs = NumFPRs; 4552 unsigned AvailableVRs = NumVRs; 4553 4554 for (const ISD::OutputArg& Param : Outs) { 4555 if (Param.Flags.isNest()) continue; 4556 4557 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4558 LinkageSize, ParamAreaSize, NumBytes, 4559 AvailableFPRs, AvailableVRs)) 4560 return true; 4561 } 4562 return false; 4563 } 4564 4565 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4566 if (CB.arg_size() != CallerFn->arg_size()) 4567 return false; 4568 4569 auto CalleeArgIter = CB.arg_begin(); 4570 auto CalleeArgEnd = CB.arg_end(); 4571 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4572 4573 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4574 const Value* CalleeArg = *CalleeArgIter; 4575 const Value* CallerArg = &(*CallerArgIter); 4576 if (CalleeArg == CallerArg) 4577 continue; 4578 4579 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4580 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4581 // } 4582 // 1st argument of callee is undef and has the same type as caller. 4583 if (CalleeArg->getType() == CallerArg->getType() && 4584 isa<UndefValue>(CalleeArg)) 4585 continue; 4586 4587 return false; 4588 } 4589 4590 return true; 4591 } 4592 4593 // Returns true if TCO is possible between the callers and callees 4594 // calling conventions. 4595 static bool 4596 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4597 CallingConv::ID CalleeCC) { 4598 // Tail calls are possible with fastcc and ccc. 4599 auto isTailCallableCC = [] (CallingConv::ID CC){ 4600 return CC == CallingConv::C || CC == CallingConv::Fast; 4601 }; 4602 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4603 return false; 4604 4605 // We can safely tail call both fastcc and ccc callees from a c calling 4606 // convention caller. If the caller is fastcc, we may have less stack space 4607 // than a non-fastcc caller with the same signature so disable tail-calls in 4608 // that case. 4609 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4610 } 4611 4612 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4613 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4614 const SmallVectorImpl<ISD::OutputArg> &Outs, 4615 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4616 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4617 4618 if (DisableSCO && !TailCallOpt) return false; 4619 4620 // Variadic argument functions are not supported. 4621 if (isVarArg) return false; 4622 4623 auto &Caller = DAG.getMachineFunction().getFunction(); 4624 // Check that the calling conventions are compatible for tco. 4625 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4626 return false; 4627 4628 // Caller contains any byval parameter is not supported. 4629 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4630 return false; 4631 4632 // Callee contains any byval parameter is not supported, too. 4633 // Note: This is a quick work around, because in some cases, e.g. 4634 // caller's stack size > callee's stack size, we are still able to apply 4635 // sibling call optimization. For example, gcc is able to do SCO for caller1 4636 // in the following example, but not for caller2. 4637 // struct test { 4638 // long int a; 4639 // char ary[56]; 4640 // } gTest; 4641 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4642 // b->a = v.a; 4643 // return 0; 4644 // } 4645 // void caller1(struct test a, struct test c, struct test *b) { 4646 // callee(gTest, b); } 4647 // void caller2(struct test *b) { callee(gTest, b); } 4648 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4649 return false; 4650 4651 // If callee and caller use different calling conventions, we cannot pass 4652 // parameters on stack since offsets for the parameter area may be different. 4653 if (Caller.getCallingConv() != CalleeCC && 4654 needStackSlotPassParameters(Subtarget, Outs)) 4655 return false; 4656 4657 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4658 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4659 // callee potentially have different TOC bases then we cannot tail call since 4660 // we need to restore the TOC pointer after the call. 4661 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4662 // We cannot guarantee this for indirect calls or calls to external functions. 4663 // When PC-Relative addressing is used, the concept of the TOC is no longer 4664 // applicable so this check is not required. 4665 // Check first for indirect calls. 4666 if (!Subtarget.isUsingPCRelativeCalls() && 4667 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4668 return false; 4669 4670 // Check if we share the TOC base. 4671 if (!Subtarget.isUsingPCRelativeCalls() && 4672 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4673 return false; 4674 4675 // TCO allows altering callee ABI, so we don't have to check further. 4676 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4677 return true; 4678 4679 if (DisableSCO) return false; 4680 4681 // If callee use the same argument list that caller is using, then we can 4682 // apply SCO on this case. If it is not, then we need to check if callee needs 4683 // stack for passing arguments. 4684 // PC Relative tail calls may not have a CallBase. 4685 // If there is no CallBase we cannot verify if we have the same argument 4686 // list so assume that we don't have the same argument list. 4687 if (CB && !hasSameArgumentList(&Caller, *CB) && 4688 needStackSlotPassParameters(Subtarget, Outs)) 4689 return false; 4690 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4691 return false; 4692 4693 return true; 4694 } 4695 4696 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4697 /// for tail call optimization. Targets which want to do tail call 4698 /// optimization should implement this function. 4699 bool 4700 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4701 CallingConv::ID CalleeCC, 4702 bool isVarArg, 4703 const SmallVectorImpl<ISD::InputArg> &Ins, 4704 SelectionDAG& DAG) const { 4705 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4706 return false; 4707 4708 // Variable argument functions are not supported. 4709 if (isVarArg) 4710 return false; 4711 4712 MachineFunction &MF = DAG.getMachineFunction(); 4713 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4714 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4715 // Functions containing by val parameters are not supported. 4716 for (unsigned i = 0; i != Ins.size(); i++) { 4717 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4718 if (Flags.isByVal()) return false; 4719 } 4720 4721 // Non-PIC/GOT tail calls are supported. 4722 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4723 return true; 4724 4725 // At the moment we can only do local tail calls (in same module, hidden 4726 // or protected) if we are generating PIC. 4727 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4728 return G->getGlobal()->hasHiddenVisibility() 4729 || G->getGlobal()->hasProtectedVisibility(); 4730 } 4731 4732 return false; 4733 } 4734 4735 /// isCallCompatibleAddress - Return the immediate to use if the specified 4736 /// 32-bit value is representable in the immediate field of a BxA instruction. 4737 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4738 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4739 if (!C) return nullptr; 4740 4741 int Addr = C->getZExtValue(); 4742 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4743 SignExtend32<26>(Addr) != Addr) 4744 return nullptr; // Top 6 bits have to be sext of immediate. 4745 4746 return DAG 4747 .getConstant( 4748 (int)C->getZExtValue() >> 2, SDLoc(Op), 4749 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4750 .getNode(); 4751 } 4752 4753 namespace { 4754 4755 struct TailCallArgumentInfo { 4756 SDValue Arg; 4757 SDValue FrameIdxOp; 4758 int FrameIdx = 0; 4759 4760 TailCallArgumentInfo() = default; 4761 }; 4762 4763 } // end anonymous namespace 4764 4765 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4766 static void StoreTailCallArgumentsToStackSlot( 4767 SelectionDAG &DAG, SDValue Chain, 4768 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4769 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4770 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4771 SDValue Arg = TailCallArgs[i].Arg; 4772 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4773 int FI = TailCallArgs[i].FrameIdx; 4774 // Store relative to framepointer. 4775 MemOpChains.push_back(DAG.getStore( 4776 Chain, dl, Arg, FIN, 4777 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4778 } 4779 } 4780 4781 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4782 /// the appropriate stack slot for the tail call optimized function call. 4783 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4784 SDValue OldRetAddr, SDValue OldFP, 4785 int SPDiff, const SDLoc &dl) { 4786 if (SPDiff) { 4787 // Calculate the new stack slot for the return address. 4788 MachineFunction &MF = DAG.getMachineFunction(); 4789 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4790 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4791 bool isPPC64 = Subtarget.isPPC64(); 4792 int SlotSize = isPPC64 ? 8 : 4; 4793 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4794 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4795 NewRetAddrLoc, true); 4796 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4797 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4798 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4799 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4800 } 4801 return Chain; 4802 } 4803 4804 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4805 /// the position of the argument. 4806 static void 4807 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4808 SDValue Arg, int SPDiff, unsigned ArgOffset, 4809 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4810 int Offset = ArgOffset + SPDiff; 4811 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4812 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4813 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4814 SDValue FIN = DAG.getFrameIndex(FI, VT); 4815 TailCallArgumentInfo Info; 4816 Info.Arg = Arg; 4817 Info.FrameIdxOp = FIN; 4818 Info.FrameIdx = FI; 4819 TailCallArguments.push_back(Info); 4820 } 4821 4822 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4823 /// stack slot. Returns the chain as result and the loaded frame pointers in 4824 /// LROpOut/FPOpout. Used when tail calling. 4825 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4826 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4827 SDValue &FPOpOut, const SDLoc &dl) const { 4828 if (SPDiff) { 4829 // Load the LR and FP stack slot for later adjusting. 4830 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4831 LROpOut = getReturnAddrFrameIndex(DAG); 4832 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4833 Chain = SDValue(LROpOut.getNode(), 1); 4834 } 4835 return Chain; 4836 } 4837 4838 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4839 /// by "Src" to address "Dst" of size "Size". Alignment information is 4840 /// specified by the specific parameter attribute. The copy will be passed as 4841 /// a byval function parameter. 4842 /// Sometimes what we are copying is the end of a larger object, the part that 4843 /// does not fit in registers. 4844 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4845 SDValue Chain, ISD::ArgFlagsTy Flags, 4846 SelectionDAG &DAG, const SDLoc &dl) { 4847 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4848 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4849 Flags.getNonZeroByValAlign(), false, false, false, 4850 MachinePointerInfo(), MachinePointerInfo()); 4851 } 4852 4853 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4854 /// tail calls. 4855 static void LowerMemOpCallTo( 4856 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4857 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4858 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4859 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4860 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4861 if (!isTailCall) { 4862 if (isVector) { 4863 SDValue StackPtr; 4864 if (isPPC64) 4865 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4866 else 4867 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4868 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4869 DAG.getConstant(ArgOffset, dl, PtrVT)); 4870 } 4871 MemOpChains.push_back( 4872 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4873 // Calculate and remember argument location. 4874 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4875 TailCallArguments); 4876 } 4877 4878 static void 4879 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4880 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4881 SDValue FPOp, 4882 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4883 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4884 // might overwrite each other in case of tail call optimization. 4885 SmallVector<SDValue, 8> MemOpChains2; 4886 // Do not flag preceding copytoreg stuff together with the following stuff. 4887 InFlag = SDValue(); 4888 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4889 MemOpChains2, dl); 4890 if (!MemOpChains2.empty()) 4891 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4892 4893 // Store the return address to the appropriate stack slot. 4894 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4895 4896 // Emit callseq_end just before tailcall node. 4897 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4898 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4899 InFlag = Chain.getValue(1); 4900 } 4901 4902 // Is this global address that of a function that can be called by name? (as 4903 // opposed to something that must hold a descriptor for an indirect call). 4904 static bool isFunctionGlobalAddress(SDValue Callee) { 4905 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4906 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4907 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4908 return false; 4909 4910 return G->getGlobal()->getValueType()->isFunctionTy(); 4911 } 4912 4913 return false; 4914 } 4915 4916 SDValue PPCTargetLowering::LowerCallResult( 4917 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4918 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4919 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4920 SmallVector<CCValAssign, 16> RVLocs; 4921 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4922 *DAG.getContext()); 4923 4924 CCRetInfo.AnalyzeCallResult( 4925 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4926 ? RetCC_PPC_Cold 4927 : RetCC_PPC); 4928 4929 // Copy all of the result registers out of their specified physreg. 4930 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4931 CCValAssign &VA = RVLocs[i]; 4932 assert(VA.isRegLoc() && "Can only return in registers!"); 4933 4934 SDValue Val; 4935 4936 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4937 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4938 InFlag); 4939 Chain = Lo.getValue(1); 4940 InFlag = Lo.getValue(2); 4941 VA = RVLocs[++i]; // skip ahead to next loc 4942 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4943 InFlag); 4944 Chain = Hi.getValue(1); 4945 InFlag = Hi.getValue(2); 4946 if (!Subtarget.isLittleEndian()) 4947 std::swap (Lo, Hi); 4948 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 4949 } else { 4950 Val = DAG.getCopyFromReg(Chain, dl, 4951 VA.getLocReg(), VA.getLocVT(), InFlag); 4952 Chain = Val.getValue(1); 4953 InFlag = Val.getValue(2); 4954 } 4955 4956 switch (VA.getLocInfo()) { 4957 default: llvm_unreachable("Unknown loc info!"); 4958 case CCValAssign::Full: break; 4959 case CCValAssign::AExt: 4960 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4961 break; 4962 case CCValAssign::ZExt: 4963 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4964 DAG.getValueType(VA.getValVT())); 4965 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4966 break; 4967 case CCValAssign::SExt: 4968 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4969 DAG.getValueType(VA.getValVT())); 4970 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4971 break; 4972 } 4973 4974 InVals.push_back(Val); 4975 } 4976 4977 return Chain; 4978 } 4979 4980 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 4981 const PPCSubtarget &Subtarget, bool isPatchPoint) { 4982 // PatchPoint calls are not indirect. 4983 if (isPatchPoint) 4984 return false; 4985 4986 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 4987 return false; 4988 4989 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 4990 // becuase the immediate function pointer points to a descriptor instead of 4991 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 4992 // pointer immediate points to the global entry point, while the BLA would 4993 // need to jump to the local entry point (see rL211174). 4994 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 4995 isBLACompatibleAddress(Callee, DAG)) 4996 return false; 4997 4998 return true; 4999 } 5000 5001 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5002 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5003 return Subtarget.isAIXABI() || 5004 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5005 } 5006 5007 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5008 const Function &Caller, 5009 const SDValue &Callee, 5010 const PPCSubtarget &Subtarget, 5011 const TargetMachine &TM) { 5012 if (CFlags.IsTailCall) 5013 return PPCISD::TC_RETURN; 5014 5015 // This is a call through a function pointer. 5016 if (CFlags.IsIndirect) { 5017 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5018 // indirect calls. The save of the caller's TOC pointer to the stack will be 5019 // inserted into the DAG as part of call lowering. The restore of the TOC 5020 // pointer is modeled by using a pseudo instruction for the call opcode that 5021 // represents the 2 instruction sequence of an indirect branch and link, 5022 // immediately followed by a load of the TOC pointer from the the stack save 5023 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5024 // as it is not saved or used. 5025 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5026 : PPCISD::BCTRL; 5027 } 5028 5029 if (Subtarget.isUsingPCRelativeCalls()) { 5030 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5031 return PPCISD::CALL_NOTOC; 5032 } 5033 5034 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5035 // immediately following the call instruction if the caller and callee may 5036 // have different TOC bases. At link time if the linker determines the calls 5037 // may not share a TOC base, the call is redirected to a trampoline inserted 5038 // by the linker. The trampoline will (among other things) save the callers 5039 // TOC pointer at an ABI designated offset in the linkage area and the linker 5040 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5041 // into gpr2. 5042 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5043 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5044 : PPCISD::CALL_NOP; 5045 5046 return PPCISD::CALL; 5047 } 5048 5049 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5050 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5051 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5052 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5053 return SDValue(Dest, 0); 5054 5055 // Returns true if the callee is local, and false otherwise. 5056 auto isLocalCallee = [&]() { 5057 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5058 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5059 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5060 5061 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5062 !dyn_cast_or_null<GlobalIFunc>(GV); 5063 }; 5064 5065 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5066 // a static relocation model causes some versions of GNU LD (2.17.50, at 5067 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5068 // built with secure-PLT. 5069 bool UsePlt = 5070 Subtarget.is32BitELFABI() && !isLocalCallee() && 5071 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5072 5073 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5074 const TargetMachine &TM = Subtarget.getTargetMachine(); 5075 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5076 MCSymbolXCOFF *S = 5077 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5078 5079 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5080 return DAG.getMCSymbol(S, PtrVT); 5081 }; 5082 5083 if (isFunctionGlobalAddress(Callee)) { 5084 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5085 5086 if (Subtarget.isAIXABI()) { 5087 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5088 return getAIXFuncEntryPointSymbolSDNode(GV); 5089 } 5090 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5091 UsePlt ? PPCII::MO_PLT : 0); 5092 } 5093 5094 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5095 const char *SymName = S->getSymbol(); 5096 if (Subtarget.isAIXABI()) { 5097 // If there exists a user-declared function whose name is the same as the 5098 // ExternalSymbol's, then we pick up the user-declared version. 5099 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5100 if (const Function *F = 5101 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5102 return getAIXFuncEntryPointSymbolSDNode(F); 5103 5104 // On AIX, direct function calls reference the symbol for the function's 5105 // entry point, which is named by prepending a "." before the function's 5106 // C-linkage name. A Qualname is returned here because an external 5107 // function entry point is a csect with XTY_ER property. 5108 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5109 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5110 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5111 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5112 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5113 return Sec->getQualNameSymbol(); 5114 }; 5115 5116 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5117 } 5118 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5119 UsePlt ? PPCII::MO_PLT : 0); 5120 } 5121 5122 // No transformation needed. 5123 assert(Callee.getNode() && "What no callee?"); 5124 return Callee; 5125 } 5126 5127 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5128 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5129 "Expected a CALLSEQ_STARTSDNode."); 5130 5131 // The last operand is the chain, except when the node has glue. If the node 5132 // has glue, then the last operand is the glue, and the chain is the second 5133 // last operand. 5134 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5135 if (LastValue.getValueType() != MVT::Glue) 5136 return LastValue; 5137 5138 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5139 } 5140 5141 // Creates the node that moves a functions address into the count register 5142 // to prepare for an indirect call instruction. 5143 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5144 SDValue &Glue, SDValue &Chain, 5145 const SDLoc &dl) { 5146 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5147 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5148 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5149 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5150 // The glue is the second value produced. 5151 Glue = Chain.getValue(1); 5152 } 5153 5154 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5155 SDValue &Glue, SDValue &Chain, 5156 SDValue CallSeqStart, 5157 const CallBase *CB, const SDLoc &dl, 5158 bool hasNest, 5159 const PPCSubtarget &Subtarget) { 5160 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5161 // entry point, but to the function descriptor (the function entry point 5162 // address is part of the function descriptor though). 5163 // The function descriptor is a three doubleword structure with the 5164 // following fields: function entry point, TOC base address and 5165 // environment pointer. 5166 // Thus for a call through a function pointer, the following actions need 5167 // to be performed: 5168 // 1. Save the TOC of the caller in the TOC save area of its stack 5169 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5170 // 2. Load the address of the function entry point from the function 5171 // descriptor. 5172 // 3. Load the TOC of the callee from the function descriptor into r2. 5173 // 4. Load the environment pointer from the function descriptor into 5174 // r11. 5175 // 5. Branch to the function entry point address. 5176 // 6. On return of the callee, the TOC of the caller needs to be 5177 // restored (this is done in FinishCall()). 5178 // 5179 // The loads are scheduled at the beginning of the call sequence, and the 5180 // register copies are flagged together to ensure that no other 5181 // operations can be scheduled in between. E.g. without flagging the 5182 // copies together, a TOC access in the caller could be scheduled between 5183 // the assignment of the callee TOC and the branch to the callee, which leads 5184 // to incorrect code. 5185 5186 // Start by loading the function address from the descriptor. 5187 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5188 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5189 ? (MachineMemOperand::MODereferenceable | 5190 MachineMemOperand::MOInvariant) 5191 : MachineMemOperand::MONone; 5192 5193 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5194 5195 // Registers used in building the DAG. 5196 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5197 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5198 5199 // Offsets of descriptor members. 5200 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5201 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5202 5203 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5204 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5205 5206 // One load for the functions entry point address. 5207 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5208 Alignment, MMOFlags); 5209 5210 // One for loading the TOC anchor for the module that contains the called 5211 // function. 5212 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5213 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5214 SDValue TOCPtr = 5215 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5216 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5217 5218 // One for loading the environment pointer. 5219 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5220 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5221 SDValue LoadEnvPtr = 5222 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5223 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5224 5225 5226 // Then copy the newly loaded TOC anchor to the TOC pointer. 5227 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5228 Chain = TOCVal.getValue(0); 5229 Glue = TOCVal.getValue(1); 5230 5231 // If the function call has an explicit 'nest' parameter, it takes the 5232 // place of the environment pointer. 5233 assert((!hasNest || !Subtarget.isAIXABI()) && 5234 "Nest parameter is not supported on AIX."); 5235 if (!hasNest) { 5236 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5237 Chain = EnvVal.getValue(0); 5238 Glue = EnvVal.getValue(1); 5239 } 5240 5241 // The rest of the indirect call sequence is the same as the non-descriptor 5242 // DAG. 5243 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5244 } 5245 5246 static void 5247 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5248 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5249 SelectionDAG &DAG, 5250 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5251 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5252 const PPCSubtarget &Subtarget) { 5253 const bool IsPPC64 = Subtarget.isPPC64(); 5254 // MVT for a general purpose register. 5255 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5256 5257 // First operand is always the chain. 5258 Ops.push_back(Chain); 5259 5260 // If it's a direct call pass the callee as the second operand. 5261 if (!CFlags.IsIndirect) 5262 Ops.push_back(Callee); 5263 else { 5264 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5265 5266 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5267 // on the stack (this would have been done in `LowerCall_64SVR4` or 5268 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5269 // represents both the indirect branch and a load that restores the TOC 5270 // pointer from the linkage area. The operand for the TOC restore is an add 5271 // of the TOC save offset to the stack pointer. This must be the second 5272 // operand: after the chain input but before any other variadic arguments. 5273 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5274 // saved or used. 5275 if (isTOCSaveRestoreRequired(Subtarget)) { 5276 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5277 5278 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5279 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5280 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5281 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5282 Ops.push_back(AddTOC); 5283 } 5284 5285 // Add the register used for the environment pointer. 5286 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5287 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5288 RegVT)); 5289 5290 5291 // Add CTR register as callee so a bctr can be emitted later. 5292 if (CFlags.IsTailCall) 5293 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5294 } 5295 5296 // If this is a tail call add stack pointer delta. 5297 if (CFlags.IsTailCall) 5298 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5299 5300 // Add argument registers to the end of the list so that they are known live 5301 // into the call. 5302 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5303 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5304 RegsToPass[i].second.getValueType())); 5305 5306 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5307 // no way to mark dependencies as implicit here. 5308 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5309 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5310 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5311 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5312 5313 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5314 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5315 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5316 5317 // Add a register mask operand representing the call-preserved registers. 5318 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5319 const uint32_t *Mask = 5320 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5321 assert(Mask && "Missing call preserved mask for calling convention"); 5322 Ops.push_back(DAG.getRegisterMask(Mask)); 5323 5324 // If the glue is valid, it is the last operand. 5325 if (Glue.getNode()) 5326 Ops.push_back(Glue); 5327 } 5328 5329 SDValue PPCTargetLowering::FinishCall( 5330 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5331 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5332 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5333 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5334 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5335 5336 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5337 Subtarget.isAIXABI()) 5338 setUsesTOCBasePtr(DAG); 5339 5340 unsigned CallOpc = 5341 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5342 Subtarget, DAG.getTarget()); 5343 5344 if (!CFlags.IsIndirect) 5345 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5346 else if (Subtarget.usesFunctionDescriptors()) 5347 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5348 dl, CFlags.HasNest, Subtarget); 5349 else 5350 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5351 5352 // Build the operand list for the call instruction. 5353 SmallVector<SDValue, 8> Ops; 5354 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5355 SPDiff, Subtarget); 5356 5357 // Emit tail call. 5358 if (CFlags.IsTailCall) { 5359 // Indirect tail call when using PC Relative calls do not have the same 5360 // constraints. 5361 assert(((Callee.getOpcode() == ISD::Register && 5362 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5363 Callee.getOpcode() == ISD::TargetExternalSymbol || 5364 Callee.getOpcode() == ISD::TargetGlobalAddress || 5365 isa<ConstantSDNode>(Callee) || 5366 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5367 "Expecting a global address, external symbol, absolute value, " 5368 "register or an indirect tail call when PC Relative calls are " 5369 "used."); 5370 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5371 assert(CallOpc == PPCISD::TC_RETURN && 5372 "Unexpected call opcode for a tail call."); 5373 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5374 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5375 } 5376 5377 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5378 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5379 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5380 Glue = Chain.getValue(1); 5381 5382 // When performing tail call optimization the callee pops its arguments off 5383 // the stack. Account for this here so these bytes can be pushed back on in 5384 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5385 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5386 getTargetMachine().Options.GuaranteedTailCallOpt) 5387 ? NumBytes 5388 : 0; 5389 5390 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5391 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5392 Glue, dl); 5393 Glue = Chain.getValue(1); 5394 5395 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5396 DAG, InVals); 5397 } 5398 5399 SDValue 5400 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5401 SmallVectorImpl<SDValue> &InVals) const { 5402 SelectionDAG &DAG = CLI.DAG; 5403 SDLoc &dl = CLI.DL; 5404 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5405 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5406 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5407 SDValue Chain = CLI.Chain; 5408 SDValue Callee = CLI.Callee; 5409 bool &isTailCall = CLI.IsTailCall; 5410 CallingConv::ID CallConv = CLI.CallConv; 5411 bool isVarArg = CLI.IsVarArg; 5412 bool isPatchPoint = CLI.IsPatchPoint; 5413 const CallBase *CB = CLI.CB; 5414 5415 if (isTailCall) { 5416 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5417 isTailCall = false; 5418 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5419 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5420 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5421 else 5422 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5423 Ins, DAG); 5424 if (isTailCall) { 5425 ++NumTailCalls; 5426 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5427 ++NumSiblingCalls; 5428 5429 // PC Relative calls no longer guarantee that the callee is a Global 5430 // Address Node. The callee could be an indirect tail call in which 5431 // case the SDValue for the callee could be a load (to load the address 5432 // of a function pointer) or it may be a register copy (to move the 5433 // address of the callee from a function parameter into a virtual 5434 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5435 assert((Subtarget.isUsingPCRelativeCalls() || 5436 isa<GlobalAddressSDNode>(Callee)) && 5437 "Callee should be an llvm::Function object."); 5438 5439 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5440 << "\nTCO callee: "); 5441 LLVM_DEBUG(Callee.dump()); 5442 } 5443 } 5444 5445 if (!isTailCall && CB && CB->isMustTailCall()) 5446 report_fatal_error("failed to perform tail call elimination on a call " 5447 "site marked musttail"); 5448 5449 // When long calls (i.e. indirect calls) are always used, calls are always 5450 // made via function pointer. If we have a function name, first translate it 5451 // into a pointer. 5452 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5453 !isTailCall) 5454 Callee = LowerGlobalAddress(Callee, DAG); 5455 5456 CallFlags CFlags( 5457 CallConv, isTailCall, isVarArg, isPatchPoint, 5458 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5459 // hasNest 5460 Subtarget.is64BitELFABI() && 5461 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5462 CLI.NoMerge); 5463 5464 if (Subtarget.isAIXABI()) 5465 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5466 InVals, CB); 5467 5468 assert(Subtarget.isSVR4ABI()); 5469 if (Subtarget.isPPC64()) 5470 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5471 InVals, CB); 5472 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5473 InVals, CB); 5474 } 5475 5476 SDValue PPCTargetLowering::LowerCall_32SVR4( 5477 SDValue Chain, SDValue Callee, CallFlags CFlags, 5478 const SmallVectorImpl<ISD::OutputArg> &Outs, 5479 const SmallVectorImpl<SDValue> &OutVals, 5480 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5481 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5482 const CallBase *CB) const { 5483 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5484 // of the 32-bit SVR4 ABI stack frame layout. 5485 5486 const CallingConv::ID CallConv = CFlags.CallConv; 5487 const bool IsVarArg = CFlags.IsVarArg; 5488 const bool IsTailCall = CFlags.IsTailCall; 5489 5490 assert((CallConv == CallingConv::C || 5491 CallConv == CallingConv::Cold || 5492 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5493 5494 const Align PtrAlign(4); 5495 5496 MachineFunction &MF = DAG.getMachineFunction(); 5497 5498 // Mark this function as potentially containing a function that contains a 5499 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5500 // and restoring the callers stack pointer in this functions epilog. This is 5501 // done because by tail calling the called function might overwrite the value 5502 // in this function's (MF) stack pointer stack slot 0(SP). 5503 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5504 CallConv == CallingConv::Fast) 5505 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5506 5507 // Count how many bytes are to be pushed on the stack, including the linkage 5508 // area, parameter list area and the part of the local variable space which 5509 // contains copies of aggregates which are passed by value. 5510 5511 // Assign locations to all of the outgoing arguments. 5512 SmallVector<CCValAssign, 16> ArgLocs; 5513 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5514 5515 // Reserve space for the linkage area on the stack. 5516 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5517 PtrAlign); 5518 if (useSoftFloat()) 5519 CCInfo.PreAnalyzeCallOperands(Outs); 5520 5521 if (IsVarArg) { 5522 // Handle fixed and variable vector arguments differently. 5523 // Fixed vector arguments go into registers as long as registers are 5524 // available. Variable vector arguments always go into memory. 5525 unsigned NumArgs = Outs.size(); 5526 5527 for (unsigned i = 0; i != NumArgs; ++i) { 5528 MVT ArgVT = Outs[i].VT; 5529 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5530 bool Result; 5531 5532 if (Outs[i].IsFixed) { 5533 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5534 CCInfo); 5535 } else { 5536 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5537 ArgFlags, CCInfo); 5538 } 5539 5540 if (Result) { 5541 #ifndef NDEBUG 5542 errs() << "Call operand #" << i << " has unhandled type " 5543 << EVT(ArgVT).getEVTString() << "\n"; 5544 #endif 5545 llvm_unreachable(nullptr); 5546 } 5547 } 5548 } else { 5549 // All arguments are treated the same. 5550 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5551 } 5552 CCInfo.clearWasPPCF128(); 5553 5554 // Assign locations to all of the outgoing aggregate by value arguments. 5555 SmallVector<CCValAssign, 16> ByValArgLocs; 5556 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5557 5558 // Reserve stack space for the allocations in CCInfo. 5559 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5560 5561 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5562 5563 // Size of the linkage area, parameter list area and the part of the local 5564 // space variable where copies of aggregates which are passed by value are 5565 // stored. 5566 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5567 5568 // Calculate by how many bytes the stack has to be adjusted in case of tail 5569 // call optimization. 5570 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5571 5572 // Adjust the stack pointer for the new arguments... 5573 // These operations are automatically eliminated by the prolog/epilog pass 5574 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5575 SDValue CallSeqStart = Chain; 5576 5577 // Load the return address and frame pointer so it can be moved somewhere else 5578 // later. 5579 SDValue LROp, FPOp; 5580 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5581 5582 // Set up a copy of the stack pointer for use loading and storing any 5583 // arguments that may not fit in the registers available for argument 5584 // passing. 5585 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5586 5587 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5588 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5589 SmallVector<SDValue, 8> MemOpChains; 5590 5591 bool seenFloatArg = false; 5592 // Walk the register/memloc assignments, inserting copies/loads. 5593 // i - Tracks the index into the list of registers allocated for the call 5594 // RealArgIdx - Tracks the index into the list of actual function arguments 5595 // j - Tracks the index into the list of byval arguments 5596 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5597 i != e; 5598 ++i, ++RealArgIdx) { 5599 CCValAssign &VA = ArgLocs[i]; 5600 SDValue Arg = OutVals[RealArgIdx]; 5601 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5602 5603 if (Flags.isByVal()) { 5604 // Argument is an aggregate which is passed by value, thus we need to 5605 // create a copy of it in the local variable space of the current stack 5606 // frame (which is the stack frame of the caller) and pass the address of 5607 // this copy to the callee. 5608 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5609 CCValAssign &ByValVA = ByValArgLocs[j++]; 5610 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5611 5612 // Memory reserved in the local variable space of the callers stack frame. 5613 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5614 5615 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5616 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5617 StackPtr, PtrOff); 5618 5619 // Create a copy of the argument in the local area of the current 5620 // stack frame. 5621 SDValue MemcpyCall = 5622 CreateCopyOfByValArgument(Arg, PtrOff, 5623 CallSeqStart.getNode()->getOperand(0), 5624 Flags, DAG, dl); 5625 5626 // This must go outside the CALLSEQ_START..END. 5627 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5628 SDLoc(MemcpyCall)); 5629 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5630 NewCallSeqStart.getNode()); 5631 Chain = CallSeqStart = NewCallSeqStart; 5632 5633 // Pass the address of the aggregate copy on the stack either in a 5634 // physical register or in the parameter list area of the current stack 5635 // frame to the callee. 5636 Arg = PtrOff; 5637 } 5638 5639 // When useCRBits() is true, there can be i1 arguments. 5640 // It is because getRegisterType(MVT::i1) => MVT::i1, 5641 // and for other integer types getRegisterType() => MVT::i32. 5642 // Extend i1 and ensure callee will get i32. 5643 if (Arg.getValueType() == MVT::i1) 5644 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5645 dl, MVT::i32, Arg); 5646 5647 if (VA.isRegLoc()) { 5648 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5649 // Put argument in a physical register. 5650 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5651 bool IsLE = Subtarget.isLittleEndian(); 5652 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5653 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5654 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5655 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5656 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5657 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5658 SVal.getValue(0))); 5659 } else 5660 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5661 } else { 5662 // Put argument in the parameter list area of the current stack frame. 5663 assert(VA.isMemLoc()); 5664 unsigned LocMemOffset = VA.getLocMemOffset(); 5665 5666 if (!IsTailCall) { 5667 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5668 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5669 StackPtr, PtrOff); 5670 5671 MemOpChains.push_back( 5672 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5673 } else { 5674 // Calculate and remember argument location. 5675 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5676 TailCallArguments); 5677 } 5678 } 5679 } 5680 5681 if (!MemOpChains.empty()) 5682 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5683 5684 // Build a sequence of copy-to-reg nodes chained together with token chain 5685 // and flag operands which copy the outgoing args into the appropriate regs. 5686 SDValue InFlag; 5687 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5688 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5689 RegsToPass[i].second, InFlag); 5690 InFlag = Chain.getValue(1); 5691 } 5692 5693 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5694 // registers. 5695 if (IsVarArg) { 5696 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5697 SDValue Ops[] = { Chain, InFlag }; 5698 5699 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5700 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5701 5702 InFlag = Chain.getValue(1); 5703 } 5704 5705 if (IsTailCall) 5706 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5707 TailCallArguments); 5708 5709 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5710 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5711 } 5712 5713 // Copy an argument into memory, being careful to do this outside the 5714 // call sequence for the call to which the argument belongs. 5715 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5716 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5717 SelectionDAG &DAG, const SDLoc &dl) const { 5718 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5719 CallSeqStart.getNode()->getOperand(0), 5720 Flags, DAG, dl); 5721 // The MEMCPY must go outside the CALLSEQ_START..END. 5722 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5723 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5724 SDLoc(MemcpyCall)); 5725 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5726 NewCallSeqStart.getNode()); 5727 return NewCallSeqStart; 5728 } 5729 5730 SDValue PPCTargetLowering::LowerCall_64SVR4( 5731 SDValue Chain, SDValue Callee, CallFlags CFlags, 5732 const SmallVectorImpl<ISD::OutputArg> &Outs, 5733 const SmallVectorImpl<SDValue> &OutVals, 5734 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5735 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5736 const CallBase *CB) const { 5737 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5738 bool isLittleEndian = Subtarget.isLittleEndian(); 5739 unsigned NumOps = Outs.size(); 5740 bool IsSibCall = false; 5741 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5742 5743 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5744 unsigned PtrByteSize = 8; 5745 5746 MachineFunction &MF = DAG.getMachineFunction(); 5747 5748 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5749 IsSibCall = true; 5750 5751 // Mark this function as potentially containing a function that contains a 5752 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5753 // and restoring the callers stack pointer in this functions epilog. This is 5754 // done because by tail calling the called function might overwrite the value 5755 // in this function's (MF) stack pointer stack slot 0(SP). 5756 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5757 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5758 5759 assert(!(IsFastCall && CFlags.IsVarArg) && 5760 "fastcc not supported on varargs functions"); 5761 5762 // Count how many bytes are to be pushed on the stack, including the linkage 5763 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5764 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5765 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5766 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5767 unsigned NumBytes = LinkageSize; 5768 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5769 5770 static const MCPhysReg GPR[] = { 5771 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5772 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5773 }; 5774 static const MCPhysReg VR[] = { 5775 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5776 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5777 }; 5778 5779 const unsigned NumGPRs = array_lengthof(GPR); 5780 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5781 const unsigned NumVRs = array_lengthof(VR); 5782 5783 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5784 // can be passed to the callee in registers. 5785 // For the fast calling convention, there is another check below. 5786 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5787 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5788 if (!HasParameterArea) { 5789 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5790 unsigned AvailableFPRs = NumFPRs; 5791 unsigned AvailableVRs = NumVRs; 5792 unsigned NumBytesTmp = NumBytes; 5793 for (unsigned i = 0; i != NumOps; ++i) { 5794 if (Outs[i].Flags.isNest()) continue; 5795 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5796 PtrByteSize, LinkageSize, ParamAreaSize, 5797 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5798 HasParameterArea = true; 5799 } 5800 } 5801 5802 // When using the fast calling convention, we don't provide backing for 5803 // arguments that will be in registers. 5804 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5805 5806 // Avoid allocating parameter area for fastcc functions if all the arguments 5807 // can be passed in the registers. 5808 if (IsFastCall) 5809 HasParameterArea = false; 5810 5811 // Add up all the space actually used. 5812 for (unsigned i = 0; i != NumOps; ++i) { 5813 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5814 EVT ArgVT = Outs[i].VT; 5815 EVT OrigVT = Outs[i].ArgVT; 5816 5817 if (Flags.isNest()) 5818 continue; 5819 5820 if (IsFastCall) { 5821 if (Flags.isByVal()) { 5822 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5823 if (NumGPRsUsed > NumGPRs) 5824 HasParameterArea = true; 5825 } else { 5826 switch (ArgVT.getSimpleVT().SimpleTy) { 5827 default: llvm_unreachable("Unexpected ValueType for argument!"); 5828 case MVT::i1: 5829 case MVT::i32: 5830 case MVT::i64: 5831 if (++NumGPRsUsed <= NumGPRs) 5832 continue; 5833 break; 5834 case MVT::v4i32: 5835 case MVT::v8i16: 5836 case MVT::v16i8: 5837 case MVT::v2f64: 5838 case MVT::v2i64: 5839 case MVT::v1i128: 5840 case MVT::f128: 5841 if (++NumVRsUsed <= NumVRs) 5842 continue; 5843 break; 5844 case MVT::v4f32: 5845 if (++NumVRsUsed <= NumVRs) 5846 continue; 5847 break; 5848 case MVT::f32: 5849 case MVT::f64: 5850 if (++NumFPRsUsed <= NumFPRs) 5851 continue; 5852 break; 5853 } 5854 HasParameterArea = true; 5855 } 5856 } 5857 5858 /* Respect alignment of argument on the stack. */ 5859 auto Alignement = 5860 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5861 NumBytes = alignTo(NumBytes, Alignement); 5862 5863 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5864 if (Flags.isInConsecutiveRegsLast()) 5865 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5866 } 5867 5868 unsigned NumBytesActuallyUsed = NumBytes; 5869 5870 // In the old ELFv1 ABI, 5871 // the prolog code of the callee may store up to 8 GPR argument registers to 5872 // the stack, allowing va_start to index over them in memory if its varargs. 5873 // Because we cannot tell if this is needed on the caller side, we have to 5874 // conservatively assume that it is needed. As such, make sure we have at 5875 // least enough stack space for the caller to store the 8 GPRs. 5876 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5877 // really requires memory operands, e.g. a vararg function. 5878 if (HasParameterArea) 5879 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5880 else 5881 NumBytes = LinkageSize; 5882 5883 // Tail call needs the stack to be aligned. 5884 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5885 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5886 5887 int SPDiff = 0; 5888 5889 // Calculate by how many bytes the stack has to be adjusted in case of tail 5890 // call optimization. 5891 if (!IsSibCall) 5892 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 5893 5894 // To protect arguments on the stack from being clobbered in a tail call, 5895 // force all the loads to happen before doing any other lowering. 5896 if (CFlags.IsTailCall) 5897 Chain = DAG.getStackArgumentTokenFactor(Chain); 5898 5899 // Adjust the stack pointer for the new arguments... 5900 // These operations are automatically eliminated by the prolog/epilog pass 5901 if (!IsSibCall) 5902 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5903 SDValue CallSeqStart = Chain; 5904 5905 // Load the return address and frame pointer so it can be move somewhere else 5906 // later. 5907 SDValue LROp, FPOp; 5908 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5909 5910 // Set up a copy of the stack pointer for use loading and storing any 5911 // arguments that may not fit in the registers available for argument 5912 // passing. 5913 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5914 5915 // Figure out which arguments are going to go in registers, and which in 5916 // memory. Also, if this is a vararg function, floating point operations 5917 // must be stored to our stack, and loaded into integer regs as well, if 5918 // any integer regs are available for argument passing. 5919 unsigned ArgOffset = LinkageSize; 5920 5921 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5922 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5923 5924 SmallVector<SDValue, 8> MemOpChains; 5925 for (unsigned i = 0; i != NumOps; ++i) { 5926 SDValue Arg = OutVals[i]; 5927 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5928 EVT ArgVT = Outs[i].VT; 5929 EVT OrigVT = Outs[i].ArgVT; 5930 5931 // PtrOff will be used to store the current argument to the stack if a 5932 // register cannot be found for it. 5933 SDValue PtrOff; 5934 5935 // We re-align the argument offset for each argument, except when using the 5936 // fast calling convention, when we need to make sure we do that only when 5937 // we'll actually use a stack slot. 5938 auto ComputePtrOff = [&]() { 5939 /* Respect alignment of argument on the stack. */ 5940 auto Alignment = 5941 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5942 ArgOffset = alignTo(ArgOffset, Alignment); 5943 5944 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5945 5946 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5947 }; 5948 5949 if (!IsFastCall) { 5950 ComputePtrOff(); 5951 5952 /* Compute GPR index associated with argument offset. */ 5953 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5954 GPR_idx = std::min(GPR_idx, NumGPRs); 5955 } 5956 5957 // Promote integers to 64-bit values. 5958 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5959 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5960 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5961 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5962 } 5963 5964 // FIXME memcpy is used way more than necessary. Correctness first. 5965 // Note: "by value" is code for passing a structure by value, not 5966 // basic types. 5967 if (Flags.isByVal()) { 5968 // Note: Size includes alignment padding, so 5969 // struct x { short a; char b; } 5970 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5971 // These are the proper values we need for right-justifying the 5972 // aggregate in a parameter register. 5973 unsigned Size = Flags.getByValSize(); 5974 5975 // An empty aggregate parameter takes up no storage and no 5976 // registers. 5977 if (Size == 0) 5978 continue; 5979 5980 if (IsFastCall) 5981 ComputePtrOff(); 5982 5983 // All aggregates smaller than 8 bytes must be passed right-justified. 5984 if (Size==1 || Size==2 || Size==4) { 5985 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5986 if (GPR_idx != NumGPRs) { 5987 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5988 MachinePointerInfo(), VT); 5989 MemOpChains.push_back(Load.getValue(1)); 5990 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5991 5992 ArgOffset += PtrByteSize; 5993 continue; 5994 } 5995 } 5996 5997 if (GPR_idx == NumGPRs && Size < 8) { 5998 SDValue AddPtr = PtrOff; 5999 if (!isLittleEndian) { 6000 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6001 PtrOff.getValueType()); 6002 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6003 } 6004 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6005 CallSeqStart, 6006 Flags, DAG, dl); 6007 ArgOffset += PtrByteSize; 6008 continue; 6009 } 6010 // Copy entire object into memory. There are cases where gcc-generated 6011 // code assumes it is there, even if it could be put entirely into 6012 // registers. (This is not what the doc says.) 6013 6014 // FIXME: The above statement is likely due to a misunderstanding of the 6015 // documents. All arguments must be copied into the parameter area BY 6016 // THE CALLEE in the event that the callee takes the address of any 6017 // formal argument. That has not yet been implemented. However, it is 6018 // reasonable to use the stack area as a staging area for the register 6019 // load. 6020 6021 // Skip this for small aggregates, as we will use the same slot for a 6022 // right-justified copy, below. 6023 if (Size >= 8) 6024 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6025 CallSeqStart, 6026 Flags, DAG, dl); 6027 6028 // When a register is available, pass a small aggregate right-justified. 6029 if (Size < 8 && GPR_idx != NumGPRs) { 6030 // The easiest way to get this right-justified in a register 6031 // is to copy the structure into the rightmost portion of a 6032 // local variable slot, then load the whole slot into the 6033 // register. 6034 // FIXME: The memcpy seems to produce pretty awful code for 6035 // small aggregates, particularly for packed ones. 6036 // FIXME: It would be preferable to use the slot in the 6037 // parameter save area instead of a new local variable. 6038 SDValue AddPtr = PtrOff; 6039 if (!isLittleEndian) { 6040 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6041 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6042 } 6043 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6044 CallSeqStart, 6045 Flags, DAG, dl); 6046 6047 // Load the slot into the register. 6048 SDValue Load = 6049 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6050 MemOpChains.push_back(Load.getValue(1)); 6051 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6052 6053 // Done with this argument. 6054 ArgOffset += PtrByteSize; 6055 continue; 6056 } 6057 6058 // For aggregates larger than PtrByteSize, copy the pieces of the 6059 // object that fit into registers from the parameter save area. 6060 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6061 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6062 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6063 if (GPR_idx != NumGPRs) { 6064 SDValue Load = 6065 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6066 MemOpChains.push_back(Load.getValue(1)); 6067 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6068 ArgOffset += PtrByteSize; 6069 } else { 6070 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6071 break; 6072 } 6073 } 6074 continue; 6075 } 6076 6077 switch (Arg.getSimpleValueType().SimpleTy) { 6078 default: llvm_unreachable("Unexpected ValueType for argument!"); 6079 case MVT::i1: 6080 case MVT::i32: 6081 case MVT::i64: 6082 if (Flags.isNest()) { 6083 // The 'nest' parameter, if any, is passed in R11. 6084 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6085 break; 6086 } 6087 6088 // These can be scalar arguments or elements of an integer array type 6089 // passed directly. Clang may use those instead of "byval" aggregate 6090 // types to avoid forcing arguments to memory unnecessarily. 6091 if (GPR_idx != NumGPRs) { 6092 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6093 } else { 6094 if (IsFastCall) 6095 ComputePtrOff(); 6096 6097 assert(HasParameterArea && 6098 "Parameter area must exist to pass an argument in memory."); 6099 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6100 true, CFlags.IsTailCall, false, MemOpChains, 6101 TailCallArguments, dl); 6102 if (IsFastCall) 6103 ArgOffset += PtrByteSize; 6104 } 6105 if (!IsFastCall) 6106 ArgOffset += PtrByteSize; 6107 break; 6108 case MVT::f32: 6109 case MVT::f64: { 6110 // These can be scalar arguments or elements of a float array type 6111 // passed directly. The latter are used to implement ELFv2 homogenous 6112 // float aggregates. 6113 6114 // Named arguments go into FPRs first, and once they overflow, the 6115 // remaining arguments go into GPRs and then the parameter save area. 6116 // Unnamed arguments for vararg functions always go to GPRs and 6117 // then the parameter save area. For now, put all arguments to vararg 6118 // routines always in both locations (FPR *and* GPR or stack slot). 6119 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6120 bool NeededLoad = false; 6121 6122 // First load the argument into the next available FPR. 6123 if (FPR_idx != NumFPRs) 6124 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6125 6126 // Next, load the argument into GPR or stack slot if needed. 6127 if (!NeedGPROrStack) 6128 ; 6129 else if (GPR_idx != NumGPRs && !IsFastCall) { 6130 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6131 // once we support fp <-> gpr moves. 6132 6133 // In the non-vararg case, this can only ever happen in the 6134 // presence of f32 array types, since otherwise we never run 6135 // out of FPRs before running out of GPRs. 6136 SDValue ArgVal; 6137 6138 // Double values are always passed in a single GPR. 6139 if (Arg.getValueType() != MVT::f32) { 6140 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6141 6142 // Non-array float values are extended and passed in a GPR. 6143 } else if (!Flags.isInConsecutiveRegs()) { 6144 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6145 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6146 6147 // If we have an array of floats, we collect every odd element 6148 // together with its predecessor into one GPR. 6149 } else if (ArgOffset % PtrByteSize != 0) { 6150 SDValue Lo, Hi; 6151 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6152 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6153 if (!isLittleEndian) 6154 std::swap(Lo, Hi); 6155 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6156 6157 // The final element, if even, goes into the first half of a GPR. 6158 } else if (Flags.isInConsecutiveRegsLast()) { 6159 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6160 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6161 if (!isLittleEndian) 6162 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6163 DAG.getConstant(32, dl, MVT::i32)); 6164 6165 // Non-final even elements are skipped; they will be handled 6166 // together the with subsequent argument on the next go-around. 6167 } else 6168 ArgVal = SDValue(); 6169 6170 if (ArgVal.getNode()) 6171 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6172 } else { 6173 if (IsFastCall) 6174 ComputePtrOff(); 6175 6176 // Single-precision floating-point values are mapped to the 6177 // second (rightmost) word of the stack doubleword. 6178 if (Arg.getValueType() == MVT::f32 && 6179 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6180 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6181 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6182 } 6183 6184 assert(HasParameterArea && 6185 "Parameter area must exist to pass an argument in memory."); 6186 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6187 true, CFlags.IsTailCall, false, MemOpChains, 6188 TailCallArguments, dl); 6189 6190 NeededLoad = true; 6191 } 6192 // When passing an array of floats, the array occupies consecutive 6193 // space in the argument area; only round up to the next doubleword 6194 // at the end of the array. Otherwise, each float takes 8 bytes. 6195 if (!IsFastCall || NeededLoad) { 6196 ArgOffset += (Arg.getValueType() == MVT::f32 && 6197 Flags.isInConsecutiveRegs()) ? 4 : 8; 6198 if (Flags.isInConsecutiveRegsLast()) 6199 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6200 } 6201 break; 6202 } 6203 case MVT::v4f32: 6204 case MVT::v4i32: 6205 case MVT::v8i16: 6206 case MVT::v16i8: 6207 case MVT::v2f64: 6208 case MVT::v2i64: 6209 case MVT::v1i128: 6210 case MVT::f128: 6211 // These can be scalar arguments or elements of a vector array type 6212 // passed directly. The latter are used to implement ELFv2 homogenous 6213 // vector aggregates. 6214 6215 // For a varargs call, named arguments go into VRs or on the stack as 6216 // usual; unnamed arguments always go to the stack or the corresponding 6217 // GPRs when within range. For now, we always put the value in both 6218 // locations (or even all three). 6219 if (CFlags.IsVarArg) { 6220 assert(HasParameterArea && 6221 "Parameter area must exist if we have a varargs call."); 6222 // We could elide this store in the case where the object fits 6223 // entirely in R registers. Maybe later. 6224 SDValue Store = 6225 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6226 MemOpChains.push_back(Store); 6227 if (VR_idx != NumVRs) { 6228 SDValue Load = 6229 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6230 MemOpChains.push_back(Load.getValue(1)); 6231 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6232 } 6233 ArgOffset += 16; 6234 for (unsigned i=0; i<16; i+=PtrByteSize) { 6235 if (GPR_idx == NumGPRs) 6236 break; 6237 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6238 DAG.getConstant(i, dl, PtrVT)); 6239 SDValue Load = 6240 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6241 MemOpChains.push_back(Load.getValue(1)); 6242 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6243 } 6244 break; 6245 } 6246 6247 // Non-varargs Altivec params go into VRs or on the stack. 6248 if (VR_idx != NumVRs) { 6249 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6250 } else { 6251 if (IsFastCall) 6252 ComputePtrOff(); 6253 6254 assert(HasParameterArea && 6255 "Parameter area must exist to pass an argument in memory."); 6256 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6257 true, CFlags.IsTailCall, true, MemOpChains, 6258 TailCallArguments, dl); 6259 if (IsFastCall) 6260 ArgOffset += 16; 6261 } 6262 6263 if (!IsFastCall) 6264 ArgOffset += 16; 6265 break; 6266 } 6267 } 6268 6269 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6270 "mismatch in size of parameter area"); 6271 (void)NumBytesActuallyUsed; 6272 6273 if (!MemOpChains.empty()) 6274 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6275 6276 // Check if this is an indirect call (MTCTR/BCTRL). 6277 // See prepareDescriptorIndirectCall and buildCallOperands for more 6278 // information about calls through function pointers in the 64-bit SVR4 ABI. 6279 if (CFlags.IsIndirect) { 6280 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6281 // caller in the TOC save area. 6282 if (isTOCSaveRestoreRequired(Subtarget)) { 6283 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6284 // Load r2 into a virtual register and store it to the TOC save area. 6285 setUsesTOCBasePtr(DAG); 6286 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6287 // TOC save area offset. 6288 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6289 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6290 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6291 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6292 MachinePointerInfo::getStack( 6293 DAG.getMachineFunction(), TOCSaveOffset)); 6294 } 6295 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6296 // This does not mean the MTCTR instruction must use R12; it's easier 6297 // to model this as an extra parameter, so do that. 6298 if (isELFv2ABI && !CFlags.IsPatchPoint) 6299 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6300 } 6301 6302 // Build a sequence of copy-to-reg nodes chained together with token chain 6303 // and flag operands which copy the outgoing args into the appropriate regs. 6304 SDValue InFlag; 6305 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6306 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6307 RegsToPass[i].second, InFlag); 6308 InFlag = Chain.getValue(1); 6309 } 6310 6311 if (CFlags.IsTailCall && !IsSibCall) 6312 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6313 TailCallArguments); 6314 6315 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6316 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6317 } 6318 6319 // Returns true when the shadow of a general purpose argument register 6320 // in the parameter save area is aligned to at least 'RequiredAlign'. 6321 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6322 assert(RequiredAlign.value() <= 16 && 6323 "Required alignment greater than stack alignment."); 6324 switch (Reg) { 6325 default: 6326 report_fatal_error("called on invalid register."); 6327 case PPC::R5: 6328 case PPC::R9: 6329 case PPC::X3: 6330 case PPC::X5: 6331 case PPC::X7: 6332 case PPC::X9: 6333 // These registers are 16 byte aligned which is the most strict aligment 6334 // we can support. 6335 return true; 6336 case PPC::R3: 6337 case PPC::R7: 6338 case PPC::X4: 6339 case PPC::X6: 6340 case PPC::X8: 6341 case PPC::X10: 6342 // The shadow of these registers in the PSA is 8 byte aligned. 6343 return RequiredAlign <= 8; 6344 case PPC::R4: 6345 case PPC::R6: 6346 case PPC::R8: 6347 case PPC::R10: 6348 return RequiredAlign <= 4; 6349 } 6350 } 6351 6352 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6353 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6354 CCState &S) { 6355 AIXCCState &State = static_cast<AIXCCState &>(S); 6356 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6357 State.getMachineFunction().getSubtarget()); 6358 const bool IsPPC64 = Subtarget.isPPC64(); 6359 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6360 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6361 6362 if (ValVT == MVT::f128) 6363 report_fatal_error("f128 is unimplemented on AIX."); 6364 6365 if (ArgFlags.isNest()) 6366 report_fatal_error("Nest arguments are unimplemented."); 6367 6368 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6369 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6370 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6371 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6372 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6373 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6374 6375 static const MCPhysReg VR[] = {// Vector registers. 6376 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6377 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6378 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6379 6380 if (ArgFlags.isByVal()) { 6381 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6382 report_fatal_error("Pass-by-value arguments with alignment greater than " 6383 "register width are not supported."); 6384 6385 const unsigned ByValSize = ArgFlags.getByValSize(); 6386 6387 // An empty aggregate parameter takes up no storage and no registers, 6388 // but needs a MemLoc for a stack slot for the formal arguments side. 6389 if (ByValSize == 0) { 6390 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6391 State.getNextStackOffset(), RegVT, 6392 LocInfo)); 6393 return false; 6394 } 6395 6396 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6397 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6398 for (const unsigned E = Offset + StackSize; Offset < E; 6399 Offset += PtrAlign.value()) { 6400 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6401 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6402 else { 6403 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6404 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6405 LocInfo)); 6406 break; 6407 } 6408 } 6409 return false; 6410 } 6411 6412 // Arguments always reserve parameter save area. 6413 switch (ValVT.SimpleTy) { 6414 default: 6415 report_fatal_error("Unhandled value type for argument."); 6416 case MVT::i64: 6417 // i64 arguments should have been split to i32 for PPC32. 6418 assert(IsPPC64 && "PPC32 should have split i64 values."); 6419 LLVM_FALLTHROUGH; 6420 case MVT::i1: 6421 case MVT::i32: { 6422 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6423 // AIX integer arguments are always passed in register width. 6424 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6425 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6426 : CCValAssign::LocInfo::ZExt; 6427 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6428 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6429 else 6430 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6431 6432 return false; 6433 } 6434 case MVT::f32: 6435 case MVT::f64: { 6436 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6437 const unsigned StoreSize = LocVT.getStoreSize(); 6438 // Floats are always 4-byte aligned in the PSA on AIX. 6439 // This includes f64 in 64-bit mode for ABI compatibility. 6440 const unsigned Offset = 6441 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6442 unsigned FReg = State.AllocateReg(FPR); 6443 if (FReg) 6444 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6445 6446 // Reserve and initialize GPRs or initialize the PSA as required. 6447 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6448 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6449 assert(FReg && "An FPR should be available when a GPR is reserved."); 6450 if (State.isVarArg()) { 6451 // Successfully reserved GPRs are only initialized for vararg calls. 6452 // Custom handling is required for: 6453 // f64 in PPC32 needs to be split into 2 GPRs. 6454 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6455 State.addLoc( 6456 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6457 } 6458 } else { 6459 // If there are insufficient GPRs, the PSA needs to be initialized. 6460 // Initialization occurs even if an FPR was initialized for 6461 // compatibility with the AIX XL compiler. The full memory for the 6462 // argument will be initialized even if a prior word is saved in GPR. 6463 // A custom memLoc is used when the argument also passes in FPR so 6464 // that the callee handling can skip over it easily. 6465 State.addLoc( 6466 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6467 LocInfo) 6468 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6469 break; 6470 } 6471 } 6472 6473 return false; 6474 } 6475 case MVT::v4f32: 6476 case MVT::v4i32: 6477 case MVT::v8i16: 6478 case MVT::v16i8: 6479 case MVT::v2i64: 6480 case MVT::v2f64: 6481 case MVT::v1i128: { 6482 const unsigned VecSize = 16; 6483 const Align VecAlign(VecSize); 6484 6485 if (!State.isVarArg()) { 6486 // If there are vector registers remaining we don't consume any stack 6487 // space. 6488 if (unsigned VReg = State.AllocateReg(VR)) { 6489 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6490 return false; 6491 } 6492 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6493 // might be allocated in the portion of the PSA that is shadowed by the 6494 // GPRs. 6495 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6496 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6497 return false; 6498 } 6499 6500 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6501 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6502 6503 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6504 // Burn any underaligned registers and their shadowed stack space until 6505 // we reach the required alignment. 6506 while (NextRegIndex != GPRs.size() && 6507 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6508 // Shadow allocate register and its stack shadow. 6509 unsigned Reg = State.AllocateReg(GPRs); 6510 State.AllocateStack(PtrSize, PtrAlign); 6511 assert(Reg && "Allocating register unexpectedly failed."); 6512 (void)Reg; 6513 NextRegIndex = State.getFirstUnallocated(GPRs); 6514 } 6515 6516 // Vectors that are passed as fixed arguments are handled differently. 6517 // They are passed in VRs if any are available (unlike arguments passed 6518 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6519 // functions) 6520 if (State.isFixed(ValNo)) { 6521 if (unsigned VReg = State.AllocateReg(VR)) { 6522 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6523 // Shadow allocate GPRs and stack space even though we pass in a VR. 6524 for (unsigned I = 0; I != VecSize; I += PtrSize) 6525 State.AllocateReg(GPRs); 6526 State.AllocateStack(VecSize, VecAlign); 6527 return false; 6528 } 6529 // No vector registers remain so pass on the stack. 6530 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6531 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6532 return false; 6533 } 6534 6535 // If all GPRS are consumed then we pass the argument fully on the stack. 6536 if (NextRegIndex == GPRs.size()) { 6537 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6538 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6539 return false; 6540 } 6541 6542 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6543 // half of the argument, and then need to pass the remaining half on the 6544 // stack. 6545 if (GPRs[NextRegIndex] == PPC::R9) { 6546 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6547 State.addLoc( 6548 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6549 6550 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6551 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6552 assert(FirstReg && SecondReg && 6553 "Allocating R9 or R10 unexpectedly failed."); 6554 State.addLoc( 6555 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6556 State.addLoc( 6557 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6558 return false; 6559 } 6560 6561 // We have enough GPRs to fully pass the vector argument, and we have 6562 // already consumed any underaligned registers. Start with the custom 6563 // MemLoc and then the custom RegLocs. 6564 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6565 State.addLoc( 6566 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6567 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6568 const unsigned Reg = State.AllocateReg(GPRs); 6569 assert(Reg && "Failed to allocated register for vararg vector argument"); 6570 State.addLoc( 6571 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6572 } 6573 return false; 6574 } 6575 } 6576 return true; 6577 } 6578 6579 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6580 bool IsPPC64) { 6581 assert((IsPPC64 || SVT != MVT::i64) && 6582 "i64 should have been split for 32-bit codegen."); 6583 6584 switch (SVT) { 6585 default: 6586 report_fatal_error("Unexpected value type for formal argument"); 6587 case MVT::i1: 6588 case MVT::i32: 6589 case MVT::i64: 6590 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6591 case MVT::f32: 6592 return &PPC::F4RCRegClass; 6593 case MVT::f64: 6594 return &PPC::F8RCRegClass; 6595 case MVT::v4f32: 6596 case MVT::v4i32: 6597 case MVT::v8i16: 6598 case MVT::v16i8: 6599 case MVT::v2i64: 6600 case MVT::v2f64: 6601 case MVT::v1i128: 6602 return &PPC::VRRCRegClass; 6603 } 6604 } 6605 6606 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6607 SelectionDAG &DAG, SDValue ArgValue, 6608 MVT LocVT, const SDLoc &dl) { 6609 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6610 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6611 6612 if (Flags.isSExt()) 6613 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6614 DAG.getValueType(ValVT)); 6615 else if (Flags.isZExt()) 6616 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6617 DAG.getValueType(ValVT)); 6618 6619 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6620 } 6621 6622 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6623 const unsigned LASize = FL->getLinkageSize(); 6624 6625 if (PPC::GPRCRegClass.contains(Reg)) { 6626 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6627 "Reg must be a valid argument register!"); 6628 return LASize + 4 * (Reg - PPC::R3); 6629 } 6630 6631 if (PPC::G8RCRegClass.contains(Reg)) { 6632 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6633 "Reg must be a valid argument register!"); 6634 return LASize + 8 * (Reg - PPC::X3); 6635 } 6636 6637 llvm_unreachable("Only general purpose registers expected."); 6638 } 6639 6640 // AIX ABI Stack Frame Layout: 6641 // 6642 // Low Memory +--------------------------------------------+ 6643 // SP +---> | Back chain | ---+ 6644 // | +--------------------------------------------+ | 6645 // | | Saved Condition Register | | 6646 // | +--------------------------------------------+ | 6647 // | | Saved Linkage Register | | 6648 // | +--------------------------------------------+ | Linkage Area 6649 // | | Reserved for compilers | | 6650 // | +--------------------------------------------+ | 6651 // | | Reserved for binders | | 6652 // | +--------------------------------------------+ | 6653 // | | Saved TOC pointer | ---+ 6654 // | +--------------------------------------------+ 6655 // | | Parameter save area | 6656 // | +--------------------------------------------+ 6657 // | | Alloca space | 6658 // | +--------------------------------------------+ 6659 // | | Local variable space | 6660 // | +--------------------------------------------+ 6661 // | | Float/int conversion temporary | 6662 // | +--------------------------------------------+ 6663 // | | Save area for AltiVec registers | 6664 // | +--------------------------------------------+ 6665 // | | AltiVec alignment padding | 6666 // | +--------------------------------------------+ 6667 // | | Save area for VRSAVE register | 6668 // | +--------------------------------------------+ 6669 // | | Save area for General Purpose registers | 6670 // | +--------------------------------------------+ 6671 // | | Save area for Floating Point registers | 6672 // | +--------------------------------------------+ 6673 // +---- | Back chain | 6674 // High Memory +--------------------------------------------+ 6675 // 6676 // Specifications: 6677 // AIX 7.2 Assembler Language Reference 6678 // Subroutine linkage convention 6679 6680 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6681 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6682 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6683 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6684 6685 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6686 CallConv == CallingConv::Fast) && 6687 "Unexpected calling convention!"); 6688 6689 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6690 report_fatal_error("Tail call support is unimplemented on AIX."); 6691 6692 if (useSoftFloat()) 6693 report_fatal_error("Soft float support is unimplemented on AIX."); 6694 6695 const PPCSubtarget &Subtarget = 6696 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6697 6698 const bool IsPPC64 = Subtarget.isPPC64(); 6699 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6700 6701 // Assign locations to all of the incoming arguments. 6702 SmallVector<CCValAssign, 16> ArgLocs; 6703 MachineFunction &MF = DAG.getMachineFunction(); 6704 MachineFrameInfo &MFI = MF.getFrameInfo(); 6705 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6706 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6707 6708 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6709 // Reserve space for the linkage area on the stack. 6710 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6711 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6712 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6713 6714 SmallVector<SDValue, 8> MemOps; 6715 6716 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6717 CCValAssign &VA = ArgLocs[I++]; 6718 MVT LocVT = VA.getLocVT(); 6719 MVT ValVT = VA.getValVT(); 6720 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6721 // For compatibility with the AIX XL compiler, the float args in the 6722 // parameter save area are initialized even if the argument is available 6723 // in register. The caller is required to initialize both the register 6724 // and memory, however, the callee can choose to expect it in either. 6725 // The memloc is dismissed here because the argument is retrieved from 6726 // the register. 6727 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6728 continue; 6729 6730 auto HandleMemLoc = [&]() { 6731 const unsigned LocSize = LocVT.getStoreSize(); 6732 const unsigned ValSize = ValVT.getStoreSize(); 6733 assert((ValSize <= LocSize) && 6734 "Object size is larger than size of MemLoc"); 6735 int CurArgOffset = VA.getLocMemOffset(); 6736 // Objects are right-justified because AIX is big-endian. 6737 if (LocSize > ValSize) 6738 CurArgOffset += LocSize - ValSize; 6739 // Potential tail calls could cause overwriting of argument stack slots. 6740 const bool IsImmutable = 6741 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6742 (CallConv == CallingConv::Fast)); 6743 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6744 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6745 SDValue ArgValue = 6746 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6747 InVals.push_back(ArgValue); 6748 }; 6749 6750 // Vector arguments to VaArg functions are passed both on the stack, and 6751 // in any available GPRs. Load the value from the stack and add the GPRs 6752 // as live ins. 6753 if (VA.isMemLoc() && VA.needsCustom()) { 6754 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 6755 assert(isVarArg && "Only use custom memloc for vararg."); 6756 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 6757 // matching custom RegLocs. 6758 const unsigned OriginalValNo = VA.getValNo(); 6759 (void)OriginalValNo; 6760 6761 auto HandleCustomVecRegLoc = [&]() { 6762 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 6763 "Missing custom RegLoc."); 6764 VA = ArgLocs[I++]; 6765 assert(VA.getValVT().isVector() && 6766 "Unexpected Val type for custom RegLoc."); 6767 assert(VA.getValNo() == OriginalValNo && 6768 "ValNo mismatch between custom MemLoc and RegLoc."); 6769 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 6770 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6771 }; 6772 6773 HandleMemLoc(); 6774 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 6775 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 6776 // R10. 6777 HandleCustomVecRegLoc(); 6778 HandleCustomVecRegLoc(); 6779 6780 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 6781 // we passed the vector in R5, R6, R7 and R8. 6782 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 6783 assert(!IsPPC64 && 6784 "Only 2 custom RegLocs expected for 64-bit codegen."); 6785 HandleCustomVecRegLoc(); 6786 HandleCustomVecRegLoc(); 6787 } 6788 6789 continue; 6790 } 6791 6792 if (VA.isRegLoc()) { 6793 if (VA.getValVT().isScalarInteger()) 6794 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 6795 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) 6796 FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32 6797 ? PPCFunctionInfo::ShortFloatPoint 6798 : PPCFunctionInfo::LongFloatPoint); 6799 } 6800 6801 if (Flags.isByVal() && VA.isMemLoc()) { 6802 const unsigned Size = 6803 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 6804 PtrByteSize); 6805 const int FI = MF.getFrameInfo().CreateFixedObject( 6806 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 6807 /* IsAliased */ true); 6808 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6809 InVals.push_back(FIN); 6810 6811 continue; 6812 } 6813 6814 if (Flags.isByVal()) { 6815 assert(VA.isRegLoc() && "MemLocs should already be handled."); 6816 6817 const MCPhysReg ArgReg = VA.getLocReg(); 6818 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 6819 6820 if (Flags.getNonZeroByValAlign() > PtrByteSize) 6821 report_fatal_error("Over aligned byvals not supported yet."); 6822 6823 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 6824 const int FI = MF.getFrameInfo().CreateFixedObject( 6825 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 6826 /* IsAliased */ true); 6827 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6828 InVals.push_back(FIN); 6829 6830 // Add live ins for all the RegLocs for the same ByVal. 6831 const TargetRegisterClass *RegClass = 6832 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6833 6834 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 6835 unsigned Offset) { 6836 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 6837 // Since the callers side has left justified the aggregate in the 6838 // register, we can simply store the entire register into the stack 6839 // slot. 6840 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6841 // The store to the fixedstack object is needed becuase accessing a 6842 // field of the ByVal will use a gep and load. Ideally we will optimize 6843 // to extracting the value from the register directly, and elide the 6844 // stores when the arguments address is not taken, but that will need to 6845 // be future work. 6846 SDValue Store = DAG.getStore( 6847 CopyFrom.getValue(1), dl, CopyFrom, 6848 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 6849 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 6850 6851 MemOps.push_back(Store); 6852 }; 6853 6854 unsigned Offset = 0; 6855 HandleRegLoc(VA.getLocReg(), Offset); 6856 Offset += PtrByteSize; 6857 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 6858 Offset += PtrByteSize) { 6859 assert(ArgLocs[I].getValNo() == VA.getValNo() && 6860 "RegLocs should be for ByVal argument."); 6861 6862 const CCValAssign RL = ArgLocs[I++]; 6863 HandleRegLoc(RL.getLocReg(), Offset); 6864 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 6865 } 6866 6867 if (Offset != StackSize) { 6868 assert(ArgLocs[I].getValNo() == VA.getValNo() && 6869 "Expected MemLoc for remaining bytes."); 6870 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 6871 // Consume the MemLoc.The InVal has already been emitted, so nothing 6872 // more needs to be done. 6873 ++I; 6874 } 6875 6876 continue; 6877 } 6878 6879 if (VA.isRegLoc() && !VA.needsCustom()) { 6880 MVT::SimpleValueType SVT = ValVT.SimpleTy; 6881 unsigned VReg = 6882 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6883 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6884 if (ValVT.isScalarInteger() && 6885 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 6886 ArgValue = 6887 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 6888 } 6889 InVals.push_back(ArgValue); 6890 continue; 6891 } 6892 if (VA.isMemLoc()) { 6893 HandleMemLoc(); 6894 continue; 6895 } 6896 } 6897 6898 // On AIX a minimum of 8 words is saved to the parameter save area. 6899 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6900 // Area that is at least reserved in the caller of this function. 6901 unsigned CallerReservedArea = 6902 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 6903 6904 // Set the size that is at least reserved in caller of this function. Tail 6905 // call optimized function's reserved stack space needs to be aligned so 6906 // that taking the difference between two stack areas will result in an 6907 // aligned stack. 6908 CallerReservedArea = 6909 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 6910 FuncInfo->setMinReservedArea(CallerReservedArea); 6911 6912 if (isVarArg) { 6913 FuncInfo->setVarArgsFrameIndex( 6914 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 6915 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 6916 6917 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6918 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6919 6920 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6921 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6922 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 6923 6924 // The fixed integer arguments of a variadic function are stored to the 6925 // VarArgsFrameIndex on the stack so that they may be loaded by 6926 // dereferencing the result of va_next. 6927 for (unsigned GPRIndex = 6928 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 6929 GPRIndex < NumGPArgRegs; ++GPRIndex) { 6930 6931 const unsigned VReg = 6932 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 6933 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 6934 6935 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 6936 SDValue Store = 6937 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 6938 MemOps.push_back(Store); 6939 // Increment the address for the next argument to store. 6940 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 6941 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 6942 } 6943 } 6944 6945 if (!MemOps.empty()) 6946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 6947 6948 return Chain; 6949 } 6950 6951 SDValue PPCTargetLowering::LowerCall_AIX( 6952 SDValue Chain, SDValue Callee, CallFlags CFlags, 6953 const SmallVectorImpl<ISD::OutputArg> &Outs, 6954 const SmallVectorImpl<SDValue> &OutVals, 6955 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6956 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6957 const CallBase *CB) const { 6958 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 6959 // AIX ABI stack frame layout. 6960 6961 assert((CFlags.CallConv == CallingConv::C || 6962 CFlags.CallConv == CallingConv::Cold || 6963 CFlags.CallConv == CallingConv::Fast) && 6964 "Unexpected calling convention!"); 6965 6966 if (CFlags.IsPatchPoint) 6967 report_fatal_error("This call type is unimplemented on AIX."); 6968 6969 const PPCSubtarget& Subtarget = 6970 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 6971 6972 MachineFunction &MF = DAG.getMachineFunction(); 6973 SmallVector<CCValAssign, 16> ArgLocs; 6974 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 6975 *DAG.getContext()); 6976 6977 // Reserve space for the linkage save area (LSA) on the stack. 6978 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 6979 // [SP][CR][LR][2 x reserved][TOC]. 6980 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 6981 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6982 const bool IsPPC64 = Subtarget.isPPC64(); 6983 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6984 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6985 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6986 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 6987 6988 // The prolog code of the callee may store up to 8 GPR argument registers to 6989 // the stack, allowing va_start to index over them in memory if the callee 6990 // is variadic. 6991 // Because we cannot tell if this is needed on the caller side, we have to 6992 // conservatively assume that it is needed. As such, make sure we have at 6993 // least enough stack space for the caller to store the 8 GPRs. 6994 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 6995 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 6996 CCInfo.getNextStackOffset()); 6997 6998 // Adjust the stack pointer for the new arguments... 6999 // These operations are automatically eliminated by the prolog/epilog pass. 7000 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7001 SDValue CallSeqStart = Chain; 7002 7003 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7004 SmallVector<SDValue, 8> MemOpChains; 7005 7006 // Set up a copy of the stack pointer for loading and storing any 7007 // arguments that may not fit in the registers available for argument 7008 // passing. 7009 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7010 : DAG.getRegister(PPC::R1, MVT::i32); 7011 7012 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7013 const unsigned ValNo = ArgLocs[I].getValNo(); 7014 SDValue Arg = OutVals[ValNo]; 7015 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7016 7017 if (Flags.isByVal()) { 7018 const unsigned ByValSize = Flags.getByValSize(); 7019 7020 // Nothing to do for zero-sized ByVals on the caller side. 7021 if (!ByValSize) { 7022 ++I; 7023 continue; 7024 } 7025 7026 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7027 return DAG.getExtLoad( 7028 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7029 (LoadOffset != 0) 7030 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7031 : Arg, 7032 MachinePointerInfo(), VT); 7033 }; 7034 7035 unsigned LoadOffset = 0; 7036 7037 // Initialize registers, which are fully occupied by the by-val argument. 7038 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7039 SDValue Load = GetLoad(PtrVT, LoadOffset); 7040 MemOpChains.push_back(Load.getValue(1)); 7041 LoadOffset += PtrByteSize; 7042 const CCValAssign &ByValVA = ArgLocs[I++]; 7043 assert(ByValVA.getValNo() == ValNo && 7044 "Unexpected location for pass-by-value argument."); 7045 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7046 } 7047 7048 if (LoadOffset == ByValSize) 7049 continue; 7050 7051 // There must be one more loc to handle the remainder. 7052 assert(ArgLocs[I].getValNo() == ValNo && 7053 "Expected additional location for by-value argument."); 7054 7055 if (ArgLocs[I].isMemLoc()) { 7056 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7057 const CCValAssign &ByValVA = ArgLocs[I++]; 7058 ISD::ArgFlagsTy MemcpyFlags = Flags; 7059 // Only memcpy the bytes that don't pass in register. 7060 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7061 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7062 (LoadOffset != 0) 7063 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7064 : Arg, 7065 DAG.getObjectPtrOffset(dl, StackPtr, 7066 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7067 CallSeqStart, MemcpyFlags, DAG, dl); 7068 continue; 7069 } 7070 7071 // Initialize the final register residue. 7072 // Any residue that occupies the final by-val arg register must be 7073 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7074 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7075 // 2 and 1 byte loads. 7076 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7077 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7078 "Unexpected register residue for by-value argument."); 7079 SDValue ResidueVal; 7080 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7081 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7082 const MVT VT = 7083 N == 1 ? MVT::i8 7084 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7085 SDValue Load = GetLoad(VT, LoadOffset); 7086 MemOpChains.push_back(Load.getValue(1)); 7087 LoadOffset += N; 7088 Bytes += N; 7089 7090 // By-val arguments are passed left-justfied in register. 7091 // Every load here needs to be shifted, otherwise a full register load 7092 // should have been used. 7093 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7094 "Unexpected load emitted during handling of pass-by-value " 7095 "argument."); 7096 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7097 EVT ShiftAmountTy = 7098 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7099 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7100 SDValue ShiftedLoad = 7101 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7102 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7103 ShiftedLoad) 7104 : ShiftedLoad; 7105 } 7106 7107 const CCValAssign &ByValVA = ArgLocs[I++]; 7108 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7109 continue; 7110 } 7111 7112 CCValAssign &VA = ArgLocs[I++]; 7113 const MVT LocVT = VA.getLocVT(); 7114 const MVT ValVT = VA.getValVT(); 7115 7116 switch (VA.getLocInfo()) { 7117 default: 7118 report_fatal_error("Unexpected argument extension type."); 7119 case CCValAssign::Full: 7120 break; 7121 case CCValAssign::ZExt: 7122 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7123 break; 7124 case CCValAssign::SExt: 7125 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7126 break; 7127 } 7128 7129 if (VA.isRegLoc() && !VA.needsCustom()) { 7130 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7131 continue; 7132 } 7133 7134 // Vector arguments passed to VarArg functions need custom handling when 7135 // they are passed (at least partially) in GPRs. 7136 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7137 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7138 // Store value to its stack slot. 7139 SDValue PtrOff = 7140 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7141 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7142 SDValue Store = 7143 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7144 MemOpChains.push_back(Store); 7145 const unsigned OriginalValNo = VA.getValNo(); 7146 // Then load the GPRs from the stack 7147 unsigned LoadOffset = 0; 7148 auto HandleCustomVecRegLoc = [&]() { 7149 assert(I != E && "Unexpected end of CCvalAssigns."); 7150 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7151 "Expected custom RegLoc."); 7152 CCValAssign RegVA = ArgLocs[I++]; 7153 assert(RegVA.getValNo() == OriginalValNo && 7154 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7155 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7156 DAG.getConstant(LoadOffset, dl, PtrVT)); 7157 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7158 MemOpChains.push_back(Load.getValue(1)); 7159 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7160 LoadOffset += PtrByteSize; 7161 }; 7162 7163 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7164 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7165 // R10. 7166 HandleCustomVecRegLoc(); 7167 HandleCustomVecRegLoc(); 7168 7169 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7170 ArgLocs[I].getValNo() == OriginalValNo) { 7171 assert(!IsPPC64 && 7172 "Only 2 custom RegLocs expected for 64-bit codegen."); 7173 HandleCustomVecRegLoc(); 7174 HandleCustomVecRegLoc(); 7175 } 7176 7177 continue; 7178 } 7179 7180 if (VA.isMemLoc()) { 7181 SDValue PtrOff = 7182 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7183 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7184 MemOpChains.push_back( 7185 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7186 7187 continue; 7188 } 7189 7190 if (!ValVT.isFloatingPoint()) 7191 report_fatal_error( 7192 "Unexpected register handling for calling convention."); 7193 7194 // Custom handling is used for GPR initializations for vararg float 7195 // arguments. 7196 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7197 LocVT.isInteger() && 7198 "Custom register handling only expected for VarArg."); 7199 7200 SDValue ArgAsInt = 7201 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7202 7203 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7204 // f32 in 32-bit GPR 7205 // f64 in 64-bit GPR 7206 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7207 else if (Arg.getValueType().getFixedSizeInBits() < 7208 LocVT.getFixedSizeInBits()) 7209 // f32 in 64-bit GPR. 7210 RegsToPass.push_back(std::make_pair( 7211 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7212 else { 7213 // f64 in two 32-bit GPRs 7214 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7215 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7216 "Unexpected custom register for argument!"); 7217 CCValAssign &GPR1 = VA; 7218 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7219 DAG.getConstant(32, dl, MVT::i8)); 7220 RegsToPass.push_back(std::make_pair( 7221 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7222 7223 if (I != E) { 7224 // If only 1 GPR was available, there will only be one custom GPR and 7225 // the argument will also pass in memory. 7226 CCValAssign &PeekArg = ArgLocs[I]; 7227 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7228 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7229 CCValAssign &GPR2 = ArgLocs[I++]; 7230 RegsToPass.push_back(std::make_pair( 7231 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7232 } 7233 } 7234 } 7235 } 7236 7237 if (!MemOpChains.empty()) 7238 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7239 7240 // For indirect calls, we need to save the TOC base to the stack for 7241 // restoration after the call. 7242 if (CFlags.IsIndirect) { 7243 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7244 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7245 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7246 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7247 const unsigned TOCSaveOffset = 7248 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7249 7250 setUsesTOCBasePtr(DAG); 7251 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7252 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7253 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7254 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7255 Chain = DAG.getStore( 7256 Val.getValue(1), dl, Val, AddPtr, 7257 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7258 } 7259 7260 // Build a sequence of copy-to-reg nodes chained together with token chain 7261 // and flag operands which copy the outgoing args into the appropriate regs. 7262 SDValue InFlag; 7263 for (auto Reg : RegsToPass) { 7264 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7265 InFlag = Chain.getValue(1); 7266 } 7267 7268 const int SPDiff = 0; 7269 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7270 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7271 } 7272 7273 bool 7274 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7275 MachineFunction &MF, bool isVarArg, 7276 const SmallVectorImpl<ISD::OutputArg> &Outs, 7277 LLVMContext &Context) const { 7278 SmallVector<CCValAssign, 16> RVLocs; 7279 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7280 return CCInfo.CheckReturn( 7281 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7282 ? RetCC_PPC_Cold 7283 : RetCC_PPC); 7284 } 7285 7286 SDValue 7287 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7288 bool isVarArg, 7289 const SmallVectorImpl<ISD::OutputArg> &Outs, 7290 const SmallVectorImpl<SDValue> &OutVals, 7291 const SDLoc &dl, SelectionDAG &DAG) const { 7292 SmallVector<CCValAssign, 16> RVLocs; 7293 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7294 *DAG.getContext()); 7295 CCInfo.AnalyzeReturn(Outs, 7296 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7297 ? RetCC_PPC_Cold 7298 : RetCC_PPC); 7299 7300 SDValue Flag; 7301 SmallVector<SDValue, 4> RetOps(1, Chain); 7302 7303 // Copy the result values into the output registers. 7304 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7305 CCValAssign &VA = RVLocs[i]; 7306 assert(VA.isRegLoc() && "Can only return in registers!"); 7307 7308 SDValue Arg = OutVals[RealResIdx]; 7309 7310 switch (VA.getLocInfo()) { 7311 default: llvm_unreachable("Unknown loc info!"); 7312 case CCValAssign::Full: break; 7313 case CCValAssign::AExt: 7314 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7315 break; 7316 case CCValAssign::ZExt: 7317 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7318 break; 7319 case CCValAssign::SExt: 7320 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7321 break; 7322 } 7323 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7324 bool isLittleEndian = Subtarget.isLittleEndian(); 7325 // Legalize ret f64 -> ret 2 x i32. 7326 SDValue SVal = 7327 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7328 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7329 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7330 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7331 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7332 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7333 Flag = Chain.getValue(1); 7334 VA = RVLocs[++i]; // skip ahead to next loc 7335 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7336 } else 7337 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7338 Flag = Chain.getValue(1); 7339 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7340 } 7341 7342 RetOps[0] = Chain; // Update chain. 7343 7344 // Add the flag if we have it. 7345 if (Flag.getNode()) 7346 RetOps.push_back(Flag); 7347 7348 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7349 } 7350 7351 SDValue 7352 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7353 SelectionDAG &DAG) const { 7354 SDLoc dl(Op); 7355 7356 // Get the correct type for integers. 7357 EVT IntVT = Op.getValueType(); 7358 7359 // Get the inputs. 7360 SDValue Chain = Op.getOperand(0); 7361 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7362 // Build a DYNAREAOFFSET node. 7363 SDValue Ops[2] = {Chain, FPSIdx}; 7364 SDVTList VTs = DAG.getVTList(IntVT); 7365 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7366 } 7367 7368 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7369 SelectionDAG &DAG) const { 7370 // When we pop the dynamic allocation we need to restore the SP link. 7371 SDLoc dl(Op); 7372 7373 // Get the correct type for pointers. 7374 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7375 7376 // Construct the stack pointer operand. 7377 bool isPPC64 = Subtarget.isPPC64(); 7378 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7379 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7380 7381 // Get the operands for the STACKRESTORE. 7382 SDValue Chain = Op.getOperand(0); 7383 SDValue SaveSP = Op.getOperand(1); 7384 7385 // Load the old link SP. 7386 SDValue LoadLinkSP = 7387 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7388 7389 // Restore the stack pointer. 7390 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7391 7392 // Store the old link SP. 7393 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7394 } 7395 7396 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7397 MachineFunction &MF = DAG.getMachineFunction(); 7398 bool isPPC64 = Subtarget.isPPC64(); 7399 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7400 7401 // Get current frame pointer save index. The users of this index will be 7402 // primarily DYNALLOC instructions. 7403 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7404 int RASI = FI->getReturnAddrSaveIndex(); 7405 7406 // If the frame pointer save index hasn't been defined yet. 7407 if (!RASI) { 7408 // Find out what the fix offset of the frame pointer save area. 7409 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7410 // Allocate the frame index for frame pointer save area. 7411 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7412 // Save the result. 7413 FI->setReturnAddrSaveIndex(RASI); 7414 } 7415 return DAG.getFrameIndex(RASI, PtrVT); 7416 } 7417 7418 SDValue 7419 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7420 MachineFunction &MF = DAG.getMachineFunction(); 7421 bool isPPC64 = Subtarget.isPPC64(); 7422 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7423 7424 // Get current frame pointer save index. The users of this index will be 7425 // primarily DYNALLOC instructions. 7426 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7427 int FPSI = FI->getFramePointerSaveIndex(); 7428 7429 // If the frame pointer save index hasn't been defined yet. 7430 if (!FPSI) { 7431 // Find out what the fix offset of the frame pointer save area. 7432 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7433 // Allocate the frame index for frame pointer save area. 7434 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7435 // Save the result. 7436 FI->setFramePointerSaveIndex(FPSI); 7437 } 7438 return DAG.getFrameIndex(FPSI, PtrVT); 7439 } 7440 7441 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7442 SelectionDAG &DAG) const { 7443 MachineFunction &MF = DAG.getMachineFunction(); 7444 // Get the inputs. 7445 SDValue Chain = Op.getOperand(0); 7446 SDValue Size = Op.getOperand(1); 7447 SDLoc dl(Op); 7448 7449 // Get the correct type for pointers. 7450 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7451 // Negate the size. 7452 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7453 DAG.getConstant(0, dl, PtrVT), Size); 7454 // Construct a node for the frame pointer save index. 7455 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7456 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7457 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7458 if (hasInlineStackProbe(MF)) 7459 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7460 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7461 } 7462 7463 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7464 SelectionDAG &DAG) const { 7465 MachineFunction &MF = DAG.getMachineFunction(); 7466 7467 bool isPPC64 = Subtarget.isPPC64(); 7468 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7469 7470 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7471 return DAG.getFrameIndex(FI, PtrVT); 7472 } 7473 7474 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7475 SelectionDAG &DAG) const { 7476 SDLoc DL(Op); 7477 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7478 DAG.getVTList(MVT::i32, MVT::Other), 7479 Op.getOperand(0), Op.getOperand(1)); 7480 } 7481 7482 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7483 SelectionDAG &DAG) const { 7484 SDLoc DL(Op); 7485 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7486 Op.getOperand(0), Op.getOperand(1)); 7487 } 7488 7489 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7490 if (Op.getValueType().isVector()) 7491 return LowerVectorLoad(Op, DAG); 7492 7493 assert(Op.getValueType() == MVT::i1 && 7494 "Custom lowering only for i1 loads"); 7495 7496 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7497 7498 SDLoc dl(Op); 7499 LoadSDNode *LD = cast<LoadSDNode>(Op); 7500 7501 SDValue Chain = LD->getChain(); 7502 SDValue BasePtr = LD->getBasePtr(); 7503 MachineMemOperand *MMO = LD->getMemOperand(); 7504 7505 SDValue NewLD = 7506 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7507 BasePtr, MVT::i8, MMO); 7508 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7509 7510 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7511 return DAG.getMergeValues(Ops, dl); 7512 } 7513 7514 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7515 if (Op.getOperand(1).getValueType().isVector()) 7516 return LowerVectorStore(Op, DAG); 7517 7518 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7519 "Custom lowering only for i1 stores"); 7520 7521 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7522 7523 SDLoc dl(Op); 7524 StoreSDNode *ST = cast<StoreSDNode>(Op); 7525 7526 SDValue Chain = ST->getChain(); 7527 SDValue BasePtr = ST->getBasePtr(); 7528 SDValue Value = ST->getValue(); 7529 MachineMemOperand *MMO = ST->getMemOperand(); 7530 7531 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7532 Value); 7533 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7534 } 7535 7536 // FIXME: Remove this once the ANDI glue bug is fixed: 7537 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7538 assert(Op.getValueType() == MVT::i1 && 7539 "Custom lowering only for i1 results"); 7540 7541 SDLoc DL(Op); 7542 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7543 } 7544 7545 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7546 SelectionDAG &DAG) const { 7547 7548 // Implements a vector truncate that fits in a vector register as a shuffle. 7549 // We want to legalize vector truncates down to where the source fits in 7550 // a vector register (and target is therefore smaller than vector register 7551 // size). At that point legalization will try to custom lower the sub-legal 7552 // result and get here - where we can contain the truncate as a single target 7553 // operation. 7554 7555 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7556 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7557 // 7558 // We will implement it for big-endian ordering as this (where x denotes 7559 // undefined): 7560 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7561 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7562 // 7563 // The same operation in little-endian ordering will be: 7564 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7565 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7566 7567 EVT TrgVT = Op.getValueType(); 7568 assert(TrgVT.isVector() && "Vector type expected."); 7569 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7570 EVT EltVT = TrgVT.getVectorElementType(); 7571 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7572 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7573 !isPowerOf2_32(EltVT.getSizeInBits())) 7574 return SDValue(); 7575 7576 SDValue N1 = Op.getOperand(0); 7577 EVT SrcVT = N1.getValueType(); 7578 unsigned SrcSize = SrcVT.getSizeInBits(); 7579 if (SrcSize > 256 || 7580 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7581 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7582 return SDValue(); 7583 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7584 return SDValue(); 7585 7586 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7587 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7588 7589 SDLoc DL(Op); 7590 SDValue Op1, Op2; 7591 if (SrcSize == 256) { 7592 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7593 EVT SplitVT = 7594 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7595 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7596 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7597 DAG.getConstant(0, DL, VecIdxTy)); 7598 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7599 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7600 } 7601 else { 7602 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7603 Op2 = DAG.getUNDEF(WideVT); 7604 } 7605 7606 // First list the elements we want to keep. 7607 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7608 SmallVector<int, 16> ShuffV; 7609 if (Subtarget.isLittleEndian()) 7610 for (unsigned i = 0; i < TrgNumElts; ++i) 7611 ShuffV.push_back(i * SizeMult); 7612 else 7613 for (unsigned i = 1; i <= TrgNumElts; ++i) 7614 ShuffV.push_back(i * SizeMult - 1); 7615 7616 // Populate the remaining elements with undefs. 7617 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7618 // ShuffV.push_back(i + WideNumElts); 7619 ShuffV.push_back(WideNumElts + 1); 7620 7621 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7622 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7623 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7624 } 7625 7626 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7627 /// possible. 7628 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7629 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7630 EVT ResVT = Op.getValueType(); 7631 EVT CmpVT = Op.getOperand(0).getValueType(); 7632 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7633 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7634 SDLoc dl(Op); 7635 7636 // Without power9-vector, we don't have native instruction for f128 comparison. 7637 // Following transformation to libcall is needed for setcc: 7638 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7639 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7640 SDValue Z = DAG.getSetCC( 7641 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7642 LHS, RHS, CC); 7643 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7644 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7645 } 7646 7647 // Not FP, or using SPE? Not a fsel. 7648 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7649 Subtarget.hasSPE()) 7650 return Op; 7651 7652 SDNodeFlags Flags = Op.getNode()->getFlags(); 7653 7654 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7655 // presence of infinities. 7656 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7657 switch (CC) { 7658 default: 7659 break; 7660 case ISD::SETOGT: 7661 case ISD::SETGT: 7662 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7663 case ISD::SETOLT: 7664 case ISD::SETLT: 7665 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7666 } 7667 } 7668 7669 // We might be able to do better than this under some circumstances, but in 7670 // general, fsel-based lowering of select is a finite-math-only optimization. 7671 // For more information, see section F.3 of the 2.06 ISA specification. 7672 // With ISA 3.0 7673 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7674 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7675 return Op; 7676 7677 // If the RHS of the comparison is a 0.0, we don't need to do the 7678 // subtraction at all. 7679 SDValue Sel1; 7680 if (isFloatingPointZero(RHS)) 7681 switch (CC) { 7682 default: break; // SETUO etc aren't handled by fsel. 7683 case ISD::SETNE: 7684 std::swap(TV, FV); 7685 LLVM_FALLTHROUGH; 7686 case ISD::SETEQ: 7687 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7688 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7689 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7690 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7691 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7692 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7693 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7694 case ISD::SETULT: 7695 case ISD::SETLT: 7696 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7697 LLVM_FALLTHROUGH; 7698 case ISD::SETOGE: 7699 case ISD::SETGE: 7700 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7701 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7702 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7703 case ISD::SETUGT: 7704 case ISD::SETGT: 7705 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7706 LLVM_FALLTHROUGH; 7707 case ISD::SETOLE: 7708 case ISD::SETLE: 7709 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7710 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7711 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7712 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7713 } 7714 7715 SDValue Cmp; 7716 switch (CC) { 7717 default: break; // SETUO etc aren't handled by fsel. 7718 case ISD::SETNE: 7719 std::swap(TV, FV); 7720 LLVM_FALLTHROUGH; 7721 case ISD::SETEQ: 7722 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7723 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7724 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7725 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7726 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7727 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7728 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7729 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7730 case ISD::SETULT: 7731 case ISD::SETLT: 7732 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7733 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7734 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7735 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7736 case ISD::SETOGE: 7737 case ISD::SETGE: 7738 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7739 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7740 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7741 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7742 case ISD::SETUGT: 7743 case ISD::SETGT: 7744 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7745 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7746 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7747 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7748 case ISD::SETOLE: 7749 case ISD::SETLE: 7750 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7751 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7752 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7753 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7754 } 7755 return Op; 7756 } 7757 7758 static unsigned getPPCStrictOpcode(unsigned Opc) { 7759 switch (Opc) { 7760 default: 7761 llvm_unreachable("No strict version of this opcode!"); 7762 case PPCISD::FCTIDZ: 7763 return PPCISD::STRICT_FCTIDZ; 7764 case PPCISD::FCTIWZ: 7765 return PPCISD::STRICT_FCTIWZ; 7766 case PPCISD::FCTIDUZ: 7767 return PPCISD::STRICT_FCTIDUZ; 7768 case PPCISD::FCTIWUZ: 7769 return PPCISD::STRICT_FCTIWUZ; 7770 case PPCISD::FCFID: 7771 return PPCISD::STRICT_FCFID; 7772 case PPCISD::FCFIDU: 7773 return PPCISD::STRICT_FCFIDU; 7774 case PPCISD::FCFIDS: 7775 return PPCISD::STRICT_FCFIDS; 7776 case PPCISD::FCFIDUS: 7777 return PPCISD::STRICT_FCFIDUS; 7778 } 7779 } 7780 7781 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 7782 const PPCSubtarget &Subtarget) { 7783 SDLoc dl(Op); 7784 bool IsStrict = Op->isStrictFPOpcode(); 7785 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7786 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7787 7788 // TODO: Any other flags to propagate? 7789 SDNodeFlags Flags; 7790 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 7791 7792 // For strict nodes, source is the second operand. 7793 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7794 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 7795 assert(Src.getValueType().isFloatingPoint()); 7796 if (Src.getValueType() == MVT::f32) { 7797 if (IsStrict) { 7798 Src = 7799 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 7800 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 7801 Chain = Src.getValue(1); 7802 } else 7803 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7804 } 7805 SDValue Conv; 7806 unsigned Opc = ISD::DELETED_NODE; 7807 switch (Op.getSimpleValueType().SimpleTy) { 7808 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7809 case MVT::i32: 7810 Opc = IsSigned ? PPCISD::FCTIWZ 7811 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 7812 break; 7813 case MVT::i64: 7814 assert((IsSigned || Subtarget.hasFPCVT()) && 7815 "i64 FP_TO_UINT is supported only with FPCVT"); 7816 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 7817 } 7818 if (IsStrict) { 7819 Opc = getPPCStrictOpcode(Opc); 7820 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 7821 {Chain, Src}, Flags); 7822 } else { 7823 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 7824 } 7825 return Conv; 7826 } 7827 7828 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7829 SelectionDAG &DAG, 7830 const SDLoc &dl) const { 7831 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 7832 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7833 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7834 bool IsStrict = Op->isStrictFPOpcode(); 7835 7836 // Convert the FP value to an int value through memory. 7837 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7838 (IsSigned || Subtarget.hasFPCVT()); 7839 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7840 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7841 MachinePointerInfo MPI = 7842 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7843 7844 // Emit a store to the stack slot. 7845 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 7846 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 7847 if (i32Stack) { 7848 MachineFunction &MF = DAG.getMachineFunction(); 7849 Alignment = Align(4); 7850 MachineMemOperand *MMO = 7851 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 7852 SDValue Ops[] = { Chain, Tmp, FIPtr }; 7853 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7854 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7855 } else 7856 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 7857 7858 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7859 // add in a bias on big endian. 7860 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7861 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7862 DAG.getConstant(4, dl, FIPtr.getValueType())); 7863 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7864 } 7865 7866 RLI.Chain = Chain; 7867 RLI.Ptr = FIPtr; 7868 RLI.MPI = MPI; 7869 RLI.Alignment = Alignment; 7870 } 7871 7872 /// Custom lowers floating point to integer conversions to use 7873 /// the direct move instructions available in ISA 2.07 to avoid the 7874 /// need for load/store combinations. 7875 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7876 SelectionDAG &DAG, 7877 const SDLoc &dl) const { 7878 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 7879 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 7880 if (Op->isStrictFPOpcode()) 7881 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 7882 else 7883 return Mov; 7884 } 7885 7886 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7887 const SDLoc &dl) const { 7888 bool IsStrict = Op->isStrictFPOpcode(); 7889 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7890 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7891 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7892 EVT SrcVT = Src.getValueType(); 7893 EVT DstVT = Op.getValueType(); 7894 7895 // FP to INT conversions are legal for f128. 7896 if (SrcVT == MVT::f128) 7897 return Subtarget.hasP9Vector() ? Op : SDValue(); 7898 7899 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7900 // PPC (the libcall is not available). 7901 if (SrcVT == MVT::ppcf128) { 7902 if (DstVT == MVT::i32) { 7903 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 7904 // set other fast-math flags to FP operations in both strict and 7905 // non-strict cases. (FP_TO_SINT, FSUB) 7906 SDNodeFlags Flags; 7907 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 7908 7909 if (IsSigned) { 7910 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 7911 DAG.getIntPtrConstant(0, dl)); 7912 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 7913 DAG.getIntPtrConstant(1, dl)); 7914 7915 // Add the two halves of the long double in round-to-zero mode, and use 7916 // a smaller FP_TO_SINT. 7917 if (IsStrict) { 7918 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 7919 DAG.getVTList(MVT::f64, MVT::Other), 7920 {Op.getOperand(0), Lo, Hi}, Flags); 7921 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 7922 DAG.getVTList(MVT::i32, MVT::Other), 7923 {Res.getValue(1), Res}, Flags); 7924 } else { 7925 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7926 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7927 } 7928 } else { 7929 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7930 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7931 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7932 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 7933 if (IsStrict) { 7934 // Sel = Src < 0x80000000 7935 // FltOfs = select Sel, 0.0, 0x80000000 7936 // IntOfs = select Sel, 0, 0x80000000 7937 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7938 SDValue Chain = Op.getOperand(0); 7939 EVT SetCCVT = 7940 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7941 EVT DstSetCCVT = 7942 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7943 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7944 Chain, true); 7945 Chain = Sel.getValue(1); 7946 7947 SDValue FltOfs = DAG.getSelect( 7948 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7949 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7950 7951 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 7952 DAG.getVTList(SrcVT, MVT::Other), 7953 {Chain, Src, FltOfs}, Flags); 7954 Chain = Val.getValue(1); 7955 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 7956 DAG.getVTList(DstVT, MVT::Other), 7957 {Chain, Val}, Flags); 7958 Chain = SInt.getValue(1); 7959 SDValue IntOfs = DAG.getSelect( 7960 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 7961 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7962 return DAG.getMergeValues({Result, Chain}, dl); 7963 } else { 7964 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7965 // FIXME: generated code sucks. 7966 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 7967 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7968 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 7969 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 7970 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 7971 } 7972 } 7973 } 7974 7975 return SDValue(); 7976 } 7977 7978 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7979 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7980 7981 ReuseLoadInfo RLI; 7982 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7983 7984 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7985 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7986 } 7987 7988 // We're trying to insert a regular store, S, and then a load, L. If the 7989 // incoming value, O, is a load, we might just be able to have our load use the 7990 // address used by O. However, we don't know if anything else will store to 7991 // that address before we can load from it. To prevent this situation, we need 7992 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7993 // the same chain operand as O, we create a token factor from the chain results 7994 // of O and L, and we replace all uses of O's chain result with that token 7995 // factor (see spliceIntoChain below for this last part). 7996 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7997 ReuseLoadInfo &RLI, 7998 SelectionDAG &DAG, 7999 ISD::LoadExtType ET) const { 8000 // Conservatively skip reusing for constrained FP nodes. 8001 if (Op->isStrictFPOpcode()) 8002 return false; 8003 8004 SDLoc dl(Op); 8005 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8006 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8007 if (ET == ISD::NON_EXTLOAD && 8008 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8009 isOperationLegalOrCustom(Op.getOpcode(), 8010 Op.getOperand(0).getValueType())) { 8011 8012 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8013 return true; 8014 } 8015 8016 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8017 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8018 LD->isNonTemporal()) 8019 return false; 8020 if (LD->getMemoryVT() != MemVT) 8021 return false; 8022 8023 // If the result of the load is an illegal type, then we can't build a 8024 // valid chain for reuse since the legalised loads and token factor node that 8025 // ties the legalised loads together uses a different output chain then the 8026 // illegal load. 8027 if (!isTypeLegal(LD->getValueType(0))) 8028 return false; 8029 8030 RLI.Ptr = LD->getBasePtr(); 8031 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8032 assert(LD->getAddressingMode() == ISD::PRE_INC && 8033 "Non-pre-inc AM on PPC?"); 8034 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8035 LD->getOffset()); 8036 } 8037 8038 RLI.Chain = LD->getChain(); 8039 RLI.MPI = LD->getPointerInfo(); 8040 RLI.IsDereferenceable = LD->isDereferenceable(); 8041 RLI.IsInvariant = LD->isInvariant(); 8042 RLI.Alignment = LD->getAlign(); 8043 RLI.AAInfo = LD->getAAInfo(); 8044 RLI.Ranges = LD->getRanges(); 8045 8046 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8047 return true; 8048 } 8049 8050 // Given the head of the old chain, ResChain, insert a token factor containing 8051 // it and NewResChain, and make users of ResChain now be users of that token 8052 // factor. 8053 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8054 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8055 SDValue NewResChain, 8056 SelectionDAG &DAG) const { 8057 if (!ResChain) 8058 return; 8059 8060 SDLoc dl(NewResChain); 8061 8062 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8063 NewResChain, DAG.getUNDEF(MVT::Other)); 8064 assert(TF.getNode() != NewResChain.getNode() && 8065 "A new TF really is required here"); 8066 8067 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8068 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8069 } 8070 8071 /// Analyze profitability of direct move 8072 /// prefer float load to int load plus direct move 8073 /// when there is no integer use of int load 8074 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8075 SDNode *Origin = Op.getOperand(0).getNode(); 8076 if (Origin->getOpcode() != ISD::LOAD) 8077 return true; 8078 8079 // If there is no LXSIBZX/LXSIHZX, like Power8, 8080 // prefer direct move if the memory size is 1 or 2 bytes. 8081 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8082 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8083 return true; 8084 8085 for (SDNode::use_iterator UI = Origin->use_begin(), 8086 UE = Origin->use_end(); 8087 UI != UE; ++UI) { 8088 8089 // Only look at the users of the loaded value. 8090 if (UI.getUse().get().getResNo() != 0) 8091 continue; 8092 8093 if (UI->getOpcode() != ISD::SINT_TO_FP && 8094 UI->getOpcode() != ISD::UINT_TO_FP && 8095 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8096 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8097 return true; 8098 } 8099 8100 return false; 8101 } 8102 8103 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8104 const PPCSubtarget &Subtarget, 8105 SDValue Chain = SDValue()) { 8106 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8107 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8108 SDLoc dl(Op); 8109 8110 // TODO: Any other flags to propagate? 8111 SDNodeFlags Flags; 8112 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8113 8114 // If we have FCFIDS, then use it when converting to single-precision. 8115 // Otherwise, convert to double-precision and then round. 8116 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8117 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8118 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8119 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8120 if (Op->isStrictFPOpcode()) { 8121 if (!Chain) 8122 Chain = Op.getOperand(0); 8123 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8124 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8125 } else 8126 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8127 } 8128 8129 /// Custom lowers integer to floating point conversions to use 8130 /// the direct move instructions available in ISA 2.07 to avoid the 8131 /// need for load/store combinations. 8132 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8133 SelectionDAG &DAG, 8134 const SDLoc &dl) const { 8135 assert((Op.getValueType() == MVT::f32 || 8136 Op.getValueType() == MVT::f64) && 8137 "Invalid floating point type as target of conversion"); 8138 assert(Subtarget.hasFPCVT() && 8139 "Int to FP conversions with direct moves require FPCVT"); 8140 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8141 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8142 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8143 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8144 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8145 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8146 return convertIntToFP(Op, Mov, DAG, Subtarget); 8147 } 8148 8149 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8150 8151 EVT VecVT = Vec.getValueType(); 8152 assert(VecVT.isVector() && "Expected a vector type."); 8153 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8154 8155 EVT EltVT = VecVT.getVectorElementType(); 8156 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8157 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8158 8159 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8160 SmallVector<SDValue, 16> Ops(NumConcat); 8161 Ops[0] = Vec; 8162 SDValue UndefVec = DAG.getUNDEF(VecVT); 8163 for (unsigned i = 1; i < NumConcat; ++i) 8164 Ops[i] = UndefVec; 8165 8166 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8167 } 8168 8169 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8170 const SDLoc &dl) const { 8171 bool IsStrict = Op->isStrictFPOpcode(); 8172 unsigned Opc = Op.getOpcode(); 8173 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8174 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8175 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8176 "Unexpected conversion type"); 8177 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8178 "Supports conversions to v2f64/v4f32 only."); 8179 8180 // TODO: Any other flags to propagate? 8181 SDNodeFlags Flags; 8182 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8183 8184 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8185 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8186 8187 SDValue Wide = widenVec(DAG, Src, dl); 8188 EVT WideVT = Wide.getValueType(); 8189 unsigned WideNumElts = WideVT.getVectorNumElements(); 8190 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8191 8192 SmallVector<int, 16> ShuffV; 8193 for (unsigned i = 0; i < WideNumElts; ++i) 8194 ShuffV.push_back(i + WideNumElts); 8195 8196 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8197 int SaveElts = FourEltRes ? 4 : 2; 8198 if (Subtarget.isLittleEndian()) 8199 for (int i = 0; i < SaveElts; i++) 8200 ShuffV[i * Stride] = i; 8201 else 8202 for (int i = 1; i <= SaveElts; i++) 8203 ShuffV[i * Stride - 1] = i - 1; 8204 8205 SDValue ShuffleSrc2 = 8206 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8207 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8208 8209 SDValue Extend; 8210 if (SignedConv) { 8211 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8212 EVT ExtVT = Src.getValueType(); 8213 if (Subtarget.hasP9Altivec()) 8214 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8215 IntermediateVT.getVectorNumElements()); 8216 8217 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8218 DAG.getValueType(ExtVT)); 8219 } else 8220 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8221 8222 if (IsStrict) 8223 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8224 {Op.getOperand(0), Extend}, Flags); 8225 8226 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8227 } 8228 8229 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8230 SelectionDAG &DAG) const { 8231 SDLoc dl(Op); 8232 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8233 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8234 bool IsStrict = Op->isStrictFPOpcode(); 8235 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8236 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8237 8238 // TODO: Any other flags to propagate? 8239 SDNodeFlags Flags; 8240 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8241 8242 EVT InVT = Src.getValueType(); 8243 EVT OutVT = Op.getValueType(); 8244 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8245 isOperationCustom(Op.getOpcode(), InVT)) 8246 return LowerINT_TO_FPVector(Op, DAG, dl); 8247 8248 // Conversions to f128 are legal. 8249 if (Op.getValueType() == MVT::f128) 8250 return Subtarget.hasP9Vector() ? Op : SDValue(); 8251 8252 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8253 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8254 return SDValue(); 8255 8256 if (Src.getValueType() == MVT::i1) { 8257 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8258 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8259 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8260 if (IsStrict) 8261 return DAG.getMergeValues({Sel, Chain}, dl); 8262 else 8263 return Sel; 8264 } 8265 8266 // If we have direct moves, we can do all the conversion, skip the store/load 8267 // however, without FPCVT we can't do most conversions. 8268 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8269 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8270 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8271 8272 assert((IsSigned || Subtarget.hasFPCVT()) && 8273 "UINT_TO_FP is supported only with FPCVT"); 8274 8275 if (Src.getValueType() == MVT::i64) { 8276 SDValue SINT = Src; 8277 // When converting to single-precision, we actually need to convert 8278 // to double-precision first and then round to single-precision. 8279 // To avoid double-rounding effects during that operation, we have 8280 // to prepare the input operand. Bits that might be truncated when 8281 // converting to double-precision are replaced by a bit that won't 8282 // be lost at this stage, but is below the single-precision rounding 8283 // position. 8284 // 8285 // However, if -enable-unsafe-fp-math is in effect, accept double 8286 // rounding to avoid the extra overhead. 8287 if (Op.getValueType() == MVT::f32 && 8288 !Subtarget.hasFPCVT() && 8289 !DAG.getTarget().Options.UnsafeFPMath) { 8290 8291 // Twiddle input to make sure the low 11 bits are zero. (If this 8292 // is the case, we are guaranteed the value will fit into the 53 bit 8293 // mantissa of an IEEE double-precision value without rounding.) 8294 // If any of those low 11 bits were not zero originally, make sure 8295 // bit 12 (value 2048) is set instead, so that the final rounding 8296 // to single-precision gets the correct result. 8297 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8298 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8299 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8300 Round, DAG.getConstant(2047, dl, MVT::i64)); 8301 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8302 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8303 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8304 8305 // However, we cannot use that value unconditionally: if the magnitude 8306 // of the input value is small, the bit-twiddling we did above might 8307 // end up visibly changing the output. Fortunately, in that case, we 8308 // don't need to twiddle bits since the original input will convert 8309 // exactly to double-precision floating-point already. Therefore, 8310 // construct a conditional to use the original value if the top 11 8311 // bits are all sign-bit copies, and use the rounded value computed 8312 // above otherwise. 8313 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8314 SINT, DAG.getConstant(53, dl, MVT::i32)); 8315 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8316 Cond, DAG.getConstant(1, dl, MVT::i64)); 8317 Cond = DAG.getSetCC( 8318 dl, 8319 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8320 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8321 8322 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8323 } 8324 8325 ReuseLoadInfo RLI; 8326 SDValue Bits; 8327 8328 MachineFunction &MF = DAG.getMachineFunction(); 8329 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8330 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8331 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8332 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8333 } else if (Subtarget.hasLFIWAX() && 8334 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8335 MachineMemOperand *MMO = 8336 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8337 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8338 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8339 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8340 DAG.getVTList(MVT::f64, MVT::Other), 8341 Ops, MVT::i32, MMO); 8342 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8343 } else if (Subtarget.hasFPCVT() && 8344 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8345 MachineMemOperand *MMO = 8346 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8347 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8348 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8349 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8350 DAG.getVTList(MVT::f64, MVT::Other), 8351 Ops, MVT::i32, MMO); 8352 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8353 } else if (((Subtarget.hasLFIWAX() && 8354 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8355 (Subtarget.hasFPCVT() && 8356 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8357 SINT.getOperand(0).getValueType() == MVT::i32) { 8358 MachineFrameInfo &MFI = MF.getFrameInfo(); 8359 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8360 8361 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8362 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8363 8364 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8365 MachinePointerInfo::getFixedStack( 8366 DAG.getMachineFunction(), FrameIdx)); 8367 Chain = Store; 8368 8369 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8370 "Expected an i32 store"); 8371 8372 RLI.Ptr = FIdx; 8373 RLI.Chain = Chain; 8374 RLI.MPI = 8375 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8376 RLI.Alignment = Align(4); 8377 8378 MachineMemOperand *MMO = 8379 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8380 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8381 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8382 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8383 PPCISD::LFIWZX : PPCISD::LFIWAX, 8384 dl, DAG.getVTList(MVT::f64, MVT::Other), 8385 Ops, MVT::i32, MMO); 8386 Chain = Bits.getValue(1); 8387 } else 8388 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8389 8390 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8391 if (IsStrict) 8392 Chain = FP.getValue(1); 8393 8394 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8395 if (IsStrict) 8396 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8397 DAG.getVTList(MVT::f32, MVT::Other), 8398 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8399 else 8400 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8401 DAG.getIntPtrConstant(0, dl)); 8402 } 8403 return FP; 8404 } 8405 8406 assert(Src.getValueType() == MVT::i32 && 8407 "Unhandled INT_TO_FP type in custom expander!"); 8408 // Since we only generate this in 64-bit mode, we can take advantage of 8409 // 64-bit registers. In particular, sign extend the input value into the 8410 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8411 // then lfd it and fcfid it. 8412 MachineFunction &MF = DAG.getMachineFunction(); 8413 MachineFrameInfo &MFI = MF.getFrameInfo(); 8414 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8415 8416 SDValue Ld; 8417 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8418 ReuseLoadInfo RLI; 8419 bool ReusingLoad; 8420 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8421 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8422 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8423 8424 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8425 MachinePointerInfo::getFixedStack( 8426 DAG.getMachineFunction(), FrameIdx)); 8427 Chain = Store; 8428 8429 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8430 "Expected an i32 store"); 8431 8432 RLI.Ptr = FIdx; 8433 RLI.Chain = Chain; 8434 RLI.MPI = 8435 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8436 RLI.Alignment = Align(4); 8437 } 8438 8439 MachineMemOperand *MMO = 8440 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8441 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8442 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8443 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8444 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8445 MVT::i32, MMO); 8446 Chain = Ld.getValue(1); 8447 if (ReusingLoad) 8448 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8449 } else { 8450 assert(Subtarget.isPPC64() && 8451 "i32->FP without LFIWAX supported only on PPC64"); 8452 8453 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8454 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8455 8456 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8457 8458 // STD the extended value into the stack slot. 8459 SDValue Store = DAG.getStore( 8460 Chain, dl, Ext64, FIdx, 8461 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8462 Chain = Store; 8463 8464 // Load the value as a double. 8465 Ld = DAG.getLoad( 8466 MVT::f64, dl, Chain, FIdx, 8467 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8468 Chain = Ld.getValue(1); 8469 } 8470 8471 // FCFID it and return it. 8472 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8473 if (IsStrict) 8474 Chain = FP.getValue(1); 8475 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8476 if (IsStrict) 8477 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8478 DAG.getVTList(MVT::f32, MVT::Other), 8479 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8480 else 8481 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8482 DAG.getIntPtrConstant(0, dl)); 8483 } 8484 return FP; 8485 } 8486 8487 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8488 SelectionDAG &DAG) const { 8489 SDLoc dl(Op); 8490 /* 8491 The rounding mode is in bits 30:31 of FPSR, and has the following 8492 settings: 8493 00 Round to nearest 8494 01 Round to 0 8495 10 Round to +inf 8496 11 Round to -inf 8497 8498 FLT_ROUNDS, on the other hand, expects the following: 8499 -1 Undefined 8500 0 Round to 0 8501 1 Round to nearest 8502 2 Round to +inf 8503 3 Round to -inf 8504 8505 To perform the conversion, we do: 8506 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8507 */ 8508 8509 MachineFunction &MF = DAG.getMachineFunction(); 8510 EVT VT = Op.getValueType(); 8511 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8512 8513 // Save FP Control Word to register 8514 SDValue Chain = Op.getOperand(0); 8515 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8516 Chain = MFFS.getValue(1); 8517 8518 SDValue CWD; 8519 if (isTypeLegal(MVT::i64)) { 8520 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8521 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8522 } else { 8523 // Save FP register to stack slot 8524 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8525 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8526 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8527 8528 // Load FP Control Word from low 32 bits of stack slot. 8529 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8530 "Stack slot adjustment is valid only on big endian subtargets!"); 8531 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8532 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8533 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8534 Chain = CWD.getValue(1); 8535 } 8536 8537 // Transform as necessary 8538 SDValue CWD1 = 8539 DAG.getNode(ISD::AND, dl, MVT::i32, 8540 CWD, DAG.getConstant(3, dl, MVT::i32)); 8541 SDValue CWD2 = 8542 DAG.getNode(ISD::SRL, dl, MVT::i32, 8543 DAG.getNode(ISD::AND, dl, MVT::i32, 8544 DAG.getNode(ISD::XOR, dl, MVT::i32, 8545 CWD, DAG.getConstant(3, dl, MVT::i32)), 8546 DAG.getConstant(3, dl, MVT::i32)), 8547 DAG.getConstant(1, dl, MVT::i32)); 8548 8549 SDValue RetVal = 8550 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8551 8552 RetVal = 8553 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8554 dl, VT, RetVal); 8555 8556 return DAG.getMergeValues({RetVal, Chain}, dl); 8557 } 8558 8559 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8560 EVT VT = Op.getValueType(); 8561 unsigned BitWidth = VT.getSizeInBits(); 8562 SDLoc dl(Op); 8563 assert(Op.getNumOperands() == 3 && 8564 VT == Op.getOperand(1).getValueType() && 8565 "Unexpected SHL!"); 8566 8567 // Expand into a bunch of logical ops. Note that these ops 8568 // depend on the PPC behavior for oversized shift amounts. 8569 SDValue Lo = Op.getOperand(0); 8570 SDValue Hi = Op.getOperand(1); 8571 SDValue Amt = Op.getOperand(2); 8572 EVT AmtVT = Amt.getValueType(); 8573 8574 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8575 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8576 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8577 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8578 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8579 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8580 DAG.getConstant(-BitWidth, dl, AmtVT)); 8581 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8582 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8583 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8584 SDValue OutOps[] = { OutLo, OutHi }; 8585 return DAG.getMergeValues(OutOps, dl); 8586 } 8587 8588 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8589 EVT VT = Op.getValueType(); 8590 SDLoc dl(Op); 8591 unsigned BitWidth = VT.getSizeInBits(); 8592 assert(Op.getNumOperands() == 3 && 8593 VT == Op.getOperand(1).getValueType() && 8594 "Unexpected SRL!"); 8595 8596 // Expand into a bunch of logical ops. Note that these ops 8597 // depend on the PPC behavior for oversized shift amounts. 8598 SDValue Lo = Op.getOperand(0); 8599 SDValue Hi = Op.getOperand(1); 8600 SDValue Amt = Op.getOperand(2); 8601 EVT AmtVT = Amt.getValueType(); 8602 8603 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8604 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8605 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8606 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8607 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8608 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8609 DAG.getConstant(-BitWidth, dl, AmtVT)); 8610 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8611 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8612 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8613 SDValue OutOps[] = { OutLo, OutHi }; 8614 return DAG.getMergeValues(OutOps, dl); 8615 } 8616 8617 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8618 SDLoc dl(Op); 8619 EVT VT = Op.getValueType(); 8620 unsigned BitWidth = VT.getSizeInBits(); 8621 assert(Op.getNumOperands() == 3 && 8622 VT == Op.getOperand(1).getValueType() && 8623 "Unexpected SRA!"); 8624 8625 // Expand into a bunch of logical ops, followed by a select_cc. 8626 SDValue Lo = Op.getOperand(0); 8627 SDValue Hi = Op.getOperand(1); 8628 SDValue Amt = Op.getOperand(2); 8629 EVT AmtVT = Amt.getValueType(); 8630 8631 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8632 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8633 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8634 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8635 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8636 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8637 DAG.getConstant(-BitWidth, dl, AmtVT)); 8638 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8639 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8640 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8641 Tmp4, Tmp6, ISD::SETLE); 8642 SDValue OutOps[] = { OutLo, OutHi }; 8643 return DAG.getMergeValues(OutOps, dl); 8644 } 8645 8646 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8647 SelectionDAG &DAG) const { 8648 SDLoc dl(Op); 8649 EVT VT = Op.getValueType(); 8650 unsigned BitWidth = VT.getSizeInBits(); 8651 8652 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8653 SDValue X = Op.getOperand(0); 8654 SDValue Y = Op.getOperand(1); 8655 SDValue Z = Op.getOperand(2); 8656 EVT AmtVT = Z.getValueType(); 8657 8658 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8659 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8660 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8661 // on PowerPC shift by BW being well defined. 8662 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8663 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8664 SDValue SubZ = 8665 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8666 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8667 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8668 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8669 } 8670 8671 //===----------------------------------------------------------------------===// 8672 // Vector related lowering. 8673 // 8674 8675 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8676 /// element size of SplatSize. Cast the result to VT. 8677 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8678 SelectionDAG &DAG, const SDLoc &dl) { 8679 static const MVT VTys[] = { // canonical VT to use for each size. 8680 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8681 }; 8682 8683 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8684 8685 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8686 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8687 SplatSize = 1; 8688 Val = 0xFF; 8689 } 8690 8691 EVT CanonicalVT = VTys[SplatSize-1]; 8692 8693 // Build a canonical splat for this value. 8694 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8695 } 8696 8697 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8698 /// specified intrinsic ID. 8699 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8700 const SDLoc &dl, EVT DestVT = MVT::Other) { 8701 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8702 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8703 DAG.getConstant(IID, dl, MVT::i32), Op); 8704 } 8705 8706 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8707 /// specified intrinsic ID. 8708 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8709 SelectionDAG &DAG, const SDLoc &dl, 8710 EVT DestVT = MVT::Other) { 8711 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8712 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8713 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8714 } 8715 8716 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8717 /// specified intrinsic ID. 8718 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8719 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8720 EVT DestVT = MVT::Other) { 8721 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8722 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8723 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8724 } 8725 8726 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8727 /// amount. The result has the specified value type. 8728 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8729 SelectionDAG &DAG, const SDLoc &dl) { 8730 // Force LHS/RHS to be the right type. 8731 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8732 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8733 8734 int Ops[16]; 8735 for (unsigned i = 0; i != 16; ++i) 8736 Ops[i] = i + Amt; 8737 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8738 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8739 } 8740 8741 /// Do we have an efficient pattern in a .td file for this node? 8742 /// 8743 /// \param V - pointer to the BuildVectorSDNode being matched 8744 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8745 /// 8746 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8747 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8748 /// the opposite is true (expansion is beneficial) are: 8749 /// - The node builds a vector out of integers that are not 32 or 64-bits 8750 /// - The node builds a vector out of constants 8751 /// - The node is a "load-and-splat" 8752 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8753 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8754 bool HasDirectMove, 8755 bool HasP8Vector) { 8756 EVT VecVT = V->getValueType(0); 8757 bool RightType = VecVT == MVT::v2f64 || 8758 (HasP8Vector && VecVT == MVT::v4f32) || 8759 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8760 if (!RightType) 8761 return false; 8762 8763 bool IsSplat = true; 8764 bool IsLoad = false; 8765 SDValue Op0 = V->getOperand(0); 8766 8767 // This function is called in a block that confirms the node is not a constant 8768 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8769 // different constants. 8770 if (V->isConstant()) 8771 return false; 8772 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8773 if (V->getOperand(i).isUndef()) 8774 return false; 8775 // We want to expand nodes that represent load-and-splat even if the 8776 // loaded value is a floating point truncation or conversion to int. 8777 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8778 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8779 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8780 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8781 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8782 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8783 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8784 IsLoad = true; 8785 // If the operands are different or the input is not a load and has more 8786 // uses than just this BV node, then it isn't a splat. 8787 if (V->getOperand(i) != Op0 || 8788 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8789 IsSplat = false; 8790 } 8791 return !(IsSplat && IsLoad); 8792 } 8793 8794 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8795 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8796 8797 SDLoc dl(Op); 8798 SDValue Op0 = Op->getOperand(0); 8799 8800 if ((Op.getValueType() != MVT::f128) || 8801 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8802 (Op0.getOperand(0).getValueType() != MVT::i64) || 8803 (Op0.getOperand(1).getValueType() != MVT::i64)) 8804 return SDValue(); 8805 8806 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8807 Op0.getOperand(1)); 8808 } 8809 8810 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 8811 const SDValue *InputLoad = &Op; 8812 if (InputLoad->getOpcode() == ISD::BITCAST) 8813 InputLoad = &InputLoad->getOperand(0); 8814 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 8815 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 8816 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 8817 InputLoad = &InputLoad->getOperand(0); 8818 } 8819 if (InputLoad->getOpcode() != ISD::LOAD) 8820 return nullptr; 8821 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8822 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8823 } 8824 8825 // Convert the argument APFloat to a single precision APFloat if there is no 8826 // loss in information during the conversion to single precision APFloat and the 8827 // resulting number is not a denormal number. Return true if successful. 8828 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 8829 APFloat APFloatToConvert = ArgAPFloat; 8830 bool LosesInfo = true; 8831 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8832 &LosesInfo); 8833 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 8834 if (Success) 8835 ArgAPFloat = APFloatToConvert; 8836 return Success; 8837 } 8838 8839 // Bitcast the argument APInt to a double and convert it to a single precision 8840 // APFloat, bitcast the APFloat to an APInt and assign it to the original 8841 // argument if there is no loss in information during the conversion from 8842 // double to single precision APFloat and the resulting number is not a denormal 8843 // number. Return true if successful. 8844 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 8845 double DpValue = ArgAPInt.bitsToDouble(); 8846 APFloat APFloatDp(DpValue); 8847 bool Success = convertToNonDenormSingle(APFloatDp); 8848 if (Success) 8849 ArgAPInt = APFloatDp.bitcastToAPInt(); 8850 return Success; 8851 } 8852 8853 // Nondestructive check for convertTonNonDenormSingle. 8854 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 8855 // Only convert if it loses info, since XXSPLTIDP should 8856 // handle the other case. 8857 APFloat APFloatToConvert = ArgAPFloat; 8858 bool LosesInfo = true; 8859 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8860 &LosesInfo); 8861 8862 return (!LosesInfo && !APFloatToConvert.isDenormal()); 8863 } 8864 8865 // If this is a case we can't handle, return null and let the default 8866 // expansion code take care of it. If we CAN select this case, and if it 8867 // selects to a single instruction, return Op. Otherwise, if we can codegen 8868 // this case more efficiently than a constant pool load, lower it to the 8869 // sequence of ops that should be used. 8870 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8871 SelectionDAG &DAG) const { 8872 SDLoc dl(Op); 8873 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8874 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8875 8876 // Check if this is a splat of a constant value. 8877 APInt APSplatBits, APSplatUndef; 8878 unsigned SplatBitSize; 8879 bool HasAnyUndefs; 8880 bool BVNIsConstantSplat = 8881 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8882 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 8883 8884 // If it is a splat of a double, check if we can shrink it to a 32 bit 8885 // non-denormal float which when converted back to double gives us the same 8886 // double. This is to exploit the XXSPLTIDP instruction. 8887 // If we lose precision, we use XXSPLTI32DX. 8888 if (BVNIsConstantSplat && (SplatBitSize == 64) && 8889 Subtarget.hasPrefixInstrs()) { 8890 // Check the type first to short-circuit so we don't modify APSplatBits if 8891 // this block isn't executed. 8892 if ((Op->getValueType(0) == MVT::v2f64) && 8893 convertToNonDenormSingle(APSplatBits)) { 8894 SDValue SplatNode = DAG.getNode( 8895 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 8896 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 8897 return DAG.getBitcast(Op.getValueType(), SplatNode); 8898 } else { 8899 // We may lose precision, so we have to use XXSPLTI32DX. 8900 8901 uint32_t Hi = 8902 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 8903 uint32_t Lo = 8904 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 8905 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 8906 8907 if (!Hi || !Lo) 8908 // If either load is 0, then we should generate XXLXOR to set to 0. 8909 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 8910 8911 if (Hi) 8912 SplatNode = DAG.getNode( 8913 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 8914 DAG.getTargetConstant(0, dl, MVT::i32), 8915 DAG.getTargetConstant(Hi, dl, MVT::i32)); 8916 8917 if (Lo) 8918 SplatNode = 8919 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 8920 DAG.getTargetConstant(1, dl, MVT::i32), 8921 DAG.getTargetConstant(Lo, dl, MVT::i32)); 8922 8923 return DAG.getBitcast(Op.getValueType(), SplatNode); 8924 } 8925 } 8926 8927 if (!BVNIsConstantSplat || SplatBitSize > 32) { 8928 8929 bool IsPermutedLoad = false; 8930 const SDValue *InputLoad = 8931 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 8932 // Handle load-and-splat patterns as we have instructions that will do this 8933 // in one go. 8934 if (InputLoad && DAG.isSplatValue(Op, true)) { 8935 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8936 8937 // We have handling for 4 and 8 byte elements. 8938 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8939 8940 // Checking for a single use of this load, we have to check for vector 8941 // width (128 bits) / ElementSize uses (since each operand of the 8942 // BUILD_VECTOR is a separate use of the value. 8943 unsigned NumUsesOfInputLD = 128 / ElementSize; 8944 for (SDValue BVInOp : Op->ops()) 8945 if (BVInOp.isUndef()) 8946 NumUsesOfInputLD--; 8947 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 8948 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 8949 ((Subtarget.hasVSX() && ElementSize == 64) || 8950 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8951 SDValue Ops[] = { 8952 LD->getChain(), // Chain 8953 LD->getBasePtr(), // Ptr 8954 DAG.getValueType(Op.getValueType()) // VT 8955 }; 8956 SDValue LdSplt = DAG.getMemIntrinsicNode( 8957 PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8958 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8959 // Replace all uses of the output chain of the original load with the 8960 // output chain of the new load. 8961 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 8962 LdSplt.getValue(1)); 8963 return LdSplt; 8964 } 8965 } 8966 8967 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 8968 // 32-bits can be lowered to VSX instructions under certain conditions. 8969 // Without VSX, there is no pattern more efficient than expanding the node. 8970 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 8971 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8972 Subtarget.hasP8Vector())) 8973 return Op; 8974 return SDValue(); 8975 } 8976 8977 uint64_t SplatBits = APSplatBits.getZExtValue(); 8978 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 8979 unsigned SplatSize = SplatBitSize / 8; 8980 8981 // First, handle single instruction cases. 8982 8983 // All zeros? 8984 if (SplatBits == 0) { 8985 // Canonicalize all zero vectors to be v4i32. 8986 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8987 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8988 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8989 } 8990 return Op; 8991 } 8992 8993 // We have XXSPLTIW for constant splats four bytes wide. 8994 // Given vector length is a multiple of 4, 2-byte splats can be replaced 8995 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 8996 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 8997 // turned into a 4-byte splat of 0xABABABAB. 8998 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 8999 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9000 Op.getValueType(), DAG, dl); 9001 9002 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9003 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9004 dl); 9005 9006 // We have XXSPLTIB for constant splats one byte wide. 9007 if (Subtarget.hasP9Vector() && SplatSize == 1) 9008 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9009 dl); 9010 9011 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9012 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9013 (32-SplatBitSize)); 9014 if (SextVal >= -16 && SextVal <= 15) 9015 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9016 dl); 9017 9018 // Two instruction sequences. 9019 9020 // If this value is in the range [-32,30] and is even, use: 9021 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9022 // If this value is in the range [17,31] and is odd, use: 9023 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9024 // If this value is in the range [-31,-17] and is odd, use: 9025 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9026 // Note the last two are three-instruction sequences. 9027 if (SextVal >= -32 && SextVal <= 31) { 9028 // To avoid having these optimizations undone by constant folding, 9029 // we convert to a pseudo that will be expanded later into one of 9030 // the above forms. 9031 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9032 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9033 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9034 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9035 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9036 if (VT == Op.getValueType()) 9037 return RetVal; 9038 else 9039 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9040 } 9041 9042 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9043 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9044 // for fneg/fabs. 9045 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9046 // Make -1 and vspltisw -1: 9047 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9048 9049 // Make the VSLW intrinsic, computing 0x8000_0000. 9050 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9051 OnesV, DAG, dl); 9052 9053 // xor by OnesV to invert it. 9054 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9055 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9056 } 9057 9058 // Check to see if this is a wide variety of vsplti*, binop self cases. 9059 static const signed char SplatCsts[] = { 9060 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9061 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9062 }; 9063 9064 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9065 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9066 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9067 int i = SplatCsts[idx]; 9068 9069 // Figure out what shift amount will be used by altivec if shifted by i in 9070 // this splat size. 9071 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9072 9073 // vsplti + shl self. 9074 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9075 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9076 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9077 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9078 Intrinsic::ppc_altivec_vslw 9079 }; 9080 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9081 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9082 } 9083 9084 // vsplti + srl self. 9085 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9086 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9087 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9088 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9089 Intrinsic::ppc_altivec_vsrw 9090 }; 9091 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9092 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9093 } 9094 9095 // vsplti + rol self. 9096 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9097 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9098 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9099 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9100 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9101 Intrinsic::ppc_altivec_vrlw 9102 }; 9103 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9104 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9105 } 9106 9107 // t = vsplti c, result = vsldoi t, t, 1 9108 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9109 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9110 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9111 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9112 } 9113 // t = vsplti c, result = vsldoi t, t, 2 9114 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9115 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9116 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9117 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9118 } 9119 // t = vsplti c, result = vsldoi t, t, 3 9120 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9121 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9122 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9123 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9124 } 9125 } 9126 9127 return SDValue(); 9128 } 9129 9130 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9131 /// the specified operations to build the shuffle. 9132 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9133 SDValue RHS, SelectionDAG &DAG, 9134 const SDLoc &dl) { 9135 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9136 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9137 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9138 9139 enum { 9140 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9141 OP_VMRGHW, 9142 OP_VMRGLW, 9143 OP_VSPLTISW0, 9144 OP_VSPLTISW1, 9145 OP_VSPLTISW2, 9146 OP_VSPLTISW3, 9147 OP_VSLDOI4, 9148 OP_VSLDOI8, 9149 OP_VSLDOI12 9150 }; 9151 9152 if (OpNum == OP_COPY) { 9153 if (LHSID == (1*9+2)*9+3) return LHS; 9154 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9155 return RHS; 9156 } 9157 9158 SDValue OpLHS, OpRHS; 9159 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9160 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9161 9162 int ShufIdxs[16]; 9163 switch (OpNum) { 9164 default: llvm_unreachable("Unknown i32 permute!"); 9165 case OP_VMRGHW: 9166 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9167 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9168 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9169 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9170 break; 9171 case OP_VMRGLW: 9172 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9173 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9174 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9175 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9176 break; 9177 case OP_VSPLTISW0: 9178 for (unsigned i = 0; i != 16; ++i) 9179 ShufIdxs[i] = (i&3)+0; 9180 break; 9181 case OP_VSPLTISW1: 9182 for (unsigned i = 0; i != 16; ++i) 9183 ShufIdxs[i] = (i&3)+4; 9184 break; 9185 case OP_VSPLTISW2: 9186 for (unsigned i = 0; i != 16; ++i) 9187 ShufIdxs[i] = (i&3)+8; 9188 break; 9189 case OP_VSPLTISW3: 9190 for (unsigned i = 0; i != 16; ++i) 9191 ShufIdxs[i] = (i&3)+12; 9192 break; 9193 case OP_VSLDOI4: 9194 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9195 case OP_VSLDOI8: 9196 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9197 case OP_VSLDOI12: 9198 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9199 } 9200 EVT VT = OpLHS.getValueType(); 9201 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9202 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9203 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9204 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9205 } 9206 9207 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9208 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9209 /// SDValue. 9210 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9211 SelectionDAG &DAG) const { 9212 const unsigned BytesInVector = 16; 9213 bool IsLE = Subtarget.isLittleEndian(); 9214 SDLoc dl(N); 9215 SDValue V1 = N->getOperand(0); 9216 SDValue V2 = N->getOperand(1); 9217 unsigned ShiftElts = 0, InsertAtByte = 0; 9218 bool Swap = false; 9219 9220 // Shifts required to get the byte we want at element 7. 9221 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9222 0, 15, 14, 13, 12, 11, 10, 9}; 9223 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9224 1, 2, 3, 4, 5, 6, 7, 8}; 9225 9226 ArrayRef<int> Mask = N->getMask(); 9227 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9228 9229 // For each mask element, find out if we're just inserting something 9230 // from V2 into V1 or vice versa. 9231 // Possible permutations inserting an element from V2 into V1: 9232 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9233 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9234 // ... 9235 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9236 // Inserting from V1 into V2 will be similar, except mask range will be 9237 // [16,31]. 9238 9239 bool FoundCandidate = false; 9240 // If both vector operands for the shuffle are the same vector, the mask 9241 // will contain only elements from the first one and the second one will be 9242 // undef. 9243 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9244 // Go through the mask of half-words to find an element that's being moved 9245 // from one vector to the other. 9246 for (unsigned i = 0; i < BytesInVector; ++i) { 9247 unsigned CurrentElement = Mask[i]; 9248 // If 2nd operand is undefined, we should only look for element 7 in the 9249 // Mask. 9250 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9251 continue; 9252 9253 bool OtherElementsInOrder = true; 9254 // Examine the other elements in the Mask to see if they're in original 9255 // order. 9256 for (unsigned j = 0; j < BytesInVector; ++j) { 9257 if (j == i) 9258 continue; 9259 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9260 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9261 // in which we always assume we're always picking from the 1st operand. 9262 int MaskOffset = 9263 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9264 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9265 OtherElementsInOrder = false; 9266 break; 9267 } 9268 } 9269 // If other elements are in original order, we record the number of shifts 9270 // we need to get the element we want into element 7. Also record which byte 9271 // in the vector we should insert into. 9272 if (OtherElementsInOrder) { 9273 // If 2nd operand is undefined, we assume no shifts and no swapping. 9274 if (V2.isUndef()) { 9275 ShiftElts = 0; 9276 Swap = false; 9277 } else { 9278 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9279 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9280 : BigEndianShifts[CurrentElement & 0xF]; 9281 Swap = CurrentElement < BytesInVector; 9282 } 9283 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9284 FoundCandidate = true; 9285 break; 9286 } 9287 } 9288 9289 if (!FoundCandidate) 9290 return SDValue(); 9291 9292 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9293 // optionally with VECSHL if shift is required. 9294 if (Swap) 9295 std::swap(V1, V2); 9296 if (V2.isUndef()) 9297 V2 = V1; 9298 if (ShiftElts) { 9299 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9300 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9301 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9302 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9303 } 9304 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9305 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9306 } 9307 9308 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9309 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9310 /// SDValue. 9311 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9312 SelectionDAG &DAG) const { 9313 const unsigned NumHalfWords = 8; 9314 const unsigned BytesInVector = NumHalfWords * 2; 9315 // Check that the shuffle is on half-words. 9316 if (!isNByteElemShuffleMask(N, 2, 1)) 9317 return SDValue(); 9318 9319 bool IsLE = Subtarget.isLittleEndian(); 9320 SDLoc dl(N); 9321 SDValue V1 = N->getOperand(0); 9322 SDValue V2 = N->getOperand(1); 9323 unsigned ShiftElts = 0, InsertAtByte = 0; 9324 bool Swap = false; 9325 9326 // Shifts required to get the half-word we want at element 3. 9327 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9328 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9329 9330 uint32_t Mask = 0; 9331 uint32_t OriginalOrderLow = 0x1234567; 9332 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9333 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9334 // 32-bit space, only need 4-bit nibbles per element. 9335 for (unsigned i = 0; i < NumHalfWords; ++i) { 9336 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9337 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9338 } 9339 9340 // For each mask element, find out if we're just inserting something 9341 // from V2 into V1 or vice versa. Possible permutations inserting an element 9342 // from V2 into V1: 9343 // X, 1, 2, 3, 4, 5, 6, 7 9344 // 0, X, 2, 3, 4, 5, 6, 7 9345 // 0, 1, X, 3, 4, 5, 6, 7 9346 // 0, 1, 2, X, 4, 5, 6, 7 9347 // 0, 1, 2, 3, X, 5, 6, 7 9348 // 0, 1, 2, 3, 4, X, 6, 7 9349 // 0, 1, 2, 3, 4, 5, X, 7 9350 // 0, 1, 2, 3, 4, 5, 6, X 9351 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9352 9353 bool FoundCandidate = false; 9354 // Go through the mask of half-words to find an element that's being moved 9355 // from one vector to the other. 9356 for (unsigned i = 0; i < NumHalfWords; ++i) { 9357 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9358 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9359 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9360 uint32_t TargetOrder = 0x0; 9361 9362 // If both vector operands for the shuffle are the same vector, the mask 9363 // will contain only elements from the first one and the second one will be 9364 // undef. 9365 if (V2.isUndef()) { 9366 ShiftElts = 0; 9367 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9368 TargetOrder = OriginalOrderLow; 9369 Swap = false; 9370 // Skip if not the correct element or mask of other elements don't equal 9371 // to our expected order. 9372 if (MaskOneElt == VINSERTHSrcElem && 9373 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9374 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9375 FoundCandidate = true; 9376 break; 9377 } 9378 } else { // If both operands are defined. 9379 // Target order is [8,15] if the current mask is between [0,7]. 9380 TargetOrder = 9381 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9382 // Skip if mask of other elements don't equal our expected order. 9383 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9384 // We only need the last 3 bits for the number of shifts. 9385 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9386 : BigEndianShifts[MaskOneElt & 0x7]; 9387 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9388 Swap = MaskOneElt < NumHalfWords; 9389 FoundCandidate = true; 9390 break; 9391 } 9392 } 9393 } 9394 9395 if (!FoundCandidate) 9396 return SDValue(); 9397 9398 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9399 // optionally with VECSHL if shift is required. 9400 if (Swap) 9401 std::swap(V1, V2); 9402 if (V2.isUndef()) 9403 V2 = V1; 9404 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9405 if (ShiftElts) { 9406 // Double ShiftElts because we're left shifting on v16i8 type. 9407 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9408 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9409 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9410 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9411 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9412 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9413 } 9414 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9415 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9416 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9417 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9418 } 9419 9420 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9421 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9422 /// return the default SDValue. 9423 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9424 SelectionDAG &DAG) const { 9425 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9426 // to v16i8. Peek through the bitcasts to get the actual operands. 9427 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9428 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9429 9430 auto ShuffleMask = SVN->getMask(); 9431 SDValue VecShuffle(SVN, 0); 9432 SDLoc DL(SVN); 9433 9434 // Check that we have a four byte shuffle. 9435 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9436 return SDValue(); 9437 9438 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9439 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9440 std::swap(LHS, RHS); 9441 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9442 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9443 } 9444 9445 // Ensure that the RHS is a vector of constants. 9446 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9447 if (!BVN) 9448 return SDValue(); 9449 9450 // Check if RHS is a splat of 4-bytes (or smaller). 9451 APInt APSplatValue, APSplatUndef; 9452 unsigned SplatBitSize; 9453 bool HasAnyUndefs; 9454 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9455 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9456 SplatBitSize > 32) 9457 return SDValue(); 9458 9459 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9460 // The instruction splats a constant C into two words of the source vector 9461 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9462 // Thus we check that the shuffle mask is the equivalent of 9463 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9464 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9465 // within each word are consecutive, so we only need to check the first byte. 9466 SDValue Index; 9467 bool IsLE = Subtarget.isLittleEndian(); 9468 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9469 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9470 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9471 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9472 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9473 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9474 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9475 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9476 else 9477 return SDValue(); 9478 9479 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9480 // for XXSPLTI32DX. 9481 unsigned SplatVal = APSplatValue.getZExtValue(); 9482 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9483 SplatVal |= (SplatVal << SplatBitSize); 9484 9485 SDValue SplatNode = DAG.getNode( 9486 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9487 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9488 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9489 } 9490 9491 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9492 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9493 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9494 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9495 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9496 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9497 assert(Op.getValueType() == MVT::v1i128 && 9498 "Only set v1i128 as custom, other type shouldn't reach here!"); 9499 SDLoc dl(Op); 9500 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9501 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9502 unsigned SHLAmt = N1.getConstantOperandVal(0); 9503 if (SHLAmt % 8 == 0) { 9504 SmallVector<int, 16> Mask(16, 0); 9505 std::iota(Mask.begin(), Mask.end(), 0); 9506 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9507 if (SDValue Shuffle = 9508 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9509 DAG.getUNDEF(MVT::v16i8), Mask)) 9510 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9511 } 9512 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9513 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9514 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9515 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9516 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9517 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9518 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9519 } 9520 9521 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9522 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9523 /// return the code it can be lowered into. Worst case, it can always be 9524 /// lowered into a vperm. 9525 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9526 SelectionDAG &DAG) const { 9527 SDLoc dl(Op); 9528 SDValue V1 = Op.getOperand(0); 9529 SDValue V2 = Op.getOperand(1); 9530 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9531 9532 // Any nodes that were combined in the target-independent combiner prior 9533 // to vector legalization will not be sent to the target combine. Try to 9534 // combine it here. 9535 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9536 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9537 return NewShuffle; 9538 Op = NewShuffle; 9539 SVOp = cast<ShuffleVectorSDNode>(Op); 9540 V1 = Op.getOperand(0); 9541 V2 = Op.getOperand(1); 9542 } 9543 EVT VT = Op.getValueType(); 9544 bool isLittleEndian = Subtarget.isLittleEndian(); 9545 9546 unsigned ShiftElts, InsertAtByte; 9547 bool Swap = false; 9548 9549 // If this is a load-and-splat, we can do that with a single instruction 9550 // in some cases. However if the load has multiple uses, we don't want to 9551 // combine it because that will just produce multiple loads. 9552 bool IsPermutedLoad = false; 9553 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9554 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9555 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9556 InputLoad->hasOneUse()) { 9557 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9558 int SplatIdx = 9559 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9560 9561 // The splat index for permuted loads will be in the left half of the vector 9562 // which is strictly wider than the loaded value by 8 bytes. So we need to 9563 // adjust the splat index to point to the correct address in memory. 9564 if (IsPermutedLoad) { 9565 assert((isLittleEndian || IsFourByte) && 9566 "Unexpected size for permuted load on big endian target"); 9567 SplatIdx += IsFourByte ? 2 : 1; 9568 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9569 "Splat of a value outside of the loaded memory"); 9570 } 9571 9572 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9573 // For 4-byte load-and-splat, we need Power9. 9574 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9575 uint64_t Offset = 0; 9576 if (IsFourByte) 9577 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9578 else 9579 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9580 9581 // If the width of the load is the same as the width of the splat, 9582 // loading with an offset would load the wrong memory. 9583 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9584 Offset = 0; 9585 9586 SDValue BasePtr = LD->getBasePtr(); 9587 if (Offset != 0) 9588 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9589 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9590 SDValue Ops[] = { 9591 LD->getChain(), // Chain 9592 BasePtr, // BasePtr 9593 DAG.getValueType(Op.getValueType()) // VT 9594 }; 9595 SDVTList VTL = 9596 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9597 SDValue LdSplt = 9598 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9599 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9600 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9601 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9602 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9603 return LdSplt; 9604 } 9605 } 9606 if (Subtarget.hasP9Vector() && 9607 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9608 isLittleEndian)) { 9609 if (Swap) 9610 std::swap(V1, V2); 9611 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9612 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9613 if (ShiftElts) { 9614 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9615 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9616 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9617 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9618 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9619 } 9620 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9621 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9622 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9623 } 9624 9625 if (Subtarget.hasPrefixInstrs()) { 9626 SDValue SplatInsertNode; 9627 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9628 return SplatInsertNode; 9629 } 9630 9631 if (Subtarget.hasP9Altivec()) { 9632 SDValue NewISDNode; 9633 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9634 return NewISDNode; 9635 9636 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9637 return NewISDNode; 9638 } 9639 9640 if (Subtarget.hasVSX() && 9641 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9642 if (Swap) 9643 std::swap(V1, V2); 9644 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9645 SDValue Conv2 = 9646 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9647 9648 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9649 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9650 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9651 } 9652 9653 if (Subtarget.hasVSX() && 9654 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9655 if (Swap) 9656 std::swap(V1, V2); 9657 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9658 SDValue Conv2 = 9659 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9660 9661 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9662 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9663 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9664 } 9665 9666 if (Subtarget.hasP9Vector()) { 9667 if (PPC::isXXBRHShuffleMask(SVOp)) { 9668 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9669 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9670 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9671 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9672 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9673 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9674 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9675 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9676 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9677 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9678 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9679 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9680 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9681 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9682 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9683 } 9684 } 9685 9686 if (Subtarget.hasVSX()) { 9687 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9688 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9689 9690 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9691 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9692 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9693 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9694 } 9695 9696 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9697 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9698 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9699 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9700 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9701 } 9702 } 9703 9704 // Cases that are handled by instructions that take permute immediates 9705 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9706 // selected by the instruction selector. 9707 if (V2.isUndef()) { 9708 if (PPC::isSplatShuffleMask(SVOp, 1) || 9709 PPC::isSplatShuffleMask(SVOp, 2) || 9710 PPC::isSplatShuffleMask(SVOp, 4) || 9711 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9712 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9713 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9714 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9715 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9716 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9717 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9718 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9719 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9720 (Subtarget.hasP8Altivec() && ( 9721 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9722 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9723 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9724 return Op; 9725 } 9726 } 9727 9728 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9729 // and produce a fixed permutation. If any of these match, do not lower to 9730 // VPERM. 9731 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9732 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9733 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9734 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9735 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9736 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9737 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9738 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9739 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9740 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9741 (Subtarget.hasP8Altivec() && ( 9742 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9743 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9744 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9745 return Op; 9746 9747 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9748 // perfect shuffle table to emit an optimal matching sequence. 9749 ArrayRef<int> PermMask = SVOp->getMask(); 9750 9751 unsigned PFIndexes[4]; 9752 bool isFourElementShuffle = true; 9753 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9754 unsigned EltNo = 8; // Start out undef. 9755 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9756 if (PermMask[i*4+j] < 0) 9757 continue; // Undef, ignore it. 9758 9759 unsigned ByteSource = PermMask[i*4+j]; 9760 if ((ByteSource & 3) != j) { 9761 isFourElementShuffle = false; 9762 break; 9763 } 9764 9765 if (EltNo == 8) { 9766 EltNo = ByteSource/4; 9767 } else if (EltNo != ByteSource/4) { 9768 isFourElementShuffle = false; 9769 break; 9770 } 9771 } 9772 PFIndexes[i] = EltNo; 9773 } 9774 9775 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9776 // perfect shuffle vector to determine if it is cost effective to do this as 9777 // discrete instructions, or whether we should use a vperm. 9778 // For now, we skip this for little endian until such time as we have a 9779 // little-endian perfect shuffle table. 9780 if (isFourElementShuffle && !isLittleEndian) { 9781 // Compute the index in the perfect shuffle table. 9782 unsigned PFTableIndex = 9783 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9784 9785 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9786 unsigned Cost = (PFEntry >> 30); 9787 9788 // Determining when to avoid vperm is tricky. Many things affect the cost 9789 // of vperm, particularly how many times the perm mask needs to be computed. 9790 // For example, if the perm mask can be hoisted out of a loop or is already 9791 // used (perhaps because there are multiple permutes with the same shuffle 9792 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9793 // the loop requires an extra register. 9794 // 9795 // As a compromise, we only emit discrete instructions if the shuffle can be 9796 // generated in 3 or fewer operations. When we have loop information 9797 // available, if this block is within a loop, we should avoid using vperm 9798 // for 3-operation perms and use a constant pool load instead. 9799 if (Cost < 3) 9800 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9801 } 9802 9803 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9804 // vector that will get spilled to the constant pool. 9805 if (V2.isUndef()) V2 = V1; 9806 9807 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9808 // that it is in input element units, not in bytes. Convert now. 9809 9810 // For little endian, the order of the input vectors is reversed, and 9811 // the permutation mask is complemented with respect to 31. This is 9812 // necessary to produce proper semantics with the big-endian-biased vperm 9813 // instruction. 9814 EVT EltVT = V1.getValueType().getVectorElementType(); 9815 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9816 9817 SmallVector<SDValue, 16> ResultMask; 9818 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9819 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9820 9821 for (unsigned j = 0; j != BytesPerElement; ++j) 9822 if (isLittleEndian) 9823 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9824 dl, MVT::i32)); 9825 else 9826 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9827 MVT::i32)); 9828 } 9829 9830 ShufflesHandledWithVPERM++; 9831 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9832 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9833 LLVM_DEBUG(SVOp->dump()); 9834 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9835 LLVM_DEBUG(VPermMask.dump()); 9836 9837 if (isLittleEndian) 9838 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9839 V2, V1, VPermMask); 9840 else 9841 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9842 V1, V2, VPermMask); 9843 } 9844 9845 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9846 /// vector comparison. If it is, return true and fill in Opc/isDot with 9847 /// information about the intrinsic. 9848 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9849 bool &isDot, const PPCSubtarget &Subtarget) { 9850 unsigned IntrinsicID = 9851 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9852 CompareOpc = -1; 9853 isDot = false; 9854 switch (IntrinsicID) { 9855 default: 9856 return false; 9857 // Comparison predicates. 9858 case Intrinsic::ppc_altivec_vcmpbfp_p: 9859 CompareOpc = 966; 9860 isDot = true; 9861 break; 9862 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9863 CompareOpc = 198; 9864 isDot = true; 9865 break; 9866 case Intrinsic::ppc_altivec_vcmpequb_p: 9867 CompareOpc = 6; 9868 isDot = true; 9869 break; 9870 case Intrinsic::ppc_altivec_vcmpequh_p: 9871 CompareOpc = 70; 9872 isDot = true; 9873 break; 9874 case Intrinsic::ppc_altivec_vcmpequw_p: 9875 CompareOpc = 134; 9876 isDot = true; 9877 break; 9878 case Intrinsic::ppc_altivec_vcmpequd_p: 9879 if (Subtarget.hasP8Altivec()) { 9880 CompareOpc = 199; 9881 isDot = true; 9882 } else 9883 return false; 9884 break; 9885 case Intrinsic::ppc_altivec_vcmpneb_p: 9886 case Intrinsic::ppc_altivec_vcmpneh_p: 9887 case Intrinsic::ppc_altivec_vcmpnew_p: 9888 case Intrinsic::ppc_altivec_vcmpnezb_p: 9889 case Intrinsic::ppc_altivec_vcmpnezh_p: 9890 case Intrinsic::ppc_altivec_vcmpnezw_p: 9891 if (Subtarget.hasP9Altivec()) { 9892 switch (IntrinsicID) { 9893 default: 9894 llvm_unreachable("Unknown comparison intrinsic."); 9895 case Intrinsic::ppc_altivec_vcmpneb_p: 9896 CompareOpc = 7; 9897 break; 9898 case Intrinsic::ppc_altivec_vcmpneh_p: 9899 CompareOpc = 71; 9900 break; 9901 case Intrinsic::ppc_altivec_vcmpnew_p: 9902 CompareOpc = 135; 9903 break; 9904 case Intrinsic::ppc_altivec_vcmpnezb_p: 9905 CompareOpc = 263; 9906 break; 9907 case Intrinsic::ppc_altivec_vcmpnezh_p: 9908 CompareOpc = 327; 9909 break; 9910 case Intrinsic::ppc_altivec_vcmpnezw_p: 9911 CompareOpc = 391; 9912 break; 9913 } 9914 isDot = true; 9915 } else 9916 return false; 9917 break; 9918 case Intrinsic::ppc_altivec_vcmpgefp_p: 9919 CompareOpc = 454; 9920 isDot = true; 9921 break; 9922 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9923 CompareOpc = 710; 9924 isDot = true; 9925 break; 9926 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9927 CompareOpc = 774; 9928 isDot = true; 9929 break; 9930 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9931 CompareOpc = 838; 9932 isDot = true; 9933 break; 9934 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9935 CompareOpc = 902; 9936 isDot = true; 9937 break; 9938 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9939 if (Subtarget.hasP8Altivec()) { 9940 CompareOpc = 967; 9941 isDot = true; 9942 } else 9943 return false; 9944 break; 9945 case Intrinsic::ppc_altivec_vcmpgtub_p: 9946 CompareOpc = 518; 9947 isDot = true; 9948 break; 9949 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9950 CompareOpc = 582; 9951 isDot = true; 9952 break; 9953 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9954 CompareOpc = 646; 9955 isDot = true; 9956 break; 9957 case Intrinsic::ppc_altivec_vcmpgtud_p: 9958 if (Subtarget.hasP8Altivec()) { 9959 CompareOpc = 711; 9960 isDot = true; 9961 } else 9962 return false; 9963 break; 9964 9965 case Intrinsic::ppc_altivec_vcmpequq: 9966 case Intrinsic::ppc_altivec_vcmpgtsq: 9967 case Intrinsic::ppc_altivec_vcmpgtuq: 9968 if (!Subtarget.isISA3_1()) 9969 return false; 9970 switch (IntrinsicID) { 9971 default: 9972 llvm_unreachable("Unknown comparison intrinsic."); 9973 case Intrinsic::ppc_altivec_vcmpequq: 9974 CompareOpc = 455; 9975 break; 9976 case Intrinsic::ppc_altivec_vcmpgtsq: 9977 CompareOpc = 903; 9978 break; 9979 case Intrinsic::ppc_altivec_vcmpgtuq: 9980 CompareOpc = 647; 9981 break; 9982 } 9983 break; 9984 9985 // VSX predicate comparisons use the same infrastructure 9986 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9987 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9988 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9989 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9990 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9991 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9992 if (Subtarget.hasVSX()) { 9993 switch (IntrinsicID) { 9994 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9995 CompareOpc = 99; 9996 break; 9997 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9998 CompareOpc = 115; 9999 break; 10000 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10001 CompareOpc = 107; 10002 break; 10003 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10004 CompareOpc = 67; 10005 break; 10006 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10007 CompareOpc = 83; 10008 break; 10009 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10010 CompareOpc = 75; 10011 break; 10012 } 10013 isDot = true; 10014 } else 10015 return false; 10016 break; 10017 10018 // Normal Comparisons. 10019 case Intrinsic::ppc_altivec_vcmpbfp: 10020 CompareOpc = 966; 10021 break; 10022 case Intrinsic::ppc_altivec_vcmpeqfp: 10023 CompareOpc = 198; 10024 break; 10025 case Intrinsic::ppc_altivec_vcmpequb: 10026 CompareOpc = 6; 10027 break; 10028 case Intrinsic::ppc_altivec_vcmpequh: 10029 CompareOpc = 70; 10030 break; 10031 case Intrinsic::ppc_altivec_vcmpequw: 10032 CompareOpc = 134; 10033 break; 10034 case Intrinsic::ppc_altivec_vcmpequd: 10035 if (Subtarget.hasP8Altivec()) 10036 CompareOpc = 199; 10037 else 10038 return false; 10039 break; 10040 case Intrinsic::ppc_altivec_vcmpneb: 10041 case Intrinsic::ppc_altivec_vcmpneh: 10042 case Intrinsic::ppc_altivec_vcmpnew: 10043 case Intrinsic::ppc_altivec_vcmpnezb: 10044 case Intrinsic::ppc_altivec_vcmpnezh: 10045 case Intrinsic::ppc_altivec_vcmpnezw: 10046 if (Subtarget.hasP9Altivec()) 10047 switch (IntrinsicID) { 10048 default: 10049 llvm_unreachable("Unknown comparison intrinsic."); 10050 case Intrinsic::ppc_altivec_vcmpneb: 10051 CompareOpc = 7; 10052 break; 10053 case Intrinsic::ppc_altivec_vcmpneh: 10054 CompareOpc = 71; 10055 break; 10056 case Intrinsic::ppc_altivec_vcmpnew: 10057 CompareOpc = 135; 10058 break; 10059 case Intrinsic::ppc_altivec_vcmpnezb: 10060 CompareOpc = 263; 10061 break; 10062 case Intrinsic::ppc_altivec_vcmpnezh: 10063 CompareOpc = 327; 10064 break; 10065 case Intrinsic::ppc_altivec_vcmpnezw: 10066 CompareOpc = 391; 10067 break; 10068 } 10069 else 10070 return false; 10071 break; 10072 case Intrinsic::ppc_altivec_vcmpgefp: 10073 CompareOpc = 454; 10074 break; 10075 case Intrinsic::ppc_altivec_vcmpgtfp: 10076 CompareOpc = 710; 10077 break; 10078 case Intrinsic::ppc_altivec_vcmpgtsb: 10079 CompareOpc = 774; 10080 break; 10081 case Intrinsic::ppc_altivec_vcmpgtsh: 10082 CompareOpc = 838; 10083 break; 10084 case Intrinsic::ppc_altivec_vcmpgtsw: 10085 CompareOpc = 902; 10086 break; 10087 case Intrinsic::ppc_altivec_vcmpgtsd: 10088 if (Subtarget.hasP8Altivec()) 10089 CompareOpc = 967; 10090 else 10091 return false; 10092 break; 10093 case Intrinsic::ppc_altivec_vcmpgtub: 10094 CompareOpc = 518; 10095 break; 10096 case Intrinsic::ppc_altivec_vcmpgtuh: 10097 CompareOpc = 582; 10098 break; 10099 case Intrinsic::ppc_altivec_vcmpgtuw: 10100 CompareOpc = 646; 10101 break; 10102 case Intrinsic::ppc_altivec_vcmpgtud: 10103 if (Subtarget.hasP8Altivec()) 10104 CompareOpc = 711; 10105 else 10106 return false; 10107 break; 10108 case Intrinsic::ppc_altivec_vcmpequq_p: 10109 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10110 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10111 if (!Subtarget.isISA3_1()) 10112 return false; 10113 switch (IntrinsicID) { 10114 default: 10115 llvm_unreachable("Unknown comparison intrinsic."); 10116 case Intrinsic::ppc_altivec_vcmpequq_p: 10117 CompareOpc = 455; 10118 break; 10119 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10120 CompareOpc = 903; 10121 break; 10122 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10123 CompareOpc = 647; 10124 break; 10125 } 10126 isDot = true; 10127 break; 10128 } 10129 return true; 10130 } 10131 10132 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10133 /// lower, do it, otherwise return null. 10134 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10135 SelectionDAG &DAG) const { 10136 unsigned IntrinsicID = 10137 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10138 10139 SDLoc dl(Op); 10140 10141 switch (IntrinsicID) { 10142 case Intrinsic::thread_pointer: 10143 // Reads the thread pointer register, used for __builtin_thread_pointer. 10144 if (Subtarget.isPPC64()) 10145 return DAG.getRegister(PPC::X13, MVT::i64); 10146 return DAG.getRegister(PPC::R2, MVT::i32); 10147 10148 case Intrinsic::ppc_mma_disassemble_acc: 10149 case Intrinsic::ppc_vsx_disassemble_pair: { 10150 int NumVecs = 2; 10151 SDValue WideVec = Op.getOperand(1); 10152 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10153 NumVecs = 4; 10154 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10155 } 10156 SmallVector<SDValue, 4> RetOps; 10157 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10158 SDValue Extract = DAG.getNode( 10159 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10160 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10161 : VecNo, 10162 dl, getPointerTy(DAG.getDataLayout()))); 10163 RetOps.push_back(Extract); 10164 } 10165 return DAG.getMergeValues(RetOps, dl); 10166 } 10167 } 10168 10169 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10170 // opcode number of the comparison. 10171 int CompareOpc; 10172 bool isDot; 10173 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10174 return SDValue(); // Don't custom lower most intrinsics. 10175 10176 // If this is a non-dot comparison, make the VCMP node and we are done. 10177 if (!isDot) { 10178 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10179 Op.getOperand(1), Op.getOperand(2), 10180 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10181 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10182 } 10183 10184 // Create the PPCISD altivec 'dot' comparison node. 10185 SDValue Ops[] = { 10186 Op.getOperand(2), // LHS 10187 Op.getOperand(3), // RHS 10188 DAG.getConstant(CompareOpc, dl, MVT::i32) 10189 }; 10190 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10191 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10192 10193 // Now that we have the comparison, emit a copy from the CR to a GPR. 10194 // This is flagged to the above dot comparison. 10195 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10196 DAG.getRegister(PPC::CR6, MVT::i32), 10197 CompNode.getValue(1)); 10198 10199 // Unpack the result based on how the target uses it. 10200 unsigned BitNo; // Bit # of CR6. 10201 bool InvertBit; // Invert result? 10202 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10203 default: // Can't happen, don't crash on invalid number though. 10204 case 0: // Return the value of the EQ bit of CR6. 10205 BitNo = 0; InvertBit = false; 10206 break; 10207 case 1: // Return the inverted value of the EQ bit of CR6. 10208 BitNo = 0; InvertBit = true; 10209 break; 10210 case 2: // Return the value of the LT bit of CR6. 10211 BitNo = 2; InvertBit = false; 10212 break; 10213 case 3: // Return the inverted value of the LT bit of CR6. 10214 BitNo = 2; InvertBit = true; 10215 break; 10216 } 10217 10218 // Shift the bit into the low position. 10219 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10220 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10221 // Isolate the bit. 10222 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10223 DAG.getConstant(1, dl, MVT::i32)); 10224 10225 // If we are supposed to, toggle the bit. 10226 if (InvertBit) 10227 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10228 DAG.getConstant(1, dl, MVT::i32)); 10229 return Flags; 10230 } 10231 10232 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10233 SelectionDAG &DAG) const { 10234 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10235 // the beginning of the argument list. 10236 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10237 SDLoc DL(Op); 10238 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10239 case Intrinsic::ppc_cfence: { 10240 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10241 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10242 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10243 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10244 Op.getOperand(ArgStart + 1)), 10245 Op.getOperand(0)), 10246 0); 10247 } 10248 default: 10249 break; 10250 } 10251 return SDValue(); 10252 } 10253 10254 // Lower scalar BSWAP64 to xxbrd. 10255 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10256 SDLoc dl(Op); 10257 // MTVSRDD 10258 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10259 Op.getOperand(0)); 10260 // XXBRD 10261 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10262 // MFVSRD 10263 int VectorIndex = 0; 10264 if (Subtarget.isLittleEndian()) 10265 VectorIndex = 1; 10266 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10267 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10268 return Op; 10269 } 10270 10271 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10272 // compared to a value that is atomically loaded (atomic loads zero-extend). 10273 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10274 SelectionDAG &DAG) const { 10275 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10276 "Expecting an atomic compare-and-swap here."); 10277 SDLoc dl(Op); 10278 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10279 EVT MemVT = AtomicNode->getMemoryVT(); 10280 if (MemVT.getSizeInBits() >= 32) 10281 return Op; 10282 10283 SDValue CmpOp = Op.getOperand(2); 10284 // If this is already correctly zero-extended, leave it alone. 10285 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10286 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10287 return Op; 10288 10289 // Clear the high bits of the compare operand. 10290 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10291 SDValue NewCmpOp = 10292 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10293 DAG.getConstant(MaskVal, dl, MVT::i32)); 10294 10295 // Replace the existing compare operand with the properly zero-extended one. 10296 SmallVector<SDValue, 4> Ops; 10297 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10298 Ops.push_back(AtomicNode->getOperand(i)); 10299 Ops[2] = NewCmpOp; 10300 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10301 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10302 auto NodeTy = 10303 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10304 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10305 } 10306 10307 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10308 SelectionDAG &DAG) const { 10309 SDLoc dl(Op); 10310 // Create a stack slot that is 16-byte aligned. 10311 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10312 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10313 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10314 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10315 10316 // Store the input value into Value#0 of the stack slot. 10317 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10318 MachinePointerInfo()); 10319 // Load it out. 10320 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10321 } 10322 10323 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10324 SelectionDAG &DAG) const { 10325 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10326 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10327 10328 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10329 10330 EVT VT = Op.getValueType(); 10331 SDLoc dl(Op); 10332 SDValue V1 = Op.getOperand(0); 10333 SDValue V2 = Op.getOperand(1); 10334 SDValue V3 = Op.getOperand(2); 10335 10336 if (VT == MVT::v2f64 && C) 10337 return Op; 10338 10339 if (Subtarget.isISA3_1()) { 10340 // On P10, we have legal lowering for constant and variable indices for 10341 // integer vectors. 10342 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10343 VT == MVT::v2i64) 10344 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10345 // For f32 and f64 vectors, we have legal lowering for variable indices. 10346 // For f32 we also have legal lowering when the element is loaded from 10347 // memory. 10348 if (VT == MVT::v4f32 || VT == MVT::v2f64) { 10349 if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2))) 10350 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10351 return Op; 10352 } 10353 } 10354 10355 // Before P10, we have legal lowering for constant indices but not for 10356 // variable ones. 10357 if (!C) 10358 return SDValue(); 10359 10360 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10361 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10362 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10363 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10364 unsigned InsertAtElement = C->getZExtValue(); 10365 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10366 if (Subtarget.isLittleEndian()) { 10367 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10368 } 10369 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10370 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10371 } 10372 return Op; 10373 } 10374 10375 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10376 SelectionDAG &DAG) const { 10377 SDLoc dl(Op); 10378 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10379 SDValue LoadChain = LN->getChain(); 10380 SDValue BasePtr = LN->getBasePtr(); 10381 EVT VT = Op.getValueType(); 10382 10383 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10384 return Op; 10385 10386 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10387 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10388 // 2 or 4 vsx registers. 10389 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10390 "Type unsupported without MMA"); 10391 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10392 "Type unsupported without paired vector support"); 10393 Align Alignment = LN->getAlign(); 10394 SmallVector<SDValue, 4> Loads; 10395 SmallVector<SDValue, 4> LoadChains; 10396 unsigned NumVecs = VT.getSizeInBits() / 128; 10397 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10398 SDValue Load = 10399 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10400 LN->getPointerInfo().getWithOffset(Idx * 16), 10401 commonAlignment(Alignment, Idx * 16), 10402 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10403 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10404 DAG.getConstant(16, dl, BasePtr.getValueType())); 10405 Loads.push_back(Load); 10406 LoadChains.push_back(Load.getValue(1)); 10407 } 10408 if (Subtarget.isLittleEndian()) { 10409 std::reverse(Loads.begin(), Loads.end()); 10410 std::reverse(LoadChains.begin(), LoadChains.end()); 10411 } 10412 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10413 SDValue Value = 10414 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10415 dl, VT, Loads); 10416 SDValue RetOps[] = {Value, TF}; 10417 return DAG.getMergeValues(RetOps, dl); 10418 } 10419 10420 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10421 SelectionDAG &DAG) const { 10422 SDLoc dl(Op); 10423 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10424 SDValue StoreChain = SN->getChain(); 10425 SDValue BasePtr = SN->getBasePtr(); 10426 SDValue Value = SN->getValue(); 10427 EVT StoreVT = Value.getValueType(); 10428 10429 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10430 return Op; 10431 10432 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10433 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10434 // underlying registers individually. 10435 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10436 "Type unsupported without MMA"); 10437 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10438 "Type unsupported without paired vector support"); 10439 Align Alignment = SN->getAlign(); 10440 SmallVector<SDValue, 4> Stores; 10441 unsigned NumVecs = 2; 10442 if (StoreVT == MVT::v512i1) { 10443 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10444 NumVecs = 4; 10445 } 10446 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10447 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10448 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10449 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 10450 SDValue Store = 10451 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10452 SN->getPointerInfo().getWithOffset(Idx * 16), 10453 commonAlignment(Alignment, Idx * 16), 10454 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10455 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10456 DAG.getConstant(16, dl, BasePtr.getValueType())); 10457 Stores.push_back(Store); 10458 } 10459 SDValue TF = DAG.getTokenFactor(dl, Stores); 10460 return TF; 10461 } 10462 10463 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10464 SDLoc dl(Op); 10465 if (Op.getValueType() == MVT::v4i32) { 10466 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10467 10468 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10469 // +16 as shift amt. 10470 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10471 SDValue RHSSwap = // = vrlw RHS, 16 10472 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10473 10474 // Shrinkify inputs to v8i16. 10475 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10476 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10477 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10478 10479 // Low parts multiplied together, generating 32-bit results (we ignore the 10480 // top parts). 10481 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10482 LHS, RHS, DAG, dl, MVT::v4i32); 10483 10484 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10485 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10486 // Shift the high parts up 16 bits. 10487 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10488 Neg16, DAG, dl); 10489 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10490 } else if (Op.getValueType() == MVT::v16i8) { 10491 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10492 bool isLittleEndian = Subtarget.isLittleEndian(); 10493 10494 // Multiply the even 8-bit parts, producing 16-bit sums. 10495 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10496 LHS, RHS, DAG, dl, MVT::v8i16); 10497 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10498 10499 // Multiply the odd 8-bit parts, producing 16-bit sums. 10500 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10501 LHS, RHS, DAG, dl, MVT::v8i16); 10502 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10503 10504 // Merge the results together. Because vmuleub and vmuloub are 10505 // instructions with a big-endian bias, we must reverse the 10506 // element numbering and reverse the meaning of "odd" and "even" 10507 // when generating little endian code. 10508 int Ops[16]; 10509 for (unsigned i = 0; i != 8; ++i) { 10510 if (isLittleEndian) { 10511 Ops[i*2 ] = 2*i; 10512 Ops[i*2+1] = 2*i+16; 10513 } else { 10514 Ops[i*2 ] = 2*i+1; 10515 Ops[i*2+1] = 2*i+1+16; 10516 } 10517 } 10518 if (isLittleEndian) 10519 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10520 else 10521 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10522 } else { 10523 llvm_unreachable("Unknown mul to lower!"); 10524 } 10525 } 10526 10527 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10528 bool IsStrict = Op->isStrictFPOpcode(); 10529 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10530 !Subtarget.hasP9Vector()) 10531 return SDValue(); 10532 10533 return Op; 10534 } 10535 10536 // Custom lowering for fpext vf32 to v2f64 10537 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10538 10539 assert(Op.getOpcode() == ISD::FP_EXTEND && 10540 "Should only be called for ISD::FP_EXTEND"); 10541 10542 // FIXME: handle extends from half precision float vectors on P9. 10543 // We only want to custom lower an extend from v2f32 to v2f64. 10544 if (Op.getValueType() != MVT::v2f64 || 10545 Op.getOperand(0).getValueType() != MVT::v2f32) 10546 return SDValue(); 10547 10548 SDLoc dl(Op); 10549 SDValue Op0 = Op.getOperand(0); 10550 10551 switch (Op0.getOpcode()) { 10552 default: 10553 return SDValue(); 10554 case ISD::EXTRACT_SUBVECTOR: { 10555 assert(Op0.getNumOperands() == 2 && 10556 isa<ConstantSDNode>(Op0->getOperand(1)) && 10557 "Node should have 2 operands with second one being a constant!"); 10558 10559 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10560 return SDValue(); 10561 10562 // Custom lower is only done for high or low doubleword. 10563 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10564 if (Idx % 2 != 0) 10565 return SDValue(); 10566 10567 // Since input is v4f32, at this point Idx is either 0 or 2. 10568 // Shift to get the doubleword position we want. 10569 int DWord = Idx >> 1; 10570 10571 // High and low word positions are different on little endian. 10572 if (Subtarget.isLittleEndian()) 10573 DWord ^= 0x1; 10574 10575 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10576 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10577 } 10578 case ISD::FADD: 10579 case ISD::FMUL: 10580 case ISD::FSUB: { 10581 SDValue NewLoad[2]; 10582 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10583 // Ensure both input are loads. 10584 SDValue LdOp = Op0.getOperand(i); 10585 if (LdOp.getOpcode() != ISD::LOAD) 10586 return SDValue(); 10587 // Generate new load node. 10588 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10589 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10590 NewLoad[i] = DAG.getMemIntrinsicNode( 10591 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10592 LD->getMemoryVT(), LD->getMemOperand()); 10593 } 10594 SDValue NewOp = 10595 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10596 NewLoad[1], Op0.getNode()->getFlags()); 10597 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10598 DAG.getConstant(0, dl, MVT::i32)); 10599 } 10600 case ISD::LOAD: { 10601 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10602 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10603 SDValue NewLd = DAG.getMemIntrinsicNode( 10604 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10605 LD->getMemoryVT(), LD->getMemOperand()); 10606 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10607 DAG.getConstant(0, dl, MVT::i32)); 10608 } 10609 } 10610 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10611 } 10612 10613 /// LowerOperation - Provide custom lowering hooks for some operations. 10614 /// 10615 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10616 switch (Op.getOpcode()) { 10617 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10618 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10619 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10620 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10621 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10622 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10623 case ISD::STRICT_FSETCC: 10624 case ISD::STRICT_FSETCCS: 10625 case ISD::SETCC: return LowerSETCC(Op, DAG); 10626 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10627 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10628 10629 // Variable argument lowering. 10630 case ISD::VASTART: return LowerVASTART(Op, DAG); 10631 case ISD::VAARG: return LowerVAARG(Op, DAG); 10632 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10633 10634 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10635 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10636 case ISD::GET_DYNAMIC_AREA_OFFSET: 10637 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10638 10639 // Exception handling lowering. 10640 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10641 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10642 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10643 10644 case ISD::LOAD: return LowerLOAD(Op, DAG); 10645 case ISD::STORE: return LowerSTORE(Op, DAG); 10646 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10647 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10648 case ISD::STRICT_FP_TO_UINT: 10649 case ISD::STRICT_FP_TO_SINT: 10650 case ISD::FP_TO_UINT: 10651 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10652 case ISD::STRICT_UINT_TO_FP: 10653 case ISD::STRICT_SINT_TO_FP: 10654 case ISD::UINT_TO_FP: 10655 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10656 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10657 10658 // Lower 64-bit shifts. 10659 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10660 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10661 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10662 10663 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10664 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10665 10666 // Vector-related lowering. 10667 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10668 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10669 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10670 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10671 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10672 case ISD::MUL: return LowerMUL(Op, DAG); 10673 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10674 case ISD::STRICT_FP_ROUND: 10675 case ISD::FP_ROUND: 10676 return LowerFP_ROUND(Op, DAG); 10677 case ISD::ROTL: return LowerROTL(Op, DAG); 10678 10679 // For counter-based loop handling. 10680 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10681 10682 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10683 10684 // Frame & Return address. 10685 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10686 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10687 10688 case ISD::INTRINSIC_VOID: 10689 return LowerINTRINSIC_VOID(Op, DAG); 10690 case ISD::BSWAP: 10691 return LowerBSWAP(Op, DAG); 10692 case ISD::ATOMIC_CMP_SWAP: 10693 return LowerATOMIC_CMP_SWAP(Op, DAG); 10694 } 10695 } 10696 10697 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10698 SmallVectorImpl<SDValue>&Results, 10699 SelectionDAG &DAG) const { 10700 SDLoc dl(N); 10701 switch (N->getOpcode()) { 10702 default: 10703 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10704 case ISD::READCYCLECOUNTER: { 10705 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10706 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10707 10708 Results.push_back( 10709 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10710 Results.push_back(RTB.getValue(2)); 10711 break; 10712 } 10713 case ISD::INTRINSIC_W_CHAIN: { 10714 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10715 Intrinsic::loop_decrement) 10716 break; 10717 10718 assert(N->getValueType(0) == MVT::i1 && 10719 "Unexpected result type for CTR decrement intrinsic"); 10720 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10721 N->getValueType(0)); 10722 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10723 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10724 N->getOperand(1)); 10725 10726 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10727 Results.push_back(NewInt.getValue(1)); 10728 break; 10729 } 10730 case ISD::VAARG: { 10731 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10732 return; 10733 10734 EVT VT = N->getValueType(0); 10735 10736 if (VT == MVT::i64) { 10737 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10738 10739 Results.push_back(NewNode); 10740 Results.push_back(NewNode.getValue(1)); 10741 } 10742 return; 10743 } 10744 case ISD::STRICT_FP_TO_SINT: 10745 case ISD::STRICT_FP_TO_UINT: 10746 case ISD::FP_TO_SINT: 10747 case ISD::FP_TO_UINT: 10748 // LowerFP_TO_INT() can only handle f32 and f64. 10749 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10750 MVT::ppcf128) 10751 return; 10752 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10753 return; 10754 case ISD::TRUNCATE: { 10755 if (!N->getValueType(0).isVector()) 10756 return; 10757 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10758 if (Lowered) 10759 Results.push_back(Lowered); 10760 return; 10761 } 10762 case ISD::FSHL: 10763 case ISD::FSHR: 10764 // Don't handle funnel shifts here. 10765 return; 10766 case ISD::BITCAST: 10767 // Don't handle bitcast here. 10768 return; 10769 case ISD::FP_EXTEND: 10770 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10771 if (Lowered) 10772 Results.push_back(Lowered); 10773 return; 10774 } 10775 } 10776 10777 //===----------------------------------------------------------------------===// 10778 // Other Lowering Code 10779 //===----------------------------------------------------------------------===// 10780 10781 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10782 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10783 Function *Func = Intrinsic::getDeclaration(M, Id); 10784 return Builder.CreateCall(Func, {}); 10785 } 10786 10787 // The mappings for emitLeading/TrailingFence is taken from 10788 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10789 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10790 Instruction *Inst, 10791 AtomicOrdering Ord) const { 10792 if (Ord == AtomicOrdering::SequentiallyConsistent) 10793 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10794 if (isReleaseOrStronger(Ord)) 10795 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10796 return nullptr; 10797 } 10798 10799 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10800 Instruction *Inst, 10801 AtomicOrdering Ord) const { 10802 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10803 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10804 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10805 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10806 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10807 return Builder.CreateCall( 10808 Intrinsic::getDeclaration( 10809 Builder.GetInsertBlock()->getParent()->getParent(), 10810 Intrinsic::ppc_cfence, {Inst->getType()}), 10811 {Inst}); 10812 // FIXME: Can use isync for rmw operation. 10813 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10814 } 10815 return nullptr; 10816 } 10817 10818 MachineBasicBlock * 10819 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10820 unsigned AtomicSize, 10821 unsigned BinOpcode, 10822 unsigned CmpOpcode, 10823 unsigned CmpPred) const { 10824 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10825 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10826 10827 auto LoadMnemonic = PPC::LDARX; 10828 auto StoreMnemonic = PPC::STDCX; 10829 switch (AtomicSize) { 10830 default: 10831 llvm_unreachable("Unexpected size of atomic entity"); 10832 case 1: 10833 LoadMnemonic = PPC::LBARX; 10834 StoreMnemonic = PPC::STBCX; 10835 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10836 break; 10837 case 2: 10838 LoadMnemonic = PPC::LHARX; 10839 StoreMnemonic = PPC::STHCX; 10840 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10841 break; 10842 case 4: 10843 LoadMnemonic = PPC::LWARX; 10844 StoreMnemonic = PPC::STWCX; 10845 break; 10846 case 8: 10847 LoadMnemonic = PPC::LDARX; 10848 StoreMnemonic = PPC::STDCX; 10849 break; 10850 } 10851 10852 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10853 MachineFunction *F = BB->getParent(); 10854 MachineFunction::iterator It = ++BB->getIterator(); 10855 10856 Register dest = MI.getOperand(0).getReg(); 10857 Register ptrA = MI.getOperand(1).getReg(); 10858 Register ptrB = MI.getOperand(2).getReg(); 10859 Register incr = MI.getOperand(3).getReg(); 10860 DebugLoc dl = MI.getDebugLoc(); 10861 10862 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10863 MachineBasicBlock *loop2MBB = 10864 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10865 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10866 F->insert(It, loopMBB); 10867 if (CmpOpcode) 10868 F->insert(It, loop2MBB); 10869 F->insert(It, exitMBB); 10870 exitMBB->splice(exitMBB->begin(), BB, 10871 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10872 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10873 10874 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10875 Register TmpReg = (!BinOpcode) ? incr : 10876 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10877 : &PPC::GPRCRegClass); 10878 10879 // thisMBB: 10880 // ... 10881 // fallthrough --> loopMBB 10882 BB->addSuccessor(loopMBB); 10883 10884 // loopMBB: 10885 // l[wd]arx dest, ptr 10886 // add r0, dest, incr 10887 // st[wd]cx. r0, ptr 10888 // bne- loopMBB 10889 // fallthrough --> exitMBB 10890 10891 // For max/min... 10892 // loopMBB: 10893 // l[wd]arx dest, ptr 10894 // cmpl?[wd] incr, dest 10895 // bgt exitMBB 10896 // loop2MBB: 10897 // st[wd]cx. dest, ptr 10898 // bne- loopMBB 10899 // fallthrough --> exitMBB 10900 10901 BB = loopMBB; 10902 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10903 .addReg(ptrA).addReg(ptrB); 10904 if (BinOpcode) 10905 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10906 if (CmpOpcode) { 10907 // Signed comparisons of byte or halfword values must be sign-extended. 10908 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10909 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10910 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10911 ExtReg).addReg(dest); 10912 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10913 .addReg(incr).addReg(ExtReg); 10914 } else 10915 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10916 .addReg(incr).addReg(dest); 10917 10918 BuildMI(BB, dl, TII->get(PPC::BCC)) 10919 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10920 BB->addSuccessor(loop2MBB); 10921 BB->addSuccessor(exitMBB); 10922 BB = loop2MBB; 10923 } 10924 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10925 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10926 BuildMI(BB, dl, TII->get(PPC::BCC)) 10927 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10928 BB->addSuccessor(loopMBB); 10929 BB->addSuccessor(exitMBB); 10930 10931 // exitMBB: 10932 // ... 10933 BB = exitMBB; 10934 return BB; 10935 } 10936 10937 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 10938 switch(MI.getOpcode()) { 10939 default: 10940 return false; 10941 case PPC::COPY: 10942 return TII->isSignExtended(MI); 10943 case PPC::LHA: 10944 case PPC::LHA8: 10945 case PPC::LHAU: 10946 case PPC::LHAU8: 10947 case PPC::LHAUX: 10948 case PPC::LHAUX8: 10949 case PPC::LHAX: 10950 case PPC::LHAX8: 10951 case PPC::LWA: 10952 case PPC::LWAUX: 10953 case PPC::LWAX: 10954 case PPC::LWAX_32: 10955 case PPC::LWA_32: 10956 case PPC::PLHA: 10957 case PPC::PLHA8: 10958 case PPC::PLHA8pc: 10959 case PPC::PLHApc: 10960 case PPC::PLWA: 10961 case PPC::PLWA8: 10962 case PPC::PLWA8pc: 10963 case PPC::PLWApc: 10964 case PPC::EXTSB: 10965 case PPC::EXTSB8: 10966 case PPC::EXTSB8_32_64: 10967 case PPC::EXTSB8_rec: 10968 case PPC::EXTSB_rec: 10969 case PPC::EXTSH: 10970 case PPC::EXTSH8: 10971 case PPC::EXTSH8_32_64: 10972 case PPC::EXTSH8_rec: 10973 case PPC::EXTSH_rec: 10974 case PPC::EXTSW: 10975 case PPC::EXTSWSLI: 10976 case PPC::EXTSWSLI_32_64: 10977 case PPC::EXTSWSLI_32_64_rec: 10978 case PPC::EXTSWSLI_rec: 10979 case PPC::EXTSW_32: 10980 case PPC::EXTSW_32_64: 10981 case PPC::EXTSW_32_64_rec: 10982 case PPC::EXTSW_rec: 10983 case PPC::SRAW: 10984 case PPC::SRAWI: 10985 case PPC::SRAWI_rec: 10986 case PPC::SRAW_rec: 10987 return true; 10988 } 10989 return false; 10990 } 10991 10992 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10993 MachineInstr &MI, MachineBasicBlock *BB, 10994 bool is8bit, // operation 10995 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10996 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10997 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 10998 10999 // If this is a signed comparison and the value being compared is not known 11000 // to be sign extended, sign extend it here. 11001 DebugLoc dl = MI.getDebugLoc(); 11002 MachineFunction *F = BB->getParent(); 11003 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11004 Register incr = MI.getOperand(3).getReg(); 11005 bool IsSignExtended = Register::isVirtualRegister(incr) && 11006 isSignExtended(*RegInfo.getVRegDef(incr), TII); 11007 11008 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11009 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11010 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11011 .addReg(MI.getOperand(3).getReg()); 11012 MI.getOperand(3).setReg(ValueReg); 11013 } 11014 // If we support part-word atomic mnemonics, just use them 11015 if (Subtarget.hasPartwordAtomics()) 11016 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11017 CmpPred); 11018 11019 // In 64 bit mode we have to use 64 bits for addresses, even though the 11020 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11021 // registers without caring whether they're 32 or 64, but here we're 11022 // doing actual arithmetic on the addresses. 11023 bool is64bit = Subtarget.isPPC64(); 11024 bool isLittleEndian = Subtarget.isLittleEndian(); 11025 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11026 11027 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11028 MachineFunction::iterator It = ++BB->getIterator(); 11029 11030 Register dest = MI.getOperand(0).getReg(); 11031 Register ptrA = MI.getOperand(1).getReg(); 11032 Register ptrB = MI.getOperand(2).getReg(); 11033 11034 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11035 MachineBasicBlock *loop2MBB = 11036 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11037 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11038 F->insert(It, loopMBB); 11039 if (CmpOpcode) 11040 F->insert(It, loop2MBB); 11041 F->insert(It, exitMBB); 11042 exitMBB->splice(exitMBB->begin(), BB, 11043 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11044 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11045 11046 const TargetRegisterClass *RC = 11047 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11048 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11049 11050 Register PtrReg = RegInfo.createVirtualRegister(RC); 11051 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11052 Register ShiftReg = 11053 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11054 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11055 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11056 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11057 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11058 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11059 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11060 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11061 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11062 Register Ptr1Reg; 11063 Register TmpReg = 11064 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11065 11066 // thisMBB: 11067 // ... 11068 // fallthrough --> loopMBB 11069 BB->addSuccessor(loopMBB); 11070 11071 // The 4-byte load must be aligned, while a char or short may be 11072 // anywhere in the word. Hence all this nasty bookkeeping code. 11073 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11074 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11075 // xori shift, shift1, 24 [16] 11076 // rlwinm ptr, ptr1, 0, 0, 29 11077 // slw incr2, incr, shift 11078 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11079 // slw mask, mask2, shift 11080 // loopMBB: 11081 // lwarx tmpDest, ptr 11082 // add tmp, tmpDest, incr2 11083 // andc tmp2, tmpDest, mask 11084 // and tmp3, tmp, mask 11085 // or tmp4, tmp3, tmp2 11086 // stwcx. tmp4, ptr 11087 // bne- loopMBB 11088 // fallthrough --> exitMBB 11089 // srw dest, tmpDest, shift 11090 if (ptrA != ZeroReg) { 11091 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11092 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11093 .addReg(ptrA) 11094 .addReg(ptrB); 11095 } else { 11096 Ptr1Reg = ptrB; 11097 } 11098 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11099 // mode. 11100 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11101 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11102 .addImm(3) 11103 .addImm(27) 11104 .addImm(is8bit ? 28 : 27); 11105 if (!isLittleEndian) 11106 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11107 .addReg(Shift1Reg) 11108 .addImm(is8bit ? 24 : 16); 11109 if (is64bit) 11110 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11111 .addReg(Ptr1Reg) 11112 .addImm(0) 11113 .addImm(61); 11114 else 11115 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11116 .addReg(Ptr1Reg) 11117 .addImm(0) 11118 .addImm(0) 11119 .addImm(29); 11120 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11121 if (is8bit) 11122 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11123 else { 11124 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11125 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11126 .addReg(Mask3Reg) 11127 .addImm(65535); 11128 } 11129 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11130 .addReg(Mask2Reg) 11131 .addReg(ShiftReg); 11132 11133 BB = loopMBB; 11134 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11135 .addReg(ZeroReg) 11136 .addReg(PtrReg); 11137 if (BinOpcode) 11138 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11139 .addReg(Incr2Reg) 11140 .addReg(TmpDestReg); 11141 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11142 .addReg(TmpDestReg) 11143 .addReg(MaskReg); 11144 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11145 if (CmpOpcode) { 11146 // For unsigned comparisons, we can directly compare the shifted values. 11147 // For signed comparisons we shift and sign extend. 11148 Register SReg = RegInfo.createVirtualRegister(GPRC); 11149 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11150 .addReg(TmpDestReg) 11151 .addReg(MaskReg); 11152 unsigned ValueReg = SReg; 11153 unsigned CmpReg = Incr2Reg; 11154 if (CmpOpcode == PPC::CMPW) { 11155 ValueReg = RegInfo.createVirtualRegister(GPRC); 11156 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11157 .addReg(SReg) 11158 .addReg(ShiftReg); 11159 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11160 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11161 .addReg(ValueReg); 11162 ValueReg = ValueSReg; 11163 CmpReg = incr; 11164 } 11165 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11166 .addReg(CmpReg) 11167 .addReg(ValueReg); 11168 BuildMI(BB, dl, TII->get(PPC::BCC)) 11169 .addImm(CmpPred) 11170 .addReg(PPC::CR0) 11171 .addMBB(exitMBB); 11172 BB->addSuccessor(loop2MBB); 11173 BB->addSuccessor(exitMBB); 11174 BB = loop2MBB; 11175 } 11176 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11177 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11178 .addReg(Tmp4Reg) 11179 .addReg(ZeroReg) 11180 .addReg(PtrReg); 11181 BuildMI(BB, dl, TII->get(PPC::BCC)) 11182 .addImm(PPC::PRED_NE) 11183 .addReg(PPC::CR0) 11184 .addMBB(loopMBB); 11185 BB->addSuccessor(loopMBB); 11186 BB->addSuccessor(exitMBB); 11187 11188 // exitMBB: 11189 // ... 11190 BB = exitMBB; 11191 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11192 .addReg(TmpDestReg) 11193 .addReg(ShiftReg); 11194 return BB; 11195 } 11196 11197 llvm::MachineBasicBlock * 11198 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11199 MachineBasicBlock *MBB) const { 11200 DebugLoc DL = MI.getDebugLoc(); 11201 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11202 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11203 11204 MachineFunction *MF = MBB->getParent(); 11205 MachineRegisterInfo &MRI = MF->getRegInfo(); 11206 11207 const BasicBlock *BB = MBB->getBasicBlock(); 11208 MachineFunction::iterator I = ++MBB->getIterator(); 11209 11210 Register DstReg = MI.getOperand(0).getReg(); 11211 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11212 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11213 Register mainDstReg = MRI.createVirtualRegister(RC); 11214 Register restoreDstReg = MRI.createVirtualRegister(RC); 11215 11216 MVT PVT = getPointerTy(MF->getDataLayout()); 11217 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11218 "Invalid Pointer Size!"); 11219 // For v = setjmp(buf), we generate 11220 // 11221 // thisMBB: 11222 // SjLjSetup mainMBB 11223 // bl mainMBB 11224 // v_restore = 1 11225 // b sinkMBB 11226 // 11227 // mainMBB: 11228 // buf[LabelOffset] = LR 11229 // v_main = 0 11230 // 11231 // sinkMBB: 11232 // v = phi(main, restore) 11233 // 11234 11235 MachineBasicBlock *thisMBB = MBB; 11236 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11237 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11238 MF->insert(I, mainMBB); 11239 MF->insert(I, sinkMBB); 11240 11241 MachineInstrBuilder MIB; 11242 11243 // Transfer the remainder of BB and its successor edges to sinkMBB. 11244 sinkMBB->splice(sinkMBB->begin(), MBB, 11245 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11246 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11247 11248 // Note that the structure of the jmp_buf used here is not compatible 11249 // with that used by libc, and is not designed to be. Specifically, it 11250 // stores only those 'reserved' registers that LLVM does not otherwise 11251 // understand how to spill. Also, by convention, by the time this 11252 // intrinsic is called, Clang has already stored the frame address in the 11253 // first slot of the buffer and stack address in the third. Following the 11254 // X86 target code, we'll store the jump address in the second slot. We also 11255 // need to save the TOC pointer (R2) to handle jumps between shared 11256 // libraries, and that will be stored in the fourth slot. The thread 11257 // identifier (R13) is not affected. 11258 11259 // thisMBB: 11260 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11261 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11262 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11263 11264 // Prepare IP either in reg. 11265 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11266 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11267 Register BufReg = MI.getOperand(1).getReg(); 11268 11269 if (Subtarget.is64BitELFABI()) { 11270 setUsesTOCBasePtr(*MBB->getParent()); 11271 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11272 .addReg(PPC::X2) 11273 .addImm(TOCOffset) 11274 .addReg(BufReg) 11275 .cloneMemRefs(MI); 11276 } 11277 11278 // Naked functions never have a base pointer, and so we use r1. For all 11279 // other functions, this decision must be delayed until during PEI. 11280 unsigned BaseReg; 11281 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11282 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11283 else 11284 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11285 11286 MIB = BuildMI(*thisMBB, MI, DL, 11287 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11288 .addReg(BaseReg) 11289 .addImm(BPOffset) 11290 .addReg(BufReg) 11291 .cloneMemRefs(MI); 11292 11293 // Setup 11294 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11295 MIB.addRegMask(TRI->getNoPreservedMask()); 11296 11297 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11298 11299 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11300 .addMBB(mainMBB); 11301 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11302 11303 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11304 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11305 11306 // mainMBB: 11307 // mainDstReg = 0 11308 MIB = 11309 BuildMI(mainMBB, DL, 11310 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11311 11312 // Store IP 11313 if (Subtarget.isPPC64()) { 11314 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11315 .addReg(LabelReg) 11316 .addImm(LabelOffset) 11317 .addReg(BufReg); 11318 } else { 11319 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11320 .addReg(LabelReg) 11321 .addImm(LabelOffset) 11322 .addReg(BufReg); 11323 } 11324 MIB.cloneMemRefs(MI); 11325 11326 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11327 mainMBB->addSuccessor(sinkMBB); 11328 11329 // sinkMBB: 11330 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11331 TII->get(PPC::PHI), DstReg) 11332 .addReg(mainDstReg).addMBB(mainMBB) 11333 .addReg(restoreDstReg).addMBB(thisMBB); 11334 11335 MI.eraseFromParent(); 11336 return sinkMBB; 11337 } 11338 11339 MachineBasicBlock * 11340 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11341 MachineBasicBlock *MBB) const { 11342 DebugLoc DL = MI.getDebugLoc(); 11343 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11344 11345 MachineFunction *MF = MBB->getParent(); 11346 MachineRegisterInfo &MRI = MF->getRegInfo(); 11347 11348 MVT PVT = getPointerTy(MF->getDataLayout()); 11349 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11350 "Invalid Pointer Size!"); 11351 11352 const TargetRegisterClass *RC = 11353 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11354 Register Tmp = MRI.createVirtualRegister(RC); 11355 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11356 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11357 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11358 unsigned BP = 11359 (PVT == MVT::i64) 11360 ? PPC::X30 11361 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11362 : PPC::R30); 11363 11364 MachineInstrBuilder MIB; 11365 11366 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11367 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11368 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11369 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11370 11371 Register BufReg = MI.getOperand(0).getReg(); 11372 11373 // Reload FP (the jumped-to function may not have had a 11374 // frame pointer, and if so, then its r31 will be restored 11375 // as necessary). 11376 if (PVT == MVT::i64) { 11377 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11378 .addImm(0) 11379 .addReg(BufReg); 11380 } else { 11381 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11382 .addImm(0) 11383 .addReg(BufReg); 11384 } 11385 MIB.cloneMemRefs(MI); 11386 11387 // Reload IP 11388 if (PVT == MVT::i64) { 11389 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11390 .addImm(LabelOffset) 11391 .addReg(BufReg); 11392 } else { 11393 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11394 .addImm(LabelOffset) 11395 .addReg(BufReg); 11396 } 11397 MIB.cloneMemRefs(MI); 11398 11399 // Reload SP 11400 if (PVT == MVT::i64) { 11401 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11402 .addImm(SPOffset) 11403 .addReg(BufReg); 11404 } else { 11405 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11406 .addImm(SPOffset) 11407 .addReg(BufReg); 11408 } 11409 MIB.cloneMemRefs(MI); 11410 11411 // Reload BP 11412 if (PVT == MVT::i64) { 11413 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11414 .addImm(BPOffset) 11415 .addReg(BufReg); 11416 } else { 11417 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11418 .addImm(BPOffset) 11419 .addReg(BufReg); 11420 } 11421 MIB.cloneMemRefs(MI); 11422 11423 // Reload TOC 11424 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11425 setUsesTOCBasePtr(*MBB->getParent()); 11426 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11427 .addImm(TOCOffset) 11428 .addReg(BufReg) 11429 .cloneMemRefs(MI); 11430 } 11431 11432 // Jump 11433 BuildMI(*MBB, MI, DL, 11434 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11435 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11436 11437 MI.eraseFromParent(); 11438 return MBB; 11439 } 11440 11441 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11442 // If the function specifically requests inline stack probes, emit them. 11443 if (MF.getFunction().hasFnAttribute("probe-stack")) 11444 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11445 "inline-asm"; 11446 return false; 11447 } 11448 11449 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11450 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11451 unsigned StackAlign = TFI->getStackAlignment(); 11452 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11453 "Unexpected stack alignment"); 11454 // The default stack probe size is 4096 if the function has no 11455 // stack-probe-size attribute. 11456 unsigned StackProbeSize = 4096; 11457 const Function &Fn = MF.getFunction(); 11458 if (Fn.hasFnAttribute("stack-probe-size")) 11459 Fn.getFnAttribute("stack-probe-size") 11460 .getValueAsString() 11461 .getAsInteger(0, StackProbeSize); 11462 // Round down to the stack alignment. 11463 StackProbeSize &= ~(StackAlign - 1); 11464 return StackProbeSize ? StackProbeSize : StackAlign; 11465 } 11466 11467 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11468 // into three phases. In the first phase, it uses pseudo instruction 11469 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11470 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11471 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11472 // MaxCallFrameSize so that it can calculate correct data area pointer. 11473 MachineBasicBlock * 11474 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11475 MachineBasicBlock *MBB) const { 11476 const bool isPPC64 = Subtarget.isPPC64(); 11477 MachineFunction *MF = MBB->getParent(); 11478 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11479 DebugLoc DL = MI.getDebugLoc(); 11480 const unsigned ProbeSize = getStackProbeSize(*MF); 11481 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11482 MachineRegisterInfo &MRI = MF->getRegInfo(); 11483 // The CFG of probing stack looks as 11484 // +-----+ 11485 // | MBB | 11486 // +--+--+ 11487 // | 11488 // +----v----+ 11489 // +--->+ TestMBB +---+ 11490 // | +----+----+ | 11491 // | | | 11492 // | +-----v----+ | 11493 // +---+ BlockMBB | | 11494 // +----------+ | 11495 // | 11496 // +---------+ | 11497 // | TailMBB +<--+ 11498 // +---------+ 11499 // In MBB, calculate previous frame pointer and final stack pointer. 11500 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11501 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11502 // TailMBB is spliced via \p MI. 11503 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11504 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11505 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11506 11507 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11508 MF->insert(MBBIter, TestMBB); 11509 MF->insert(MBBIter, BlockMBB); 11510 MF->insert(MBBIter, TailMBB); 11511 11512 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11513 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11514 11515 Register DstReg = MI.getOperand(0).getReg(); 11516 Register NegSizeReg = MI.getOperand(1).getReg(); 11517 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11518 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11519 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11520 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11521 11522 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11523 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11524 // NegSize. 11525 unsigned ProbeOpc; 11526 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11527 ProbeOpc = 11528 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11529 else 11530 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11531 // and NegSizeReg will be allocated in the same phyreg to avoid 11532 // redundant copy when NegSizeReg has only one use which is current MI and 11533 // will be replaced by PREPARE_PROBED_ALLOCA then. 11534 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11535 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11536 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11537 .addDef(ActualNegSizeReg) 11538 .addReg(NegSizeReg) 11539 .add(MI.getOperand(2)) 11540 .add(MI.getOperand(3)); 11541 11542 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11543 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11544 FinalStackPtr) 11545 .addReg(SPReg) 11546 .addReg(ActualNegSizeReg); 11547 11548 // Materialize a scratch register for update. 11549 int64_t NegProbeSize = -(int64_t)ProbeSize; 11550 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11551 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11552 if (!isInt<16>(NegProbeSize)) { 11553 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11554 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11555 .addImm(NegProbeSize >> 16); 11556 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11557 ScratchReg) 11558 .addReg(TempReg) 11559 .addImm(NegProbeSize & 0xFFFF); 11560 } else 11561 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11562 .addImm(NegProbeSize); 11563 11564 { 11565 // Probing leading residual part. 11566 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11567 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11568 .addReg(ActualNegSizeReg) 11569 .addReg(ScratchReg); 11570 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11571 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11572 .addReg(Div) 11573 .addReg(ScratchReg); 11574 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11575 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11576 .addReg(Mul) 11577 .addReg(ActualNegSizeReg); 11578 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11579 .addReg(FramePointer) 11580 .addReg(SPReg) 11581 .addReg(NegMod); 11582 } 11583 11584 { 11585 // Remaining part should be multiple of ProbeSize. 11586 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11587 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11588 .addReg(SPReg) 11589 .addReg(FinalStackPtr); 11590 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11591 .addImm(PPC::PRED_EQ) 11592 .addReg(CmpResult) 11593 .addMBB(TailMBB); 11594 TestMBB->addSuccessor(BlockMBB); 11595 TestMBB->addSuccessor(TailMBB); 11596 } 11597 11598 { 11599 // Touch the block. 11600 // |P...|P...|P... 11601 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11602 .addReg(FramePointer) 11603 .addReg(SPReg) 11604 .addReg(ScratchReg); 11605 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11606 BlockMBB->addSuccessor(TestMBB); 11607 } 11608 11609 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11610 // DYNAREAOFFSET pseudo instruction to get the future result. 11611 Register MaxCallFrameSizeReg = 11612 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11613 BuildMI(TailMBB, DL, 11614 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11615 MaxCallFrameSizeReg) 11616 .add(MI.getOperand(2)) 11617 .add(MI.getOperand(3)); 11618 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11619 .addReg(SPReg) 11620 .addReg(MaxCallFrameSizeReg); 11621 11622 // Splice instructions after MI to TailMBB. 11623 TailMBB->splice(TailMBB->end(), MBB, 11624 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11625 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11626 MBB->addSuccessor(TestMBB); 11627 11628 // Delete the pseudo instruction. 11629 MI.eraseFromParent(); 11630 11631 ++NumDynamicAllocaProbed; 11632 return TailMBB; 11633 } 11634 11635 MachineBasicBlock * 11636 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11637 MachineBasicBlock *BB) const { 11638 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11639 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11640 if (Subtarget.is64BitELFABI() && 11641 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11642 !Subtarget.isUsingPCRelativeCalls()) { 11643 // Call lowering should have added an r2 operand to indicate a dependence 11644 // on the TOC base pointer value. It can't however, because there is no 11645 // way to mark the dependence as implicit there, and so the stackmap code 11646 // will confuse it with a regular operand. Instead, add the dependence 11647 // here. 11648 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11649 } 11650 11651 return emitPatchPoint(MI, BB); 11652 } 11653 11654 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11655 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11656 return emitEHSjLjSetJmp(MI, BB); 11657 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11658 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11659 return emitEHSjLjLongJmp(MI, BB); 11660 } 11661 11662 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11663 11664 // To "insert" these instructions we actually have to insert their 11665 // control-flow patterns. 11666 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11667 MachineFunction::iterator It = ++BB->getIterator(); 11668 11669 MachineFunction *F = BB->getParent(); 11670 11671 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11672 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11673 MI.getOpcode() == PPC::SELECT_I8) { 11674 SmallVector<MachineOperand, 2> Cond; 11675 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11676 MI.getOpcode() == PPC::SELECT_CC_I8) 11677 Cond.push_back(MI.getOperand(4)); 11678 else 11679 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11680 Cond.push_back(MI.getOperand(1)); 11681 11682 DebugLoc dl = MI.getDebugLoc(); 11683 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11684 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11685 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11686 MI.getOpcode() == PPC::SELECT_CC_F8 || 11687 MI.getOpcode() == PPC::SELECT_CC_F16 || 11688 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11689 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11690 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11691 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11692 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11693 MI.getOpcode() == PPC::SELECT_CC_SPE || 11694 MI.getOpcode() == PPC::SELECT_F4 || 11695 MI.getOpcode() == PPC::SELECT_F8 || 11696 MI.getOpcode() == PPC::SELECT_F16 || 11697 MI.getOpcode() == PPC::SELECT_SPE || 11698 MI.getOpcode() == PPC::SELECT_SPE4 || 11699 MI.getOpcode() == PPC::SELECT_VRRC || 11700 MI.getOpcode() == PPC::SELECT_VSFRC || 11701 MI.getOpcode() == PPC::SELECT_VSSRC || 11702 MI.getOpcode() == PPC::SELECT_VSRC) { 11703 // The incoming instruction knows the destination vreg to set, the 11704 // condition code register to branch on, the true/false values to 11705 // select between, and a branch opcode to use. 11706 11707 // thisMBB: 11708 // ... 11709 // TrueVal = ... 11710 // cmpTY ccX, r1, r2 11711 // bCC copy1MBB 11712 // fallthrough --> copy0MBB 11713 MachineBasicBlock *thisMBB = BB; 11714 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11715 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11716 DebugLoc dl = MI.getDebugLoc(); 11717 F->insert(It, copy0MBB); 11718 F->insert(It, sinkMBB); 11719 11720 // Transfer the remainder of BB and its successor edges to sinkMBB. 11721 sinkMBB->splice(sinkMBB->begin(), BB, 11722 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11723 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11724 11725 // Next, add the true and fallthrough blocks as its successors. 11726 BB->addSuccessor(copy0MBB); 11727 BB->addSuccessor(sinkMBB); 11728 11729 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11730 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11731 MI.getOpcode() == PPC::SELECT_F16 || 11732 MI.getOpcode() == PPC::SELECT_SPE4 || 11733 MI.getOpcode() == PPC::SELECT_SPE || 11734 MI.getOpcode() == PPC::SELECT_VRRC || 11735 MI.getOpcode() == PPC::SELECT_VSFRC || 11736 MI.getOpcode() == PPC::SELECT_VSSRC || 11737 MI.getOpcode() == PPC::SELECT_VSRC) { 11738 BuildMI(BB, dl, TII->get(PPC::BC)) 11739 .addReg(MI.getOperand(1).getReg()) 11740 .addMBB(sinkMBB); 11741 } else { 11742 unsigned SelectPred = MI.getOperand(4).getImm(); 11743 BuildMI(BB, dl, TII->get(PPC::BCC)) 11744 .addImm(SelectPred) 11745 .addReg(MI.getOperand(1).getReg()) 11746 .addMBB(sinkMBB); 11747 } 11748 11749 // copy0MBB: 11750 // %FalseValue = ... 11751 // # fallthrough to sinkMBB 11752 BB = copy0MBB; 11753 11754 // Update machine-CFG edges 11755 BB->addSuccessor(sinkMBB); 11756 11757 // sinkMBB: 11758 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11759 // ... 11760 BB = sinkMBB; 11761 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11762 .addReg(MI.getOperand(3).getReg()) 11763 .addMBB(copy0MBB) 11764 .addReg(MI.getOperand(2).getReg()) 11765 .addMBB(thisMBB); 11766 } else if (MI.getOpcode() == PPC::ReadTB) { 11767 // To read the 64-bit time-base register on a 32-bit target, we read the 11768 // two halves. Should the counter have wrapped while it was being read, we 11769 // need to try again. 11770 // ... 11771 // readLoop: 11772 // mfspr Rx,TBU # load from TBU 11773 // mfspr Ry,TB # load from TB 11774 // mfspr Rz,TBU # load from TBU 11775 // cmpw crX,Rx,Rz # check if 'old'='new' 11776 // bne readLoop # branch if they're not equal 11777 // ... 11778 11779 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11780 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11781 DebugLoc dl = MI.getDebugLoc(); 11782 F->insert(It, readMBB); 11783 F->insert(It, sinkMBB); 11784 11785 // Transfer the remainder of BB and its successor edges to sinkMBB. 11786 sinkMBB->splice(sinkMBB->begin(), BB, 11787 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11788 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11789 11790 BB->addSuccessor(readMBB); 11791 BB = readMBB; 11792 11793 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11794 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11795 Register LoReg = MI.getOperand(0).getReg(); 11796 Register HiReg = MI.getOperand(1).getReg(); 11797 11798 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11799 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11800 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11801 11802 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11803 11804 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11805 .addReg(HiReg) 11806 .addReg(ReadAgainReg); 11807 BuildMI(BB, dl, TII->get(PPC::BCC)) 11808 .addImm(PPC::PRED_NE) 11809 .addReg(CmpReg) 11810 .addMBB(readMBB); 11811 11812 BB->addSuccessor(readMBB); 11813 BB->addSuccessor(sinkMBB); 11814 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11815 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11816 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11817 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11818 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11819 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11820 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11821 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11822 11823 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11824 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11825 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11826 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11828 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11829 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11830 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11831 11832 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11833 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11835 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11837 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11838 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11839 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11840 11841 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11842 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11844 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11846 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11847 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11848 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11849 11850 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11851 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11852 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11853 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11854 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11855 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11856 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11857 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11858 11859 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11860 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11861 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11862 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11863 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11864 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11865 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11866 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11867 11868 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11869 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11870 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11871 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11872 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11873 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11874 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11875 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11876 11877 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11878 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11879 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11880 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11881 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11882 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11883 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11884 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11885 11886 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11887 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11888 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11889 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11890 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11891 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11892 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11893 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11894 11895 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11896 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11897 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11898 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11899 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11900 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11901 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11902 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11903 11904 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11905 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11906 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11907 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11908 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11909 BB = EmitAtomicBinary(MI, BB, 4, 0); 11910 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11911 BB = EmitAtomicBinary(MI, BB, 8, 0); 11912 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11913 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11914 (Subtarget.hasPartwordAtomics() && 11915 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11916 (Subtarget.hasPartwordAtomics() && 11917 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11918 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11919 11920 auto LoadMnemonic = PPC::LDARX; 11921 auto StoreMnemonic = PPC::STDCX; 11922 switch (MI.getOpcode()) { 11923 default: 11924 llvm_unreachable("Compare and swap of unknown size"); 11925 case PPC::ATOMIC_CMP_SWAP_I8: 11926 LoadMnemonic = PPC::LBARX; 11927 StoreMnemonic = PPC::STBCX; 11928 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11929 break; 11930 case PPC::ATOMIC_CMP_SWAP_I16: 11931 LoadMnemonic = PPC::LHARX; 11932 StoreMnemonic = PPC::STHCX; 11933 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11934 break; 11935 case PPC::ATOMIC_CMP_SWAP_I32: 11936 LoadMnemonic = PPC::LWARX; 11937 StoreMnemonic = PPC::STWCX; 11938 break; 11939 case PPC::ATOMIC_CMP_SWAP_I64: 11940 LoadMnemonic = PPC::LDARX; 11941 StoreMnemonic = PPC::STDCX; 11942 break; 11943 } 11944 Register dest = MI.getOperand(0).getReg(); 11945 Register ptrA = MI.getOperand(1).getReg(); 11946 Register ptrB = MI.getOperand(2).getReg(); 11947 Register oldval = MI.getOperand(3).getReg(); 11948 Register newval = MI.getOperand(4).getReg(); 11949 DebugLoc dl = MI.getDebugLoc(); 11950 11951 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11952 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11953 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11954 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11955 F->insert(It, loop1MBB); 11956 F->insert(It, loop2MBB); 11957 F->insert(It, midMBB); 11958 F->insert(It, exitMBB); 11959 exitMBB->splice(exitMBB->begin(), BB, 11960 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11961 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11962 11963 // thisMBB: 11964 // ... 11965 // fallthrough --> loopMBB 11966 BB->addSuccessor(loop1MBB); 11967 11968 // loop1MBB: 11969 // l[bhwd]arx dest, ptr 11970 // cmp[wd] dest, oldval 11971 // bne- midMBB 11972 // loop2MBB: 11973 // st[bhwd]cx. newval, ptr 11974 // bne- loopMBB 11975 // b exitBB 11976 // midMBB: 11977 // st[bhwd]cx. dest, ptr 11978 // exitBB: 11979 BB = loop1MBB; 11980 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11981 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11982 .addReg(oldval) 11983 .addReg(dest); 11984 BuildMI(BB, dl, TII->get(PPC::BCC)) 11985 .addImm(PPC::PRED_NE) 11986 .addReg(PPC::CR0) 11987 .addMBB(midMBB); 11988 BB->addSuccessor(loop2MBB); 11989 BB->addSuccessor(midMBB); 11990 11991 BB = loop2MBB; 11992 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11993 .addReg(newval) 11994 .addReg(ptrA) 11995 .addReg(ptrB); 11996 BuildMI(BB, dl, TII->get(PPC::BCC)) 11997 .addImm(PPC::PRED_NE) 11998 .addReg(PPC::CR0) 11999 .addMBB(loop1MBB); 12000 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12001 BB->addSuccessor(loop1MBB); 12002 BB->addSuccessor(exitMBB); 12003 12004 BB = midMBB; 12005 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12006 .addReg(dest) 12007 .addReg(ptrA) 12008 .addReg(ptrB); 12009 BB->addSuccessor(exitMBB); 12010 12011 // exitMBB: 12012 // ... 12013 BB = exitMBB; 12014 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12015 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12016 // We must use 64-bit registers for addresses when targeting 64-bit, 12017 // since we're actually doing arithmetic on them. Other registers 12018 // can be 32-bit. 12019 bool is64bit = Subtarget.isPPC64(); 12020 bool isLittleEndian = Subtarget.isLittleEndian(); 12021 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12022 12023 Register dest = MI.getOperand(0).getReg(); 12024 Register ptrA = MI.getOperand(1).getReg(); 12025 Register ptrB = MI.getOperand(2).getReg(); 12026 Register oldval = MI.getOperand(3).getReg(); 12027 Register newval = MI.getOperand(4).getReg(); 12028 DebugLoc dl = MI.getDebugLoc(); 12029 12030 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12031 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12032 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12033 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12034 F->insert(It, loop1MBB); 12035 F->insert(It, loop2MBB); 12036 F->insert(It, midMBB); 12037 F->insert(It, exitMBB); 12038 exitMBB->splice(exitMBB->begin(), BB, 12039 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12040 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12041 12042 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12043 const TargetRegisterClass *RC = 12044 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12045 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12046 12047 Register PtrReg = RegInfo.createVirtualRegister(RC); 12048 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12049 Register ShiftReg = 12050 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12051 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12052 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12053 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12054 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12055 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12056 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12057 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12058 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12059 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12060 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12061 Register Ptr1Reg; 12062 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12063 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12064 // thisMBB: 12065 // ... 12066 // fallthrough --> loopMBB 12067 BB->addSuccessor(loop1MBB); 12068 12069 // The 4-byte load must be aligned, while a char or short may be 12070 // anywhere in the word. Hence all this nasty bookkeeping code. 12071 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12072 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12073 // xori shift, shift1, 24 [16] 12074 // rlwinm ptr, ptr1, 0, 0, 29 12075 // slw newval2, newval, shift 12076 // slw oldval2, oldval,shift 12077 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12078 // slw mask, mask2, shift 12079 // and newval3, newval2, mask 12080 // and oldval3, oldval2, mask 12081 // loop1MBB: 12082 // lwarx tmpDest, ptr 12083 // and tmp, tmpDest, mask 12084 // cmpw tmp, oldval3 12085 // bne- midMBB 12086 // loop2MBB: 12087 // andc tmp2, tmpDest, mask 12088 // or tmp4, tmp2, newval3 12089 // stwcx. tmp4, ptr 12090 // bne- loop1MBB 12091 // b exitBB 12092 // midMBB: 12093 // stwcx. tmpDest, ptr 12094 // exitBB: 12095 // srw dest, tmpDest, shift 12096 if (ptrA != ZeroReg) { 12097 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12098 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12099 .addReg(ptrA) 12100 .addReg(ptrB); 12101 } else { 12102 Ptr1Reg = ptrB; 12103 } 12104 12105 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12106 // mode. 12107 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12108 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12109 .addImm(3) 12110 .addImm(27) 12111 .addImm(is8bit ? 28 : 27); 12112 if (!isLittleEndian) 12113 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12114 .addReg(Shift1Reg) 12115 .addImm(is8bit ? 24 : 16); 12116 if (is64bit) 12117 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12118 .addReg(Ptr1Reg) 12119 .addImm(0) 12120 .addImm(61); 12121 else 12122 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12123 .addReg(Ptr1Reg) 12124 .addImm(0) 12125 .addImm(0) 12126 .addImm(29); 12127 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12128 .addReg(newval) 12129 .addReg(ShiftReg); 12130 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12131 .addReg(oldval) 12132 .addReg(ShiftReg); 12133 if (is8bit) 12134 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12135 else { 12136 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12137 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12138 .addReg(Mask3Reg) 12139 .addImm(65535); 12140 } 12141 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12142 .addReg(Mask2Reg) 12143 .addReg(ShiftReg); 12144 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12145 .addReg(NewVal2Reg) 12146 .addReg(MaskReg); 12147 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12148 .addReg(OldVal2Reg) 12149 .addReg(MaskReg); 12150 12151 BB = loop1MBB; 12152 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12153 .addReg(ZeroReg) 12154 .addReg(PtrReg); 12155 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12156 .addReg(TmpDestReg) 12157 .addReg(MaskReg); 12158 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12159 .addReg(TmpReg) 12160 .addReg(OldVal3Reg); 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(PPC::ANDC), Tmp2Reg) 12170 .addReg(TmpDestReg) 12171 .addReg(MaskReg); 12172 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12173 .addReg(Tmp2Reg) 12174 .addReg(NewVal3Reg); 12175 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12176 .addReg(Tmp4Reg) 12177 .addReg(ZeroReg) 12178 .addReg(PtrReg); 12179 BuildMI(BB, dl, TII->get(PPC::BCC)) 12180 .addImm(PPC::PRED_NE) 12181 .addReg(PPC::CR0) 12182 .addMBB(loop1MBB); 12183 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12184 BB->addSuccessor(loop1MBB); 12185 BB->addSuccessor(exitMBB); 12186 12187 BB = midMBB; 12188 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12189 .addReg(TmpDestReg) 12190 .addReg(ZeroReg) 12191 .addReg(PtrReg); 12192 BB->addSuccessor(exitMBB); 12193 12194 // exitMBB: 12195 // ... 12196 BB = exitMBB; 12197 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12198 .addReg(TmpReg) 12199 .addReg(ShiftReg); 12200 } else if (MI.getOpcode() == PPC::FADDrtz) { 12201 // This pseudo performs an FADD with rounding mode temporarily forced 12202 // to round-to-zero. We emit this via custom inserter since the FPSCR 12203 // is not modeled at the SelectionDAG level. 12204 Register Dest = MI.getOperand(0).getReg(); 12205 Register Src1 = MI.getOperand(1).getReg(); 12206 Register Src2 = MI.getOperand(2).getReg(); 12207 DebugLoc dl = MI.getDebugLoc(); 12208 12209 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12210 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12211 12212 // Save FPSCR value. 12213 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12214 12215 // Set rounding mode to round-to-zero. 12216 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12217 .addImm(31) 12218 .addReg(PPC::RM, RegState::ImplicitDefine); 12219 12220 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12221 .addImm(30) 12222 .addReg(PPC::RM, RegState::ImplicitDefine); 12223 12224 // Perform addition. 12225 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12226 .addReg(Src1) 12227 .addReg(Src2); 12228 if (MI.getFlag(MachineInstr::NoFPExcept)) 12229 MIB.setMIFlag(MachineInstr::NoFPExcept); 12230 12231 // Restore FPSCR value. 12232 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12233 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12234 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12235 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12236 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12237 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12238 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12239 ? PPC::ANDI8_rec 12240 : PPC::ANDI_rec; 12241 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12242 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12243 12244 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12245 Register Dest = RegInfo.createVirtualRegister( 12246 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12247 12248 DebugLoc Dl = MI.getDebugLoc(); 12249 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12250 .addReg(MI.getOperand(1).getReg()) 12251 .addImm(1); 12252 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12253 MI.getOperand(0).getReg()) 12254 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12255 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12256 DebugLoc Dl = MI.getDebugLoc(); 12257 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12258 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12259 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12260 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12261 MI.getOperand(0).getReg()) 12262 .addReg(CRReg); 12263 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12264 DebugLoc Dl = MI.getDebugLoc(); 12265 unsigned Imm = MI.getOperand(1).getImm(); 12266 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12267 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12268 MI.getOperand(0).getReg()) 12269 .addReg(PPC::CR0EQ); 12270 } else if (MI.getOpcode() == PPC::SETRNDi) { 12271 DebugLoc dl = MI.getDebugLoc(); 12272 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12273 12274 // Save FPSCR value. 12275 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12276 12277 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12278 // the following settings: 12279 // 00 Round to nearest 12280 // 01 Round to 0 12281 // 10 Round to +inf 12282 // 11 Round to -inf 12283 12284 // When the operand is immediate, using the two least significant bits of 12285 // the immediate to set the bits 62:63 of FPSCR. 12286 unsigned Mode = MI.getOperand(1).getImm(); 12287 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12288 .addImm(31) 12289 .addReg(PPC::RM, RegState::ImplicitDefine); 12290 12291 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12292 .addImm(30) 12293 .addReg(PPC::RM, RegState::ImplicitDefine); 12294 } else if (MI.getOpcode() == PPC::SETRND) { 12295 DebugLoc dl = MI.getDebugLoc(); 12296 12297 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12298 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12299 // If the target doesn't have DirectMove, we should use stack to do the 12300 // conversion, because the target doesn't have the instructions like mtvsrd 12301 // or mfvsrd to do this conversion directly. 12302 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12303 if (Subtarget.hasDirectMove()) { 12304 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12305 .addReg(SrcReg); 12306 } else { 12307 // Use stack to do the register copy. 12308 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12309 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12310 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12311 if (RC == &PPC::F8RCRegClass) { 12312 // Copy register from F8RCRegClass to G8RCRegclass. 12313 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12314 "Unsupported RegClass."); 12315 12316 StoreOp = PPC::STFD; 12317 LoadOp = PPC::LD; 12318 } else { 12319 // Copy register from G8RCRegClass to F8RCRegclass. 12320 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12321 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12322 "Unsupported RegClass."); 12323 } 12324 12325 MachineFrameInfo &MFI = F->getFrameInfo(); 12326 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12327 12328 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12329 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12330 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12331 MFI.getObjectAlign(FrameIdx)); 12332 12333 // Store the SrcReg into the stack. 12334 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12335 .addReg(SrcReg) 12336 .addImm(0) 12337 .addFrameIndex(FrameIdx) 12338 .addMemOperand(MMOStore); 12339 12340 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12341 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12342 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12343 MFI.getObjectAlign(FrameIdx)); 12344 12345 // Load from the stack where SrcReg is stored, and save to DestReg, 12346 // so we have done the RegClass conversion from RegClass::SrcReg to 12347 // RegClass::DestReg. 12348 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12349 .addImm(0) 12350 .addFrameIndex(FrameIdx) 12351 .addMemOperand(MMOLoad); 12352 } 12353 }; 12354 12355 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12356 12357 // Save FPSCR value. 12358 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12359 12360 // When the operand is gprc register, use two least significant bits of the 12361 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12362 // 12363 // copy OldFPSCRTmpReg, OldFPSCRReg 12364 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12365 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12366 // copy NewFPSCRReg, NewFPSCRTmpReg 12367 // mtfsf 255, NewFPSCRReg 12368 MachineOperand SrcOp = MI.getOperand(1); 12369 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12370 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12371 12372 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12373 12374 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12375 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12376 12377 // The first operand of INSERT_SUBREG should be a register which has 12378 // subregisters, we only care about its RegClass, so we should use an 12379 // IMPLICIT_DEF register. 12380 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12381 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12382 .addReg(ImDefReg) 12383 .add(SrcOp) 12384 .addImm(1); 12385 12386 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12387 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12388 .addReg(OldFPSCRTmpReg) 12389 .addReg(ExtSrcReg) 12390 .addImm(0) 12391 .addImm(62); 12392 12393 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12394 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12395 12396 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12397 // bits of FPSCR. 12398 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12399 .addImm(255) 12400 .addReg(NewFPSCRReg) 12401 .addImm(0) 12402 .addImm(0); 12403 } else if (MI.getOpcode() == PPC::SETFLM) { 12404 DebugLoc Dl = MI.getDebugLoc(); 12405 12406 // Result of setflm is previous FPSCR content, so we need to save it first. 12407 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12408 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12409 12410 // Put bits in 32:63 to FPSCR. 12411 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12412 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12413 .addImm(255) 12414 .addReg(NewFPSCRReg) 12415 .addImm(0) 12416 .addImm(0); 12417 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12418 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12419 return emitProbedAlloca(MI, BB); 12420 } else { 12421 llvm_unreachable("Unexpected instr type to insert"); 12422 } 12423 12424 MI.eraseFromParent(); // The pseudo instruction is gone now. 12425 return BB; 12426 } 12427 12428 //===----------------------------------------------------------------------===// 12429 // Target Optimization Hooks 12430 //===----------------------------------------------------------------------===// 12431 12432 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12433 // For the estimates, convergence is quadratic, so we essentially double the 12434 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12435 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12436 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12437 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12438 if (VT.getScalarType() == MVT::f64) 12439 RefinementSteps++; 12440 return RefinementSteps; 12441 } 12442 12443 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12444 const DenormalMode &Mode) const { 12445 // We only have VSX Vector Test for software Square Root. 12446 EVT VT = Op.getValueType(); 12447 if (!isTypeLegal(MVT::i1) || 12448 (VT != MVT::f64 && 12449 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12450 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 12451 12452 SDLoc DL(Op); 12453 // The output register of FTSQRT is CR field. 12454 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12455 // ftsqrt BF,FRB 12456 // Let e_b be the unbiased exponent of the double-precision 12457 // floating-point operand in register FRB. 12458 // fe_flag is set to 1 if either of the following conditions occurs. 12459 // - The double-precision floating-point operand in register FRB is a zero, 12460 // a NaN, or an infinity, or a negative value. 12461 // - e_b is less than or equal to -970. 12462 // Otherwise fe_flag is set to 0. 12463 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 12464 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 12465 // exponent is less than -970) 12466 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 12467 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 12468 FTSQRT, SRIdxVal), 12469 0); 12470 } 12471 12472 SDValue 12473 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 12474 SelectionDAG &DAG) const { 12475 // We only have VSX Vector Square Root. 12476 EVT VT = Op.getValueType(); 12477 if (VT != MVT::f64 && 12478 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 12479 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 12480 12481 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 12482 } 12483 12484 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12485 int Enabled, int &RefinementSteps, 12486 bool &UseOneConstNR, 12487 bool Reciprocal) const { 12488 EVT VT = Operand.getValueType(); 12489 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12490 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12491 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12492 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12493 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12494 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12495 12496 // The Newton-Raphson computation with a single constant does not provide 12497 // enough accuracy on some CPUs. 12498 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12499 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12500 } 12501 return SDValue(); 12502 } 12503 12504 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12505 int Enabled, 12506 int &RefinementSteps) const { 12507 EVT VT = Operand.getValueType(); 12508 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12509 (VT == MVT::f64 && Subtarget.hasFRE()) || 12510 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12511 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12512 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12513 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12514 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12515 } 12516 return SDValue(); 12517 } 12518 12519 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12520 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12521 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12522 // enabled for division), this functionality is redundant with the default 12523 // combiner logic (once the division -> reciprocal/multiply transformation 12524 // has taken place). As a result, this matters more for older cores than for 12525 // newer ones. 12526 12527 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12528 // reciprocal if there are two or more FDIVs (for embedded cores with only 12529 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12530 switch (Subtarget.getCPUDirective()) { 12531 default: 12532 return 3; 12533 case PPC::DIR_440: 12534 case PPC::DIR_A2: 12535 case PPC::DIR_E500: 12536 case PPC::DIR_E500mc: 12537 case PPC::DIR_E5500: 12538 return 2; 12539 } 12540 } 12541 12542 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12543 // collapsed, and so we need to look through chains of them. 12544 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12545 int64_t& Offset, SelectionDAG &DAG) { 12546 if (DAG.isBaseWithConstantOffset(Loc)) { 12547 Base = Loc.getOperand(0); 12548 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12549 12550 // The base might itself be a base plus an offset, and if so, accumulate 12551 // that as well. 12552 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12553 } 12554 } 12555 12556 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12557 unsigned Bytes, int Dist, 12558 SelectionDAG &DAG) { 12559 if (VT.getSizeInBits() / 8 != Bytes) 12560 return false; 12561 12562 SDValue BaseLoc = Base->getBasePtr(); 12563 if (Loc.getOpcode() == ISD::FrameIndex) { 12564 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12565 return false; 12566 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12567 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12568 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12569 int FS = MFI.getObjectSize(FI); 12570 int BFS = MFI.getObjectSize(BFI); 12571 if (FS != BFS || FS != (int)Bytes) return false; 12572 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12573 } 12574 12575 SDValue Base1 = Loc, Base2 = BaseLoc; 12576 int64_t Offset1 = 0, Offset2 = 0; 12577 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12578 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12579 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12580 return true; 12581 12582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12583 const GlobalValue *GV1 = nullptr; 12584 const GlobalValue *GV2 = nullptr; 12585 Offset1 = 0; 12586 Offset2 = 0; 12587 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12588 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12589 if (isGA1 && isGA2 && GV1 == GV2) 12590 return Offset1 == (Offset2 + Dist*Bytes); 12591 return false; 12592 } 12593 12594 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12595 // not enforce equality of the chain operands. 12596 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12597 unsigned Bytes, int Dist, 12598 SelectionDAG &DAG) { 12599 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12600 EVT VT = LS->getMemoryVT(); 12601 SDValue Loc = LS->getBasePtr(); 12602 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12603 } 12604 12605 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12606 EVT VT; 12607 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12608 default: return false; 12609 case Intrinsic::ppc_altivec_lvx: 12610 case Intrinsic::ppc_altivec_lvxl: 12611 case Intrinsic::ppc_vsx_lxvw4x: 12612 case Intrinsic::ppc_vsx_lxvw4x_be: 12613 VT = MVT::v4i32; 12614 break; 12615 case Intrinsic::ppc_vsx_lxvd2x: 12616 case Intrinsic::ppc_vsx_lxvd2x_be: 12617 VT = MVT::v2f64; 12618 break; 12619 case Intrinsic::ppc_altivec_lvebx: 12620 VT = MVT::i8; 12621 break; 12622 case Intrinsic::ppc_altivec_lvehx: 12623 VT = MVT::i16; 12624 break; 12625 case Intrinsic::ppc_altivec_lvewx: 12626 VT = MVT::i32; 12627 break; 12628 } 12629 12630 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12631 } 12632 12633 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12634 EVT VT; 12635 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12636 default: return false; 12637 case Intrinsic::ppc_altivec_stvx: 12638 case Intrinsic::ppc_altivec_stvxl: 12639 case Intrinsic::ppc_vsx_stxvw4x: 12640 VT = MVT::v4i32; 12641 break; 12642 case Intrinsic::ppc_vsx_stxvd2x: 12643 VT = MVT::v2f64; 12644 break; 12645 case Intrinsic::ppc_vsx_stxvw4x_be: 12646 VT = MVT::v4i32; 12647 break; 12648 case Intrinsic::ppc_vsx_stxvd2x_be: 12649 VT = MVT::v2f64; 12650 break; 12651 case Intrinsic::ppc_altivec_stvebx: 12652 VT = MVT::i8; 12653 break; 12654 case Intrinsic::ppc_altivec_stvehx: 12655 VT = MVT::i16; 12656 break; 12657 case Intrinsic::ppc_altivec_stvewx: 12658 VT = MVT::i32; 12659 break; 12660 } 12661 12662 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12663 } 12664 12665 return false; 12666 } 12667 12668 // Return true is there is a nearyby consecutive load to the one provided 12669 // (regardless of alignment). We search up and down the chain, looking though 12670 // token factors and other loads (but nothing else). As a result, a true result 12671 // indicates that it is safe to create a new consecutive load adjacent to the 12672 // load provided. 12673 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12674 SDValue Chain = LD->getChain(); 12675 EVT VT = LD->getMemoryVT(); 12676 12677 SmallSet<SDNode *, 16> LoadRoots; 12678 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12679 SmallSet<SDNode *, 16> Visited; 12680 12681 // First, search up the chain, branching to follow all token-factor operands. 12682 // If we find a consecutive load, then we're done, otherwise, record all 12683 // nodes just above the top-level loads and token factors. 12684 while (!Queue.empty()) { 12685 SDNode *ChainNext = Queue.pop_back_val(); 12686 if (!Visited.insert(ChainNext).second) 12687 continue; 12688 12689 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12690 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12691 return true; 12692 12693 if (!Visited.count(ChainLD->getChain().getNode())) 12694 Queue.push_back(ChainLD->getChain().getNode()); 12695 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12696 for (const SDUse &O : ChainNext->ops()) 12697 if (!Visited.count(O.getNode())) 12698 Queue.push_back(O.getNode()); 12699 } else 12700 LoadRoots.insert(ChainNext); 12701 } 12702 12703 // Second, search down the chain, starting from the top-level nodes recorded 12704 // in the first phase. These top-level nodes are the nodes just above all 12705 // loads and token factors. Starting with their uses, recursively look though 12706 // all loads (just the chain uses) and token factors to find a consecutive 12707 // load. 12708 Visited.clear(); 12709 Queue.clear(); 12710 12711 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12712 IE = LoadRoots.end(); I != IE; ++I) { 12713 Queue.push_back(*I); 12714 12715 while (!Queue.empty()) { 12716 SDNode *LoadRoot = Queue.pop_back_val(); 12717 if (!Visited.insert(LoadRoot).second) 12718 continue; 12719 12720 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12721 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12722 return true; 12723 12724 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12725 UE = LoadRoot->use_end(); UI != UE; ++UI) 12726 if (((isa<MemSDNode>(*UI) && 12727 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12728 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12729 Queue.push_back(*UI); 12730 } 12731 } 12732 12733 return false; 12734 } 12735 12736 /// This function is called when we have proved that a SETCC node can be replaced 12737 /// by subtraction (and other supporting instructions) so that the result of 12738 /// comparison is kept in a GPR instead of CR. This function is purely for 12739 /// codegen purposes and has some flags to guide the codegen process. 12740 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12741 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12742 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12743 12744 // Zero extend the operands to the largest legal integer. Originally, they 12745 // must be of a strictly smaller size. 12746 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12747 DAG.getConstant(Size, DL, MVT::i32)); 12748 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12749 DAG.getConstant(Size, DL, MVT::i32)); 12750 12751 // Swap if needed. Depends on the condition code. 12752 if (Swap) 12753 std::swap(Op0, Op1); 12754 12755 // Subtract extended integers. 12756 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12757 12758 // Move the sign bit to the least significant position and zero out the rest. 12759 // Now the least significant bit carries the result of original comparison. 12760 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12761 DAG.getConstant(Size - 1, DL, MVT::i32)); 12762 auto Final = Shifted; 12763 12764 // Complement the result if needed. Based on the condition code. 12765 if (Complement) 12766 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12767 DAG.getConstant(1, DL, MVT::i64)); 12768 12769 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12770 } 12771 12772 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12773 DAGCombinerInfo &DCI) const { 12774 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12775 12776 SelectionDAG &DAG = DCI.DAG; 12777 SDLoc DL(N); 12778 12779 // Size of integers being compared has a critical role in the following 12780 // analysis, so we prefer to do this when all types are legal. 12781 if (!DCI.isAfterLegalizeDAG()) 12782 return SDValue(); 12783 12784 // If all users of SETCC extend its value to a legal integer type 12785 // then we replace SETCC with a subtraction 12786 for (SDNode::use_iterator UI = N->use_begin(), 12787 UE = N->use_end(); UI != UE; ++UI) { 12788 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12789 return SDValue(); 12790 } 12791 12792 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12793 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12794 12795 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12796 12797 if (OpSize < Size) { 12798 switch (CC) { 12799 default: break; 12800 case ISD::SETULT: 12801 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12802 case ISD::SETULE: 12803 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12804 case ISD::SETUGT: 12805 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12806 case ISD::SETUGE: 12807 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12808 } 12809 } 12810 12811 return SDValue(); 12812 } 12813 12814 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12815 DAGCombinerInfo &DCI) const { 12816 SelectionDAG &DAG = DCI.DAG; 12817 SDLoc dl(N); 12818 12819 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12820 // If we're tracking CR bits, we need to be careful that we don't have: 12821 // trunc(binary-ops(zext(x), zext(y))) 12822 // or 12823 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12824 // such that we're unnecessarily moving things into GPRs when it would be 12825 // better to keep them in CR bits. 12826 12827 // Note that trunc here can be an actual i1 trunc, or can be the effective 12828 // truncation that comes from a setcc or select_cc. 12829 if (N->getOpcode() == ISD::TRUNCATE && 12830 N->getValueType(0) != MVT::i1) 12831 return SDValue(); 12832 12833 if (N->getOperand(0).getValueType() != MVT::i32 && 12834 N->getOperand(0).getValueType() != MVT::i64) 12835 return SDValue(); 12836 12837 if (N->getOpcode() == ISD::SETCC || 12838 N->getOpcode() == ISD::SELECT_CC) { 12839 // If we're looking at a comparison, then we need to make sure that the 12840 // high bits (all except for the first) don't matter the result. 12841 ISD::CondCode CC = 12842 cast<CondCodeSDNode>(N->getOperand( 12843 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12844 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12845 12846 if (ISD::isSignedIntSetCC(CC)) { 12847 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12848 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12849 return SDValue(); 12850 } else if (ISD::isUnsignedIntSetCC(CC)) { 12851 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12852 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12853 !DAG.MaskedValueIsZero(N->getOperand(1), 12854 APInt::getHighBitsSet(OpBits, OpBits-1))) 12855 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12856 : SDValue()); 12857 } else { 12858 // This is neither a signed nor an unsigned comparison, just make sure 12859 // that the high bits are equal. 12860 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12861 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12862 12863 // We don't really care about what is known about the first bit (if 12864 // anything), so pretend that it is known zero for both to ensure they can 12865 // be compared as constants. 12866 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 12867 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 12868 12869 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 12870 Op1Known.getConstant() != Op2Known.getConstant()) 12871 return SDValue(); 12872 } 12873 } 12874 12875 // We now know that the higher-order bits are irrelevant, we just need to 12876 // make sure that all of the intermediate operations are bit operations, and 12877 // all inputs are extensions. 12878 if (N->getOperand(0).getOpcode() != ISD::AND && 12879 N->getOperand(0).getOpcode() != ISD::OR && 12880 N->getOperand(0).getOpcode() != ISD::XOR && 12881 N->getOperand(0).getOpcode() != ISD::SELECT && 12882 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12883 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12884 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12885 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12886 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12887 return SDValue(); 12888 12889 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12890 N->getOperand(1).getOpcode() != ISD::AND && 12891 N->getOperand(1).getOpcode() != ISD::OR && 12892 N->getOperand(1).getOpcode() != ISD::XOR && 12893 N->getOperand(1).getOpcode() != ISD::SELECT && 12894 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12895 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12896 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12897 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12898 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12899 return SDValue(); 12900 12901 SmallVector<SDValue, 4> Inputs; 12902 SmallVector<SDValue, 8> BinOps, PromOps; 12903 SmallPtrSet<SDNode *, 16> Visited; 12904 12905 for (unsigned i = 0; i < 2; ++i) { 12906 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12907 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12908 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12909 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12910 isa<ConstantSDNode>(N->getOperand(i))) 12911 Inputs.push_back(N->getOperand(i)); 12912 else 12913 BinOps.push_back(N->getOperand(i)); 12914 12915 if (N->getOpcode() == ISD::TRUNCATE) 12916 break; 12917 } 12918 12919 // Visit all inputs, collect all binary operations (and, or, xor and 12920 // select) that are all fed by extensions. 12921 while (!BinOps.empty()) { 12922 SDValue BinOp = BinOps.pop_back_val(); 12923 12924 if (!Visited.insert(BinOp.getNode()).second) 12925 continue; 12926 12927 PromOps.push_back(BinOp); 12928 12929 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12930 // The condition of the select is not promoted. 12931 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12932 continue; 12933 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12934 continue; 12935 12936 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12937 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12938 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12939 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12940 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12941 Inputs.push_back(BinOp.getOperand(i)); 12942 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12943 BinOp.getOperand(i).getOpcode() == ISD::OR || 12944 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12945 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12946 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12947 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12948 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12949 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12950 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12951 BinOps.push_back(BinOp.getOperand(i)); 12952 } else { 12953 // We have an input that is not an extension or another binary 12954 // operation; we'll abort this transformation. 12955 return SDValue(); 12956 } 12957 } 12958 } 12959 12960 // Make sure that this is a self-contained cluster of operations (which 12961 // is not quite the same thing as saying that everything has only one 12962 // use). 12963 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12964 if (isa<ConstantSDNode>(Inputs[i])) 12965 continue; 12966 12967 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12968 UE = Inputs[i].getNode()->use_end(); 12969 UI != UE; ++UI) { 12970 SDNode *User = *UI; 12971 if (User != N && !Visited.count(User)) 12972 return SDValue(); 12973 12974 // Make sure that we're not going to promote the non-output-value 12975 // operand(s) or SELECT or SELECT_CC. 12976 // FIXME: Although we could sometimes handle this, and it does occur in 12977 // practice that one of the condition inputs to the select is also one of 12978 // the outputs, we currently can't deal with this. 12979 if (User->getOpcode() == ISD::SELECT) { 12980 if (User->getOperand(0) == Inputs[i]) 12981 return SDValue(); 12982 } else if (User->getOpcode() == ISD::SELECT_CC) { 12983 if (User->getOperand(0) == Inputs[i] || 12984 User->getOperand(1) == Inputs[i]) 12985 return SDValue(); 12986 } 12987 } 12988 } 12989 12990 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12991 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12992 UE = PromOps[i].getNode()->use_end(); 12993 UI != UE; ++UI) { 12994 SDNode *User = *UI; 12995 if (User != N && !Visited.count(User)) 12996 return SDValue(); 12997 12998 // Make sure that we're not going to promote the non-output-value 12999 // operand(s) or SELECT or SELECT_CC. 13000 // FIXME: Although we could sometimes handle this, and it does occur in 13001 // practice that one of the condition inputs to the select is also one of 13002 // the outputs, we currently can't deal with this. 13003 if (User->getOpcode() == ISD::SELECT) { 13004 if (User->getOperand(0) == PromOps[i]) 13005 return SDValue(); 13006 } else if (User->getOpcode() == ISD::SELECT_CC) { 13007 if (User->getOperand(0) == PromOps[i] || 13008 User->getOperand(1) == PromOps[i]) 13009 return SDValue(); 13010 } 13011 } 13012 } 13013 13014 // Replace all inputs with the extension operand. 13015 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13016 // Constants may have users outside the cluster of to-be-promoted nodes, 13017 // and so we need to replace those as we do the promotions. 13018 if (isa<ConstantSDNode>(Inputs[i])) 13019 continue; 13020 else 13021 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13022 } 13023 13024 std::list<HandleSDNode> PromOpHandles; 13025 for (auto &PromOp : PromOps) 13026 PromOpHandles.emplace_back(PromOp); 13027 13028 // Replace all operations (these are all the same, but have a different 13029 // (i1) return type). DAG.getNode will validate that the types of 13030 // a binary operator match, so go through the list in reverse so that 13031 // we've likely promoted both operands first. Any intermediate truncations or 13032 // extensions disappear. 13033 while (!PromOpHandles.empty()) { 13034 SDValue PromOp = PromOpHandles.back().getValue(); 13035 PromOpHandles.pop_back(); 13036 13037 if (PromOp.getOpcode() == ISD::TRUNCATE || 13038 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13039 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13040 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13041 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13042 PromOp.getOperand(0).getValueType() != MVT::i1) { 13043 // The operand is not yet ready (see comment below). 13044 PromOpHandles.emplace_front(PromOp); 13045 continue; 13046 } 13047 13048 SDValue RepValue = PromOp.getOperand(0); 13049 if (isa<ConstantSDNode>(RepValue)) 13050 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13051 13052 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13053 continue; 13054 } 13055 13056 unsigned C; 13057 switch (PromOp.getOpcode()) { 13058 default: C = 0; break; 13059 case ISD::SELECT: C = 1; break; 13060 case ISD::SELECT_CC: C = 2; break; 13061 } 13062 13063 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13064 PromOp.getOperand(C).getValueType() != MVT::i1) || 13065 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13066 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13067 // The to-be-promoted operands of this node have not yet been 13068 // promoted (this should be rare because we're going through the 13069 // list backward, but if one of the operands has several users in 13070 // this cluster of to-be-promoted nodes, it is possible). 13071 PromOpHandles.emplace_front(PromOp); 13072 continue; 13073 } 13074 13075 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13076 PromOp.getNode()->op_end()); 13077 13078 // If there are any constant inputs, make sure they're replaced now. 13079 for (unsigned i = 0; i < 2; ++i) 13080 if (isa<ConstantSDNode>(Ops[C+i])) 13081 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13082 13083 DAG.ReplaceAllUsesOfValueWith(PromOp, 13084 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13085 } 13086 13087 // Now we're left with the initial truncation itself. 13088 if (N->getOpcode() == ISD::TRUNCATE) 13089 return N->getOperand(0); 13090 13091 // Otherwise, this is a comparison. The operands to be compared have just 13092 // changed type (to i1), but everything else is the same. 13093 return SDValue(N, 0); 13094 } 13095 13096 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13097 DAGCombinerInfo &DCI) const { 13098 SelectionDAG &DAG = DCI.DAG; 13099 SDLoc dl(N); 13100 13101 // If we're tracking CR bits, we need to be careful that we don't have: 13102 // zext(binary-ops(trunc(x), trunc(y))) 13103 // or 13104 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13105 // such that we're unnecessarily moving things into CR bits that can more 13106 // efficiently stay in GPRs. Note that if we're not certain that the high 13107 // bits are set as required by the final extension, we still may need to do 13108 // some masking to get the proper behavior. 13109 13110 // This same functionality is important on PPC64 when dealing with 13111 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13112 // the return values of functions. Because it is so similar, it is handled 13113 // here as well. 13114 13115 if (N->getValueType(0) != MVT::i32 && 13116 N->getValueType(0) != MVT::i64) 13117 return SDValue(); 13118 13119 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13120 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13121 return SDValue(); 13122 13123 if (N->getOperand(0).getOpcode() != ISD::AND && 13124 N->getOperand(0).getOpcode() != ISD::OR && 13125 N->getOperand(0).getOpcode() != ISD::XOR && 13126 N->getOperand(0).getOpcode() != ISD::SELECT && 13127 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13128 return SDValue(); 13129 13130 SmallVector<SDValue, 4> Inputs; 13131 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13132 SmallPtrSet<SDNode *, 16> Visited; 13133 13134 // Visit all inputs, collect all binary operations (and, or, xor and 13135 // select) that are all fed by truncations. 13136 while (!BinOps.empty()) { 13137 SDValue BinOp = BinOps.pop_back_val(); 13138 13139 if (!Visited.insert(BinOp.getNode()).second) 13140 continue; 13141 13142 PromOps.push_back(BinOp); 13143 13144 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13145 // The condition of the select is not promoted. 13146 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13147 continue; 13148 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13149 continue; 13150 13151 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13152 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13153 Inputs.push_back(BinOp.getOperand(i)); 13154 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13155 BinOp.getOperand(i).getOpcode() == ISD::OR || 13156 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13157 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13158 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13159 BinOps.push_back(BinOp.getOperand(i)); 13160 } else { 13161 // We have an input that is not a truncation or another binary 13162 // operation; we'll abort this transformation. 13163 return SDValue(); 13164 } 13165 } 13166 } 13167 13168 // The operands of a select that must be truncated when the select is 13169 // promoted because the operand is actually part of the to-be-promoted set. 13170 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13171 13172 // Make sure that this is a self-contained cluster of operations (which 13173 // is not quite the same thing as saying that everything has only one 13174 // use). 13175 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13176 if (isa<ConstantSDNode>(Inputs[i])) 13177 continue; 13178 13179 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13180 UE = Inputs[i].getNode()->use_end(); 13181 UI != UE; ++UI) { 13182 SDNode *User = *UI; 13183 if (User != N && !Visited.count(User)) 13184 return SDValue(); 13185 13186 // If we're going to promote the non-output-value operand(s) or SELECT or 13187 // SELECT_CC, record them for truncation. 13188 if (User->getOpcode() == ISD::SELECT) { 13189 if (User->getOperand(0) == Inputs[i]) 13190 SelectTruncOp[0].insert(std::make_pair(User, 13191 User->getOperand(0).getValueType())); 13192 } else if (User->getOpcode() == ISD::SELECT_CC) { 13193 if (User->getOperand(0) == Inputs[i]) 13194 SelectTruncOp[0].insert(std::make_pair(User, 13195 User->getOperand(0).getValueType())); 13196 if (User->getOperand(1) == Inputs[i]) 13197 SelectTruncOp[1].insert(std::make_pair(User, 13198 User->getOperand(1).getValueType())); 13199 } 13200 } 13201 } 13202 13203 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13204 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13205 UE = PromOps[i].getNode()->use_end(); 13206 UI != UE; ++UI) { 13207 SDNode *User = *UI; 13208 if (User != N && !Visited.count(User)) 13209 return SDValue(); 13210 13211 // If we're going to promote the non-output-value operand(s) or SELECT or 13212 // SELECT_CC, record them for truncation. 13213 if (User->getOpcode() == ISD::SELECT) { 13214 if (User->getOperand(0) == PromOps[i]) 13215 SelectTruncOp[0].insert(std::make_pair(User, 13216 User->getOperand(0).getValueType())); 13217 } else if (User->getOpcode() == ISD::SELECT_CC) { 13218 if (User->getOperand(0) == PromOps[i]) 13219 SelectTruncOp[0].insert(std::make_pair(User, 13220 User->getOperand(0).getValueType())); 13221 if (User->getOperand(1) == PromOps[i]) 13222 SelectTruncOp[1].insert(std::make_pair(User, 13223 User->getOperand(1).getValueType())); 13224 } 13225 } 13226 } 13227 13228 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13229 bool ReallyNeedsExt = false; 13230 if (N->getOpcode() != ISD::ANY_EXTEND) { 13231 // If all of the inputs are not already sign/zero extended, then 13232 // we'll still need to do that at the end. 13233 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13234 if (isa<ConstantSDNode>(Inputs[i])) 13235 continue; 13236 13237 unsigned OpBits = 13238 Inputs[i].getOperand(0).getValueSizeInBits(); 13239 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13240 13241 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13242 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13243 APInt::getHighBitsSet(OpBits, 13244 OpBits-PromBits))) || 13245 (N->getOpcode() == ISD::SIGN_EXTEND && 13246 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13247 (OpBits-(PromBits-1)))) { 13248 ReallyNeedsExt = true; 13249 break; 13250 } 13251 } 13252 } 13253 13254 // Replace all inputs, either with the truncation operand, or a 13255 // truncation or extension to the final output type. 13256 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13257 // Constant inputs need to be replaced with the to-be-promoted nodes that 13258 // use them because they might have users outside of the cluster of 13259 // promoted nodes. 13260 if (isa<ConstantSDNode>(Inputs[i])) 13261 continue; 13262 13263 SDValue InSrc = Inputs[i].getOperand(0); 13264 if (Inputs[i].getValueType() == N->getValueType(0)) 13265 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13266 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13267 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13268 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13269 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13270 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13271 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13272 else 13273 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13274 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13275 } 13276 13277 std::list<HandleSDNode> PromOpHandles; 13278 for (auto &PromOp : PromOps) 13279 PromOpHandles.emplace_back(PromOp); 13280 13281 // Replace all operations (these are all the same, but have a different 13282 // (promoted) return type). DAG.getNode will validate that the types of 13283 // a binary operator match, so go through the list in reverse so that 13284 // we've likely promoted both operands first. 13285 while (!PromOpHandles.empty()) { 13286 SDValue PromOp = PromOpHandles.back().getValue(); 13287 PromOpHandles.pop_back(); 13288 13289 unsigned C; 13290 switch (PromOp.getOpcode()) { 13291 default: C = 0; break; 13292 case ISD::SELECT: C = 1; break; 13293 case ISD::SELECT_CC: C = 2; break; 13294 } 13295 13296 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13297 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13298 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13299 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13300 // The to-be-promoted operands of this node have not yet been 13301 // promoted (this should be rare because we're going through the 13302 // list backward, but if one of the operands has several users in 13303 // this cluster of to-be-promoted nodes, it is possible). 13304 PromOpHandles.emplace_front(PromOp); 13305 continue; 13306 } 13307 13308 // For SELECT and SELECT_CC nodes, we do a similar check for any 13309 // to-be-promoted comparison inputs. 13310 if (PromOp.getOpcode() == ISD::SELECT || 13311 PromOp.getOpcode() == ISD::SELECT_CC) { 13312 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13313 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13314 (SelectTruncOp[1].count(PromOp.getNode()) && 13315 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13316 PromOpHandles.emplace_front(PromOp); 13317 continue; 13318 } 13319 } 13320 13321 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13322 PromOp.getNode()->op_end()); 13323 13324 // If this node has constant inputs, then they'll need to be promoted here. 13325 for (unsigned i = 0; i < 2; ++i) { 13326 if (!isa<ConstantSDNode>(Ops[C+i])) 13327 continue; 13328 if (Ops[C+i].getValueType() == N->getValueType(0)) 13329 continue; 13330 13331 if (N->getOpcode() == ISD::SIGN_EXTEND) 13332 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13333 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13334 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13335 else 13336 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13337 } 13338 13339 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13340 // truncate them again to the original value type. 13341 if (PromOp.getOpcode() == ISD::SELECT || 13342 PromOp.getOpcode() == ISD::SELECT_CC) { 13343 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13344 if (SI0 != SelectTruncOp[0].end()) 13345 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13346 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13347 if (SI1 != SelectTruncOp[1].end()) 13348 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13349 } 13350 13351 DAG.ReplaceAllUsesOfValueWith(PromOp, 13352 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13353 } 13354 13355 // Now we're left with the initial extension itself. 13356 if (!ReallyNeedsExt) 13357 return N->getOperand(0); 13358 13359 // To zero extend, just mask off everything except for the first bit (in the 13360 // i1 case). 13361 if (N->getOpcode() == ISD::ZERO_EXTEND) 13362 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13363 DAG.getConstant(APInt::getLowBitsSet( 13364 N->getValueSizeInBits(0), PromBits), 13365 dl, N->getValueType(0))); 13366 13367 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13368 "Invalid extension type"); 13369 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13370 SDValue ShiftCst = 13371 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13372 return DAG.getNode( 13373 ISD::SRA, dl, N->getValueType(0), 13374 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13375 ShiftCst); 13376 } 13377 13378 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13379 DAGCombinerInfo &DCI) const { 13380 assert(N->getOpcode() == ISD::SETCC && 13381 "Should be called with a SETCC node"); 13382 13383 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13384 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13385 SDValue LHS = N->getOperand(0); 13386 SDValue RHS = N->getOperand(1); 13387 13388 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13389 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13390 LHS.hasOneUse()) 13391 std::swap(LHS, RHS); 13392 13393 // x == 0-y --> x+y == 0 13394 // x != 0-y --> x+y != 0 13395 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13396 RHS.hasOneUse()) { 13397 SDLoc DL(N); 13398 SelectionDAG &DAG = DCI.DAG; 13399 EVT VT = N->getValueType(0); 13400 EVT OpVT = LHS.getValueType(); 13401 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13402 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13403 } 13404 } 13405 13406 return DAGCombineTruncBoolExt(N, DCI); 13407 } 13408 13409 // Is this an extending load from an f32 to an f64? 13410 static bool isFPExtLoad(SDValue Op) { 13411 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13412 return LD->getExtensionType() == ISD::EXTLOAD && 13413 Op.getValueType() == MVT::f64; 13414 return false; 13415 } 13416 13417 /// Reduces the number of fp-to-int conversion when building a vector. 13418 /// 13419 /// If this vector is built out of floating to integer conversions, 13420 /// transform it to a vector built out of floating point values followed by a 13421 /// single floating to integer conversion of the vector. 13422 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13423 /// becomes (fptosi (build_vector ($A, $B, ...))) 13424 SDValue PPCTargetLowering:: 13425 combineElementTruncationToVectorTruncation(SDNode *N, 13426 DAGCombinerInfo &DCI) const { 13427 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13428 "Should be called with a BUILD_VECTOR node"); 13429 13430 SelectionDAG &DAG = DCI.DAG; 13431 SDLoc dl(N); 13432 13433 SDValue FirstInput = N->getOperand(0); 13434 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13435 "The input operand must be an fp-to-int conversion."); 13436 13437 // This combine happens after legalization so the fp_to_[su]i nodes are 13438 // already converted to PPCSISD nodes. 13439 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13440 if (FirstConversion == PPCISD::FCTIDZ || 13441 FirstConversion == PPCISD::FCTIDUZ || 13442 FirstConversion == PPCISD::FCTIWZ || 13443 FirstConversion == PPCISD::FCTIWUZ) { 13444 bool IsSplat = true; 13445 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13446 FirstConversion == PPCISD::FCTIWUZ; 13447 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13448 SmallVector<SDValue, 4> Ops; 13449 EVT TargetVT = N->getValueType(0); 13450 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13451 SDValue NextOp = N->getOperand(i); 13452 if (NextOp.getOpcode() != PPCISD::MFVSR) 13453 return SDValue(); 13454 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13455 if (NextConversion != FirstConversion) 13456 return SDValue(); 13457 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13458 // This is not valid if the input was originally double precision. It is 13459 // also not profitable to do unless this is an extending load in which 13460 // case doing this combine will allow us to combine consecutive loads. 13461 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13462 return SDValue(); 13463 if (N->getOperand(i) != FirstInput) 13464 IsSplat = false; 13465 } 13466 13467 // If this is a splat, we leave it as-is since there will be only a single 13468 // fp-to-int conversion followed by a splat of the integer. This is better 13469 // for 32-bit and smaller ints and neutral for 64-bit ints. 13470 if (IsSplat) 13471 return SDValue(); 13472 13473 // Now that we know we have the right type of node, get its operands 13474 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13475 SDValue In = N->getOperand(i).getOperand(0); 13476 if (Is32Bit) { 13477 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13478 // here, we know that all inputs are extending loads so this is safe). 13479 if (In.isUndef()) 13480 Ops.push_back(DAG.getUNDEF(SrcVT)); 13481 else { 13482 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13483 MVT::f32, In.getOperand(0), 13484 DAG.getIntPtrConstant(1, dl)); 13485 Ops.push_back(Trunc); 13486 } 13487 } else 13488 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13489 } 13490 13491 unsigned Opcode; 13492 if (FirstConversion == PPCISD::FCTIDZ || 13493 FirstConversion == PPCISD::FCTIWZ) 13494 Opcode = ISD::FP_TO_SINT; 13495 else 13496 Opcode = ISD::FP_TO_UINT; 13497 13498 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13499 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13500 return DAG.getNode(Opcode, dl, TargetVT, BV); 13501 } 13502 return SDValue(); 13503 } 13504 13505 /// Reduce the number of loads when building a vector. 13506 /// 13507 /// Building a vector out of multiple loads can be converted to a load 13508 /// of the vector type if the loads are consecutive. If the loads are 13509 /// consecutive but in descending order, a shuffle is added at the end 13510 /// to reorder the vector. 13511 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13512 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13513 "Should be called with a BUILD_VECTOR node"); 13514 13515 SDLoc dl(N); 13516 13517 // Return early for non byte-sized type, as they can't be consecutive. 13518 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13519 return SDValue(); 13520 13521 bool InputsAreConsecutiveLoads = true; 13522 bool InputsAreReverseConsecutive = true; 13523 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13524 SDValue FirstInput = N->getOperand(0); 13525 bool IsRoundOfExtLoad = false; 13526 13527 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13528 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13529 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13530 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13531 } 13532 // Not a build vector of (possibly fp_rounded) loads. 13533 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13534 N->getNumOperands() == 1) 13535 return SDValue(); 13536 13537 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13538 // If any inputs are fp_round(extload), they all must be. 13539 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13540 return SDValue(); 13541 13542 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13543 N->getOperand(i); 13544 if (NextInput.getOpcode() != ISD::LOAD) 13545 return SDValue(); 13546 13547 SDValue PreviousInput = 13548 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13549 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13550 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13551 13552 // If any inputs are fp_round(extload), they all must be. 13553 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13554 return SDValue(); 13555 13556 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13557 InputsAreConsecutiveLoads = false; 13558 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13559 InputsAreReverseConsecutive = false; 13560 13561 // Exit early if the loads are neither consecutive nor reverse consecutive. 13562 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13563 return SDValue(); 13564 } 13565 13566 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13567 "The loads cannot be both consecutive and reverse consecutive."); 13568 13569 SDValue FirstLoadOp = 13570 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13571 SDValue LastLoadOp = 13572 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13573 N->getOperand(N->getNumOperands()-1); 13574 13575 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13576 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13577 if (InputsAreConsecutiveLoads) { 13578 assert(LD1 && "Input needs to be a LoadSDNode."); 13579 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13580 LD1->getBasePtr(), LD1->getPointerInfo(), 13581 LD1->getAlignment()); 13582 } 13583 if (InputsAreReverseConsecutive) { 13584 assert(LDL && "Input needs to be a LoadSDNode."); 13585 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13586 LDL->getBasePtr(), LDL->getPointerInfo(), 13587 LDL->getAlignment()); 13588 SmallVector<int, 16> Ops; 13589 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13590 Ops.push_back(i); 13591 13592 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13593 DAG.getUNDEF(N->getValueType(0)), Ops); 13594 } 13595 return SDValue(); 13596 } 13597 13598 // This function adds the required vector_shuffle needed to get 13599 // the elements of the vector extract in the correct position 13600 // as specified by the CorrectElems encoding. 13601 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13602 SDValue Input, uint64_t Elems, 13603 uint64_t CorrectElems) { 13604 SDLoc dl(N); 13605 13606 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13607 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13608 13609 // Knowing the element indices being extracted from the original 13610 // vector and the order in which they're being inserted, just put 13611 // them at element indices required for the instruction. 13612 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13613 if (DAG.getDataLayout().isLittleEndian()) 13614 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13615 else 13616 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13617 CorrectElems = CorrectElems >> 8; 13618 Elems = Elems >> 8; 13619 } 13620 13621 SDValue Shuffle = 13622 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13623 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13624 13625 EVT VT = N->getValueType(0); 13626 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13627 13628 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13629 Input.getValueType().getVectorElementType(), 13630 VT.getVectorNumElements()); 13631 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13632 DAG.getValueType(ExtVT)); 13633 } 13634 13635 // Look for build vector patterns where input operands come from sign 13636 // extended vector_extract elements of specific indices. If the correct indices 13637 // aren't used, add a vector shuffle to fix up the indices and create 13638 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13639 // during instruction selection. 13640 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13641 // This array encodes the indices that the vector sign extend instructions 13642 // extract from when extending from one type to another for both BE and LE. 13643 // The right nibble of each byte corresponds to the LE incides. 13644 // and the left nibble of each byte corresponds to the BE incides. 13645 // For example: 0x3074B8FC byte->word 13646 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13647 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13648 // For example: 0x000070F8 byte->double word 13649 // For LE: the allowed indices are: 0x0,0x8 13650 // For BE: the allowed indices are: 0x7,0xF 13651 uint64_t TargetElems[] = { 13652 0x3074B8FC, // b->w 13653 0x000070F8, // b->d 13654 0x10325476, // h->w 13655 0x00003074, // h->d 13656 0x00001032, // w->d 13657 }; 13658 13659 uint64_t Elems = 0; 13660 int Index; 13661 SDValue Input; 13662 13663 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13664 if (!Op) 13665 return false; 13666 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13667 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13668 return false; 13669 13670 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13671 // of the right width. 13672 SDValue Extract = Op.getOperand(0); 13673 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13674 Extract = Extract.getOperand(0); 13675 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13676 return false; 13677 13678 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13679 if (!ExtOp) 13680 return false; 13681 13682 Index = ExtOp->getZExtValue(); 13683 if (Input && Input != Extract.getOperand(0)) 13684 return false; 13685 13686 if (!Input) 13687 Input = Extract.getOperand(0); 13688 13689 Elems = Elems << 8; 13690 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13691 Elems |= Index; 13692 13693 return true; 13694 }; 13695 13696 // If the build vector operands aren't sign extended vector extracts, 13697 // of the same input vector, then return. 13698 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13699 if (!isSExtOfVecExtract(N->getOperand(i))) { 13700 return SDValue(); 13701 } 13702 } 13703 13704 // If the vector extract indicies are not correct, add the appropriate 13705 // vector_shuffle. 13706 int TgtElemArrayIdx; 13707 int InputSize = Input.getValueType().getScalarSizeInBits(); 13708 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13709 if (InputSize + OutputSize == 40) 13710 TgtElemArrayIdx = 0; 13711 else if (InputSize + OutputSize == 72) 13712 TgtElemArrayIdx = 1; 13713 else if (InputSize + OutputSize == 48) 13714 TgtElemArrayIdx = 2; 13715 else if (InputSize + OutputSize == 80) 13716 TgtElemArrayIdx = 3; 13717 else if (InputSize + OutputSize == 96) 13718 TgtElemArrayIdx = 4; 13719 else 13720 return SDValue(); 13721 13722 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13723 CorrectElems = DAG.getDataLayout().isLittleEndian() 13724 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13725 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13726 if (Elems != CorrectElems) { 13727 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13728 } 13729 13730 // Regular lowering will catch cases where a shuffle is not needed. 13731 return SDValue(); 13732 } 13733 13734 // Look for the pattern of a load from a narrow width to i128, feeding 13735 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13736 // (LXVRZX). This node represents a zero extending load that will be matched 13737 // to the Load VSX Vector Rightmost instructions. 13738 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13739 SDLoc DL(N); 13740 13741 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13742 if (N->getValueType(0) != MVT::v1i128) 13743 return SDValue(); 13744 13745 SDValue Operand = N->getOperand(0); 13746 // Proceed with the transformation if the operand to the BUILD_VECTOR 13747 // is a load instruction. 13748 if (Operand.getOpcode() != ISD::LOAD) 13749 return SDValue(); 13750 13751 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13752 EVT MemoryType = LD->getMemoryVT(); 13753 13754 // This transformation is only valid if the we are loading either a byte, 13755 // halfword, word, or doubleword. 13756 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13757 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13758 13759 // Ensure that the load from the narrow width is being zero extended to i128. 13760 if (!ValidLDType || 13761 (LD->getExtensionType() != ISD::ZEXTLOAD && 13762 LD->getExtensionType() != ISD::EXTLOAD)) 13763 return SDValue(); 13764 13765 SDValue LoadOps[] = { 13766 LD->getChain(), LD->getBasePtr(), 13767 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13768 13769 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13770 DAG.getVTList(MVT::v1i128, MVT::Other), 13771 LoadOps, MemoryType, LD->getMemOperand()); 13772 } 13773 13774 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13775 DAGCombinerInfo &DCI) const { 13776 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13777 "Should be called with a BUILD_VECTOR node"); 13778 13779 SelectionDAG &DAG = DCI.DAG; 13780 SDLoc dl(N); 13781 13782 if (!Subtarget.hasVSX()) 13783 return SDValue(); 13784 13785 // The target independent DAG combiner will leave a build_vector of 13786 // float-to-int conversions intact. We can generate MUCH better code for 13787 // a float-to-int conversion of a vector of floats. 13788 SDValue FirstInput = N->getOperand(0); 13789 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13790 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13791 if (Reduced) 13792 return Reduced; 13793 } 13794 13795 // If we're building a vector out of consecutive loads, just load that 13796 // vector type. 13797 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13798 if (Reduced) 13799 return Reduced; 13800 13801 // If we're building a vector out of extended elements from another vector 13802 // we have P9 vector integer extend instructions. The code assumes legal 13803 // input types (i.e. it can't handle things like v4i16) so do not run before 13804 // legalization. 13805 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13806 Reduced = combineBVOfVecSExt(N, DAG); 13807 if (Reduced) 13808 return Reduced; 13809 } 13810 13811 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13812 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13813 // is a load from <valid narrow width> to i128. 13814 if (Subtarget.isISA3_1()) { 13815 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13816 if (BVOfZLoad) 13817 return BVOfZLoad; 13818 } 13819 13820 if (N->getValueType(0) != MVT::v2f64) 13821 return SDValue(); 13822 13823 // Looking for: 13824 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13825 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13826 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13827 return SDValue(); 13828 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13829 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13830 return SDValue(); 13831 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13832 return SDValue(); 13833 13834 SDValue Ext1 = FirstInput.getOperand(0); 13835 SDValue Ext2 = N->getOperand(1).getOperand(0); 13836 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13837 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13838 return SDValue(); 13839 13840 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13841 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13842 if (!Ext1Op || !Ext2Op) 13843 return SDValue(); 13844 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13845 Ext1.getOperand(0) != Ext2.getOperand(0)) 13846 return SDValue(); 13847 13848 int FirstElem = Ext1Op->getZExtValue(); 13849 int SecondElem = Ext2Op->getZExtValue(); 13850 int SubvecIdx; 13851 if (FirstElem == 0 && SecondElem == 1) 13852 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13853 else if (FirstElem == 2 && SecondElem == 3) 13854 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13855 else 13856 return SDValue(); 13857 13858 SDValue SrcVec = Ext1.getOperand(0); 13859 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13860 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13861 return DAG.getNode(NodeType, dl, MVT::v2f64, 13862 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13863 } 13864 13865 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13866 DAGCombinerInfo &DCI) const { 13867 assert((N->getOpcode() == ISD::SINT_TO_FP || 13868 N->getOpcode() == ISD::UINT_TO_FP) && 13869 "Need an int -> FP conversion node here"); 13870 13871 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13872 return SDValue(); 13873 13874 SelectionDAG &DAG = DCI.DAG; 13875 SDLoc dl(N); 13876 SDValue Op(N, 0); 13877 13878 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13879 // from the hardware. 13880 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13881 return SDValue(); 13882 if (!Op.getOperand(0).getValueType().isSimple()) 13883 return SDValue(); 13884 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13885 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13886 return SDValue(); 13887 13888 SDValue FirstOperand(Op.getOperand(0)); 13889 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13890 (FirstOperand.getValueType() == MVT::i8 || 13891 FirstOperand.getValueType() == MVT::i16); 13892 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13893 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13894 bool DstDouble = Op.getValueType() == MVT::f64; 13895 unsigned ConvOp = Signed ? 13896 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13897 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13898 SDValue WidthConst = 13899 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13900 dl, false); 13901 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13902 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13903 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13904 DAG.getVTList(MVT::f64, MVT::Other), 13905 Ops, MVT::i8, LDN->getMemOperand()); 13906 13907 // For signed conversion, we need to sign-extend the value in the VSR 13908 if (Signed) { 13909 SDValue ExtOps[] = { Ld, WidthConst }; 13910 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13911 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13912 } else 13913 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13914 } 13915 13916 13917 // For i32 intermediate values, unfortunately, the conversion functions 13918 // leave the upper 32 bits of the value are undefined. Within the set of 13919 // scalar instructions, we have no method for zero- or sign-extending the 13920 // value. Thus, we cannot handle i32 intermediate values here. 13921 if (Op.getOperand(0).getValueType() == MVT::i32) 13922 return SDValue(); 13923 13924 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13925 "UINT_TO_FP is supported only with FPCVT"); 13926 13927 // If we have FCFIDS, then use it when converting to single-precision. 13928 // Otherwise, convert to double-precision and then round. 13929 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13930 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13931 : PPCISD::FCFIDS) 13932 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13933 : PPCISD::FCFID); 13934 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13935 ? MVT::f32 13936 : MVT::f64; 13937 13938 // If we're converting from a float, to an int, and back to a float again, 13939 // then we don't need the store/load pair at all. 13940 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13941 Subtarget.hasFPCVT()) || 13942 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13943 SDValue Src = Op.getOperand(0).getOperand(0); 13944 if (Src.getValueType() == MVT::f32) { 13945 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13946 DCI.AddToWorklist(Src.getNode()); 13947 } else if (Src.getValueType() != MVT::f64) { 13948 // Make sure that we don't pick up a ppc_fp128 source value. 13949 return SDValue(); 13950 } 13951 13952 unsigned FCTOp = 13953 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13954 PPCISD::FCTIDUZ; 13955 13956 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13957 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13958 13959 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13960 FP = DAG.getNode(ISD::FP_ROUND, dl, 13961 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13962 DCI.AddToWorklist(FP.getNode()); 13963 } 13964 13965 return FP; 13966 } 13967 13968 return SDValue(); 13969 } 13970 13971 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13972 // builtins) into loads with swaps. 13973 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13974 DAGCombinerInfo &DCI) const { 13975 SelectionDAG &DAG = DCI.DAG; 13976 SDLoc dl(N); 13977 SDValue Chain; 13978 SDValue Base; 13979 MachineMemOperand *MMO; 13980 13981 switch (N->getOpcode()) { 13982 default: 13983 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13984 case ISD::LOAD: { 13985 LoadSDNode *LD = cast<LoadSDNode>(N); 13986 Chain = LD->getChain(); 13987 Base = LD->getBasePtr(); 13988 MMO = LD->getMemOperand(); 13989 // If the MMO suggests this isn't a load of a full vector, leave 13990 // things alone. For a built-in, we have to make the change for 13991 // correctness, so if there is a size problem that will be a bug. 13992 if (MMO->getSize() < 16) 13993 return SDValue(); 13994 break; 13995 } 13996 case ISD::INTRINSIC_W_CHAIN: { 13997 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13998 Chain = Intrin->getChain(); 13999 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14000 // us what we want. Get operand 2 instead. 14001 Base = Intrin->getOperand(2); 14002 MMO = Intrin->getMemOperand(); 14003 break; 14004 } 14005 } 14006 14007 MVT VecTy = N->getValueType(0).getSimpleVT(); 14008 14009 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14010 // aligned and the type is a vector with elements up to 4 bytes 14011 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14012 VecTy.getScalarSizeInBits() <= 32) { 14013 return SDValue(); 14014 } 14015 14016 SDValue LoadOps[] = { Chain, Base }; 14017 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14018 DAG.getVTList(MVT::v2f64, MVT::Other), 14019 LoadOps, MVT::v2f64, MMO); 14020 14021 DCI.AddToWorklist(Load.getNode()); 14022 Chain = Load.getValue(1); 14023 SDValue Swap = DAG.getNode( 14024 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14025 DCI.AddToWorklist(Swap.getNode()); 14026 14027 // Add a bitcast if the resulting load type doesn't match v2f64. 14028 if (VecTy != MVT::v2f64) { 14029 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14030 DCI.AddToWorklist(N.getNode()); 14031 // Package {bitcast value, swap's chain} to match Load's shape. 14032 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14033 N, Swap.getValue(1)); 14034 } 14035 14036 return Swap; 14037 } 14038 14039 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14040 // builtins) into stores with swaps. 14041 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14042 DAGCombinerInfo &DCI) const { 14043 SelectionDAG &DAG = DCI.DAG; 14044 SDLoc dl(N); 14045 SDValue Chain; 14046 SDValue Base; 14047 unsigned SrcOpnd; 14048 MachineMemOperand *MMO; 14049 14050 switch (N->getOpcode()) { 14051 default: 14052 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14053 case ISD::STORE: { 14054 StoreSDNode *ST = cast<StoreSDNode>(N); 14055 Chain = ST->getChain(); 14056 Base = ST->getBasePtr(); 14057 MMO = ST->getMemOperand(); 14058 SrcOpnd = 1; 14059 // If the MMO suggests this isn't a store of a full vector, leave 14060 // things alone. For a built-in, we have to make the change for 14061 // correctness, so if there is a size problem that will be a bug. 14062 if (MMO->getSize() < 16) 14063 return SDValue(); 14064 break; 14065 } 14066 case ISD::INTRINSIC_VOID: { 14067 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14068 Chain = Intrin->getChain(); 14069 // Intrin->getBasePtr() oddly does not get what we want. 14070 Base = Intrin->getOperand(3); 14071 MMO = Intrin->getMemOperand(); 14072 SrcOpnd = 2; 14073 break; 14074 } 14075 } 14076 14077 SDValue Src = N->getOperand(SrcOpnd); 14078 MVT VecTy = Src.getValueType().getSimpleVT(); 14079 14080 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14081 // aligned and the type is a vector with elements up to 4 bytes 14082 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14083 VecTy.getScalarSizeInBits() <= 32) { 14084 return SDValue(); 14085 } 14086 14087 // All stores are done as v2f64 and possible bit cast. 14088 if (VecTy != MVT::v2f64) { 14089 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14090 DCI.AddToWorklist(Src.getNode()); 14091 } 14092 14093 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14094 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14095 DCI.AddToWorklist(Swap.getNode()); 14096 Chain = Swap.getValue(1); 14097 SDValue StoreOps[] = { Chain, Swap, Base }; 14098 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14099 DAG.getVTList(MVT::Other), 14100 StoreOps, VecTy, MMO); 14101 DCI.AddToWorklist(Store.getNode()); 14102 return Store; 14103 } 14104 14105 // Handle DAG combine for STORE (FP_TO_INT F). 14106 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14107 DAGCombinerInfo &DCI) const { 14108 14109 SelectionDAG &DAG = DCI.DAG; 14110 SDLoc dl(N); 14111 unsigned Opcode = N->getOperand(1).getOpcode(); 14112 14113 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14114 && "Not a FP_TO_INT Instruction!"); 14115 14116 SDValue Val = N->getOperand(1).getOperand(0); 14117 EVT Op1VT = N->getOperand(1).getValueType(); 14118 EVT ResVT = Val.getValueType(); 14119 14120 if (!isTypeLegal(ResVT)) 14121 return SDValue(); 14122 14123 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14124 bool ValidTypeForStoreFltAsInt = 14125 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14126 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14127 14128 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14129 return SDValue(); 14130 14131 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14132 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14133 return SDValue(); 14134 14135 // Extend f32 values to f64 14136 if (ResVT.getScalarSizeInBits() == 32) { 14137 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14138 DCI.AddToWorklist(Val.getNode()); 14139 } 14140 14141 // Set signed or unsigned conversion opcode. 14142 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14143 PPCISD::FP_TO_SINT_IN_VSR : 14144 PPCISD::FP_TO_UINT_IN_VSR; 14145 14146 Val = DAG.getNode(ConvOpcode, 14147 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14148 DCI.AddToWorklist(Val.getNode()); 14149 14150 // Set number of bytes being converted. 14151 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14152 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14153 DAG.getIntPtrConstant(ByteSize, dl, false), 14154 DAG.getValueType(Op1VT) }; 14155 14156 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14157 DAG.getVTList(MVT::Other), Ops, 14158 cast<StoreSDNode>(N)->getMemoryVT(), 14159 cast<StoreSDNode>(N)->getMemOperand()); 14160 14161 DCI.AddToWorklist(Val.getNode()); 14162 return Val; 14163 } 14164 14165 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14166 // Check that the source of the element keeps flipping 14167 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14168 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14169 for (int i = 1, e = Mask.size(); i < e; i++) { 14170 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14171 return false; 14172 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14173 return false; 14174 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14175 } 14176 return true; 14177 } 14178 14179 static bool isSplatBV(SDValue Op) { 14180 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14181 return false; 14182 SDValue FirstOp; 14183 14184 // Find first non-undef input. 14185 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14186 FirstOp = Op.getOperand(i); 14187 if (!FirstOp.isUndef()) 14188 break; 14189 } 14190 14191 // All inputs are undef or the same as the first non-undef input. 14192 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14193 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14194 return false; 14195 return true; 14196 } 14197 14198 static SDValue isScalarToVec(SDValue Op) { 14199 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14200 return Op; 14201 if (Op.getOpcode() != ISD::BITCAST) 14202 return SDValue(); 14203 Op = Op.getOperand(0); 14204 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14205 return Op; 14206 return SDValue(); 14207 } 14208 14209 // Fix up the shuffle mask to account for the fact that the result of 14210 // scalar_to_vector is not in lane zero. This just takes all values in 14211 // the ranges specified by the min/max indices and adds the number of 14212 // elements required to ensure each element comes from the respective 14213 // position in the valid lane. 14214 // On little endian, that's just the corresponding element in the other 14215 // half of the vector. On big endian, it is in the same half but right 14216 // justified rather than left justified in that half. 14217 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14218 int LHSMaxIdx, int RHSMinIdx, 14219 int RHSMaxIdx, int HalfVec, 14220 unsigned ValidLaneWidth, 14221 const PPCSubtarget &Subtarget) { 14222 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14223 int Idx = ShuffV[i]; 14224 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14225 ShuffV[i] += 14226 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14227 } 14228 } 14229 14230 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14231 // the original is: 14232 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14233 // In such a case, just change the shuffle mask to extract the element 14234 // from the permuted index. 14235 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14236 const PPCSubtarget &Subtarget) { 14237 SDLoc dl(OrigSToV); 14238 EVT VT = OrigSToV.getValueType(); 14239 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14240 "Expecting a SCALAR_TO_VECTOR here"); 14241 SDValue Input = OrigSToV.getOperand(0); 14242 14243 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14244 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14245 SDValue OrigVector = Input.getOperand(0); 14246 14247 // Can't handle non-const element indices or different vector types 14248 // for the input to the extract and the output of the scalar_to_vector. 14249 if (Idx && VT == OrigVector.getValueType()) { 14250 unsigned NumElts = VT.getVectorNumElements(); 14251 assert( 14252 NumElts > 1 && 14253 "Cannot produce a permuted scalar_to_vector for one element vector"); 14254 SmallVector<int, 16> NewMask(NumElts, -1); 14255 unsigned ResultInElt = NumElts / 2; 14256 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14257 NewMask[ResultInElt] = Idx->getZExtValue(); 14258 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14259 } 14260 } 14261 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14262 OrigSToV.getOperand(0)); 14263 } 14264 14265 // On little endian subtargets, combine shuffles such as: 14266 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14267 // into: 14268 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14269 // because the latter can be matched to a single instruction merge. 14270 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14271 // to put the value into element zero. Adjust the shuffle mask so that the 14272 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14273 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 14274 // nodes with elements smaller than doubleword because all the ways 14275 // of getting scalar data into a vector register put the value in the 14276 // rightmost element of the left half of the vector. 14277 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14278 SelectionDAG &DAG) const { 14279 SDValue LHS = SVN->getOperand(0); 14280 SDValue RHS = SVN->getOperand(1); 14281 auto Mask = SVN->getMask(); 14282 int NumElts = LHS.getValueType().getVectorNumElements(); 14283 SDValue Res(SVN, 0); 14284 SDLoc dl(SVN); 14285 bool IsLittleEndian = Subtarget.isLittleEndian(); 14286 14287 // On little endian targets, do these combines on all VSX targets since 14288 // canonical shuffles match efficient permutes. On big endian targets, 14289 // this is only useful for targets with direct moves. 14290 if (!Subtarget.hasDirectMove() && !(IsLittleEndian && Subtarget.hasVSX())) 14291 return Res; 14292 14293 // If this is not a shuffle of a shuffle and the first element comes from 14294 // the second vector, canonicalize to the commuted form. This will make it 14295 // more likely to match one of the single instruction patterns. 14296 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14297 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14298 std::swap(LHS, RHS); 14299 Res = DAG.getCommutedVectorShuffle(*SVN); 14300 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14301 } 14302 14303 // Adjust the shuffle mask if either input vector comes from a 14304 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14305 // form (to prevent the need for a swap). 14306 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14307 SDValue SToVLHS = isScalarToVec(LHS); 14308 SDValue SToVRHS = isScalarToVec(RHS); 14309 if (SToVLHS || SToVRHS) { 14310 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14311 : SToVRHS.getValueType().getVectorNumElements(); 14312 int NumEltsOut = ShuffV.size(); 14313 unsigned InElemSizeInBits = 14314 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() 14315 : SToVRHS.getValueType().getScalarSizeInBits(); 14316 unsigned OutElemSizeInBits = SToVLHS 14317 ? LHS.getValueType().getScalarSizeInBits() 14318 : RHS.getValueType().getScalarSizeInBits(); 14319 14320 // The width of the "valid lane" (i.e. the lane that contains the value that 14321 // is vectorized) needs to be expressed in terms of the number of elements 14322 // of the shuffle. It is thereby the ratio of the values before and after 14323 // any bitcast. 14324 unsigned ValidLaneWidth = InElemSizeInBits / OutElemSizeInBits; 14325 14326 // Initially assume that neither input is permuted. These will be adjusted 14327 // accordingly if either input is. 14328 int LHSMaxIdx = -1; 14329 int RHSMinIdx = -1; 14330 int RHSMaxIdx = -1; 14331 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14332 14333 // Get the permuted scalar to vector nodes for the source(s) that come from 14334 // ISD::SCALAR_TO_VECTOR. 14335 // On big endian systems, this only makes sense for element sizes smaller 14336 // than 64 bits since for 64-bit elements, all instructions already put 14337 // the value into element zero. 14338 if (SToVLHS) { 14339 if (!IsLittleEndian && InElemSizeInBits >= 64) 14340 return Res; 14341 // Set up the values for the shuffle vector fixup. 14342 LHSMaxIdx = NumEltsOut / NumEltsIn; 14343 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 14344 if (SToVLHS.getValueType() != LHS.getValueType()) 14345 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14346 LHS = SToVLHS; 14347 } 14348 if (SToVRHS) { 14349 if (!IsLittleEndian && InElemSizeInBits >= 64) 14350 return Res; 14351 RHSMinIdx = NumEltsOut; 14352 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14353 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 14354 if (SToVRHS.getValueType() != RHS.getValueType()) 14355 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14356 RHS = SToVRHS; 14357 } 14358 14359 // Fix up the shuffle mask to reflect where the desired element actually is. 14360 // The minimum and maximum indices that correspond to element zero for both 14361 // the LHS and RHS are computed and will control which shuffle mask entries 14362 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14363 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 14364 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14365 HalfVec, ValidLaneWidth, Subtarget); 14366 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14367 14368 // We may have simplified away the shuffle. We won't be able to do anything 14369 // further with it here. 14370 if (!isa<ShuffleVectorSDNode>(Res)) 14371 return Res; 14372 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14373 } 14374 14375 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 14376 // The common case after we commuted the shuffle is that the RHS is a splat 14377 // and we have elements coming in from the splat at indices that are not 14378 // conducive to using a merge. 14379 // Example: 14380 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14381 if (!isSplatBV(TheSplat)) 14382 return Res; 14383 14384 // We are looking for a mask such that all even elements are from 14385 // one vector and all odd elements from the other. 14386 if (!isAlternatingShuffMask(Mask, NumElts)) 14387 return Res; 14388 14389 // Adjust the mask so we are pulling in the same index from the splat 14390 // as the index from the interesting vector in consecutive elements. 14391 if (IsLittleEndian) { 14392 // Example (even elements from first vector): 14393 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14394 if (Mask[0] < NumElts) 14395 for (int i = 1, e = Mask.size(); i < e; i += 2) 14396 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14397 // Example (odd elements from first vector): 14398 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14399 else 14400 for (int i = 0, e = Mask.size(); i < e; i += 2) 14401 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14402 } else { 14403 // Example (even elements from first vector): 14404 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 14405 if (Mask[0] < NumElts) 14406 for (int i = 0, e = Mask.size(); i < e; i += 2) 14407 ShuffV[i] = ShuffV[i + 1] - NumElts; 14408 // Example (odd elements from first vector): 14409 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 14410 else 14411 for (int i = 1, e = Mask.size(); i < e; i += 2) 14412 ShuffV[i] = ShuffV[i - 1] - NumElts; 14413 } 14414 14415 // If the RHS has undefs, we need to remove them since we may have created 14416 // a shuffle that adds those instead of the splat value. 14417 SDValue SplatVal = 14418 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 14419 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 14420 14421 if (IsLittleEndian) 14422 RHS = TheSplat; 14423 else 14424 LHS = TheSplat; 14425 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14426 } 14427 14428 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14429 LSBaseSDNode *LSBase, 14430 DAGCombinerInfo &DCI) const { 14431 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14432 "Not a reverse memop pattern!"); 14433 14434 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14435 auto Mask = SVN->getMask(); 14436 int i = 0; 14437 auto I = Mask.rbegin(); 14438 auto E = Mask.rend(); 14439 14440 for (; I != E; ++I) { 14441 if (*I != i) 14442 return false; 14443 i++; 14444 } 14445 return true; 14446 }; 14447 14448 SelectionDAG &DAG = DCI.DAG; 14449 EVT VT = SVN->getValueType(0); 14450 14451 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14452 return SDValue(); 14453 14454 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14455 // See comment in PPCVSXSwapRemoval.cpp. 14456 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14457 if (!Subtarget.hasP9Vector()) 14458 return SDValue(); 14459 14460 if(!IsElementReverse(SVN)) 14461 return SDValue(); 14462 14463 if (LSBase->getOpcode() == ISD::LOAD) { 14464 // If the load has more than one user except the shufflevector instruction, 14465 // it is not profitable to replace the shufflevector with a reverse load. 14466 if (!LSBase->hasOneUse()) 14467 return SDValue(); 14468 14469 SDLoc dl(SVN); 14470 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14471 return DAG.getMemIntrinsicNode( 14472 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14473 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14474 } 14475 14476 if (LSBase->getOpcode() == ISD::STORE) { 14477 // If there are other uses of the shuffle, the swap cannot be avoided. 14478 // Forcing the use of an X-Form (since swapped stores only have 14479 // X-Forms) without removing the swap is unprofitable. 14480 if (!SVN->hasOneUse()) 14481 return SDValue(); 14482 14483 SDLoc dl(LSBase); 14484 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14485 LSBase->getBasePtr()}; 14486 return DAG.getMemIntrinsicNode( 14487 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14488 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14489 } 14490 14491 llvm_unreachable("Expected a load or store node here"); 14492 } 14493 14494 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14495 DAGCombinerInfo &DCI) const { 14496 SelectionDAG &DAG = DCI.DAG; 14497 SDLoc dl(N); 14498 switch (N->getOpcode()) { 14499 default: break; 14500 case ISD::ADD: 14501 return combineADD(N, DCI); 14502 case ISD::SHL: 14503 return combineSHL(N, DCI); 14504 case ISD::SRA: 14505 return combineSRA(N, DCI); 14506 case ISD::SRL: 14507 return combineSRL(N, DCI); 14508 case ISD::MUL: 14509 return combineMUL(N, DCI); 14510 case ISD::FMA: 14511 case PPCISD::FNMSUB: 14512 return combineFMALike(N, DCI); 14513 case PPCISD::SHL: 14514 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14515 return N->getOperand(0); 14516 break; 14517 case PPCISD::SRL: 14518 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14519 return N->getOperand(0); 14520 break; 14521 case PPCISD::SRA: 14522 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14523 if (C->isNullValue() || // 0 >>s V -> 0. 14524 C->isAllOnesValue()) // -1 >>s V -> -1. 14525 return N->getOperand(0); 14526 } 14527 break; 14528 case ISD::SIGN_EXTEND: 14529 case ISD::ZERO_EXTEND: 14530 case ISD::ANY_EXTEND: 14531 return DAGCombineExtBoolTrunc(N, DCI); 14532 case ISD::TRUNCATE: 14533 return combineTRUNCATE(N, DCI); 14534 case ISD::SETCC: 14535 if (SDValue CSCC = combineSetCC(N, DCI)) 14536 return CSCC; 14537 LLVM_FALLTHROUGH; 14538 case ISD::SELECT_CC: 14539 return DAGCombineTruncBoolExt(N, DCI); 14540 case ISD::SINT_TO_FP: 14541 case ISD::UINT_TO_FP: 14542 return combineFPToIntToFP(N, DCI); 14543 case ISD::VECTOR_SHUFFLE: 14544 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14545 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14546 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14547 } 14548 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14549 case ISD::STORE: { 14550 14551 EVT Op1VT = N->getOperand(1).getValueType(); 14552 unsigned Opcode = N->getOperand(1).getOpcode(); 14553 14554 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14555 SDValue Val= combineStoreFPToInt(N, DCI); 14556 if (Val) 14557 return Val; 14558 } 14559 14560 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14561 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14562 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14563 if (Val) 14564 return Val; 14565 } 14566 14567 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14568 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14569 N->getOperand(1).getNode()->hasOneUse() && 14570 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14571 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14572 14573 // STBRX can only handle simple types and it makes no sense to store less 14574 // two bytes in byte-reversed order. 14575 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14576 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14577 break; 14578 14579 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14580 // Do an any-extend to 32-bits if this is a half-word input. 14581 if (BSwapOp.getValueType() == MVT::i16) 14582 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14583 14584 // If the type of BSWAP operand is wider than stored memory width 14585 // it need to be shifted to the right side before STBRX. 14586 if (Op1VT.bitsGT(mVT)) { 14587 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14588 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14589 DAG.getConstant(Shift, dl, MVT::i32)); 14590 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14591 if (Op1VT == MVT::i64) 14592 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14593 } 14594 14595 SDValue Ops[] = { 14596 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14597 }; 14598 return 14599 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14600 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14601 cast<StoreSDNode>(N)->getMemOperand()); 14602 } 14603 14604 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14605 // So it can increase the chance of CSE constant construction. 14606 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14607 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14608 // Need to sign-extended to 64-bits to handle negative values. 14609 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14610 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14611 MemVT.getSizeInBits()); 14612 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14613 14614 // DAG.getTruncStore() can't be used here because it doesn't accept 14615 // the general (base + offset) addressing mode. 14616 // So we use UpdateNodeOperands and setTruncatingStore instead. 14617 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14618 N->getOperand(3)); 14619 cast<StoreSDNode>(N)->setTruncatingStore(true); 14620 return SDValue(N, 0); 14621 } 14622 14623 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14624 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14625 if (Op1VT.isSimple()) { 14626 MVT StoreVT = Op1VT.getSimpleVT(); 14627 if (Subtarget.needsSwapsForVSXMemOps() && 14628 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14629 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14630 return expandVSXStoreForLE(N, DCI); 14631 } 14632 break; 14633 } 14634 case ISD::LOAD: { 14635 LoadSDNode *LD = cast<LoadSDNode>(N); 14636 EVT VT = LD->getValueType(0); 14637 14638 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14639 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14640 if (VT.isSimple()) { 14641 MVT LoadVT = VT.getSimpleVT(); 14642 if (Subtarget.needsSwapsForVSXMemOps() && 14643 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14644 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14645 return expandVSXLoadForLE(N, DCI); 14646 } 14647 14648 // We sometimes end up with a 64-bit integer load, from which we extract 14649 // two single-precision floating-point numbers. This happens with 14650 // std::complex<float>, and other similar structures, because of the way we 14651 // canonicalize structure copies. However, if we lack direct moves, 14652 // then the final bitcasts from the extracted integer values to the 14653 // floating-point numbers turn into store/load pairs. Even with direct moves, 14654 // just loading the two floating-point numbers is likely better. 14655 auto ReplaceTwoFloatLoad = [&]() { 14656 if (VT != MVT::i64) 14657 return false; 14658 14659 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14660 LD->isVolatile()) 14661 return false; 14662 14663 // We're looking for a sequence like this: 14664 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14665 // t16: i64 = srl t13, Constant:i32<32> 14666 // t17: i32 = truncate t16 14667 // t18: f32 = bitcast t17 14668 // t19: i32 = truncate t13 14669 // t20: f32 = bitcast t19 14670 14671 if (!LD->hasNUsesOfValue(2, 0)) 14672 return false; 14673 14674 auto UI = LD->use_begin(); 14675 while (UI.getUse().getResNo() != 0) ++UI; 14676 SDNode *Trunc = *UI++; 14677 while (UI.getUse().getResNo() != 0) ++UI; 14678 SDNode *RightShift = *UI; 14679 if (Trunc->getOpcode() != ISD::TRUNCATE) 14680 std::swap(Trunc, RightShift); 14681 14682 if (Trunc->getOpcode() != ISD::TRUNCATE || 14683 Trunc->getValueType(0) != MVT::i32 || 14684 !Trunc->hasOneUse()) 14685 return false; 14686 if (RightShift->getOpcode() != ISD::SRL || 14687 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14688 RightShift->getConstantOperandVal(1) != 32 || 14689 !RightShift->hasOneUse()) 14690 return false; 14691 14692 SDNode *Trunc2 = *RightShift->use_begin(); 14693 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14694 Trunc2->getValueType(0) != MVT::i32 || 14695 !Trunc2->hasOneUse()) 14696 return false; 14697 14698 SDNode *Bitcast = *Trunc->use_begin(); 14699 SDNode *Bitcast2 = *Trunc2->use_begin(); 14700 14701 if (Bitcast->getOpcode() != ISD::BITCAST || 14702 Bitcast->getValueType(0) != MVT::f32) 14703 return false; 14704 if (Bitcast2->getOpcode() != ISD::BITCAST || 14705 Bitcast2->getValueType(0) != MVT::f32) 14706 return false; 14707 14708 if (Subtarget.isLittleEndian()) 14709 std::swap(Bitcast, Bitcast2); 14710 14711 // Bitcast has the second float (in memory-layout order) and Bitcast2 14712 // has the first one. 14713 14714 SDValue BasePtr = LD->getBasePtr(); 14715 if (LD->isIndexed()) { 14716 assert(LD->getAddressingMode() == ISD::PRE_INC && 14717 "Non-pre-inc AM on PPC?"); 14718 BasePtr = 14719 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14720 LD->getOffset()); 14721 } 14722 14723 auto MMOFlags = 14724 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14725 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14726 LD->getPointerInfo(), LD->getAlignment(), 14727 MMOFlags, LD->getAAInfo()); 14728 SDValue AddPtr = 14729 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14730 BasePtr, DAG.getIntPtrConstant(4, dl)); 14731 SDValue FloatLoad2 = DAG.getLoad( 14732 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14733 LD->getPointerInfo().getWithOffset(4), 14734 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14735 14736 if (LD->isIndexed()) { 14737 // Note that DAGCombine should re-form any pre-increment load(s) from 14738 // what is produced here if that makes sense. 14739 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14740 } 14741 14742 DCI.CombineTo(Bitcast2, FloatLoad); 14743 DCI.CombineTo(Bitcast, FloatLoad2); 14744 14745 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14746 SDValue(FloatLoad2.getNode(), 1)); 14747 return true; 14748 }; 14749 14750 if (ReplaceTwoFloatLoad()) 14751 return SDValue(N, 0); 14752 14753 EVT MemVT = LD->getMemoryVT(); 14754 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14755 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14756 if (LD->isUnindexed() && VT.isVector() && 14757 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14758 // P8 and later hardware should just use LOAD. 14759 !Subtarget.hasP8Vector() && 14760 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14761 VT == MVT::v4f32))) && 14762 LD->getAlign() < ABIAlignment) { 14763 // This is a type-legal unaligned Altivec load. 14764 SDValue Chain = LD->getChain(); 14765 SDValue Ptr = LD->getBasePtr(); 14766 bool isLittleEndian = Subtarget.isLittleEndian(); 14767 14768 // This implements the loading of unaligned vectors as described in 14769 // the venerable Apple Velocity Engine overview. Specifically: 14770 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14771 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14772 // 14773 // The general idea is to expand a sequence of one or more unaligned 14774 // loads into an alignment-based permutation-control instruction (lvsl 14775 // or lvsr), a series of regular vector loads (which always truncate 14776 // their input address to an aligned address), and a series of 14777 // permutations. The results of these permutations are the requested 14778 // loaded values. The trick is that the last "extra" load is not taken 14779 // from the address you might suspect (sizeof(vector) bytes after the 14780 // last requested load), but rather sizeof(vector) - 1 bytes after the 14781 // last requested vector. The point of this is to avoid a page fault if 14782 // the base address happened to be aligned. This works because if the 14783 // base address is aligned, then adding less than a full vector length 14784 // will cause the last vector in the sequence to be (re)loaded. 14785 // Otherwise, the next vector will be fetched as you might suspect was 14786 // necessary. 14787 14788 // We might be able to reuse the permutation generation from 14789 // a different base address offset from this one by an aligned amount. 14790 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14791 // optimization later. 14792 Intrinsic::ID Intr, IntrLD, IntrPerm; 14793 MVT PermCntlTy, PermTy, LDTy; 14794 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14795 : Intrinsic::ppc_altivec_lvsl; 14796 IntrLD = Intrinsic::ppc_altivec_lvx; 14797 IntrPerm = Intrinsic::ppc_altivec_vperm; 14798 PermCntlTy = MVT::v16i8; 14799 PermTy = MVT::v4i32; 14800 LDTy = MVT::v4i32; 14801 14802 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14803 14804 // Create the new MMO for the new base load. It is like the original MMO, 14805 // but represents an area in memory almost twice the vector size centered 14806 // on the original address. If the address is unaligned, we might start 14807 // reading up to (sizeof(vector)-1) bytes below the address of the 14808 // original unaligned load. 14809 MachineFunction &MF = DAG.getMachineFunction(); 14810 MachineMemOperand *BaseMMO = 14811 MF.getMachineMemOperand(LD->getMemOperand(), 14812 -(long)MemVT.getStoreSize()+1, 14813 2*MemVT.getStoreSize()-1); 14814 14815 // Create the new base load. 14816 SDValue LDXIntID = 14817 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14818 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14819 SDValue BaseLoad = 14820 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14821 DAG.getVTList(PermTy, MVT::Other), 14822 BaseLoadOps, LDTy, BaseMMO); 14823 14824 // Note that the value of IncOffset (which is provided to the next 14825 // load's pointer info offset value, and thus used to calculate the 14826 // alignment), and the value of IncValue (which is actually used to 14827 // increment the pointer value) are different! This is because we 14828 // require the next load to appear to be aligned, even though it 14829 // is actually offset from the base pointer by a lesser amount. 14830 int IncOffset = VT.getSizeInBits() / 8; 14831 int IncValue = IncOffset; 14832 14833 // Walk (both up and down) the chain looking for another load at the real 14834 // (aligned) offset (the alignment of the other load does not matter in 14835 // this case). If found, then do not use the offset reduction trick, as 14836 // that will prevent the loads from being later combined (as they would 14837 // otherwise be duplicates). 14838 if (!findConsecutiveLoad(LD, DAG)) 14839 --IncValue; 14840 14841 SDValue Increment = 14842 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14843 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14844 14845 MachineMemOperand *ExtraMMO = 14846 MF.getMachineMemOperand(LD->getMemOperand(), 14847 1, 2*MemVT.getStoreSize()-1); 14848 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14849 SDValue ExtraLoad = 14850 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14851 DAG.getVTList(PermTy, MVT::Other), 14852 ExtraLoadOps, LDTy, ExtraMMO); 14853 14854 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14855 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14856 14857 // Because vperm has a big-endian bias, we must reverse the order 14858 // of the input vectors and complement the permute control vector 14859 // when generating little endian code. We have already handled the 14860 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14861 // and ExtraLoad here. 14862 SDValue Perm; 14863 if (isLittleEndian) 14864 Perm = BuildIntrinsicOp(IntrPerm, 14865 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14866 else 14867 Perm = BuildIntrinsicOp(IntrPerm, 14868 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14869 14870 if (VT != PermTy) 14871 Perm = Subtarget.hasAltivec() 14872 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14873 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14874 DAG.getTargetConstant(1, dl, MVT::i64)); 14875 // second argument is 1 because this rounding 14876 // is always exact. 14877 14878 // The output of the permutation is our loaded result, the TokenFactor is 14879 // our new chain. 14880 DCI.CombineTo(N, Perm, TF); 14881 return SDValue(N, 0); 14882 } 14883 } 14884 break; 14885 case ISD::INTRINSIC_WO_CHAIN: { 14886 bool isLittleEndian = Subtarget.isLittleEndian(); 14887 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14888 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14889 : Intrinsic::ppc_altivec_lvsl); 14890 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14891 SDValue Add = N->getOperand(1); 14892 14893 int Bits = 4 /* 16 byte alignment */; 14894 14895 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14896 APInt::getAllOnesValue(Bits /* alignment */) 14897 .zext(Add.getScalarValueSizeInBits()))) { 14898 SDNode *BasePtr = Add->getOperand(0).getNode(); 14899 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14900 UE = BasePtr->use_end(); 14901 UI != UE; ++UI) { 14902 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14903 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14904 IID) { 14905 // We've found another LVSL/LVSR, and this address is an aligned 14906 // multiple of that one. The results will be the same, so use the 14907 // one we've just found instead. 14908 14909 return SDValue(*UI, 0); 14910 } 14911 } 14912 } 14913 14914 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14915 SDNode *BasePtr = Add->getOperand(0).getNode(); 14916 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14917 UE = BasePtr->use_end(); UI != UE; ++UI) { 14918 if (UI->getOpcode() == ISD::ADD && 14919 isa<ConstantSDNode>(UI->getOperand(1)) && 14920 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14921 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14922 (1ULL << Bits) == 0) { 14923 SDNode *OtherAdd = *UI; 14924 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14925 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14926 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14927 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14928 return SDValue(*VI, 0); 14929 } 14930 } 14931 } 14932 } 14933 } 14934 } 14935 14936 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14937 // Expose the vabsduw/h/b opportunity for down stream 14938 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14939 (IID == Intrinsic::ppc_altivec_vmaxsw || 14940 IID == Intrinsic::ppc_altivec_vmaxsh || 14941 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14942 SDValue V1 = N->getOperand(1); 14943 SDValue V2 = N->getOperand(2); 14944 if ((V1.getSimpleValueType() == MVT::v4i32 || 14945 V1.getSimpleValueType() == MVT::v8i16 || 14946 V1.getSimpleValueType() == MVT::v16i8) && 14947 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14948 // (0-a, a) 14949 if (V1.getOpcode() == ISD::SUB && 14950 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14951 V1.getOperand(1) == V2) { 14952 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14953 } 14954 // (a, 0-a) 14955 if (V2.getOpcode() == ISD::SUB && 14956 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14957 V2.getOperand(1) == V1) { 14958 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14959 } 14960 // (x-y, y-x) 14961 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14962 V1.getOperand(0) == V2.getOperand(1) && 14963 V1.getOperand(1) == V2.getOperand(0)) { 14964 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14965 } 14966 } 14967 } 14968 } 14969 14970 break; 14971 case ISD::INTRINSIC_W_CHAIN: 14972 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14973 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14974 if (Subtarget.needsSwapsForVSXMemOps()) { 14975 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14976 default: 14977 break; 14978 case Intrinsic::ppc_vsx_lxvw4x: 14979 case Intrinsic::ppc_vsx_lxvd2x: 14980 return expandVSXLoadForLE(N, DCI); 14981 } 14982 } 14983 break; 14984 case ISD::INTRINSIC_VOID: 14985 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14986 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14987 if (Subtarget.needsSwapsForVSXMemOps()) { 14988 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14989 default: 14990 break; 14991 case Intrinsic::ppc_vsx_stxvw4x: 14992 case Intrinsic::ppc_vsx_stxvd2x: 14993 return expandVSXStoreForLE(N, DCI); 14994 } 14995 } 14996 break; 14997 case ISD::BSWAP: 14998 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14999 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 15000 N->getOperand(0).hasOneUse() && 15001 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15002 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 15003 N->getValueType(0) == MVT::i64))) { 15004 SDValue Load = N->getOperand(0); 15005 LoadSDNode *LD = cast<LoadSDNode>(Load); 15006 // Create the byte-swapping load. 15007 SDValue Ops[] = { 15008 LD->getChain(), // Chain 15009 LD->getBasePtr(), // Ptr 15010 DAG.getValueType(N->getValueType(0)) // VT 15011 }; 15012 SDValue BSLoad = 15013 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15014 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15015 MVT::i64 : MVT::i32, MVT::Other), 15016 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15017 15018 // If this is an i16 load, insert the truncate. 15019 SDValue ResVal = BSLoad; 15020 if (N->getValueType(0) == MVT::i16) 15021 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15022 15023 // First, combine the bswap away. This makes the value produced by the 15024 // load dead. 15025 DCI.CombineTo(N, ResVal); 15026 15027 // Next, combine the load away, we give it a bogus result value but a real 15028 // chain result. The result value is dead because the bswap is dead. 15029 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15030 15031 // Return N so it doesn't get rechecked! 15032 return SDValue(N, 0); 15033 } 15034 break; 15035 case PPCISD::VCMP: 15036 // If a VCMP_rec node already exists with exactly the same operands as this 15037 // node, use its result instead of this node (VCMP_rec computes both a CR6 15038 // and a normal output). 15039 // 15040 if (!N->getOperand(0).hasOneUse() && 15041 !N->getOperand(1).hasOneUse() && 15042 !N->getOperand(2).hasOneUse()) { 15043 15044 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15045 SDNode *VCMPrecNode = nullptr; 15046 15047 SDNode *LHSN = N->getOperand(0).getNode(); 15048 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15049 UI != E; ++UI) 15050 if (UI->getOpcode() == PPCISD::VCMP_rec && 15051 UI->getOperand(1) == N->getOperand(1) && 15052 UI->getOperand(2) == N->getOperand(2) && 15053 UI->getOperand(0) == N->getOperand(0)) { 15054 VCMPrecNode = *UI; 15055 break; 15056 } 15057 15058 // If there is no VCMP_rec node, or if the flag value has a single use, 15059 // don't transform this. 15060 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15061 break; 15062 15063 // Look at the (necessarily single) use of the flag value. If it has a 15064 // chain, this transformation is more complex. Note that multiple things 15065 // could use the value result, which we should ignore. 15066 SDNode *FlagUser = nullptr; 15067 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15068 FlagUser == nullptr; ++UI) { 15069 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15070 SDNode *User = *UI; 15071 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15072 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15073 FlagUser = User; 15074 break; 15075 } 15076 } 15077 } 15078 15079 // If the user is a MFOCRF instruction, we know this is safe. 15080 // Otherwise we give up for right now. 15081 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15082 return SDValue(VCMPrecNode, 0); 15083 } 15084 break; 15085 case ISD::BRCOND: { 15086 SDValue Cond = N->getOperand(1); 15087 SDValue Target = N->getOperand(2); 15088 15089 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15090 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15091 Intrinsic::loop_decrement) { 15092 15093 // We now need to make the intrinsic dead (it cannot be instruction 15094 // selected). 15095 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15096 assert(Cond.getNode()->hasOneUse() && 15097 "Counter decrement has more than one use"); 15098 15099 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15100 N->getOperand(0), Target); 15101 } 15102 } 15103 break; 15104 case ISD::BR_CC: { 15105 // If this is a branch on an altivec predicate comparison, lower this so 15106 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15107 // lowering is done pre-legalize, because the legalizer lowers the predicate 15108 // compare down to code that is difficult to reassemble. 15109 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15110 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15111 15112 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15113 // value. If so, pass-through the AND to get to the intrinsic. 15114 if (LHS.getOpcode() == ISD::AND && 15115 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15116 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15117 Intrinsic::loop_decrement && 15118 isa<ConstantSDNode>(LHS.getOperand(1)) && 15119 !isNullConstant(LHS.getOperand(1))) 15120 LHS = LHS.getOperand(0); 15121 15122 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15123 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15124 Intrinsic::loop_decrement && 15125 isa<ConstantSDNode>(RHS)) { 15126 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15127 "Counter decrement comparison is not EQ or NE"); 15128 15129 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15130 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15131 (CC == ISD::SETNE && !Val); 15132 15133 // We now need to make the intrinsic dead (it cannot be instruction 15134 // selected). 15135 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15136 assert(LHS.getNode()->hasOneUse() && 15137 "Counter decrement has more than one use"); 15138 15139 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15140 N->getOperand(0), N->getOperand(4)); 15141 } 15142 15143 int CompareOpc; 15144 bool isDot; 15145 15146 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15147 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15148 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15149 assert(isDot && "Can't compare against a vector result!"); 15150 15151 // If this is a comparison against something other than 0/1, then we know 15152 // that the condition is never/always true. 15153 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15154 if (Val != 0 && Val != 1) { 15155 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15156 return N->getOperand(0); 15157 // Always !=, turn it into an unconditional branch. 15158 return DAG.getNode(ISD::BR, dl, MVT::Other, 15159 N->getOperand(0), N->getOperand(4)); 15160 } 15161 15162 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15163 15164 // Create the PPCISD altivec 'dot' comparison node. 15165 SDValue Ops[] = { 15166 LHS.getOperand(2), // LHS of compare 15167 LHS.getOperand(3), // RHS of compare 15168 DAG.getConstant(CompareOpc, dl, MVT::i32) 15169 }; 15170 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15171 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15172 15173 // Unpack the result based on how the target uses it. 15174 PPC::Predicate CompOpc; 15175 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15176 default: // Can't happen, don't crash on invalid number though. 15177 case 0: // Branch on the value of the EQ bit of CR6. 15178 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15179 break; 15180 case 1: // Branch on the inverted value of the EQ bit of CR6. 15181 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15182 break; 15183 case 2: // Branch on the value of the LT bit of CR6. 15184 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15185 break; 15186 case 3: // Branch on the inverted value of the LT bit of CR6. 15187 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15188 break; 15189 } 15190 15191 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15192 DAG.getConstant(CompOpc, dl, MVT::i32), 15193 DAG.getRegister(PPC::CR6, MVT::i32), 15194 N->getOperand(4), CompNode.getValue(1)); 15195 } 15196 break; 15197 } 15198 case ISD::BUILD_VECTOR: 15199 return DAGCombineBuildVector(N, DCI); 15200 case ISD::ABS: 15201 return combineABS(N, DCI); 15202 case ISD::VSELECT: 15203 return combineVSelect(N, DCI); 15204 } 15205 15206 return SDValue(); 15207 } 15208 15209 SDValue 15210 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15211 SelectionDAG &DAG, 15212 SmallVectorImpl<SDNode *> &Created) const { 15213 // fold (sdiv X, pow2) 15214 EVT VT = N->getValueType(0); 15215 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15216 return SDValue(); 15217 if ((VT != MVT::i32 && VT != MVT::i64) || 15218 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15219 return SDValue(); 15220 15221 SDLoc DL(N); 15222 SDValue N0 = N->getOperand(0); 15223 15224 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15225 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15226 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15227 15228 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15229 Created.push_back(Op.getNode()); 15230 15231 if (IsNegPow2) { 15232 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15233 Created.push_back(Op.getNode()); 15234 } 15235 15236 return Op; 15237 } 15238 15239 //===----------------------------------------------------------------------===// 15240 // Inline Assembly Support 15241 //===----------------------------------------------------------------------===// 15242 15243 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15244 KnownBits &Known, 15245 const APInt &DemandedElts, 15246 const SelectionDAG &DAG, 15247 unsigned Depth) const { 15248 Known.resetAll(); 15249 switch (Op.getOpcode()) { 15250 default: break; 15251 case PPCISD::LBRX: { 15252 // lhbrx is known to have the top bits cleared out. 15253 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15254 Known.Zero = 0xFFFF0000; 15255 break; 15256 } 15257 case ISD::INTRINSIC_WO_CHAIN: { 15258 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15259 default: break; 15260 case Intrinsic::ppc_altivec_vcmpbfp_p: 15261 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15262 case Intrinsic::ppc_altivec_vcmpequb_p: 15263 case Intrinsic::ppc_altivec_vcmpequh_p: 15264 case Intrinsic::ppc_altivec_vcmpequw_p: 15265 case Intrinsic::ppc_altivec_vcmpequd_p: 15266 case Intrinsic::ppc_altivec_vcmpequq_p: 15267 case Intrinsic::ppc_altivec_vcmpgefp_p: 15268 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15269 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15270 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15271 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15272 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15273 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15274 case Intrinsic::ppc_altivec_vcmpgtub_p: 15275 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15276 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15277 case Intrinsic::ppc_altivec_vcmpgtud_p: 15278 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15279 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15280 break; 15281 } 15282 } 15283 } 15284 } 15285 15286 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15287 switch (Subtarget.getCPUDirective()) { 15288 default: break; 15289 case PPC::DIR_970: 15290 case PPC::DIR_PWR4: 15291 case PPC::DIR_PWR5: 15292 case PPC::DIR_PWR5X: 15293 case PPC::DIR_PWR6: 15294 case PPC::DIR_PWR6X: 15295 case PPC::DIR_PWR7: 15296 case PPC::DIR_PWR8: 15297 case PPC::DIR_PWR9: 15298 case PPC::DIR_PWR10: 15299 case PPC::DIR_PWR_FUTURE: { 15300 if (!ML) 15301 break; 15302 15303 if (!DisableInnermostLoopAlign32) { 15304 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15305 // so that we can decrease cache misses and branch-prediction misses. 15306 // Actual alignment of the loop will depend on the hotness check and other 15307 // logic in alignBlocks. 15308 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15309 return Align(32); 15310 } 15311 15312 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15313 15314 // For small loops (between 5 and 8 instructions), align to a 32-byte 15315 // boundary so that the entire loop fits in one instruction-cache line. 15316 uint64_t LoopSize = 0; 15317 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15318 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15319 LoopSize += TII->getInstSizeInBytes(*J); 15320 if (LoopSize > 32) 15321 break; 15322 } 15323 15324 if (LoopSize > 16 && LoopSize <= 32) 15325 return Align(32); 15326 15327 break; 15328 } 15329 } 15330 15331 return TargetLowering::getPrefLoopAlignment(ML); 15332 } 15333 15334 /// getConstraintType - Given a constraint, return the type of 15335 /// constraint it is for this target. 15336 PPCTargetLowering::ConstraintType 15337 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15338 if (Constraint.size() == 1) { 15339 switch (Constraint[0]) { 15340 default: break; 15341 case 'b': 15342 case 'r': 15343 case 'f': 15344 case 'd': 15345 case 'v': 15346 case 'y': 15347 return C_RegisterClass; 15348 case 'Z': 15349 // FIXME: While Z does indicate a memory constraint, it specifically 15350 // indicates an r+r address (used in conjunction with the 'y' modifier 15351 // in the replacement string). Currently, we're forcing the base 15352 // register to be r0 in the asm printer (which is interpreted as zero) 15353 // and forming the complete address in the second register. This is 15354 // suboptimal. 15355 return C_Memory; 15356 } 15357 } else if (Constraint == "wc") { // individual CR bits. 15358 return C_RegisterClass; 15359 } else if (Constraint == "wa" || Constraint == "wd" || 15360 Constraint == "wf" || Constraint == "ws" || 15361 Constraint == "wi" || Constraint == "ww") { 15362 return C_RegisterClass; // VSX registers. 15363 } 15364 return TargetLowering::getConstraintType(Constraint); 15365 } 15366 15367 /// Examine constraint type and operand type and determine a weight value. 15368 /// This object must already have been set up with the operand type 15369 /// and the current alternative constraint selected. 15370 TargetLowering::ConstraintWeight 15371 PPCTargetLowering::getSingleConstraintMatchWeight( 15372 AsmOperandInfo &info, const char *constraint) const { 15373 ConstraintWeight weight = CW_Invalid; 15374 Value *CallOperandVal = info.CallOperandVal; 15375 // If we don't have a value, we can't do a match, 15376 // but allow it at the lowest weight. 15377 if (!CallOperandVal) 15378 return CW_Default; 15379 Type *type = CallOperandVal->getType(); 15380 15381 // Look at the constraint type. 15382 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15383 return CW_Register; // an individual CR bit. 15384 else if ((StringRef(constraint) == "wa" || 15385 StringRef(constraint) == "wd" || 15386 StringRef(constraint) == "wf") && 15387 type->isVectorTy()) 15388 return CW_Register; 15389 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15390 return CW_Register; // just hold 64-bit integers data. 15391 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15392 return CW_Register; 15393 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15394 return CW_Register; 15395 15396 switch (*constraint) { 15397 default: 15398 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15399 break; 15400 case 'b': 15401 if (type->isIntegerTy()) 15402 weight = CW_Register; 15403 break; 15404 case 'f': 15405 if (type->isFloatTy()) 15406 weight = CW_Register; 15407 break; 15408 case 'd': 15409 if (type->isDoubleTy()) 15410 weight = CW_Register; 15411 break; 15412 case 'v': 15413 if (type->isVectorTy()) 15414 weight = CW_Register; 15415 break; 15416 case 'y': 15417 weight = CW_Register; 15418 break; 15419 case 'Z': 15420 weight = CW_Memory; 15421 break; 15422 } 15423 return weight; 15424 } 15425 15426 std::pair<unsigned, const TargetRegisterClass *> 15427 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15428 StringRef Constraint, 15429 MVT VT) const { 15430 if (Constraint.size() == 1) { 15431 // GCC RS6000 Constraint Letters 15432 switch (Constraint[0]) { 15433 case 'b': // R1-R31 15434 if (VT == MVT::i64 && Subtarget.isPPC64()) 15435 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15436 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15437 case 'r': // R0-R31 15438 if (VT == MVT::i64 && Subtarget.isPPC64()) 15439 return std::make_pair(0U, &PPC::G8RCRegClass); 15440 return std::make_pair(0U, &PPC::GPRCRegClass); 15441 // 'd' and 'f' constraints are both defined to be "the floating point 15442 // registers", where one is for 32-bit and the other for 64-bit. We don't 15443 // really care overly much here so just give them all the same reg classes. 15444 case 'd': 15445 case 'f': 15446 if (Subtarget.hasSPE()) { 15447 if (VT == MVT::f32 || VT == MVT::i32) 15448 return std::make_pair(0U, &PPC::GPRCRegClass); 15449 if (VT == MVT::f64 || VT == MVT::i64) 15450 return std::make_pair(0U, &PPC::SPERCRegClass); 15451 } else { 15452 if (VT == MVT::f32 || VT == MVT::i32) 15453 return std::make_pair(0U, &PPC::F4RCRegClass); 15454 if (VT == MVT::f64 || VT == MVT::i64) 15455 return std::make_pair(0U, &PPC::F8RCRegClass); 15456 } 15457 break; 15458 case 'v': 15459 if (Subtarget.hasAltivec()) 15460 return std::make_pair(0U, &PPC::VRRCRegClass); 15461 break; 15462 case 'y': // crrc 15463 return std::make_pair(0U, &PPC::CRRCRegClass); 15464 } 15465 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15466 // An individual CR bit. 15467 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15468 } else if ((Constraint == "wa" || Constraint == "wd" || 15469 Constraint == "wf" || Constraint == "wi") && 15470 Subtarget.hasVSX()) { 15471 return std::make_pair(0U, &PPC::VSRCRegClass); 15472 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15473 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15474 return std::make_pair(0U, &PPC::VSSRCRegClass); 15475 else 15476 return std::make_pair(0U, &PPC::VSFRCRegClass); 15477 } 15478 15479 // Handle special cases of physical registers that are not properly handled 15480 // by the base class. 15481 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 15482 // If we name a VSX register, we can't defer to the base class because it 15483 // will not recognize the correct register (their names will be VSL{0-31} 15484 // and V{0-31} so they won't match). So we match them here. 15485 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15486 int VSNum = atoi(Constraint.data() + 3); 15487 assert(VSNum >= 0 && VSNum <= 63 && 15488 "Attempted to access a vsr out of range"); 15489 if (VSNum < 32) 15490 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15491 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15492 } 15493 15494 // For float registers, we can't defer to the base class as it will match 15495 // the SPILLTOVSRRC class. 15496 if (Constraint.size() > 3 && Constraint[1] == 'f') { 15497 int RegNum = atoi(Constraint.data() + 2); 15498 if (RegNum > 31 || RegNum < 0) 15499 report_fatal_error("Invalid floating point register number"); 15500 if (VT == MVT::f32 || VT == MVT::i32) 15501 return Subtarget.hasSPE() 15502 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 15503 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 15504 if (VT == MVT::f64 || VT == MVT::i64) 15505 return Subtarget.hasSPE() 15506 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 15507 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 15508 } 15509 } 15510 15511 std::pair<unsigned, const TargetRegisterClass *> R = 15512 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15513 15514 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15515 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15516 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15517 // register. 15518 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15519 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15520 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15521 PPC::GPRCRegClass.contains(R.first)) 15522 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15523 PPC::sub_32, &PPC::G8RCRegClass), 15524 &PPC::G8RCRegClass); 15525 15526 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15527 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15528 R.first = PPC::CR0; 15529 R.second = &PPC::CRRCRegClass; 15530 } 15531 // FIXME: This warning should ideally be emitted in the front end. 15532 const auto &TM = getTargetMachine(); 15533 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 15534 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 15535 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 15536 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 15537 errs() << "warning: vector registers 20 to 32 are reserved in the " 15538 "default AIX AltiVec ABI and cannot be used\n"; 15539 } 15540 15541 return R; 15542 } 15543 15544 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15545 /// vector. If it is invalid, don't add anything to Ops. 15546 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15547 std::string &Constraint, 15548 std::vector<SDValue>&Ops, 15549 SelectionDAG &DAG) const { 15550 SDValue Result; 15551 15552 // Only support length 1 constraints. 15553 if (Constraint.length() > 1) return; 15554 15555 char Letter = Constraint[0]; 15556 switch (Letter) { 15557 default: break; 15558 case 'I': 15559 case 'J': 15560 case 'K': 15561 case 'L': 15562 case 'M': 15563 case 'N': 15564 case 'O': 15565 case 'P': { 15566 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15567 if (!CST) return; // Must be an immediate to match. 15568 SDLoc dl(Op); 15569 int64_t Value = CST->getSExtValue(); 15570 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15571 // numbers are printed as such. 15572 switch (Letter) { 15573 default: llvm_unreachable("Unknown constraint letter!"); 15574 case 'I': // "I" is a signed 16-bit constant. 15575 if (isInt<16>(Value)) 15576 Result = DAG.getTargetConstant(Value, dl, TCVT); 15577 break; 15578 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15579 if (isShiftedUInt<16, 16>(Value)) 15580 Result = DAG.getTargetConstant(Value, dl, TCVT); 15581 break; 15582 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15583 if (isShiftedInt<16, 16>(Value)) 15584 Result = DAG.getTargetConstant(Value, dl, TCVT); 15585 break; 15586 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15587 if (isUInt<16>(Value)) 15588 Result = DAG.getTargetConstant(Value, dl, TCVT); 15589 break; 15590 case 'M': // "M" is a constant that is greater than 31. 15591 if (Value > 31) 15592 Result = DAG.getTargetConstant(Value, dl, TCVT); 15593 break; 15594 case 'N': // "N" is a positive constant that is an exact power of two. 15595 if (Value > 0 && isPowerOf2_64(Value)) 15596 Result = DAG.getTargetConstant(Value, dl, TCVT); 15597 break; 15598 case 'O': // "O" is the constant zero. 15599 if (Value == 0) 15600 Result = DAG.getTargetConstant(Value, dl, TCVT); 15601 break; 15602 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15603 if (isInt<16>(-Value)) 15604 Result = DAG.getTargetConstant(Value, dl, TCVT); 15605 break; 15606 } 15607 break; 15608 } 15609 } 15610 15611 if (Result.getNode()) { 15612 Ops.push_back(Result); 15613 return; 15614 } 15615 15616 // Handle standard constraint letters. 15617 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15618 } 15619 15620 // isLegalAddressingMode - Return true if the addressing mode represented 15621 // by AM is legal for this target, for a load/store of the specified type. 15622 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15623 const AddrMode &AM, Type *Ty, 15624 unsigned AS, 15625 Instruction *I) const { 15626 // Vector type r+i form is supported since power9 as DQ form. We don't check 15627 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15628 // imm form is preferred and the offset can be adjusted to use imm form later 15629 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15630 // max offset to check legal addressing mode, we should be a little aggressive 15631 // to contain other offsets for that LSRUse. 15632 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15633 return false; 15634 15635 // PPC allows a sign-extended 16-bit immediate field. 15636 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15637 return false; 15638 15639 // No global is ever allowed as a base. 15640 if (AM.BaseGV) 15641 return false; 15642 15643 // PPC only support r+r, 15644 switch (AM.Scale) { 15645 case 0: // "r+i" or just "i", depending on HasBaseReg. 15646 break; 15647 case 1: 15648 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15649 return false; 15650 // Otherwise we have r+r or r+i. 15651 break; 15652 case 2: 15653 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15654 return false; 15655 // Allow 2*r as r+r. 15656 break; 15657 default: 15658 // No other scales are supported. 15659 return false; 15660 } 15661 15662 return true; 15663 } 15664 15665 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15666 SelectionDAG &DAG) const { 15667 MachineFunction &MF = DAG.getMachineFunction(); 15668 MachineFrameInfo &MFI = MF.getFrameInfo(); 15669 MFI.setReturnAddressIsTaken(true); 15670 15671 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15672 return SDValue(); 15673 15674 SDLoc dl(Op); 15675 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15676 15677 // Make sure the function does not optimize away the store of the RA to 15678 // the stack. 15679 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15680 FuncInfo->setLRStoreRequired(); 15681 bool isPPC64 = Subtarget.isPPC64(); 15682 auto PtrVT = getPointerTy(MF.getDataLayout()); 15683 15684 if (Depth > 0) { 15685 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15686 SDValue Offset = 15687 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15688 isPPC64 ? MVT::i64 : MVT::i32); 15689 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15690 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15691 MachinePointerInfo()); 15692 } 15693 15694 // Just load the return address off the stack. 15695 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15696 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15697 MachinePointerInfo()); 15698 } 15699 15700 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15701 SelectionDAG &DAG) const { 15702 SDLoc dl(Op); 15703 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15704 15705 MachineFunction &MF = DAG.getMachineFunction(); 15706 MachineFrameInfo &MFI = MF.getFrameInfo(); 15707 MFI.setFrameAddressIsTaken(true); 15708 15709 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15710 bool isPPC64 = PtrVT == MVT::i64; 15711 15712 // Naked functions never have a frame pointer, and so we use r1. For all 15713 // other functions, this decision must be delayed until during PEI. 15714 unsigned FrameReg; 15715 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15716 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15717 else 15718 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15719 15720 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15721 PtrVT); 15722 while (Depth--) 15723 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15724 FrameAddr, MachinePointerInfo()); 15725 return FrameAddr; 15726 } 15727 15728 // FIXME? Maybe this could be a TableGen attribute on some registers and 15729 // this table could be generated automatically from RegInfo. 15730 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15731 const MachineFunction &MF) const { 15732 bool isPPC64 = Subtarget.isPPC64(); 15733 15734 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15735 if (!is64Bit && VT != LLT::scalar(32)) 15736 report_fatal_error("Invalid register global variable type"); 15737 15738 Register Reg = StringSwitch<Register>(RegName) 15739 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15740 .Case("r2", isPPC64 ? Register() : PPC::R2) 15741 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15742 .Default(Register()); 15743 15744 if (Reg) 15745 return Reg; 15746 report_fatal_error("Invalid register name global variable"); 15747 } 15748 15749 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15750 // 32-bit SVR4 ABI access everything as got-indirect. 15751 if (Subtarget.is32BitELFABI()) 15752 return true; 15753 15754 // AIX accesses everything indirectly through the TOC, which is similar to 15755 // the GOT. 15756 if (Subtarget.isAIXABI()) 15757 return true; 15758 15759 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15760 // If it is small or large code model, module locals are accessed 15761 // indirectly by loading their address from .toc/.got. 15762 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15763 return true; 15764 15765 // JumpTable and BlockAddress are accessed as got-indirect. 15766 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15767 return true; 15768 15769 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15770 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15771 15772 return false; 15773 } 15774 15775 bool 15776 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15777 // The PowerPC target isn't yet aware of offsets. 15778 return false; 15779 } 15780 15781 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15782 const CallInst &I, 15783 MachineFunction &MF, 15784 unsigned Intrinsic) const { 15785 switch (Intrinsic) { 15786 case Intrinsic::ppc_altivec_lvx: 15787 case Intrinsic::ppc_altivec_lvxl: 15788 case Intrinsic::ppc_altivec_lvebx: 15789 case Intrinsic::ppc_altivec_lvehx: 15790 case Intrinsic::ppc_altivec_lvewx: 15791 case Intrinsic::ppc_vsx_lxvd2x: 15792 case Intrinsic::ppc_vsx_lxvw4x: 15793 case Intrinsic::ppc_vsx_lxvd2x_be: 15794 case Intrinsic::ppc_vsx_lxvw4x_be: 15795 case Intrinsic::ppc_vsx_lxvl: 15796 case Intrinsic::ppc_vsx_lxvll: { 15797 EVT VT; 15798 switch (Intrinsic) { 15799 case Intrinsic::ppc_altivec_lvebx: 15800 VT = MVT::i8; 15801 break; 15802 case Intrinsic::ppc_altivec_lvehx: 15803 VT = MVT::i16; 15804 break; 15805 case Intrinsic::ppc_altivec_lvewx: 15806 VT = MVT::i32; 15807 break; 15808 case Intrinsic::ppc_vsx_lxvd2x: 15809 case Intrinsic::ppc_vsx_lxvd2x_be: 15810 VT = MVT::v2f64; 15811 break; 15812 default: 15813 VT = MVT::v4i32; 15814 break; 15815 } 15816 15817 Info.opc = ISD::INTRINSIC_W_CHAIN; 15818 Info.memVT = VT; 15819 Info.ptrVal = I.getArgOperand(0); 15820 Info.offset = -VT.getStoreSize()+1; 15821 Info.size = 2*VT.getStoreSize()-1; 15822 Info.align = Align(1); 15823 Info.flags = MachineMemOperand::MOLoad; 15824 return true; 15825 } 15826 case Intrinsic::ppc_altivec_stvx: 15827 case Intrinsic::ppc_altivec_stvxl: 15828 case Intrinsic::ppc_altivec_stvebx: 15829 case Intrinsic::ppc_altivec_stvehx: 15830 case Intrinsic::ppc_altivec_stvewx: 15831 case Intrinsic::ppc_vsx_stxvd2x: 15832 case Intrinsic::ppc_vsx_stxvw4x: 15833 case Intrinsic::ppc_vsx_stxvd2x_be: 15834 case Intrinsic::ppc_vsx_stxvw4x_be: 15835 case Intrinsic::ppc_vsx_stxvl: 15836 case Intrinsic::ppc_vsx_stxvll: { 15837 EVT VT; 15838 switch (Intrinsic) { 15839 case Intrinsic::ppc_altivec_stvebx: 15840 VT = MVT::i8; 15841 break; 15842 case Intrinsic::ppc_altivec_stvehx: 15843 VT = MVT::i16; 15844 break; 15845 case Intrinsic::ppc_altivec_stvewx: 15846 VT = MVT::i32; 15847 break; 15848 case Intrinsic::ppc_vsx_stxvd2x: 15849 case Intrinsic::ppc_vsx_stxvd2x_be: 15850 VT = MVT::v2f64; 15851 break; 15852 default: 15853 VT = MVT::v4i32; 15854 break; 15855 } 15856 15857 Info.opc = ISD::INTRINSIC_VOID; 15858 Info.memVT = VT; 15859 Info.ptrVal = I.getArgOperand(1); 15860 Info.offset = -VT.getStoreSize()+1; 15861 Info.size = 2*VT.getStoreSize()-1; 15862 Info.align = Align(1); 15863 Info.flags = MachineMemOperand::MOStore; 15864 return true; 15865 } 15866 default: 15867 break; 15868 } 15869 15870 return false; 15871 } 15872 15873 /// It returns EVT::Other if the type should be determined using generic 15874 /// target-independent logic. 15875 EVT PPCTargetLowering::getOptimalMemOpType( 15876 const MemOp &Op, const AttributeList &FuncAttributes) const { 15877 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15878 // We should use Altivec/VSX loads and stores when available. For unaligned 15879 // addresses, unaligned VSX loads are only fast starting with the P8. 15880 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15881 (Op.isAligned(Align(16)) || 15882 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15883 return MVT::v4i32; 15884 } 15885 15886 if (Subtarget.isPPC64()) { 15887 return MVT::i64; 15888 } 15889 15890 return MVT::i32; 15891 } 15892 15893 /// Returns true if it is beneficial to convert a load of a constant 15894 /// to just the constant itself. 15895 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15896 Type *Ty) const { 15897 assert(Ty->isIntegerTy()); 15898 15899 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15900 return !(BitSize == 0 || BitSize > 64); 15901 } 15902 15903 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15904 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15905 return false; 15906 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15907 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15908 return NumBits1 == 64 && NumBits2 == 32; 15909 } 15910 15911 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15912 if (!VT1.isInteger() || !VT2.isInteger()) 15913 return false; 15914 unsigned NumBits1 = VT1.getSizeInBits(); 15915 unsigned NumBits2 = VT2.getSizeInBits(); 15916 return NumBits1 == 64 && NumBits2 == 32; 15917 } 15918 15919 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15920 // Generally speaking, zexts are not free, but they are free when they can be 15921 // folded with other operations. 15922 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15923 EVT MemVT = LD->getMemoryVT(); 15924 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15925 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15926 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15927 LD->getExtensionType() == ISD::ZEXTLOAD)) 15928 return true; 15929 } 15930 15931 // FIXME: Add other cases... 15932 // - 32-bit shifts with a zext to i64 15933 // - zext after ctlz, bswap, etc. 15934 // - zext after and by a constant mask 15935 15936 return TargetLowering::isZExtFree(Val, VT2); 15937 } 15938 15939 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15940 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15941 "invalid fpext types"); 15942 // Extending to float128 is not free. 15943 if (DestVT == MVT::f128) 15944 return false; 15945 return true; 15946 } 15947 15948 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15949 return isInt<16>(Imm) || isUInt<16>(Imm); 15950 } 15951 15952 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15953 return isInt<16>(Imm) || isUInt<16>(Imm); 15954 } 15955 15956 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 15957 MachineMemOperand::Flags, 15958 bool *Fast) const { 15959 if (DisablePPCUnaligned) 15960 return false; 15961 15962 // PowerPC supports unaligned memory access for simple non-vector types. 15963 // Although accessing unaligned addresses is not as efficient as accessing 15964 // aligned addresses, it is generally more efficient than manual expansion, 15965 // and generally only traps for software emulation when crossing page 15966 // boundaries. 15967 15968 if (!VT.isSimple()) 15969 return false; 15970 15971 if (VT.isFloatingPoint() && !VT.isVector() && 15972 !Subtarget.allowsUnalignedFPAccess()) 15973 return false; 15974 15975 if (VT.getSimpleVT().isVector()) { 15976 if (Subtarget.hasVSX()) { 15977 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15978 VT != MVT::v4f32 && VT != MVT::v4i32) 15979 return false; 15980 } else { 15981 return false; 15982 } 15983 } 15984 15985 if (VT == MVT::ppcf128) 15986 return false; 15987 15988 if (Fast) 15989 *Fast = true; 15990 15991 return true; 15992 } 15993 15994 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 15995 SDValue C) const { 15996 // Check integral scalar types. 15997 if (!VT.isScalarInteger()) 15998 return false; 15999 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16000 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16001 return false; 16002 // This transformation will generate >= 2 operations. But the following 16003 // cases will generate <= 2 instructions during ISEL. So exclude them. 16004 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16005 // HW instruction, ie. MULLI 16006 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16007 // instruction is needed than case 1, ie. MULLI and RLDICR 16008 int64_t Imm = ConstNode->getSExtValue(); 16009 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16010 Imm >>= Shift; 16011 if (isInt<16>(Imm)) 16012 return false; 16013 uint64_t UImm = static_cast<uint64_t>(Imm); 16014 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16015 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16016 return true; 16017 } 16018 return false; 16019 } 16020 16021 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16022 EVT VT) const { 16023 return isFMAFasterThanFMulAndFAdd( 16024 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16025 } 16026 16027 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16028 Type *Ty) const { 16029 switch (Ty->getScalarType()->getTypeID()) { 16030 case Type::FloatTyID: 16031 case Type::DoubleTyID: 16032 return true; 16033 case Type::FP128TyID: 16034 return Subtarget.hasP9Vector(); 16035 default: 16036 return false; 16037 } 16038 } 16039 16040 // FIXME: add more patterns which are not profitable to hoist. 16041 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16042 if (!I->hasOneUse()) 16043 return true; 16044 16045 Instruction *User = I->user_back(); 16046 assert(User && "A single use instruction with no uses."); 16047 16048 switch (I->getOpcode()) { 16049 case Instruction::FMul: { 16050 // Don't break FMA, PowerPC prefers FMA. 16051 if (User->getOpcode() != Instruction::FSub && 16052 User->getOpcode() != Instruction::FAdd) 16053 return true; 16054 16055 const TargetOptions &Options = getTargetMachine().Options; 16056 const Function *F = I->getFunction(); 16057 const DataLayout &DL = F->getParent()->getDataLayout(); 16058 Type *Ty = User->getOperand(0)->getType(); 16059 16060 return !( 16061 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16062 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16063 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16064 } 16065 case Instruction::Load: { 16066 // Don't break "store (load float*)" pattern, this pattern will be combined 16067 // to "store (load int32)" in later InstCombine pass. See function 16068 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16069 // cycles than loading a 32 bit integer. 16070 LoadInst *LI = cast<LoadInst>(I); 16071 // For the loads that combineLoadToOperationType does nothing, like 16072 // ordered load, it should be profitable to hoist them. 16073 // For swifterror load, it can only be used for pointer to pointer type, so 16074 // later type check should get rid of this case. 16075 if (!LI->isUnordered()) 16076 return true; 16077 16078 if (User->getOpcode() != Instruction::Store) 16079 return true; 16080 16081 if (I->getType()->getTypeID() != Type::FloatTyID) 16082 return true; 16083 16084 return false; 16085 } 16086 default: 16087 return true; 16088 } 16089 return true; 16090 } 16091 16092 const MCPhysReg * 16093 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16094 // LR is a callee-save register, but we must treat it as clobbered by any call 16095 // site. Hence we include LR in the scratch registers, which are in turn added 16096 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16097 // to CTR, which is used by any indirect call. 16098 static const MCPhysReg ScratchRegs[] = { 16099 PPC::X12, PPC::LR8, PPC::CTR8, 0 16100 }; 16101 16102 return ScratchRegs; 16103 } 16104 16105 Register PPCTargetLowering::getExceptionPointerRegister( 16106 const Constant *PersonalityFn) const { 16107 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16108 } 16109 16110 Register PPCTargetLowering::getExceptionSelectorRegister( 16111 const Constant *PersonalityFn) const { 16112 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16113 } 16114 16115 bool 16116 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16117 EVT VT , unsigned DefinedValues) const { 16118 if (VT == MVT::v2i64) 16119 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16120 16121 if (Subtarget.hasVSX()) 16122 return true; 16123 16124 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16125 } 16126 16127 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16128 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16129 return TargetLowering::getSchedulingPreference(N); 16130 16131 return Sched::ILP; 16132 } 16133 16134 // Create a fast isel object. 16135 FastISel * 16136 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16137 const TargetLibraryInfo *LibInfo) const { 16138 return PPC::createFastISel(FuncInfo, LibInfo); 16139 } 16140 16141 // 'Inverted' means the FMA opcode after negating one multiplicand. 16142 // For example, (fma -a b c) = (fnmsub a b c) 16143 static unsigned invertFMAOpcode(unsigned Opc) { 16144 switch (Opc) { 16145 default: 16146 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16147 case ISD::FMA: 16148 return PPCISD::FNMSUB; 16149 case PPCISD::FNMSUB: 16150 return ISD::FMA; 16151 } 16152 } 16153 16154 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16155 bool LegalOps, bool OptForSize, 16156 NegatibleCost &Cost, 16157 unsigned Depth) const { 16158 if (Depth > SelectionDAG::MaxRecursionDepth) 16159 return SDValue(); 16160 16161 unsigned Opc = Op.getOpcode(); 16162 EVT VT = Op.getValueType(); 16163 SDNodeFlags Flags = Op.getNode()->getFlags(); 16164 16165 switch (Opc) { 16166 case PPCISD::FNMSUB: 16167 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16168 break; 16169 16170 const TargetOptions &Options = getTargetMachine().Options; 16171 SDValue N0 = Op.getOperand(0); 16172 SDValue N1 = Op.getOperand(1); 16173 SDValue N2 = Op.getOperand(2); 16174 SDLoc Loc(Op); 16175 16176 NegatibleCost N2Cost = NegatibleCost::Expensive; 16177 SDValue NegN2 = 16178 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16179 16180 if (!NegN2) 16181 return SDValue(); 16182 16183 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16184 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16185 // These transformations may change sign of zeroes. For example, 16186 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16187 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16188 // Try and choose the cheaper one to negate. 16189 NegatibleCost N0Cost = NegatibleCost::Expensive; 16190 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16191 N0Cost, Depth + 1); 16192 16193 NegatibleCost N1Cost = NegatibleCost::Expensive; 16194 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16195 N1Cost, Depth + 1); 16196 16197 if (NegN0 && N0Cost <= N1Cost) { 16198 Cost = std::min(N0Cost, N2Cost); 16199 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16200 } else if (NegN1) { 16201 Cost = std::min(N1Cost, N2Cost); 16202 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16203 } 16204 } 16205 16206 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16207 if (isOperationLegal(ISD::FMA, VT)) { 16208 Cost = N2Cost; 16209 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16210 } 16211 16212 break; 16213 } 16214 16215 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16216 Cost, Depth); 16217 } 16218 16219 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16220 bool PPCTargetLowering::useLoadStackGuardNode() const { 16221 if (!Subtarget.isTargetLinux()) 16222 return TargetLowering::useLoadStackGuardNode(); 16223 return true; 16224 } 16225 16226 // Override to disable global variable loading on Linux. 16227 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16228 if (!Subtarget.isTargetLinux()) 16229 return TargetLowering::insertSSPDeclarations(M); 16230 } 16231 16232 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16233 bool ForCodeSize) const { 16234 if (!VT.isSimple() || !Subtarget.hasVSX()) 16235 return false; 16236 16237 switch(VT.getSimpleVT().SimpleTy) { 16238 default: 16239 // For FP types that are currently not supported by PPC backend, return 16240 // false. Examples: f16, f80. 16241 return false; 16242 case MVT::f32: 16243 case MVT::f64: 16244 if (Subtarget.hasPrefixInstrs()) { 16245 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 16246 return true; 16247 } 16248 LLVM_FALLTHROUGH; 16249 case MVT::ppcf128: 16250 return Imm.isPosZero(); 16251 } 16252 } 16253 16254 // For vector shift operation op, fold 16255 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16256 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16257 SelectionDAG &DAG) { 16258 SDValue N0 = N->getOperand(0); 16259 SDValue N1 = N->getOperand(1); 16260 EVT VT = N0.getValueType(); 16261 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16262 unsigned Opcode = N->getOpcode(); 16263 unsigned TargetOpcode; 16264 16265 switch (Opcode) { 16266 default: 16267 llvm_unreachable("Unexpected shift operation"); 16268 case ISD::SHL: 16269 TargetOpcode = PPCISD::SHL; 16270 break; 16271 case ISD::SRL: 16272 TargetOpcode = PPCISD::SRL; 16273 break; 16274 case ISD::SRA: 16275 TargetOpcode = PPCISD::SRA; 16276 break; 16277 } 16278 16279 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16280 N1->getOpcode() == ISD::AND) 16281 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16282 if (Mask->getZExtValue() == OpSizeInBits - 1) 16283 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16284 16285 return SDValue(); 16286 } 16287 16288 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16289 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16290 return Value; 16291 16292 SDValue N0 = N->getOperand(0); 16293 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16294 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16295 N0.getOpcode() != ISD::SIGN_EXTEND || 16296 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16297 N->getValueType(0) != MVT::i64) 16298 return SDValue(); 16299 16300 // We can't save an operation here if the value is already extended, and 16301 // the existing shift is easier to combine. 16302 SDValue ExtsSrc = N0.getOperand(0); 16303 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16304 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16305 return SDValue(); 16306 16307 SDLoc DL(N0); 16308 SDValue ShiftBy = SDValue(CN1, 0); 16309 // We want the shift amount to be i32 on the extswli, but the shift could 16310 // have an i64. 16311 if (ShiftBy.getValueType() == MVT::i64) 16312 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16313 16314 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16315 ShiftBy); 16316 } 16317 16318 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16319 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16320 return Value; 16321 16322 return SDValue(); 16323 } 16324 16325 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16326 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16327 return Value; 16328 16329 return SDValue(); 16330 } 16331 16332 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16333 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16334 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16335 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16336 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16337 const PPCSubtarget &Subtarget) { 16338 if (!Subtarget.isPPC64()) 16339 return SDValue(); 16340 16341 SDValue LHS = N->getOperand(0); 16342 SDValue RHS = N->getOperand(1); 16343 16344 auto isZextOfCompareWithConstant = [](SDValue Op) { 16345 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16346 Op.getValueType() != MVT::i64) 16347 return false; 16348 16349 SDValue Cmp = Op.getOperand(0); 16350 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16351 Cmp.getOperand(0).getValueType() != MVT::i64) 16352 return false; 16353 16354 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16355 int64_t NegConstant = 0 - Constant->getSExtValue(); 16356 // Due to the limitations of the addi instruction, 16357 // -C is required to be [-32768, 32767]. 16358 return isInt<16>(NegConstant); 16359 } 16360 16361 return false; 16362 }; 16363 16364 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16365 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16366 16367 // If there is a pattern, canonicalize a zext operand to the RHS. 16368 if (LHSHasPattern && !RHSHasPattern) 16369 std::swap(LHS, RHS); 16370 else if (!LHSHasPattern && !RHSHasPattern) 16371 return SDValue(); 16372 16373 SDLoc DL(N); 16374 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16375 SDValue Cmp = RHS.getOperand(0); 16376 SDValue Z = Cmp.getOperand(0); 16377 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16378 16379 assert(Constant && "Constant Should not be a null pointer."); 16380 int64_t NegConstant = 0 - Constant->getSExtValue(); 16381 16382 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16383 default: break; 16384 case ISD::SETNE: { 16385 // when C == 0 16386 // --> addze X, (addic Z, -1).carry 16387 // / 16388 // add X, (zext(setne Z, C))-- 16389 // \ when -32768 <= -C <= 32767 && C != 0 16390 // --> addze X, (addic (addi Z, -C), -1).carry 16391 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16392 DAG.getConstant(NegConstant, DL, MVT::i64)); 16393 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16394 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16395 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16396 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16397 SDValue(Addc.getNode(), 1)); 16398 } 16399 case ISD::SETEQ: { 16400 // when C == 0 16401 // --> addze X, (subfic Z, 0).carry 16402 // / 16403 // add X, (zext(sete Z, C))-- 16404 // \ when -32768 <= -C <= 32767 && C != 0 16405 // --> addze X, (subfic (addi Z, -C), 0).carry 16406 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16407 DAG.getConstant(NegConstant, DL, MVT::i64)); 16408 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16409 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16410 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16411 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16412 SDValue(Subc.getNode(), 1)); 16413 } 16414 } 16415 16416 return SDValue(); 16417 } 16418 16419 // Transform 16420 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16421 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16422 // In this case both C1 and C2 must be known constants. 16423 // C1+C2 must fit into a 34 bit signed integer. 16424 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16425 const PPCSubtarget &Subtarget) { 16426 if (!Subtarget.isUsingPCRelativeCalls()) 16427 return SDValue(); 16428 16429 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16430 // If we find that node try to cast the Global Address and the Constant. 16431 SDValue LHS = N->getOperand(0); 16432 SDValue RHS = N->getOperand(1); 16433 16434 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16435 std::swap(LHS, RHS); 16436 16437 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16438 return SDValue(); 16439 16440 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16441 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16442 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16443 16444 // Check that both casts succeeded. 16445 if (!GSDN || !ConstNode) 16446 return SDValue(); 16447 16448 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16449 SDLoc DL(GSDN); 16450 16451 // The signed int offset needs to fit in 34 bits. 16452 if (!isInt<34>(NewOffset)) 16453 return SDValue(); 16454 16455 // The new global address is a copy of the old global address except 16456 // that it has the updated Offset. 16457 SDValue GA = 16458 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16459 NewOffset, GSDN->getTargetFlags()); 16460 SDValue MatPCRel = 16461 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16462 return MatPCRel; 16463 } 16464 16465 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16466 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16467 return Value; 16468 16469 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16470 return Value; 16471 16472 return SDValue(); 16473 } 16474 16475 // Detect TRUNCATE operations on bitcasts of float128 values. 16476 // What we are looking for here is the situtation where we extract a subset 16477 // of bits from a 128 bit float. 16478 // This can be of two forms: 16479 // 1) BITCAST of f128 feeding TRUNCATE 16480 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16481 // The reason this is required is because we do not have a legal i128 type 16482 // and so we want to prevent having to store the f128 and then reload part 16483 // of it. 16484 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16485 DAGCombinerInfo &DCI) const { 16486 // If we are using CRBits then try that first. 16487 if (Subtarget.useCRBits()) { 16488 // Check if CRBits did anything and return that if it did. 16489 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16490 return CRTruncValue; 16491 } 16492 16493 SDLoc dl(N); 16494 SDValue Op0 = N->getOperand(0); 16495 16496 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16497 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16498 EVT VT = N->getValueType(0); 16499 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16500 return SDValue(); 16501 SDValue Sub = Op0.getOperand(0); 16502 if (Sub.getOpcode() == ISD::SUB) { 16503 SDValue SubOp0 = Sub.getOperand(0); 16504 SDValue SubOp1 = Sub.getOperand(1); 16505 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16506 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16507 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16508 SubOp1.getOperand(0), 16509 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16510 } 16511 } 16512 } 16513 16514 // Looking for a truncate of i128 to i64. 16515 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16516 return SDValue(); 16517 16518 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16519 16520 // SRL feeding TRUNCATE. 16521 if (Op0.getOpcode() == ISD::SRL) { 16522 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16523 // The right shift has to be by 64 bits. 16524 if (!ConstNode || ConstNode->getZExtValue() != 64) 16525 return SDValue(); 16526 16527 // Switch the element number to extract. 16528 EltToExtract = EltToExtract ? 0 : 1; 16529 // Update Op0 past the SRL. 16530 Op0 = Op0.getOperand(0); 16531 } 16532 16533 // BITCAST feeding a TRUNCATE possibly via SRL. 16534 if (Op0.getOpcode() == ISD::BITCAST && 16535 Op0.getValueType() == MVT::i128 && 16536 Op0.getOperand(0).getValueType() == MVT::f128) { 16537 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16538 return DCI.DAG.getNode( 16539 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16540 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16541 } 16542 return SDValue(); 16543 } 16544 16545 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16546 SelectionDAG &DAG = DCI.DAG; 16547 16548 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16549 if (!ConstOpOrElement) 16550 return SDValue(); 16551 16552 // An imul is usually smaller than the alternative sequence for legal type. 16553 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16554 isOperationLegal(ISD::MUL, N->getValueType(0))) 16555 return SDValue(); 16556 16557 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16558 switch (this->Subtarget.getCPUDirective()) { 16559 default: 16560 // TODO: enhance the condition for subtarget before pwr8 16561 return false; 16562 case PPC::DIR_PWR8: 16563 // type mul add shl 16564 // scalar 4 1 1 16565 // vector 7 2 2 16566 return true; 16567 case PPC::DIR_PWR9: 16568 case PPC::DIR_PWR10: 16569 case PPC::DIR_PWR_FUTURE: 16570 // type mul add shl 16571 // scalar 5 2 2 16572 // vector 7 2 2 16573 16574 // The cycle RATIO of related operations are showed as a table above. 16575 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16576 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16577 // are 4, it is always profitable; but for 3 instrs patterns 16578 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16579 // So we should only do it for vector type. 16580 return IsAddOne && IsNeg ? VT.isVector() : true; 16581 } 16582 }; 16583 16584 EVT VT = N->getValueType(0); 16585 SDLoc DL(N); 16586 16587 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16588 bool IsNeg = MulAmt.isNegative(); 16589 APInt MulAmtAbs = MulAmt.abs(); 16590 16591 if ((MulAmtAbs - 1).isPowerOf2()) { 16592 // (mul x, 2^N + 1) => (add (shl x, N), x) 16593 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16594 16595 if (!IsProfitable(IsNeg, true, VT)) 16596 return SDValue(); 16597 16598 SDValue Op0 = N->getOperand(0); 16599 SDValue Op1 = 16600 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16601 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16602 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16603 16604 if (!IsNeg) 16605 return Res; 16606 16607 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16608 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16609 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16610 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16611 16612 if (!IsProfitable(IsNeg, false, VT)) 16613 return SDValue(); 16614 16615 SDValue Op0 = N->getOperand(0); 16616 SDValue Op1 = 16617 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16618 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16619 16620 if (!IsNeg) 16621 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16622 else 16623 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16624 16625 } else { 16626 return SDValue(); 16627 } 16628 } 16629 16630 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16631 // in combiner since we need to check SD flags and other subtarget features. 16632 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16633 DAGCombinerInfo &DCI) const { 16634 SDValue N0 = N->getOperand(0); 16635 SDValue N1 = N->getOperand(1); 16636 SDValue N2 = N->getOperand(2); 16637 SDNodeFlags Flags = N->getFlags(); 16638 EVT VT = N->getValueType(0); 16639 SelectionDAG &DAG = DCI.DAG; 16640 const TargetOptions &Options = getTargetMachine().Options; 16641 unsigned Opc = N->getOpcode(); 16642 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16643 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16644 SDLoc Loc(N); 16645 16646 if (!isOperationLegal(ISD::FMA, VT)) 16647 return SDValue(); 16648 16649 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16650 // since (fnmsub a b c)=-0 while c-ab=+0. 16651 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16652 return SDValue(); 16653 16654 // (fma (fneg a) b c) => (fnmsub a b c) 16655 // (fnmsub (fneg a) b c) => (fma a b c) 16656 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16657 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16658 16659 // (fma a (fneg b) c) => (fnmsub a b c) 16660 // (fnmsub a (fneg b) c) => (fma a b c) 16661 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16662 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16663 16664 return SDValue(); 16665 } 16666 16667 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16668 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16669 if (!Subtarget.is64BitELFABI()) 16670 return false; 16671 16672 // If not a tail call then no need to proceed. 16673 if (!CI->isTailCall()) 16674 return false; 16675 16676 // If sibling calls have been disabled and tail-calls aren't guaranteed 16677 // there is no reason to duplicate. 16678 auto &TM = getTargetMachine(); 16679 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16680 return false; 16681 16682 // Can't tail call a function called indirectly, or if it has variadic args. 16683 const Function *Callee = CI->getCalledFunction(); 16684 if (!Callee || Callee->isVarArg()) 16685 return false; 16686 16687 // Make sure the callee and caller calling conventions are eligible for tco. 16688 const Function *Caller = CI->getParent()->getParent(); 16689 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16690 CI->getCallingConv())) 16691 return false; 16692 16693 // If the function is local then we have a good chance at tail-calling it 16694 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16695 } 16696 16697 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16698 if (!Subtarget.hasVSX()) 16699 return false; 16700 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16701 return true; 16702 return VT == MVT::f32 || VT == MVT::f64 || 16703 VT == MVT::v4f32 || VT == MVT::v2f64; 16704 } 16705 16706 bool PPCTargetLowering:: 16707 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16708 const Value *Mask = AndI.getOperand(1); 16709 // If the mask is suitable for andi. or andis. we should sink the and. 16710 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16711 // Can't handle constants wider than 64-bits. 16712 if (CI->getBitWidth() > 64) 16713 return false; 16714 int64_t ConstVal = CI->getZExtValue(); 16715 return isUInt<16>(ConstVal) || 16716 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16717 } 16718 16719 // For non-constant masks, we can always use the record-form and. 16720 return true; 16721 } 16722 16723 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16724 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16725 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16726 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16727 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16728 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16729 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16730 assert(Subtarget.hasP9Altivec() && 16731 "Only combine this when P9 altivec supported!"); 16732 EVT VT = N->getValueType(0); 16733 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16734 return SDValue(); 16735 16736 SelectionDAG &DAG = DCI.DAG; 16737 SDLoc dl(N); 16738 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16739 // Even for signed integers, if it's known to be positive (as signed 16740 // integer) due to zero-extended inputs. 16741 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16742 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16743 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16744 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16745 (SubOpcd1 == ISD::ZERO_EXTEND || 16746 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16747 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16748 N->getOperand(0)->getOperand(0), 16749 N->getOperand(0)->getOperand(1), 16750 DAG.getTargetConstant(0, dl, MVT::i32)); 16751 } 16752 16753 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16754 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16755 N->getOperand(0).hasOneUse()) { 16756 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16757 N->getOperand(0)->getOperand(0), 16758 N->getOperand(0)->getOperand(1), 16759 DAG.getTargetConstant(1, dl, MVT::i32)); 16760 } 16761 } 16762 16763 return SDValue(); 16764 } 16765 16766 // For type v4i32/v8ii16/v16i8, transform 16767 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16768 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16769 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16770 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16771 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16772 DAGCombinerInfo &DCI) const { 16773 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16774 assert(Subtarget.hasP9Altivec() && 16775 "Only combine this when P9 altivec supported!"); 16776 16777 SelectionDAG &DAG = DCI.DAG; 16778 SDLoc dl(N); 16779 SDValue Cond = N->getOperand(0); 16780 SDValue TrueOpnd = N->getOperand(1); 16781 SDValue FalseOpnd = N->getOperand(2); 16782 EVT VT = N->getOperand(1).getValueType(); 16783 16784 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16785 FalseOpnd.getOpcode() != ISD::SUB) 16786 return SDValue(); 16787 16788 // ABSD only available for type v4i32/v8i16/v16i8 16789 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16790 return SDValue(); 16791 16792 // At least to save one more dependent computation 16793 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16794 return SDValue(); 16795 16796 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16797 16798 // Can only handle unsigned comparison here 16799 switch (CC) { 16800 default: 16801 return SDValue(); 16802 case ISD::SETUGT: 16803 case ISD::SETUGE: 16804 break; 16805 case ISD::SETULT: 16806 case ISD::SETULE: 16807 std::swap(TrueOpnd, FalseOpnd); 16808 break; 16809 } 16810 16811 SDValue CmpOpnd1 = Cond.getOperand(0); 16812 SDValue CmpOpnd2 = Cond.getOperand(1); 16813 16814 // SETCC CmpOpnd1 CmpOpnd2 cond 16815 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16816 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16817 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16818 TrueOpnd.getOperand(1) == CmpOpnd2 && 16819 FalseOpnd.getOperand(0) == CmpOpnd2 && 16820 FalseOpnd.getOperand(1) == CmpOpnd1) { 16821 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16822 CmpOpnd1, CmpOpnd2, 16823 DAG.getTargetConstant(0, dl, MVT::i32)); 16824 } 16825 16826 return SDValue(); 16827 } 16828