1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSectionXCOFF.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 122 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 123 124 static cl::opt<bool> EnablePPCPCRelTLS( 125 "enable-ppc-pcrel-tls", 126 cl::desc("enable the use of PC relative memops in TLS instructions on PPC"), 127 cl::Hidden); 128 129 STATISTIC(NumTailCalls, "Number of tail calls"); 130 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 133 134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 135 136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 137 138 // FIXME: Remove this once the bug has been fixed! 139 extern cl::opt<bool> ANDIGlueBug; 140 141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 142 const PPCSubtarget &STI) 143 : TargetLowering(TM), Subtarget(STI) { 144 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 145 // arguments are at least 4/8 bytes aligned. 146 bool isPPC64 = Subtarget.isPPC64(); 147 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 148 149 // Set up the register classes. 150 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 151 if (!useSoftFloat()) { 152 if (hasSPE()) { 153 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 154 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 155 } else { 156 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 157 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 158 } 159 } 160 161 // Match BITREVERSE to customized fast code sequence in the td file. 162 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 163 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 164 165 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 166 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 167 168 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 169 for (MVT VT : MVT::integer_valuetypes()) { 170 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 172 } 173 174 if (Subtarget.isISA3_0()) { 175 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 176 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 177 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 178 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 179 } else { 180 // No extending loads from f16 or HW conversions back and forth. 181 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 182 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 183 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 184 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 185 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 186 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 187 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 188 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 189 } 190 191 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 192 193 // PowerPC has pre-inc load and store's. 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 200 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 201 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 204 if (!Subtarget.hasSPE()) { 205 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 206 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 207 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 208 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 209 } 210 211 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 212 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 213 for (MVT VT : ScalarIntVTs) { 214 setOperationAction(ISD::ADDC, VT, Legal); 215 setOperationAction(ISD::ADDE, VT, Legal); 216 setOperationAction(ISD::SUBC, VT, Legal); 217 setOperationAction(ISD::SUBE, VT, Legal); 218 } 219 220 if (Subtarget.useCRBits()) { 221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 222 223 if (isPPC64 || Subtarget.hasFPCVT()) { 224 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 225 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 226 isPPC64 ? MVT::i64 : MVT::i32); 227 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 228 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 229 isPPC64 ? MVT::i64 : MVT::i32); 230 231 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 232 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 233 isPPC64 ? MVT::i64 : MVT::i32); 234 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 235 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 236 isPPC64 ? MVT::i64 : MVT::i32); 237 } else { 238 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 239 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 240 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 241 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 242 } 243 244 // PowerPC does not support direct load/store of condition registers. 245 setOperationAction(ISD::LOAD, MVT::i1, Custom); 246 setOperationAction(ISD::STORE, MVT::i1, Custom); 247 248 // FIXME: Remove this once the ANDI glue bug is fixed: 249 if (ANDIGlueBug) 250 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 251 252 for (MVT VT : MVT::integer_valuetypes()) { 253 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 254 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 255 setTruncStoreAction(VT, MVT::i1, Expand); 256 } 257 258 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 259 } 260 261 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 262 // PPC (the libcall is not available). 263 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 264 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 265 266 // We do not currently implement these libm ops for PowerPC. 267 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 268 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 269 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 270 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 271 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 272 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 273 274 // PowerPC has no SREM/UREM instructions unless we are on P9 275 // On P9 we may use a hardware instruction to compute the remainder. 276 // When the result of both the remainder and the division is required it is 277 // more efficient to compute the remainder from the result of the division 278 // rather than use the remainder instruction. The instructions are legalized 279 // directly because the DivRemPairsPass performs the transformation at the IR 280 // level. 281 if (Subtarget.isISA3_0()) { 282 setOperationAction(ISD::SREM, MVT::i32, Legal); 283 setOperationAction(ISD::UREM, MVT::i32, Legal); 284 setOperationAction(ISD::SREM, MVT::i64, Legal); 285 setOperationAction(ISD::UREM, MVT::i64, Legal); 286 } else { 287 setOperationAction(ISD::SREM, MVT::i32, Expand); 288 setOperationAction(ISD::UREM, MVT::i32, Expand); 289 setOperationAction(ISD::SREM, MVT::i64, Expand); 290 setOperationAction(ISD::UREM, MVT::i64, Expand); 291 } 292 293 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 294 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 295 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 296 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 297 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 298 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 299 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 300 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 301 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 302 303 // Handle constrained floating-point operations of scalar. 304 // TODO: Handle SPE specific operation. 305 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 306 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 307 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 308 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 309 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 310 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 311 312 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 313 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 314 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 315 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 316 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 317 if (Subtarget.hasVSX()) 318 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal); 319 320 if (Subtarget.hasFSQRT()) { 321 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 322 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 323 } 324 325 if (Subtarget.hasFPRND()) { 326 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 327 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 328 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 329 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 330 331 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 332 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 333 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 334 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 335 } 336 337 // We don't support sin/cos/sqrt/fmod/pow 338 setOperationAction(ISD::FSIN , MVT::f64, Expand); 339 setOperationAction(ISD::FCOS , MVT::f64, Expand); 340 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 341 setOperationAction(ISD::FREM , MVT::f64, Expand); 342 setOperationAction(ISD::FPOW , MVT::f64, Expand); 343 setOperationAction(ISD::FSIN , MVT::f32, Expand); 344 setOperationAction(ISD::FCOS , MVT::f32, Expand); 345 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 346 setOperationAction(ISD::FREM , MVT::f32, Expand); 347 setOperationAction(ISD::FPOW , MVT::f32, Expand); 348 if (Subtarget.hasSPE()) { 349 setOperationAction(ISD::FMA , MVT::f64, Expand); 350 setOperationAction(ISD::FMA , MVT::f32, Expand); 351 } else { 352 setOperationAction(ISD::FMA , MVT::f64, Legal); 353 setOperationAction(ISD::FMA , MVT::f32, Legal); 354 } 355 356 if (Subtarget.hasSPE()) 357 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 358 359 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 360 361 // If we're enabling GP optimizations, use hardware square root 362 if (!Subtarget.hasFSQRT() && 363 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 364 Subtarget.hasFRE())) 365 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 366 367 if (!Subtarget.hasFSQRT() && 368 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 369 Subtarget.hasFRES())) 370 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 371 372 if (Subtarget.hasFCPSGN()) { 373 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 374 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 375 } else { 376 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 377 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 378 } 379 380 if (Subtarget.hasFPRND()) { 381 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 382 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 383 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 384 setOperationAction(ISD::FROUND, MVT::f64, Legal); 385 386 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 387 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 388 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 389 setOperationAction(ISD::FROUND, MVT::f32, Legal); 390 } 391 392 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 393 // to speed up scalar BSWAP64. 394 // CTPOP or CTTZ were introduced in P8/P9 respectively 395 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 396 if (Subtarget.hasP9Vector()) 397 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 398 else 399 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 400 if (Subtarget.isISA3_0()) { 401 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 402 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 403 } else { 404 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 405 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 406 } 407 408 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 409 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 410 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 411 } else { 412 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 413 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 414 } 415 416 // PowerPC does not have ROTR 417 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 418 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 419 420 if (!Subtarget.useCRBits()) { 421 // PowerPC does not have Select 422 setOperationAction(ISD::SELECT, MVT::i32, Expand); 423 setOperationAction(ISD::SELECT, MVT::i64, Expand); 424 setOperationAction(ISD::SELECT, MVT::f32, Expand); 425 setOperationAction(ISD::SELECT, MVT::f64, Expand); 426 } 427 428 // PowerPC wants to turn select_cc of FP into fsel when possible. 429 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 430 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 431 432 // PowerPC wants to optimize integer setcc a bit 433 if (!Subtarget.useCRBits()) 434 setOperationAction(ISD::SETCC, MVT::i32, Custom); 435 436 if (Subtarget.hasFPU()) { 437 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 438 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 439 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 440 441 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 442 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 443 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 444 } 445 446 // PowerPC does not have BRCOND which requires SetCC 447 if (!Subtarget.useCRBits()) 448 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 449 450 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 451 452 if (Subtarget.hasSPE()) { 453 // SPE has built-in conversions 454 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 455 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 456 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 457 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 458 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 459 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 460 } else { 461 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 462 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 463 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 464 465 // PowerPC does not have [U|S]INT_TO_FP 466 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 467 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 468 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 469 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 470 } 471 472 if (Subtarget.hasDirectMove() && isPPC64) { 473 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 474 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 475 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 476 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 477 if (TM.Options.UnsafeFPMath) { 478 setOperationAction(ISD::LRINT, MVT::f64, Legal); 479 setOperationAction(ISD::LRINT, MVT::f32, Legal); 480 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 481 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 482 setOperationAction(ISD::LROUND, MVT::f64, Legal); 483 setOperationAction(ISD::LROUND, MVT::f32, Legal); 484 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 485 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 486 } 487 } else { 488 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 489 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 490 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 491 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 492 } 493 494 // We cannot sextinreg(i1). Expand to shifts. 495 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 496 497 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 498 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 499 // support continuation, user-level threading, and etc.. As a result, no 500 // other SjLj exception interfaces are implemented and please don't build 501 // your own exception handling based on them. 502 // LLVM/Clang supports zero-cost DWARF exception handling. 503 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 504 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 505 506 // We want to legalize GlobalAddress and ConstantPool nodes into the 507 // appropriate instructions to materialize the address. 508 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 509 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 510 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 511 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 512 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 513 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 514 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 515 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 516 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 517 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 518 519 // TRAP is legal. 520 setOperationAction(ISD::TRAP, MVT::Other, Legal); 521 522 // TRAMPOLINE is custom lowered. 523 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 524 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 525 526 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 527 setOperationAction(ISD::VASTART , MVT::Other, Custom); 528 529 if (Subtarget.is64BitELFABI()) { 530 // VAARG always uses double-word chunks, so promote anything smaller. 531 setOperationAction(ISD::VAARG, MVT::i1, Promote); 532 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 533 setOperationAction(ISD::VAARG, MVT::i8, Promote); 534 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 535 setOperationAction(ISD::VAARG, MVT::i16, Promote); 536 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 537 setOperationAction(ISD::VAARG, MVT::i32, Promote); 538 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 539 setOperationAction(ISD::VAARG, MVT::Other, Expand); 540 } else if (Subtarget.is32BitELFABI()) { 541 // VAARG is custom lowered with the 32-bit SVR4 ABI. 542 setOperationAction(ISD::VAARG, MVT::Other, Custom); 543 setOperationAction(ISD::VAARG, MVT::i64, Custom); 544 } else 545 setOperationAction(ISD::VAARG, MVT::Other, Expand); 546 547 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 548 if (Subtarget.is32BitELFABI()) 549 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 550 else 551 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 552 553 // Use the default implementation. 554 setOperationAction(ISD::VAEND , MVT::Other, Expand); 555 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 556 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 557 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 558 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 559 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 560 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 561 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 562 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 563 564 // We want to custom lower some of our intrinsics. 565 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 566 567 // To handle counter-based loop conditions. 568 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 569 570 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 571 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 572 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 573 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 574 575 // Comparisons that require checking two conditions. 576 if (Subtarget.hasSPE()) { 577 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 578 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 579 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 580 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 581 } 582 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 583 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 584 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 585 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 586 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 587 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 588 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 589 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 590 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 591 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 592 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 593 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 594 595 if (Subtarget.has64BitSupport()) { 596 // They also have instructions for converting between i64 and fp. 597 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 598 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 599 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 600 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 601 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 602 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 603 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 604 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 605 // This is just the low 32 bits of a (signed) fp->i64 conversion. 606 // We cannot do this with Promote because i64 is not a legal type. 607 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 608 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 609 610 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 611 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 612 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 613 } 614 } else { 615 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 616 if (Subtarget.hasSPE()) { 617 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 618 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 619 } else { 620 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 621 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 622 } 623 } 624 625 // With the instructions enabled under FPCVT, we can do everything. 626 if (Subtarget.hasFPCVT()) { 627 if (Subtarget.has64BitSupport()) { 628 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 629 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 630 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 631 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 632 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 633 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 634 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 635 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 636 } 637 638 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 639 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 640 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 641 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 642 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 643 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 644 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 645 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 646 } 647 648 if (Subtarget.use64BitRegs()) { 649 // 64-bit PowerPC implementations can support i64 types directly 650 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 651 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 652 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 653 // 64-bit PowerPC wants to expand i128 shifts itself. 654 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 655 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 656 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 657 } else { 658 // 32-bit PowerPC wants to expand i64 shifts itself. 659 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 660 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 661 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 662 } 663 664 // PowerPC has better expansions for funnel shifts than the generic 665 // TargetLowering::expandFunnelShift. 666 if (Subtarget.has64BitSupport()) { 667 setOperationAction(ISD::FSHL, MVT::i64, Custom); 668 setOperationAction(ISD::FSHR, MVT::i64, Custom); 669 } 670 setOperationAction(ISD::FSHL, MVT::i32, Custom); 671 setOperationAction(ISD::FSHR, MVT::i32, Custom); 672 673 if (Subtarget.hasVSX()) { 674 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 675 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 676 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 677 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 678 } 679 680 if (Subtarget.hasAltivec()) { 681 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 682 setOperationAction(ISD::SADDSAT, VT, Legal); 683 setOperationAction(ISD::SSUBSAT, VT, Legal); 684 setOperationAction(ISD::UADDSAT, VT, Legal); 685 setOperationAction(ISD::USUBSAT, VT, Legal); 686 } 687 // First set operation action for all vector types to expand. Then we 688 // will selectively turn on ones that can be effectively codegen'd. 689 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 690 // add/sub are legal for all supported vector VT's. 691 setOperationAction(ISD::ADD, VT, Legal); 692 setOperationAction(ISD::SUB, VT, Legal); 693 694 // For v2i64, these are only valid with P8Vector. This is corrected after 695 // the loop. 696 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 697 setOperationAction(ISD::SMAX, VT, Legal); 698 setOperationAction(ISD::SMIN, VT, Legal); 699 setOperationAction(ISD::UMAX, VT, Legal); 700 setOperationAction(ISD::UMIN, VT, Legal); 701 } 702 else { 703 setOperationAction(ISD::SMAX, VT, Expand); 704 setOperationAction(ISD::SMIN, VT, Expand); 705 setOperationAction(ISD::UMAX, VT, Expand); 706 setOperationAction(ISD::UMIN, VT, Expand); 707 } 708 709 if (Subtarget.hasVSX()) { 710 setOperationAction(ISD::FMAXNUM, VT, Legal); 711 setOperationAction(ISD::FMINNUM, VT, Legal); 712 } 713 714 // Vector instructions introduced in P8 715 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 716 setOperationAction(ISD::CTPOP, VT, Legal); 717 setOperationAction(ISD::CTLZ, VT, Legal); 718 } 719 else { 720 setOperationAction(ISD::CTPOP, VT, Expand); 721 setOperationAction(ISD::CTLZ, VT, Expand); 722 } 723 724 // Vector instructions introduced in P9 725 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 726 setOperationAction(ISD::CTTZ, VT, Legal); 727 else 728 setOperationAction(ISD::CTTZ, VT, Expand); 729 730 // We promote all shuffles to v16i8. 731 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 732 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 733 734 // We promote all non-typed operations to v4i32. 735 setOperationAction(ISD::AND , VT, Promote); 736 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 737 setOperationAction(ISD::OR , VT, Promote); 738 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 739 setOperationAction(ISD::XOR , VT, Promote); 740 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 741 setOperationAction(ISD::LOAD , VT, Promote); 742 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 743 setOperationAction(ISD::SELECT, VT, Promote); 744 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 745 setOperationAction(ISD::VSELECT, VT, Legal); 746 setOperationAction(ISD::SELECT_CC, VT, Promote); 747 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 748 setOperationAction(ISD::STORE, VT, Promote); 749 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 750 751 // No other operations are legal. 752 setOperationAction(ISD::MUL , VT, Expand); 753 setOperationAction(ISD::SDIV, VT, Expand); 754 setOperationAction(ISD::SREM, VT, Expand); 755 setOperationAction(ISD::UDIV, VT, Expand); 756 setOperationAction(ISD::UREM, VT, Expand); 757 setOperationAction(ISD::FDIV, VT, Expand); 758 setOperationAction(ISD::FREM, VT, Expand); 759 setOperationAction(ISD::FNEG, VT, Expand); 760 setOperationAction(ISD::FSQRT, VT, Expand); 761 setOperationAction(ISD::FLOG, VT, Expand); 762 setOperationAction(ISD::FLOG10, VT, Expand); 763 setOperationAction(ISD::FLOG2, VT, Expand); 764 setOperationAction(ISD::FEXP, VT, Expand); 765 setOperationAction(ISD::FEXP2, VT, Expand); 766 setOperationAction(ISD::FSIN, VT, Expand); 767 setOperationAction(ISD::FCOS, VT, Expand); 768 setOperationAction(ISD::FABS, VT, Expand); 769 setOperationAction(ISD::FFLOOR, VT, Expand); 770 setOperationAction(ISD::FCEIL, VT, Expand); 771 setOperationAction(ISD::FTRUNC, VT, Expand); 772 setOperationAction(ISD::FRINT, VT, Expand); 773 setOperationAction(ISD::FNEARBYINT, VT, Expand); 774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 775 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 776 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 777 setOperationAction(ISD::MULHU, VT, Expand); 778 setOperationAction(ISD::MULHS, VT, Expand); 779 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 780 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 781 setOperationAction(ISD::UDIVREM, VT, Expand); 782 setOperationAction(ISD::SDIVREM, VT, Expand); 783 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 784 setOperationAction(ISD::FPOW, VT, Expand); 785 setOperationAction(ISD::BSWAP, VT, Expand); 786 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 787 setOperationAction(ISD::ROTL, VT, Expand); 788 setOperationAction(ISD::ROTR, VT, Expand); 789 790 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 791 setTruncStoreAction(VT, InnerVT, Expand); 792 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 793 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 794 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 795 } 796 } 797 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 798 if (!Subtarget.hasP8Vector()) { 799 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 800 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 801 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 802 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 803 } 804 805 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 806 setOperationAction(ISD::ABS, VT, Custom); 807 808 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 809 // with merges, splats, etc. 810 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 811 812 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 813 // are cheap, so handle them before they get expanded to scalar. 814 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 815 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 816 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 817 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 818 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 819 820 setOperationAction(ISD::AND , MVT::v4i32, Legal); 821 setOperationAction(ISD::OR , MVT::v4i32, Legal); 822 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 823 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 824 setOperationAction(ISD::SELECT, MVT::v4i32, 825 Subtarget.useCRBits() ? Legal : Expand); 826 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 827 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 828 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 829 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 830 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 831 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 832 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 833 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 834 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 835 836 // Without hasP8Altivec set, v2i64 SMAX isn't available. 837 // But ABS custom lowering requires SMAX support. 838 if (!Subtarget.hasP8Altivec()) 839 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 840 841 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 842 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 843 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 844 if (Subtarget.hasAltivec()) 845 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 846 setOperationAction(ISD::ROTL, VT, Legal); 847 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 848 if (Subtarget.hasP8Altivec()) 849 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 850 851 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 852 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 853 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 854 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 855 856 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 857 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 858 859 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 860 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 861 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 862 } 863 864 if (Subtarget.hasP8Altivec()) 865 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 866 else 867 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 868 869 if (Subtarget.isISA3_1()) { 870 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 871 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 872 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 873 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 874 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 875 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 876 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 877 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 878 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 879 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 880 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 881 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 882 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 883 } 884 885 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 886 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 887 888 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 889 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 890 891 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 892 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 893 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 894 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 895 896 // Altivec does not contain unordered floating-point compare instructions 897 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 898 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 899 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 900 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 901 902 if (Subtarget.hasVSX()) { 903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 904 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 905 if (Subtarget.hasP8Vector()) { 906 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 907 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 908 } 909 if (Subtarget.hasDirectMove() && isPPC64) { 910 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 911 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 912 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 914 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 915 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 918 } 919 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 920 921 // The nearbyint variants are not allowed to raise the inexact exception 922 // so we can only code-gen them with unsafe math. 923 if (TM.Options.UnsafeFPMath) { 924 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 925 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 926 } 927 928 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 929 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 930 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 931 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 932 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 933 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 934 setOperationAction(ISD::FROUND, MVT::f64, Legal); 935 setOperationAction(ISD::FRINT, MVT::f64, Legal); 936 937 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 938 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 939 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 940 setOperationAction(ISD::FROUND, MVT::f32, Legal); 941 setOperationAction(ISD::FRINT, MVT::f32, Legal); 942 943 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 944 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 945 946 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 947 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 948 949 // Share the Altivec comparison restrictions. 950 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 951 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 952 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 953 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 954 955 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 956 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 957 958 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 959 960 if (Subtarget.hasP8Vector()) 961 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 962 963 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 964 965 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 966 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 967 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 968 969 if (Subtarget.hasP8Altivec()) { 970 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 971 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 972 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 973 974 // 128 bit shifts can be accomplished via 3 instructions for SHL and 975 // SRL, but not for SRA because of the instructions available: 976 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 977 // doing 978 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 979 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 980 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 981 982 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 983 } 984 else { 985 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 986 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 987 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 988 989 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 990 991 // VSX v2i64 only supports non-arithmetic operations. 992 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 993 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 994 } 995 996 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 997 998 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 999 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1000 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1001 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1002 1003 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1004 1005 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1006 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1007 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1008 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1009 1010 // Custom handling for partial vectors of integers converted to 1011 // floating point. We already have optimal handling for v2i32 through 1012 // the DAG combine, so those aren't necessary. 1013 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1014 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1015 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1016 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1017 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1018 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1019 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1020 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1021 1022 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1023 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1024 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1025 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1026 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1027 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1028 1029 if (Subtarget.hasDirectMove()) 1030 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1032 1033 // Handle constrained floating-point operations of vector. 1034 // The predictor is `hasVSX` because altivec instruction has 1035 // no exception but VSX vector instruction has. 1036 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1037 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1038 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1039 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1040 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1041 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1042 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1043 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1044 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 1045 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1046 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1047 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1048 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1049 1050 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1051 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1052 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1053 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1054 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1055 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1056 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1057 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1058 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 1059 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1060 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1061 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1062 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1063 1064 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1065 } 1066 1067 if (Subtarget.hasP8Altivec()) { 1068 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1069 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1070 } 1071 1072 if (Subtarget.hasP9Vector()) { 1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1075 1076 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1077 // SRL, but not for SRA because of the instructions available: 1078 // VS{RL} and VS{RL}O. 1079 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1080 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1081 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1082 1083 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1084 setOperationAction(ISD::FADD, MVT::f128, Legal); 1085 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1086 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1087 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1088 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1089 // No extending loads to f128 on PPC. 1090 for (MVT FPT : MVT::fp_valuetypes()) 1091 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1092 setOperationAction(ISD::FMA, MVT::f128, Legal); 1093 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1094 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1095 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1096 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1097 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1098 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1099 1100 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1101 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1102 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1103 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1104 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1105 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1106 1107 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1108 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1109 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1110 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1111 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1112 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1113 // No implementation for these ops for PowerPC. 1114 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1115 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1116 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1117 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1118 setOperationAction(ISD::FREM, MVT::f128, Expand); 1119 1120 // Handle constrained floating-point operations of fp128 1121 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1122 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1123 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1124 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1125 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1126 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1127 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1128 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1129 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1130 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1131 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1132 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1133 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1134 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1135 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1136 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1137 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1138 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1139 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1140 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1141 } 1142 1143 if (Subtarget.hasP9Altivec()) { 1144 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1145 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1146 1147 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1148 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1149 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1150 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1151 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1152 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1153 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1154 } 1155 } 1156 1157 if (Subtarget.has64BitSupport()) 1158 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1159 1160 if (Subtarget.isISA3_1()) 1161 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1162 1163 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1164 1165 if (!isPPC64) { 1166 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1167 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1168 } 1169 1170 setBooleanContents(ZeroOrOneBooleanContent); 1171 1172 if (Subtarget.hasAltivec()) { 1173 // Altivec instructions set fields to all zeros or all ones. 1174 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1175 } 1176 1177 if (!isPPC64) { 1178 // These libcalls are not available in 32-bit. 1179 setLibcallName(RTLIB::SHL_I128, nullptr); 1180 setLibcallName(RTLIB::SRL_I128, nullptr); 1181 setLibcallName(RTLIB::SRA_I128, nullptr); 1182 } 1183 1184 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1185 1186 // We have target-specific dag combine patterns for the following nodes: 1187 setTargetDAGCombine(ISD::ADD); 1188 setTargetDAGCombine(ISD::SHL); 1189 setTargetDAGCombine(ISD::SRA); 1190 setTargetDAGCombine(ISD::SRL); 1191 setTargetDAGCombine(ISD::MUL); 1192 setTargetDAGCombine(ISD::FMA); 1193 setTargetDAGCombine(ISD::SINT_TO_FP); 1194 setTargetDAGCombine(ISD::BUILD_VECTOR); 1195 if (Subtarget.hasFPCVT()) 1196 setTargetDAGCombine(ISD::UINT_TO_FP); 1197 setTargetDAGCombine(ISD::LOAD); 1198 setTargetDAGCombine(ISD::STORE); 1199 setTargetDAGCombine(ISD::BR_CC); 1200 if (Subtarget.useCRBits()) 1201 setTargetDAGCombine(ISD::BRCOND); 1202 setTargetDAGCombine(ISD::BSWAP); 1203 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1204 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1205 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1206 1207 setTargetDAGCombine(ISD::SIGN_EXTEND); 1208 setTargetDAGCombine(ISD::ZERO_EXTEND); 1209 setTargetDAGCombine(ISD::ANY_EXTEND); 1210 1211 setTargetDAGCombine(ISD::TRUNCATE); 1212 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1213 1214 1215 if (Subtarget.useCRBits()) { 1216 setTargetDAGCombine(ISD::TRUNCATE); 1217 setTargetDAGCombine(ISD::SETCC); 1218 setTargetDAGCombine(ISD::SELECT_CC); 1219 } 1220 1221 // Use reciprocal estimates. 1222 if (TM.Options.UnsafeFPMath) { 1223 setTargetDAGCombine(ISD::FDIV); 1224 setTargetDAGCombine(ISD::FSQRT); 1225 } 1226 1227 if (Subtarget.hasP9Altivec()) { 1228 setTargetDAGCombine(ISD::ABS); 1229 setTargetDAGCombine(ISD::VSELECT); 1230 } 1231 1232 setLibcallName(RTLIB::LOG_F128, "logf128"); 1233 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1234 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1235 setLibcallName(RTLIB::EXP_F128, "expf128"); 1236 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1237 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1238 setLibcallName(RTLIB::COS_F128, "cosf128"); 1239 setLibcallName(RTLIB::POW_F128, "powf128"); 1240 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1241 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1242 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1243 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1244 1245 // With 32 condition bits, we don't need to sink (and duplicate) compares 1246 // aggressively in CodeGenPrep. 1247 if (Subtarget.useCRBits()) { 1248 setHasMultipleConditionRegisters(); 1249 setJumpIsExpensive(); 1250 } 1251 1252 setMinFunctionAlignment(Align(4)); 1253 1254 switch (Subtarget.getCPUDirective()) { 1255 default: break; 1256 case PPC::DIR_970: 1257 case PPC::DIR_A2: 1258 case PPC::DIR_E500: 1259 case PPC::DIR_E500mc: 1260 case PPC::DIR_E5500: 1261 case PPC::DIR_PWR4: 1262 case PPC::DIR_PWR5: 1263 case PPC::DIR_PWR5X: 1264 case PPC::DIR_PWR6: 1265 case PPC::DIR_PWR6X: 1266 case PPC::DIR_PWR7: 1267 case PPC::DIR_PWR8: 1268 case PPC::DIR_PWR9: 1269 case PPC::DIR_PWR10: 1270 case PPC::DIR_PWR_FUTURE: 1271 setPrefLoopAlignment(Align(16)); 1272 setPrefFunctionAlignment(Align(16)); 1273 break; 1274 } 1275 1276 if (Subtarget.enableMachineScheduler()) 1277 setSchedulingPreference(Sched::Source); 1278 else 1279 setSchedulingPreference(Sched::Hybrid); 1280 1281 computeRegisterProperties(STI.getRegisterInfo()); 1282 1283 // The Freescale cores do better with aggressive inlining of memcpy and 1284 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1285 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1286 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1287 MaxStoresPerMemset = 32; 1288 MaxStoresPerMemsetOptSize = 16; 1289 MaxStoresPerMemcpy = 32; 1290 MaxStoresPerMemcpyOptSize = 8; 1291 MaxStoresPerMemmove = 32; 1292 MaxStoresPerMemmoveOptSize = 8; 1293 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1294 // The A2 also benefits from (very) aggressive inlining of memcpy and 1295 // friends. The overhead of a the function call, even when warm, can be 1296 // over one hundred cycles. 1297 MaxStoresPerMemset = 128; 1298 MaxStoresPerMemcpy = 128; 1299 MaxStoresPerMemmove = 128; 1300 MaxLoadsPerMemcmp = 128; 1301 } else { 1302 MaxLoadsPerMemcmp = 8; 1303 MaxLoadsPerMemcmpOptSize = 4; 1304 } 1305 1306 // Let the subtarget (CPU) decide if a predictable select is more expensive 1307 // than the corresponding branch. This information is used in CGP to decide 1308 // when to convert selects into branches. 1309 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1310 } 1311 1312 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1313 /// the desired ByVal argument alignment. 1314 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1315 if (MaxAlign == MaxMaxAlign) 1316 return; 1317 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1318 if (MaxMaxAlign >= 32 && 1319 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1320 MaxAlign = Align(32); 1321 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1322 MaxAlign < 16) 1323 MaxAlign = Align(16); 1324 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1325 Align EltAlign; 1326 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1327 if (EltAlign > MaxAlign) 1328 MaxAlign = EltAlign; 1329 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1330 for (auto *EltTy : STy->elements()) { 1331 Align EltAlign; 1332 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1333 if (EltAlign > MaxAlign) 1334 MaxAlign = EltAlign; 1335 if (MaxAlign == MaxMaxAlign) 1336 break; 1337 } 1338 } 1339 } 1340 1341 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1342 /// function arguments in the caller parameter area. 1343 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1344 const DataLayout &DL) const { 1345 // 16byte and wider vectors are passed on 16byte boundary. 1346 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1347 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1348 if (Subtarget.hasAltivec()) 1349 getMaxByValAlign(Ty, Alignment, Align(16)); 1350 return Alignment.value(); 1351 } 1352 1353 bool PPCTargetLowering::useSoftFloat() const { 1354 return Subtarget.useSoftFloat(); 1355 } 1356 1357 bool PPCTargetLowering::hasSPE() const { 1358 return Subtarget.hasSPE(); 1359 } 1360 1361 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1362 return VT.isScalarInteger(); 1363 } 1364 1365 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1366 /// type is cheaper than a multiply followed by a shift. 1367 /// This is true for words and doublewords on 64-bit PowerPC. 1368 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1369 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1370 isOperationLegal(ISD::MULHU, Type))) 1371 return true; 1372 return TargetLowering::isMulhCheaperThanMulShift(Type); 1373 } 1374 1375 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1376 switch ((PPCISD::NodeType)Opcode) { 1377 case PPCISD::FIRST_NUMBER: break; 1378 case PPCISD::FSEL: return "PPCISD::FSEL"; 1379 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1380 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1381 case PPCISD::FCFID: return "PPCISD::FCFID"; 1382 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1383 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1384 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1385 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1386 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1387 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1388 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1389 case PPCISD::FP_TO_UINT_IN_VSR: 1390 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1391 case PPCISD::FP_TO_SINT_IN_VSR: 1392 return "PPCISD::FP_TO_SINT_IN_VSR"; 1393 case PPCISD::FRE: return "PPCISD::FRE"; 1394 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1395 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1396 case PPCISD::VPERM: return "PPCISD::VPERM"; 1397 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1398 case PPCISD::XXSPLTI_SP_TO_DP: 1399 return "PPCISD::XXSPLTI_SP_TO_DP"; 1400 case PPCISD::XXSPLTI32DX: 1401 return "PPCISD::XXSPLTI32DX"; 1402 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1403 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1404 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1405 case PPCISD::CMPB: return "PPCISD::CMPB"; 1406 case PPCISD::Hi: return "PPCISD::Hi"; 1407 case PPCISD::Lo: return "PPCISD::Lo"; 1408 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1409 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1410 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1411 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1412 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1413 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1414 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1415 case PPCISD::SRL: return "PPCISD::SRL"; 1416 case PPCISD::SRA: return "PPCISD::SRA"; 1417 case PPCISD::SHL: return "PPCISD::SHL"; 1418 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1419 case PPCISD::CALL: return "PPCISD::CALL"; 1420 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1421 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1422 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1423 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1424 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1425 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1426 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1427 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1428 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1429 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1430 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1431 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1432 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1433 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1434 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1435 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1436 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1437 case PPCISD::ANDI_rec_1_EQ_BIT: 1438 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1439 case PPCISD::ANDI_rec_1_GT_BIT: 1440 return "PPCISD::ANDI_rec_1_GT_BIT"; 1441 case PPCISD::VCMP: return "PPCISD::VCMP"; 1442 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1443 case PPCISD::LBRX: return "PPCISD::LBRX"; 1444 case PPCISD::STBRX: return "PPCISD::STBRX"; 1445 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1446 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1447 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1448 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1449 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1450 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1451 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1452 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1453 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1454 case PPCISD::ST_VSR_SCAL_INT: 1455 return "PPCISD::ST_VSR_SCAL_INT"; 1456 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1457 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1458 case PPCISD::BDZ: return "PPCISD::BDZ"; 1459 case PPCISD::MFFS: return "PPCISD::MFFS"; 1460 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1461 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1462 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1463 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1464 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1465 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1466 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1467 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1468 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1469 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1470 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1471 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1472 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1473 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1474 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1475 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1476 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1477 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1478 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1479 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1480 case PPCISD::SC: return "PPCISD::SC"; 1481 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1482 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1483 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1484 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1485 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1486 case PPCISD::VABSD: return "PPCISD::VABSD"; 1487 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1488 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1489 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1490 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1491 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1492 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1493 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1494 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1495 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1496 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1497 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1498 case PPCISD::STRICT_FCTIDZ: 1499 return "PPCISD::STRICT_FCTIDZ"; 1500 case PPCISD::STRICT_FCTIWZ: 1501 return "PPCISD::STRICT_FCTIWZ"; 1502 case PPCISD::STRICT_FCTIDUZ: 1503 return "PPCISD::STRICT_FCTIDUZ"; 1504 case PPCISD::STRICT_FCTIWUZ: 1505 return "PPCISD::STRICT_FCTIWUZ"; 1506 case PPCISD::STRICT_FCFID: 1507 return "PPCISD::STRICT_FCFID"; 1508 case PPCISD::STRICT_FCFIDU: 1509 return "PPCISD::STRICT_FCFIDU"; 1510 case PPCISD::STRICT_FCFIDS: 1511 return "PPCISD::STRICT_FCFIDS"; 1512 case PPCISD::STRICT_FCFIDUS: 1513 return "PPCISD::STRICT_FCFIDUS"; 1514 } 1515 return nullptr; 1516 } 1517 1518 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1519 EVT VT) const { 1520 if (!VT.isVector()) 1521 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1522 1523 return VT.changeVectorElementTypeToInteger(); 1524 } 1525 1526 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1527 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1528 return true; 1529 } 1530 1531 //===----------------------------------------------------------------------===// 1532 // Node matching predicates, for use by the tblgen matching code. 1533 //===----------------------------------------------------------------------===// 1534 1535 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1536 static bool isFloatingPointZero(SDValue Op) { 1537 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1538 return CFP->getValueAPF().isZero(); 1539 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1540 // Maybe this has already been legalized into the constant pool? 1541 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1542 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1543 return CFP->getValueAPF().isZero(); 1544 } 1545 return false; 1546 } 1547 1548 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1549 /// true if Op is undef or if it matches the specified value. 1550 static bool isConstantOrUndef(int Op, int Val) { 1551 return Op < 0 || Op == Val; 1552 } 1553 1554 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1555 /// VPKUHUM instruction. 1556 /// The ShuffleKind distinguishes between big-endian operations with 1557 /// two different inputs (0), either-endian operations with two identical 1558 /// inputs (1), and little-endian operations with two different inputs (2). 1559 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1560 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1561 SelectionDAG &DAG) { 1562 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1563 if (ShuffleKind == 0) { 1564 if (IsLE) 1565 return false; 1566 for (unsigned i = 0; i != 16; ++i) 1567 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1568 return false; 1569 } else if (ShuffleKind == 2) { 1570 if (!IsLE) 1571 return false; 1572 for (unsigned i = 0; i != 16; ++i) 1573 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1574 return false; 1575 } else if (ShuffleKind == 1) { 1576 unsigned j = IsLE ? 0 : 1; 1577 for (unsigned i = 0; i != 8; ++i) 1578 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1579 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1580 return false; 1581 } 1582 return true; 1583 } 1584 1585 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1586 /// VPKUWUM instruction. 1587 /// The ShuffleKind distinguishes between big-endian operations with 1588 /// two different inputs (0), either-endian operations with two identical 1589 /// inputs (1), and little-endian operations with two different inputs (2). 1590 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1591 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1592 SelectionDAG &DAG) { 1593 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1594 if (ShuffleKind == 0) { 1595 if (IsLE) 1596 return false; 1597 for (unsigned i = 0; i != 16; i += 2) 1598 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1599 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1600 return false; 1601 } else if (ShuffleKind == 2) { 1602 if (!IsLE) 1603 return false; 1604 for (unsigned i = 0; i != 16; i += 2) 1605 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1606 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1607 return false; 1608 } else if (ShuffleKind == 1) { 1609 unsigned j = IsLE ? 0 : 2; 1610 for (unsigned i = 0; i != 8; i += 2) 1611 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1612 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1613 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1614 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1615 return false; 1616 } 1617 return true; 1618 } 1619 1620 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1621 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1622 /// current subtarget. 1623 /// 1624 /// The ShuffleKind distinguishes between big-endian operations with 1625 /// two different inputs (0), either-endian operations with two identical 1626 /// inputs (1), and little-endian operations with two different inputs (2). 1627 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1628 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1629 SelectionDAG &DAG) { 1630 const PPCSubtarget& Subtarget = 1631 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1632 if (!Subtarget.hasP8Vector()) 1633 return false; 1634 1635 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1636 if (ShuffleKind == 0) { 1637 if (IsLE) 1638 return false; 1639 for (unsigned i = 0; i != 16; i += 4) 1640 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1641 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1642 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1643 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1644 return false; 1645 } else if (ShuffleKind == 2) { 1646 if (!IsLE) 1647 return false; 1648 for (unsigned i = 0; i != 16; i += 4) 1649 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1650 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1651 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1652 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1653 return false; 1654 } else if (ShuffleKind == 1) { 1655 unsigned j = IsLE ? 0 : 4; 1656 for (unsigned i = 0; i != 8; i += 4) 1657 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1658 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1659 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1660 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1661 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1662 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1663 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1664 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1665 return false; 1666 } 1667 return true; 1668 } 1669 1670 /// isVMerge - Common function, used to match vmrg* shuffles. 1671 /// 1672 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1673 unsigned LHSStart, unsigned RHSStart) { 1674 if (N->getValueType(0) != MVT::v16i8) 1675 return false; 1676 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1677 "Unsupported merge size!"); 1678 1679 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1680 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1681 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1682 LHSStart+j+i*UnitSize) || 1683 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1684 RHSStart+j+i*UnitSize)) 1685 return false; 1686 } 1687 return true; 1688 } 1689 1690 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1691 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1692 /// The ShuffleKind distinguishes between big-endian merges with two 1693 /// different inputs (0), either-endian merges with two identical inputs (1), 1694 /// and little-endian merges with two different inputs (2). For the latter, 1695 /// the input operands are swapped (see PPCInstrAltivec.td). 1696 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1697 unsigned ShuffleKind, SelectionDAG &DAG) { 1698 if (DAG.getDataLayout().isLittleEndian()) { 1699 if (ShuffleKind == 1) // unary 1700 return isVMerge(N, UnitSize, 0, 0); 1701 else if (ShuffleKind == 2) // swapped 1702 return isVMerge(N, UnitSize, 0, 16); 1703 else 1704 return false; 1705 } else { 1706 if (ShuffleKind == 1) // unary 1707 return isVMerge(N, UnitSize, 8, 8); 1708 else if (ShuffleKind == 0) // normal 1709 return isVMerge(N, UnitSize, 8, 24); 1710 else 1711 return false; 1712 } 1713 } 1714 1715 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1716 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1717 /// The ShuffleKind distinguishes between big-endian merges with two 1718 /// different inputs (0), either-endian merges with two identical inputs (1), 1719 /// and little-endian merges with two different inputs (2). For the latter, 1720 /// the input operands are swapped (see PPCInstrAltivec.td). 1721 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1722 unsigned ShuffleKind, SelectionDAG &DAG) { 1723 if (DAG.getDataLayout().isLittleEndian()) { 1724 if (ShuffleKind == 1) // unary 1725 return isVMerge(N, UnitSize, 8, 8); 1726 else if (ShuffleKind == 2) // swapped 1727 return isVMerge(N, UnitSize, 8, 24); 1728 else 1729 return false; 1730 } else { 1731 if (ShuffleKind == 1) // unary 1732 return isVMerge(N, UnitSize, 0, 0); 1733 else if (ShuffleKind == 0) // normal 1734 return isVMerge(N, UnitSize, 0, 16); 1735 else 1736 return false; 1737 } 1738 } 1739 1740 /** 1741 * Common function used to match vmrgew and vmrgow shuffles 1742 * 1743 * The indexOffset determines whether to look for even or odd words in 1744 * the shuffle mask. This is based on the of the endianness of the target 1745 * machine. 1746 * - Little Endian: 1747 * - Use offset of 0 to check for odd elements 1748 * - Use offset of 4 to check for even elements 1749 * - Big Endian: 1750 * - Use offset of 0 to check for even elements 1751 * - Use offset of 4 to check for odd elements 1752 * A detailed description of the vector element ordering for little endian and 1753 * big endian can be found at 1754 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1755 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1756 * compiler differences mean to you 1757 * 1758 * The mask to the shuffle vector instruction specifies the indices of the 1759 * elements from the two input vectors to place in the result. The elements are 1760 * numbered in array-access order, starting with the first vector. These vectors 1761 * are always of type v16i8, thus each vector will contain 16 elements of size 1762 * 8. More info on the shuffle vector can be found in the 1763 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1764 * Language Reference. 1765 * 1766 * The RHSStartValue indicates whether the same input vectors are used (unary) 1767 * or two different input vectors are used, based on the following: 1768 * - If the instruction uses the same vector for both inputs, the range of the 1769 * indices will be 0 to 15. In this case, the RHSStart value passed should 1770 * be 0. 1771 * - If the instruction has two different vectors then the range of the 1772 * indices will be 0 to 31. In this case, the RHSStart value passed should 1773 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1774 * to 31 specify elements in the second vector). 1775 * 1776 * \param[in] N The shuffle vector SD Node to analyze 1777 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1778 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1779 * vector to the shuffle_vector instruction 1780 * \return true iff this shuffle vector represents an even or odd word merge 1781 */ 1782 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1783 unsigned RHSStartValue) { 1784 if (N->getValueType(0) != MVT::v16i8) 1785 return false; 1786 1787 for (unsigned i = 0; i < 2; ++i) 1788 for (unsigned j = 0; j < 4; ++j) 1789 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1790 i*RHSStartValue+j+IndexOffset) || 1791 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1792 i*RHSStartValue+j+IndexOffset+8)) 1793 return false; 1794 return true; 1795 } 1796 1797 /** 1798 * Determine if the specified shuffle mask is suitable for the vmrgew or 1799 * vmrgow instructions. 1800 * 1801 * \param[in] N The shuffle vector SD Node to analyze 1802 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1803 * \param[in] ShuffleKind Identify the type of merge: 1804 * - 0 = big-endian merge with two different inputs; 1805 * - 1 = either-endian merge with two identical inputs; 1806 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1807 * little-endian merges). 1808 * \param[in] DAG The current SelectionDAG 1809 * \return true iff this shuffle mask 1810 */ 1811 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1812 unsigned ShuffleKind, SelectionDAG &DAG) { 1813 if (DAG.getDataLayout().isLittleEndian()) { 1814 unsigned indexOffset = CheckEven ? 4 : 0; 1815 if (ShuffleKind == 1) // Unary 1816 return isVMerge(N, indexOffset, 0); 1817 else if (ShuffleKind == 2) // swapped 1818 return isVMerge(N, indexOffset, 16); 1819 else 1820 return false; 1821 } 1822 else { 1823 unsigned indexOffset = CheckEven ? 0 : 4; 1824 if (ShuffleKind == 1) // Unary 1825 return isVMerge(N, indexOffset, 0); 1826 else if (ShuffleKind == 0) // Normal 1827 return isVMerge(N, indexOffset, 16); 1828 else 1829 return false; 1830 } 1831 return false; 1832 } 1833 1834 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1835 /// amount, otherwise return -1. 1836 /// The ShuffleKind distinguishes between big-endian operations with two 1837 /// different inputs (0), either-endian operations with two identical inputs 1838 /// (1), and little-endian operations with two different inputs (2). For the 1839 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1840 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1841 SelectionDAG &DAG) { 1842 if (N->getValueType(0) != MVT::v16i8) 1843 return -1; 1844 1845 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1846 1847 // Find the first non-undef value in the shuffle mask. 1848 unsigned i; 1849 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1850 /*search*/; 1851 1852 if (i == 16) return -1; // all undef. 1853 1854 // Otherwise, check to see if the rest of the elements are consecutively 1855 // numbered from this value. 1856 unsigned ShiftAmt = SVOp->getMaskElt(i); 1857 if (ShiftAmt < i) return -1; 1858 1859 ShiftAmt -= i; 1860 bool isLE = DAG.getDataLayout().isLittleEndian(); 1861 1862 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1863 // Check the rest of the elements to see if they are consecutive. 1864 for (++i; i != 16; ++i) 1865 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1866 return -1; 1867 } else if (ShuffleKind == 1) { 1868 // Check the rest of the elements to see if they are consecutive. 1869 for (++i; i != 16; ++i) 1870 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1871 return -1; 1872 } else 1873 return -1; 1874 1875 if (isLE) 1876 ShiftAmt = 16 - ShiftAmt; 1877 1878 return ShiftAmt; 1879 } 1880 1881 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1882 /// specifies a splat of a single element that is suitable for input to 1883 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1884 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1885 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1886 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1887 1888 // The consecutive indices need to specify an element, not part of two 1889 // different elements. So abandon ship early if this isn't the case. 1890 if (N->getMaskElt(0) % EltSize != 0) 1891 return false; 1892 1893 // This is a splat operation if each element of the permute is the same, and 1894 // if the value doesn't reference the second vector. 1895 unsigned ElementBase = N->getMaskElt(0); 1896 1897 // FIXME: Handle UNDEF elements too! 1898 if (ElementBase >= 16) 1899 return false; 1900 1901 // Check that the indices are consecutive, in the case of a multi-byte element 1902 // splatted with a v16i8 mask. 1903 for (unsigned i = 1; i != EltSize; ++i) 1904 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1905 return false; 1906 1907 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1908 if (N->getMaskElt(i) < 0) continue; 1909 for (unsigned j = 0; j != EltSize; ++j) 1910 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1911 return false; 1912 } 1913 return true; 1914 } 1915 1916 /// Check that the mask is shuffling N byte elements. Within each N byte 1917 /// element of the mask, the indices could be either in increasing or 1918 /// decreasing order as long as they are consecutive. 1919 /// \param[in] N the shuffle vector SD Node to analyze 1920 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1921 /// Word/DoubleWord/QuadWord). 1922 /// \param[in] StepLen the delta indices number among the N byte element, if 1923 /// the mask is in increasing/decreasing order then it is 1/-1. 1924 /// \return true iff the mask is shuffling N byte elements. 1925 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1926 int StepLen) { 1927 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1928 "Unexpected element width."); 1929 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1930 1931 unsigned NumOfElem = 16 / Width; 1932 unsigned MaskVal[16]; // Width is never greater than 16 1933 for (unsigned i = 0; i < NumOfElem; ++i) { 1934 MaskVal[0] = N->getMaskElt(i * Width); 1935 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1936 return false; 1937 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1938 return false; 1939 } 1940 1941 for (unsigned int j = 1; j < Width; ++j) { 1942 MaskVal[j] = N->getMaskElt(i * Width + j); 1943 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1944 return false; 1945 } 1946 } 1947 } 1948 1949 return true; 1950 } 1951 1952 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1953 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1954 if (!isNByteElemShuffleMask(N, 4, 1)) 1955 return false; 1956 1957 // Now we look at mask elements 0,4,8,12 1958 unsigned M0 = N->getMaskElt(0) / 4; 1959 unsigned M1 = N->getMaskElt(4) / 4; 1960 unsigned M2 = N->getMaskElt(8) / 4; 1961 unsigned M3 = N->getMaskElt(12) / 4; 1962 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1963 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1964 1965 // Below, let H and L be arbitrary elements of the shuffle mask 1966 // where H is in the range [4,7] and L is in the range [0,3]. 1967 // H, 1, 2, 3 or L, 5, 6, 7 1968 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1969 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1970 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1971 InsertAtByte = IsLE ? 12 : 0; 1972 Swap = M0 < 4; 1973 return true; 1974 } 1975 // 0, H, 2, 3 or 4, L, 6, 7 1976 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1977 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1978 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1979 InsertAtByte = IsLE ? 8 : 4; 1980 Swap = M1 < 4; 1981 return true; 1982 } 1983 // 0, 1, H, 3 or 4, 5, L, 7 1984 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1985 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1986 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1987 InsertAtByte = IsLE ? 4 : 8; 1988 Swap = M2 < 4; 1989 return true; 1990 } 1991 // 0, 1, 2, H or 4, 5, 6, L 1992 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1993 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1994 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1995 InsertAtByte = IsLE ? 0 : 12; 1996 Swap = M3 < 4; 1997 return true; 1998 } 1999 2000 // If both vector operands for the shuffle are the same vector, the mask will 2001 // contain only elements from the first one and the second one will be undef. 2002 if (N->getOperand(1).isUndef()) { 2003 ShiftElts = 0; 2004 Swap = true; 2005 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2006 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2007 InsertAtByte = IsLE ? 12 : 0; 2008 return true; 2009 } 2010 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2011 InsertAtByte = IsLE ? 8 : 4; 2012 return true; 2013 } 2014 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2015 InsertAtByte = IsLE ? 4 : 8; 2016 return true; 2017 } 2018 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2019 InsertAtByte = IsLE ? 0 : 12; 2020 return true; 2021 } 2022 } 2023 2024 return false; 2025 } 2026 2027 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2028 bool &Swap, bool IsLE) { 2029 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2030 // Ensure each byte index of the word is consecutive. 2031 if (!isNByteElemShuffleMask(N, 4, 1)) 2032 return false; 2033 2034 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2035 unsigned M0 = N->getMaskElt(0) / 4; 2036 unsigned M1 = N->getMaskElt(4) / 4; 2037 unsigned M2 = N->getMaskElt(8) / 4; 2038 unsigned M3 = N->getMaskElt(12) / 4; 2039 2040 // If both vector operands for the shuffle are the same vector, the mask will 2041 // contain only elements from the first one and the second one will be undef. 2042 if (N->getOperand(1).isUndef()) { 2043 assert(M0 < 4 && "Indexing into an undef vector?"); 2044 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2045 return false; 2046 2047 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2048 Swap = false; 2049 return true; 2050 } 2051 2052 // Ensure each word index of the ShuffleVector Mask is consecutive. 2053 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2054 return false; 2055 2056 if (IsLE) { 2057 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2058 // Input vectors don't need to be swapped if the leading element 2059 // of the result is one of the 3 left elements of the second vector 2060 // (or if there is no shift to be done at all). 2061 Swap = false; 2062 ShiftElts = (8 - M0) % 8; 2063 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2064 // Input vectors need to be swapped if the leading element 2065 // of the result is one of the 3 left elements of the first vector 2066 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2067 Swap = true; 2068 ShiftElts = (4 - M0) % 4; 2069 } 2070 2071 return true; 2072 } else { // BE 2073 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2074 // Input vectors don't need to be swapped if the leading element 2075 // of the result is one of the 4 elements of the first vector. 2076 Swap = false; 2077 ShiftElts = M0; 2078 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2079 // Input vectors need to be swapped if the leading element 2080 // of the result is one of the 4 elements of the right vector. 2081 Swap = true; 2082 ShiftElts = M0 - 4; 2083 } 2084 2085 return true; 2086 } 2087 } 2088 2089 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2090 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2091 2092 if (!isNByteElemShuffleMask(N, Width, -1)) 2093 return false; 2094 2095 for (int i = 0; i < 16; i += Width) 2096 if (N->getMaskElt(i) != i + Width - 1) 2097 return false; 2098 2099 return true; 2100 } 2101 2102 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2103 return isXXBRShuffleMaskHelper(N, 2); 2104 } 2105 2106 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2107 return isXXBRShuffleMaskHelper(N, 4); 2108 } 2109 2110 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2111 return isXXBRShuffleMaskHelper(N, 8); 2112 } 2113 2114 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2115 return isXXBRShuffleMaskHelper(N, 16); 2116 } 2117 2118 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2119 /// if the inputs to the instruction should be swapped and set \p DM to the 2120 /// value for the immediate. 2121 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2122 /// AND element 0 of the result comes from the first input (LE) or second input 2123 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2124 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2125 /// mask. 2126 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2127 bool &Swap, bool IsLE) { 2128 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2129 2130 // Ensure each byte index of the double word is consecutive. 2131 if (!isNByteElemShuffleMask(N, 8, 1)) 2132 return false; 2133 2134 unsigned M0 = N->getMaskElt(0) / 8; 2135 unsigned M1 = N->getMaskElt(8) / 8; 2136 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2137 2138 // If both vector operands for the shuffle are the same vector, the mask will 2139 // contain only elements from the first one and the second one will be undef. 2140 if (N->getOperand(1).isUndef()) { 2141 if ((M0 | M1) < 2) { 2142 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2143 Swap = false; 2144 return true; 2145 } else 2146 return false; 2147 } 2148 2149 if (IsLE) { 2150 if (M0 > 1 && M1 < 2) { 2151 Swap = false; 2152 } else if (M0 < 2 && M1 > 1) { 2153 M0 = (M0 + 2) % 4; 2154 M1 = (M1 + 2) % 4; 2155 Swap = true; 2156 } else 2157 return false; 2158 2159 // Note: if control flow comes here that means Swap is already set above 2160 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2161 return true; 2162 } else { // BE 2163 if (M0 < 2 && M1 > 1) { 2164 Swap = false; 2165 } else if (M0 > 1 && M1 < 2) { 2166 M0 = (M0 + 2) % 4; 2167 M1 = (M1 + 2) % 4; 2168 Swap = true; 2169 } else 2170 return false; 2171 2172 // Note: if control flow comes here that means Swap is already set above 2173 DM = (M0 << 1) + (M1 & 1); 2174 return true; 2175 } 2176 } 2177 2178 2179 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2180 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2181 /// elements are counted from the left of the vector register). 2182 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2183 SelectionDAG &DAG) { 2184 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2185 assert(isSplatShuffleMask(SVOp, EltSize)); 2186 if (DAG.getDataLayout().isLittleEndian()) 2187 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2188 else 2189 return SVOp->getMaskElt(0) / EltSize; 2190 } 2191 2192 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2193 /// by using a vspltis[bhw] instruction of the specified element size, return 2194 /// the constant being splatted. The ByteSize field indicates the number of 2195 /// bytes of each element [124] -> [bhw]. 2196 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2197 SDValue OpVal(nullptr, 0); 2198 2199 // If ByteSize of the splat is bigger than the element size of the 2200 // build_vector, then we have a case where we are checking for a splat where 2201 // multiple elements of the buildvector are folded together into a single 2202 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2203 unsigned EltSize = 16/N->getNumOperands(); 2204 if (EltSize < ByteSize) { 2205 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2206 SDValue UniquedVals[4]; 2207 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2208 2209 // See if all of the elements in the buildvector agree across. 2210 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2211 if (N->getOperand(i).isUndef()) continue; 2212 // If the element isn't a constant, bail fully out. 2213 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2214 2215 if (!UniquedVals[i&(Multiple-1)].getNode()) 2216 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2217 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2218 return SDValue(); // no match. 2219 } 2220 2221 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2222 // either constant or undef values that are identical for each chunk. See 2223 // if these chunks can form into a larger vspltis*. 2224 2225 // Check to see if all of the leading entries are either 0 or -1. If 2226 // neither, then this won't fit into the immediate field. 2227 bool LeadingZero = true; 2228 bool LeadingOnes = true; 2229 for (unsigned i = 0; i != Multiple-1; ++i) { 2230 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2231 2232 LeadingZero &= isNullConstant(UniquedVals[i]); 2233 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2234 } 2235 // Finally, check the least significant entry. 2236 if (LeadingZero) { 2237 if (!UniquedVals[Multiple-1].getNode()) 2238 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2239 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2240 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2241 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2242 } 2243 if (LeadingOnes) { 2244 if (!UniquedVals[Multiple-1].getNode()) 2245 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2246 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2247 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2248 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2249 } 2250 2251 return SDValue(); 2252 } 2253 2254 // Check to see if this buildvec has a single non-undef value in its elements. 2255 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2256 if (N->getOperand(i).isUndef()) continue; 2257 if (!OpVal.getNode()) 2258 OpVal = N->getOperand(i); 2259 else if (OpVal != N->getOperand(i)) 2260 return SDValue(); 2261 } 2262 2263 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2264 2265 unsigned ValSizeInBytes = EltSize; 2266 uint64_t Value = 0; 2267 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2268 Value = CN->getZExtValue(); 2269 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2270 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2271 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2272 } 2273 2274 // If the splat value is larger than the element value, then we can never do 2275 // this splat. The only case that we could fit the replicated bits into our 2276 // immediate field for would be zero, and we prefer to use vxor for it. 2277 if (ValSizeInBytes < ByteSize) return SDValue(); 2278 2279 // If the element value is larger than the splat value, check if it consists 2280 // of a repeated bit pattern of size ByteSize. 2281 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2282 return SDValue(); 2283 2284 // Properly sign extend the value. 2285 int MaskVal = SignExtend32(Value, ByteSize * 8); 2286 2287 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2288 if (MaskVal == 0) return SDValue(); 2289 2290 // Finally, if this value fits in a 5 bit sext field, return it 2291 if (SignExtend32<5>(MaskVal) == MaskVal) 2292 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2293 return SDValue(); 2294 } 2295 2296 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2297 /// amount, otherwise return -1. 2298 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2299 EVT VT = N->getValueType(0); 2300 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2301 return -1; 2302 2303 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2304 2305 // Find the first non-undef value in the shuffle mask. 2306 unsigned i; 2307 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2308 /*search*/; 2309 2310 if (i == 4) return -1; // all undef. 2311 2312 // Otherwise, check to see if the rest of the elements are consecutively 2313 // numbered from this value. 2314 unsigned ShiftAmt = SVOp->getMaskElt(i); 2315 if (ShiftAmt < i) return -1; 2316 ShiftAmt -= i; 2317 2318 // Check the rest of the elements to see if they are consecutive. 2319 for (++i; i != 4; ++i) 2320 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2321 return -1; 2322 2323 return ShiftAmt; 2324 } 2325 2326 //===----------------------------------------------------------------------===// 2327 // Addressing Mode Selection 2328 //===----------------------------------------------------------------------===// 2329 2330 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2331 /// or 64-bit immediate, and if the value can be accurately represented as a 2332 /// sign extension from a 16-bit value. If so, this returns true and the 2333 /// immediate. 2334 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2335 if (!isa<ConstantSDNode>(N)) 2336 return false; 2337 2338 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2339 if (N->getValueType(0) == MVT::i32) 2340 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2341 else 2342 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2343 } 2344 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2345 return isIntS16Immediate(Op.getNode(), Imm); 2346 } 2347 2348 2349 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2350 /// be represented as an indexed [r+r] operation. 2351 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2352 SDValue &Index, 2353 SelectionDAG &DAG) const { 2354 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2355 UI != E; ++UI) { 2356 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2357 if (Memop->getMemoryVT() == MVT::f64) { 2358 Base = N.getOperand(0); 2359 Index = N.getOperand(1); 2360 return true; 2361 } 2362 } 2363 } 2364 return false; 2365 } 2366 2367 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2368 /// can be represented as an indexed [r+r] operation. Returns false if it 2369 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2370 /// non-zero and N can be represented by a base register plus a signed 16-bit 2371 /// displacement, make a more precise judgement by checking (displacement % \p 2372 /// EncodingAlignment). 2373 bool PPCTargetLowering::SelectAddressRegReg( 2374 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2375 MaybeAlign EncodingAlignment) const { 2376 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2377 // a [pc+imm]. 2378 if (SelectAddressPCRel(N, Base)) 2379 return false; 2380 2381 int16_t Imm = 0; 2382 if (N.getOpcode() == ISD::ADD) { 2383 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2384 // SPE load/store can only handle 8-bit offsets. 2385 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2386 return true; 2387 if (isIntS16Immediate(N.getOperand(1), Imm) && 2388 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2389 return false; // r+i 2390 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2391 return false; // r+i 2392 2393 Base = N.getOperand(0); 2394 Index = N.getOperand(1); 2395 return true; 2396 } else if (N.getOpcode() == ISD::OR) { 2397 if (isIntS16Immediate(N.getOperand(1), Imm) && 2398 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2399 return false; // r+i can fold it if we can. 2400 2401 // If this is an or of disjoint bitfields, we can codegen this as an add 2402 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2403 // disjoint. 2404 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2405 2406 if (LHSKnown.Zero.getBoolValue()) { 2407 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2408 // If all of the bits are known zero on the LHS or RHS, the add won't 2409 // carry. 2410 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2411 Base = N.getOperand(0); 2412 Index = N.getOperand(1); 2413 return true; 2414 } 2415 } 2416 } 2417 2418 return false; 2419 } 2420 2421 // If we happen to be doing an i64 load or store into a stack slot that has 2422 // less than a 4-byte alignment, then the frame-index elimination may need to 2423 // use an indexed load or store instruction (because the offset may not be a 2424 // multiple of 4). The extra register needed to hold the offset comes from the 2425 // register scavenger, and it is possible that the scavenger will need to use 2426 // an emergency spill slot. As a result, we need to make sure that a spill slot 2427 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2428 // stack slot. 2429 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2430 // FIXME: This does not handle the LWA case. 2431 if (VT != MVT::i64) 2432 return; 2433 2434 // NOTE: We'll exclude negative FIs here, which come from argument 2435 // lowering, because there are no known test cases triggering this problem 2436 // using packed structures (or similar). We can remove this exclusion if 2437 // we find such a test case. The reason why this is so test-case driven is 2438 // because this entire 'fixup' is only to prevent crashes (from the 2439 // register scavenger) on not-really-valid inputs. For example, if we have: 2440 // %a = alloca i1 2441 // %b = bitcast i1* %a to i64* 2442 // store i64* a, i64 b 2443 // then the store should really be marked as 'align 1', but is not. If it 2444 // were marked as 'align 1' then the indexed form would have been 2445 // instruction-selected initially, and the problem this 'fixup' is preventing 2446 // won't happen regardless. 2447 if (FrameIdx < 0) 2448 return; 2449 2450 MachineFunction &MF = DAG.getMachineFunction(); 2451 MachineFrameInfo &MFI = MF.getFrameInfo(); 2452 2453 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2454 return; 2455 2456 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2457 FuncInfo->setHasNonRISpills(); 2458 } 2459 2460 /// Returns true if the address N can be represented by a base register plus 2461 /// a signed 16-bit displacement [r+imm], and if it is not better 2462 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2463 /// displacements that are multiples of that value. 2464 bool PPCTargetLowering::SelectAddressRegImm( 2465 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2466 MaybeAlign EncodingAlignment) const { 2467 // FIXME dl should come from parent load or store, not from address 2468 SDLoc dl(N); 2469 2470 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2471 // a [pc+imm]. 2472 if (SelectAddressPCRel(N, Base)) 2473 return false; 2474 2475 // If this can be more profitably realized as r+r, fail. 2476 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2477 return false; 2478 2479 if (N.getOpcode() == ISD::ADD) { 2480 int16_t imm = 0; 2481 if (isIntS16Immediate(N.getOperand(1), imm) && 2482 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2483 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2484 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2485 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2486 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2487 } else { 2488 Base = N.getOperand(0); 2489 } 2490 return true; // [r+i] 2491 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2492 // Match LOAD (ADD (X, Lo(G))). 2493 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2494 && "Cannot handle constant offsets yet!"); 2495 Disp = N.getOperand(1).getOperand(0); // The global address. 2496 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2497 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2498 Disp.getOpcode() == ISD::TargetConstantPool || 2499 Disp.getOpcode() == ISD::TargetJumpTable); 2500 Base = N.getOperand(0); 2501 return true; // [&g+r] 2502 } 2503 } else if (N.getOpcode() == ISD::OR) { 2504 int16_t imm = 0; 2505 if (isIntS16Immediate(N.getOperand(1), imm) && 2506 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2507 // If this is an or of disjoint bitfields, we can codegen this as an add 2508 // (for better address arithmetic) if the LHS and RHS of the OR are 2509 // provably disjoint. 2510 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2511 2512 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2513 // If all of the bits are known zero on the LHS or RHS, the add won't 2514 // carry. 2515 if (FrameIndexSDNode *FI = 2516 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2517 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2518 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2519 } else { 2520 Base = N.getOperand(0); 2521 } 2522 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2523 return true; 2524 } 2525 } 2526 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2527 // Loading from a constant address. 2528 2529 // If this address fits entirely in a 16-bit sext immediate field, codegen 2530 // this as "d, 0" 2531 int16_t Imm; 2532 if (isIntS16Immediate(CN, Imm) && 2533 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2534 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2535 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2536 CN->getValueType(0)); 2537 return true; 2538 } 2539 2540 // Handle 32-bit sext immediates with LIS + addr mode. 2541 if ((CN->getValueType(0) == MVT::i32 || 2542 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2543 (!EncodingAlignment || 2544 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2545 int Addr = (int)CN->getZExtValue(); 2546 2547 // Otherwise, break this down into an LIS + disp. 2548 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2549 2550 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2551 MVT::i32); 2552 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2553 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2554 return true; 2555 } 2556 } 2557 2558 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2559 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2560 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2561 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2562 } else 2563 Base = N; 2564 return true; // [r+0] 2565 } 2566 2567 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2568 /// represented as an indexed [r+r] operation. 2569 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2570 SDValue &Index, 2571 SelectionDAG &DAG) const { 2572 // Check to see if we can easily represent this as an [r+r] address. This 2573 // will fail if it thinks that the address is more profitably represented as 2574 // reg+imm, e.g. where imm = 0. 2575 if (SelectAddressRegReg(N, Base, Index, DAG)) 2576 return true; 2577 2578 // If the address is the result of an add, we will utilize the fact that the 2579 // address calculation includes an implicit add. However, we can reduce 2580 // register pressure if we do not materialize a constant just for use as the 2581 // index register. We only get rid of the add if it is not an add of a 2582 // value and a 16-bit signed constant and both have a single use. 2583 int16_t imm = 0; 2584 if (N.getOpcode() == ISD::ADD && 2585 (!isIntS16Immediate(N.getOperand(1), imm) || 2586 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2587 Base = N.getOperand(0); 2588 Index = N.getOperand(1); 2589 return true; 2590 } 2591 2592 // Otherwise, do it the hard way, using R0 as the base register. 2593 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2594 N.getValueType()); 2595 Index = N; 2596 return true; 2597 } 2598 2599 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2600 Ty *PCRelCand = dyn_cast<Ty>(N); 2601 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2602 } 2603 2604 /// Returns true if this address is a PC Relative address. 2605 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2606 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2607 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2608 // This is a materialize PC Relative node. Always select this as PC Relative. 2609 Base = N; 2610 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2611 return true; 2612 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2613 isValidPCRelNode<GlobalAddressSDNode>(N) || 2614 isValidPCRelNode<JumpTableSDNode>(N) || 2615 isValidPCRelNode<BlockAddressSDNode>(N)) 2616 return true; 2617 return false; 2618 } 2619 2620 /// Returns true if we should use a direct load into vector instruction 2621 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2622 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2623 2624 // If there are any other uses other than scalar to vector, then we should 2625 // keep it as a scalar load -> direct move pattern to prevent multiple 2626 // loads. 2627 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2628 if (!LD) 2629 return false; 2630 2631 EVT MemVT = LD->getMemoryVT(); 2632 if (!MemVT.isSimple()) 2633 return false; 2634 switch(MemVT.getSimpleVT().SimpleTy) { 2635 case MVT::i64: 2636 break; 2637 case MVT::i32: 2638 if (!ST.hasP8Vector()) 2639 return false; 2640 break; 2641 case MVT::i16: 2642 case MVT::i8: 2643 if (!ST.hasP9Vector()) 2644 return false; 2645 break; 2646 default: 2647 return false; 2648 } 2649 2650 SDValue LoadedVal(N, 0); 2651 if (!LoadedVal.hasOneUse()) 2652 return false; 2653 2654 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2655 UI != UE; ++UI) 2656 if (UI.getUse().get().getResNo() == 0 && 2657 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2658 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2659 return false; 2660 2661 return true; 2662 } 2663 2664 /// getPreIndexedAddressParts - returns true by value, base pointer and 2665 /// offset pointer and addressing mode by reference if the node's address 2666 /// can be legally represented as pre-indexed load / store address. 2667 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2668 SDValue &Offset, 2669 ISD::MemIndexedMode &AM, 2670 SelectionDAG &DAG) const { 2671 if (DisablePPCPreinc) return false; 2672 2673 bool isLoad = true; 2674 SDValue Ptr; 2675 EVT VT; 2676 unsigned Alignment; 2677 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2678 Ptr = LD->getBasePtr(); 2679 VT = LD->getMemoryVT(); 2680 Alignment = LD->getAlignment(); 2681 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2682 Ptr = ST->getBasePtr(); 2683 VT = ST->getMemoryVT(); 2684 Alignment = ST->getAlignment(); 2685 isLoad = false; 2686 } else 2687 return false; 2688 2689 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2690 // instructions because we can fold these into a more efficient instruction 2691 // instead, (such as LXSD). 2692 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2693 return false; 2694 } 2695 2696 // PowerPC doesn't have preinc load/store instructions for vectors 2697 if (VT.isVector()) 2698 return false; 2699 2700 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2701 // Common code will reject creating a pre-inc form if the base pointer 2702 // is a frame index, or if N is a store and the base pointer is either 2703 // the same as or a predecessor of the value being stored. Check for 2704 // those situations here, and try with swapped Base/Offset instead. 2705 bool Swap = false; 2706 2707 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2708 Swap = true; 2709 else if (!isLoad) { 2710 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2711 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2712 Swap = true; 2713 } 2714 2715 if (Swap) 2716 std::swap(Base, Offset); 2717 2718 AM = ISD::PRE_INC; 2719 return true; 2720 } 2721 2722 // LDU/STU can only handle immediates that are a multiple of 4. 2723 if (VT != MVT::i64) { 2724 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2725 return false; 2726 } else { 2727 // LDU/STU need an address with at least 4-byte alignment. 2728 if (Alignment < 4) 2729 return false; 2730 2731 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2732 return false; 2733 } 2734 2735 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2736 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2737 // sext i32 to i64 when addr mode is r+i. 2738 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2739 LD->getExtensionType() == ISD::SEXTLOAD && 2740 isa<ConstantSDNode>(Offset)) 2741 return false; 2742 } 2743 2744 AM = ISD::PRE_INC; 2745 return true; 2746 } 2747 2748 //===----------------------------------------------------------------------===// 2749 // LowerOperation implementation 2750 //===----------------------------------------------------------------------===// 2751 2752 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2753 /// and LoOpFlags to the target MO flags. 2754 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2755 unsigned &HiOpFlags, unsigned &LoOpFlags, 2756 const GlobalValue *GV = nullptr) { 2757 HiOpFlags = PPCII::MO_HA; 2758 LoOpFlags = PPCII::MO_LO; 2759 2760 // Don't use the pic base if not in PIC relocation model. 2761 if (IsPIC) { 2762 HiOpFlags |= PPCII::MO_PIC_FLAG; 2763 LoOpFlags |= PPCII::MO_PIC_FLAG; 2764 } 2765 } 2766 2767 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2768 SelectionDAG &DAG) { 2769 SDLoc DL(HiPart); 2770 EVT PtrVT = HiPart.getValueType(); 2771 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2772 2773 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2774 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2775 2776 // With PIC, the first instruction is actually "GR+hi(&G)". 2777 if (isPIC) 2778 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2779 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2780 2781 // Generate non-pic code that has direct accesses to the constant pool. 2782 // The address of the global is just (hi(&g)+lo(&g)). 2783 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2784 } 2785 2786 static void setUsesTOCBasePtr(MachineFunction &MF) { 2787 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2788 FuncInfo->setUsesTOCBasePtr(); 2789 } 2790 2791 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2792 setUsesTOCBasePtr(DAG.getMachineFunction()); 2793 } 2794 2795 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2796 SDValue GA) const { 2797 const bool Is64Bit = Subtarget.isPPC64(); 2798 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2799 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2800 : Subtarget.isAIXABI() 2801 ? DAG.getRegister(PPC::R2, VT) 2802 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2803 SDValue Ops[] = { GA, Reg }; 2804 return DAG.getMemIntrinsicNode( 2805 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2806 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2807 MachineMemOperand::MOLoad); 2808 } 2809 2810 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2811 SelectionDAG &DAG) const { 2812 EVT PtrVT = Op.getValueType(); 2813 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2814 const Constant *C = CP->getConstVal(); 2815 2816 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2817 // The actual address of the GlobalValue is stored in the TOC. 2818 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2819 if (Subtarget.isUsingPCRelativeCalls()) { 2820 SDLoc DL(CP); 2821 EVT Ty = getPointerTy(DAG.getDataLayout()); 2822 SDValue ConstPool = DAG.getTargetConstantPool( 2823 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2824 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2825 } 2826 setUsesTOCBasePtr(DAG); 2827 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2828 return getTOCEntry(DAG, SDLoc(CP), GA); 2829 } 2830 2831 unsigned MOHiFlag, MOLoFlag; 2832 bool IsPIC = isPositionIndependent(); 2833 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2834 2835 if (IsPIC && Subtarget.isSVR4ABI()) { 2836 SDValue GA = 2837 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2838 return getTOCEntry(DAG, SDLoc(CP), GA); 2839 } 2840 2841 SDValue CPIHi = 2842 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2843 SDValue CPILo = 2844 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2845 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2846 } 2847 2848 // For 64-bit PowerPC, prefer the more compact relative encodings. 2849 // This trades 32 bits per jump table entry for one or two instructions 2850 // on the jump site. 2851 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2852 if (isJumpTableRelative()) 2853 return MachineJumpTableInfo::EK_LabelDifference32; 2854 2855 return TargetLowering::getJumpTableEncoding(); 2856 } 2857 2858 bool PPCTargetLowering::isJumpTableRelative() const { 2859 if (UseAbsoluteJumpTables) 2860 return false; 2861 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2862 return true; 2863 return TargetLowering::isJumpTableRelative(); 2864 } 2865 2866 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2867 SelectionDAG &DAG) const { 2868 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2869 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2870 2871 switch (getTargetMachine().getCodeModel()) { 2872 case CodeModel::Small: 2873 case CodeModel::Medium: 2874 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2875 default: 2876 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2877 getPointerTy(DAG.getDataLayout())); 2878 } 2879 } 2880 2881 const MCExpr * 2882 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2883 unsigned JTI, 2884 MCContext &Ctx) const { 2885 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2886 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2887 2888 switch (getTargetMachine().getCodeModel()) { 2889 case CodeModel::Small: 2890 case CodeModel::Medium: 2891 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2892 default: 2893 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2894 } 2895 } 2896 2897 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2898 EVT PtrVT = Op.getValueType(); 2899 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2900 2901 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2902 if (Subtarget.isUsingPCRelativeCalls()) { 2903 SDLoc DL(JT); 2904 EVT Ty = getPointerTy(DAG.getDataLayout()); 2905 SDValue GA = 2906 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2907 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2908 return MatAddr; 2909 } 2910 2911 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2912 // The actual address of the GlobalValue is stored in the TOC. 2913 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2914 setUsesTOCBasePtr(DAG); 2915 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2916 return getTOCEntry(DAG, SDLoc(JT), GA); 2917 } 2918 2919 unsigned MOHiFlag, MOLoFlag; 2920 bool IsPIC = isPositionIndependent(); 2921 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2922 2923 if (IsPIC && Subtarget.isSVR4ABI()) { 2924 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2925 PPCII::MO_PIC_FLAG); 2926 return getTOCEntry(DAG, SDLoc(GA), GA); 2927 } 2928 2929 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2930 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2931 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2932 } 2933 2934 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2935 SelectionDAG &DAG) const { 2936 EVT PtrVT = Op.getValueType(); 2937 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2938 const BlockAddress *BA = BASDN->getBlockAddress(); 2939 2940 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2941 if (Subtarget.isUsingPCRelativeCalls()) { 2942 SDLoc DL(BASDN); 2943 EVT Ty = getPointerTy(DAG.getDataLayout()); 2944 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2945 PPCII::MO_PCREL_FLAG); 2946 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2947 return MatAddr; 2948 } 2949 2950 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2951 // The actual BlockAddress is stored in the TOC. 2952 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2953 setUsesTOCBasePtr(DAG); 2954 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2955 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2956 } 2957 2958 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2959 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2960 return getTOCEntry( 2961 DAG, SDLoc(BASDN), 2962 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2963 2964 unsigned MOHiFlag, MOLoFlag; 2965 bool IsPIC = isPositionIndependent(); 2966 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2967 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2968 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2969 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2970 } 2971 2972 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2973 SelectionDAG &DAG) const { 2974 // FIXME: TLS addresses currently use medium model code sequences, 2975 // which is the most useful form. Eventually support for small and 2976 // large models could be added if users need it, at the cost of 2977 // additional complexity. 2978 if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS) 2979 report_fatal_error("Thread local storage is not supported with pc-relative" 2980 " addressing - please compile with -mno-pcrel"); 2981 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2982 if (DAG.getTarget().useEmulatedTLS()) 2983 return LowerToTLSEmulatedModel(GA, DAG); 2984 2985 SDLoc dl(GA); 2986 const GlobalValue *GV = GA->getGlobal(); 2987 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2988 bool is64bit = Subtarget.isPPC64(); 2989 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2990 PICLevel::Level picLevel = M->getPICLevel(); 2991 2992 const TargetMachine &TM = getTargetMachine(); 2993 TLSModel::Model Model = TM.getTLSModel(GV); 2994 2995 if (Model == TLSModel::LocalExec) { 2996 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2997 PPCII::MO_TPREL_HA); 2998 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2999 PPCII::MO_TPREL_LO); 3000 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3001 : DAG.getRegister(PPC::R2, MVT::i32); 3002 3003 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3004 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3005 } 3006 3007 if (Model == TLSModel::InitialExec) { 3008 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3009 SDValue TGA = DAG.getTargetGlobalAddress( 3010 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3011 SDValue TGATLS = DAG.getTargetGlobalAddress( 3012 GV, dl, PtrVT, 0, 3013 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3014 SDValue TPOffset; 3015 if (IsPCRel) { 3016 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3017 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3018 MachinePointerInfo()); 3019 } else { 3020 SDValue GOTPtr; 3021 if (is64bit) { 3022 setUsesTOCBasePtr(DAG); 3023 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3024 GOTPtr = 3025 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3026 } else { 3027 if (!TM.isPositionIndependent()) 3028 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3029 else if (picLevel == PICLevel::SmallPIC) 3030 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3031 else 3032 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3033 } 3034 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3035 } 3036 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3037 } 3038 3039 if (Model == TLSModel::GeneralDynamic) { 3040 if (Subtarget.isUsingPCRelativeCalls()) { 3041 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3042 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3043 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3044 } 3045 3046 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3047 SDValue GOTPtr; 3048 if (is64bit) { 3049 setUsesTOCBasePtr(DAG); 3050 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3051 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3052 GOTReg, TGA); 3053 } else { 3054 if (picLevel == PICLevel::SmallPIC) 3055 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3056 else 3057 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3058 } 3059 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3060 GOTPtr, TGA, TGA); 3061 } 3062 3063 if (Model == TLSModel::LocalDynamic) { 3064 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3065 SDValue GOTPtr; 3066 if (is64bit) { 3067 setUsesTOCBasePtr(DAG); 3068 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3069 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3070 GOTReg, TGA); 3071 } else { 3072 if (picLevel == PICLevel::SmallPIC) 3073 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3074 else 3075 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3076 } 3077 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3078 PtrVT, GOTPtr, TGA, TGA); 3079 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3080 PtrVT, TLSAddr, TGA); 3081 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3082 } 3083 3084 llvm_unreachable("Unknown TLS model!"); 3085 } 3086 3087 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3088 SelectionDAG &DAG) const { 3089 EVT PtrVT = Op.getValueType(); 3090 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3091 SDLoc DL(GSDN); 3092 const GlobalValue *GV = GSDN->getGlobal(); 3093 3094 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3095 // The actual address of the GlobalValue is stored in the TOC. 3096 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3097 if (Subtarget.isUsingPCRelativeCalls()) { 3098 EVT Ty = getPointerTy(DAG.getDataLayout()); 3099 if (isAccessedAsGotIndirect(Op)) { 3100 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3101 PPCII::MO_PCREL_FLAG | 3102 PPCII::MO_GOT_FLAG); 3103 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3104 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3105 MachinePointerInfo()); 3106 return Load; 3107 } else { 3108 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3109 PPCII::MO_PCREL_FLAG); 3110 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3111 } 3112 } 3113 setUsesTOCBasePtr(DAG); 3114 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3115 return getTOCEntry(DAG, DL, GA); 3116 } 3117 3118 unsigned MOHiFlag, MOLoFlag; 3119 bool IsPIC = isPositionIndependent(); 3120 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3121 3122 if (IsPIC && Subtarget.isSVR4ABI()) { 3123 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3124 GSDN->getOffset(), 3125 PPCII::MO_PIC_FLAG); 3126 return getTOCEntry(DAG, DL, GA); 3127 } 3128 3129 SDValue GAHi = 3130 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3131 SDValue GALo = 3132 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3133 3134 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3135 } 3136 3137 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3138 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3139 SDLoc dl(Op); 3140 3141 if (Op.getValueType() == MVT::v2i64) { 3142 // When the operands themselves are v2i64 values, we need to do something 3143 // special because VSX has no underlying comparison operations for these. 3144 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3145 // Equality can be handled by casting to the legal type for Altivec 3146 // comparisons, everything else needs to be expanded. 3147 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3148 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3149 DAG.getSetCC(dl, MVT::v4i32, 3150 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3151 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3152 CC)); 3153 } 3154 3155 return SDValue(); 3156 } 3157 3158 // We handle most of these in the usual way. 3159 return Op; 3160 } 3161 3162 // If we're comparing for equality to zero, expose the fact that this is 3163 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3164 // fold the new nodes. 3165 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3166 return V; 3167 3168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3169 // Leave comparisons against 0 and -1 alone for now, since they're usually 3170 // optimized. FIXME: revisit this when we can custom lower all setcc 3171 // optimizations. 3172 if (C->isAllOnesValue() || C->isNullValue()) 3173 return SDValue(); 3174 } 3175 3176 // If we have an integer seteq/setne, turn it into a compare against zero 3177 // by xor'ing the rhs with the lhs, which is faster than setting a 3178 // condition register, reading it back out, and masking the correct bit. The 3179 // normal approach here uses sub to do this instead of xor. Using xor exposes 3180 // the result to other bit-twiddling opportunities. 3181 EVT LHSVT = Op.getOperand(0).getValueType(); 3182 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3183 EVT VT = Op.getValueType(); 3184 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3185 Op.getOperand(1)); 3186 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3187 } 3188 return SDValue(); 3189 } 3190 3191 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3192 SDNode *Node = Op.getNode(); 3193 EVT VT = Node->getValueType(0); 3194 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3195 SDValue InChain = Node->getOperand(0); 3196 SDValue VAListPtr = Node->getOperand(1); 3197 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3198 SDLoc dl(Node); 3199 3200 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3201 3202 // gpr_index 3203 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3204 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3205 InChain = GprIndex.getValue(1); 3206 3207 if (VT == MVT::i64) { 3208 // Check if GprIndex is even 3209 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3210 DAG.getConstant(1, dl, MVT::i32)); 3211 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3212 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3213 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3214 DAG.getConstant(1, dl, MVT::i32)); 3215 // Align GprIndex to be even if it isn't 3216 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3217 GprIndex); 3218 } 3219 3220 // fpr index is 1 byte after gpr 3221 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3222 DAG.getConstant(1, dl, MVT::i32)); 3223 3224 // fpr 3225 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3226 FprPtr, MachinePointerInfo(SV), MVT::i8); 3227 InChain = FprIndex.getValue(1); 3228 3229 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3230 DAG.getConstant(8, dl, MVT::i32)); 3231 3232 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3233 DAG.getConstant(4, dl, MVT::i32)); 3234 3235 // areas 3236 SDValue OverflowArea = 3237 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3238 InChain = OverflowArea.getValue(1); 3239 3240 SDValue RegSaveArea = 3241 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3242 InChain = RegSaveArea.getValue(1); 3243 3244 // select overflow_area if index > 8 3245 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3246 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3247 3248 // adjustment constant gpr_index * 4/8 3249 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3250 VT.isInteger() ? GprIndex : FprIndex, 3251 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3252 MVT::i32)); 3253 3254 // OurReg = RegSaveArea + RegConstant 3255 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3256 RegConstant); 3257 3258 // Floating types are 32 bytes into RegSaveArea 3259 if (VT.isFloatingPoint()) 3260 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3261 DAG.getConstant(32, dl, MVT::i32)); 3262 3263 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3264 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3265 VT.isInteger() ? GprIndex : FprIndex, 3266 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3267 MVT::i32)); 3268 3269 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3270 VT.isInteger() ? VAListPtr : FprPtr, 3271 MachinePointerInfo(SV), MVT::i8); 3272 3273 // determine if we should load from reg_save_area or overflow_area 3274 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3275 3276 // increase overflow_area by 4/8 if gpr/fpr > 8 3277 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3278 DAG.getConstant(VT.isInteger() ? 4 : 8, 3279 dl, MVT::i32)); 3280 3281 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3282 OverflowAreaPlusN); 3283 3284 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3285 MachinePointerInfo(), MVT::i32); 3286 3287 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3288 } 3289 3290 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3291 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3292 3293 // We have to copy the entire va_list struct: 3294 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3295 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3296 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3297 false, true, false, MachinePointerInfo(), 3298 MachinePointerInfo()); 3299 } 3300 3301 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3302 SelectionDAG &DAG) const { 3303 if (Subtarget.isAIXABI()) 3304 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3305 3306 return Op.getOperand(0); 3307 } 3308 3309 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3310 SelectionDAG &DAG) const { 3311 if (Subtarget.isAIXABI()) 3312 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3313 3314 SDValue Chain = Op.getOperand(0); 3315 SDValue Trmp = Op.getOperand(1); // trampoline 3316 SDValue FPtr = Op.getOperand(2); // nested function 3317 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3318 SDLoc dl(Op); 3319 3320 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3321 bool isPPC64 = (PtrVT == MVT::i64); 3322 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3323 3324 TargetLowering::ArgListTy Args; 3325 TargetLowering::ArgListEntry Entry; 3326 3327 Entry.Ty = IntPtrTy; 3328 Entry.Node = Trmp; Args.push_back(Entry); 3329 3330 // TrampSize == (isPPC64 ? 48 : 40); 3331 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3332 isPPC64 ? MVT::i64 : MVT::i32); 3333 Args.push_back(Entry); 3334 3335 Entry.Node = FPtr; Args.push_back(Entry); 3336 Entry.Node = Nest; Args.push_back(Entry); 3337 3338 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3339 TargetLowering::CallLoweringInfo CLI(DAG); 3340 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3341 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3342 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3343 3344 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3345 return CallResult.second; 3346 } 3347 3348 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3349 MachineFunction &MF = DAG.getMachineFunction(); 3350 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3351 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3352 3353 SDLoc dl(Op); 3354 3355 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3356 // vastart just stores the address of the VarArgsFrameIndex slot into the 3357 // memory location argument. 3358 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3359 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3360 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3361 MachinePointerInfo(SV)); 3362 } 3363 3364 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3365 // We suppose the given va_list is already allocated. 3366 // 3367 // typedef struct { 3368 // char gpr; /* index into the array of 8 GPRs 3369 // * stored in the register save area 3370 // * gpr=0 corresponds to r3, 3371 // * gpr=1 to r4, etc. 3372 // */ 3373 // char fpr; /* index into the array of 8 FPRs 3374 // * stored in the register save area 3375 // * fpr=0 corresponds to f1, 3376 // * fpr=1 to f2, etc. 3377 // */ 3378 // char *overflow_arg_area; 3379 // /* location on stack that holds 3380 // * the next overflow argument 3381 // */ 3382 // char *reg_save_area; 3383 // /* where r3:r10 and f1:f8 (if saved) 3384 // * are stored 3385 // */ 3386 // } va_list[1]; 3387 3388 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3389 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3390 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3391 PtrVT); 3392 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3393 PtrVT); 3394 3395 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3396 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3397 3398 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3399 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3400 3401 uint64_t FPROffset = 1; 3402 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3403 3404 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3405 3406 // Store first byte : number of int regs 3407 SDValue firstStore = 3408 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3409 MachinePointerInfo(SV), MVT::i8); 3410 uint64_t nextOffset = FPROffset; 3411 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3412 ConstFPROffset); 3413 3414 // Store second byte : number of float regs 3415 SDValue secondStore = 3416 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3417 MachinePointerInfo(SV, nextOffset), MVT::i8); 3418 nextOffset += StackOffset; 3419 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3420 3421 // Store second word : arguments given on stack 3422 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3423 MachinePointerInfo(SV, nextOffset)); 3424 nextOffset += FrameOffset; 3425 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3426 3427 // Store third word : arguments given in registers 3428 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3429 MachinePointerInfo(SV, nextOffset)); 3430 } 3431 3432 /// FPR - The set of FP registers that should be allocated for arguments 3433 /// on Darwin and AIX. 3434 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3435 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3436 PPC::F11, PPC::F12, PPC::F13}; 3437 3438 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3439 /// the stack. 3440 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3441 unsigned PtrByteSize) { 3442 unsigned ArgSize = ArgVT.getStoreSize(); 3443 if (Flags.isByVal()) 3444 ArgSize = Flags.getByValSize(); 3445 3446 // Round up to multiples of the pointer size, except for array members, 3447 // which are always packed. 3448 if (!Flags.isInConsecutiveRegs()) 3449 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3450 3451 return ArgSize; 3452 } 3453 3454 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3455 /// on the stack. 3456 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3457 ISD::ArgFlagsTy Flags, 3458 unsigned PtrByteSize) { 3459 Align Alignment(PtrByteSize); 3460 3461 // Altivec parameters are padded to a 16 byte boundary. 3462 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3463 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3464 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3465 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3466 Alignment = Align(16); 3467 3468 // ByVal parameters are aligned as requested. 3469 if (Flags.isByVal()) { 3470 auto BVAlign = Flags.getNonZeroByValAlign(); 3471 if (BVAlign > PtrByteSize) { 3472 if (BVAlign.value() % PtrByteSize != 0) 3473 llvm_unreachable( 3474 "ByVal alignment is not a multiple of the pointer size"); 3475 3476 Alignment = BVAlign; 3477 } 3478 } 3479 3480 // Array members are always packed to their original alignment. 3481 if (Flags.isInConsecutiveRegs()) { 3482 // If the array member was split into multiple registers, the first 3483 // needs to be aligned to the size of the full type. (Except for 3484 // ppcf128, which is only aligned as its f64 components.) 3485 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3486 Alignment = Align(OrigVT.getStoreSize()); 3487 else 3488 Alignment = Align(ArgVT.getStoreSize()); 3489 } 3490 3491 return Alignment; 3492 } 3493 3494 /// CalculateStackSlotUsed - Return whether this argument will use its 3495 /// stack slot (instead of being passed in registers). ArgOffset, 3496 /// AvailableFPRs, and AvailableVRs must hold the current argument 3497 /// position, and will be updated to account for this argument. 3498 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3499 unsigned PtrByteSize, unsigned LinkageSize, 3500 unsigned ParamAreaSize, unsigned &ArgOffset, 3501 unsigned &AvailableFPRs, 3502 unsigned &AvailableVRs) { 3503 bool UseMemory = false; 3504 3505 // Respect alignment of argument on the stack. 3506 Align Alignment = 3507 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3508 ArgOffset = alignTo(ArgOffset, Alignment); 3509 // If there's no space left in the argument save area, we must 3510 // use memory (this check also catches zero-sized arguments). 3511 if (ArgOffset >= LinkageSize + ParamAreaSize) 3512 UseMemory = true; 3513 3514 // Allocate argument on the stack. 3515 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3516 if (Flags.isInConsecutiveRegsLast()) 3517 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3518 // If we overran the argument save area, we must use memory 3519 // (this check catches arguments passed partially in memory) 3520 if (ArgOffset > LinkageSize + ParamAreaSize) 3521 UseMemory = true; 3522 3523 // However, if the argument is actually passed in an FPR or a VR, 3524 // we don't use memory after all. 3525 if (!Flags.isByVal()) { 3526 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3527 if (AvailableFPRs > 0) { 3528 --AvailableFPRs; 3529 return false; 3530 } 3531 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3532 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3533 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3534 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3535 if (AvailableVRs > 0) { 3536 --AvailableVRs; 3537 return false; 3538 } 3539 } 3540 3541 return UseMemory; 3542 } 3543 3544 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3545 /// ensure minimum alignment required for target. 3546 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3547 unsigned NumBytes) { 3548 return alignTo(NumBytes, Lowering->getStackAlign()); 3549 } 3550 3551 SDValue PPCTargetLowering::LowerFormalArguments( 3552 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3553 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3554 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3555 if (Subtarget.isAIXABI()) 3556 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3557 InVals); 3558 if (Subtarget.is64BitELFABI()) 3559 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3560 InVals); 3561 if (Subtarget.is32BitELFABI()) 3562 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3563 InVals); 3564 3565 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3566 InVals); 3567 } 3568 3569 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3570 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3571 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3572 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3573 3574 // 32-bit SVR4 ABI Stack Frame Layout: 3575 // +-----------------------------------+ 3576 // +--> | Back chain | 3577 // | +-----------------------------------+ 3578 // | | Floating-point register save area | 3579 // | +-----------------------------------+ 3580 // | | General register save area | 3581 // | +-----------------------------------+ 3582 // | | CR save word | 3583 // | +-----------------------------------+ 3584 // | | VRSAVE save word | 3585 // | +-----------------------------------+ 3586 // | | Alignment padding | 3587 // | +-----------------------------------+ 3588 // | | Vector register save area | 3589 // | +-----------------------------------+ 3590 // | | Local variable space | 3591 // | +-----------------------------------+ 3592 // | | Parameter list area | 3593 // | +-----------------------------------+ 3594 // | | LR save word | 3595 // | +-----------------------------------+ 3596 // SP--> +--- | Back chain | 3597 // +-----------------------------------+ 3598 // 3599 // Specifications: 3600 // System V Application Binary Interface PowerPC Processor Supplement 3601 // AltiVec Technology Programming Interface Manual 3602 3603 MachineFunction &MF = DAG.getMachineFunction(); 3604 MachineFrameInfo &MFI = MF.getFrameInfo(); 3605 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3606 3607 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3608 // Potential tail calls could cause overwriting of argument stack slots. 3609 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3610 (CallConv == CallingConv::Fast)); 3611 const Align PtrAlign(4); 3612 3613 // Assign locations to all of the incoming arguments. 3614 SmallVector<CCValAssign, 16> ArgLocs; 3615 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3616 *DAG.getContext()); 3617 3618 // Reserve space for the linkage area on the stack. 3619 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3620 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3621 if (useSoftFloat()) 3622 CCInfo.PreAnalyzeFormalArguments(Ins); 3623 3624 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3625 CCInfo.clearWasPPCF128(); 3626 3627 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3628 CCValAssign &VA = ArgLocs[i]; 3629 3630 // Arguments stored in registers. 3631 if (VA.isRegLoc()) { 3632 const TargetRegisterClass *RC; 3633 EVT ValVT = VA.getValVT(); 3634 3635 switch (ValVT.getSimpleVT().SimpleTy) { 3636 default: 3637 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3638 case MVT::i1: 3639 case MVT::i32: 3640 RC = &PPC::GPRCRegClass; 3641 break; 3642 case MVT::f32: 3643 if (Subtarget.hasP8Vector()) 3644 RC = &PPC::VSSRCRegClass; 3645 else if (Subtarget.hasSPE()) 3646 RC = &PPC::GPRCRegClass; 3647 else 3648 RC = &PPC::F4RCRegClass; 3649 break; 3650 case MVT::f64: 3651 if (Subtarget.hasVSX()) 3652 RC = &PPC::VSFRCRegClass; 3653 else if (Subtarget.hasSPE()) 3654 // SPE passes doubles in GPR pairs. 3655 RC = &PPC::GPRCRegClass; 3656 else 3657 RC = &PPC::F8RCRegClass; 3658 break; 3659 case MVT::v16i8: 3660 case MVT::v8i16: 3661 case MVT::v4i32: 3662 RC = &PPC::VRRCRegClass; 3663 break; 3664 case MVT::v4f32: 3665 RC = &PPC::VRRCRegClass; 3666 break; 3667 case MVT::v2f64: 3668 case MVT::v2i64: 3669 RC = &PPC::VRRCRegClass; 3670 break; 3671 } 3672 3673 SDValue ArgValue; 3674 // Transform the arguments stored in physical registers into 3675 // virtual ones. 3676 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3677 assert(i + 1 < e && "No second half of double precision argument"); 3678 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3679 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3680 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3681 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3682 if (!Subtarget.isLittleEndian()) 3683 std::swap (ArgValueLo, ArgValueHi); 3684 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3685 ArgValueHi); 3686 } else { 3687 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3688 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3689 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3690 if (ValVT == MVT::i1) 3691 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3692 } 3693 3694 InVals.push_back(ArgValue); 3695 } else { 3696 // Argument stored in memory. 3697 assert(VA.isMemLoc()); 3698 3699 // Get the extended size of the argument type in stack 3700 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3701 // Get the actual size of the argument type 3702 unsigned ObjSize = VA.getValVT().getStoreSize(); 3703 unsigned ArgOffset = VA.getLocMemOffset(); 3704 // Stack objects in PPC32 are right justified. 3705 ArgOffset += ArgSize - ObjSize; 3706 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3707 3708 // Create load nodes to retrieve arguments from the stack. 3709 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3710 InVals.push_back( 3711 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3712 } 3713 } 3714 3715 // Assign locations to all of the incoming aggregate by value arguments. 3716 // Aggregates passed by value are stored in the local variable space of the 3717 // caller's stack frame, right above the parameter list area. 3718 SmallVector<CCValAssign, 16> ByValArgLocs; 3719 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3720 ByValArgLocs, *DAG.getContext()); 3721 3722 // Reserve stack space for the allocations in CCInfo. 3723 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3724 3725 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3726 3727 // Area that is at least reserved in the caller of this function. 3728 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3729 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3730 3731 // Set the size that is at least reserved in caller of this function. Tail 3732 // call optimized function's reserved stack space needs to be aligned so that 3733 // taking the difference between two stack areas will result in an aligned 3734 // stack. 3735 MinReservedArea = 3736 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3737 FuncInfo->setMinReservedArea(MinReservedArea); 3738 3739 SmallVector<SDValue, 8> MemOps; 3740 3741 // If the function takes variable number of arguments, make a frame index for 3742 // the start of the first vararg value... for expansion of llvm.va_start. 3743 if (isVarArg) { 3744 static const MCPhysReg GPArgRegs[] = { 3745 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3746 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3747 }; 3748 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3749 3750 static const MCPhysReg FPArgRegs[] = { 3751 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3752 PPC::F8 3753 }; 3754 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3755 3756 if (useSoftFloat() || hasSPE()) 3757 NumFPArgRegs = 0; 3758 3759 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3760 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3761 3762 // Make room for NumGPArgRegs and NumFPArgRegs. 3763 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3764 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3765 3766 FuncInfo->setVarArgsStackOffset( 3767 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3768 CCInfo.getNextStackOffset(), true)); 3769 3770 FuncInfo->setVarArgsFrameIndex( 3771 MFI.CreateStackObject(Depth, Align(8), false)); 3772 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3773 3774 // The fixed integer arguments of a variadic function are stored to the 3775 // VarArgsFrameIndex on the stack so that they may be loaded by 3776 // dereferencing the result of va_next. 3777 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3778 // Get an existing live-in vreg, or add a new one. 3779 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3780 if (!VReg) 3781 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3782 3783 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3784 SDValue Store = 3785 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3786 MemOps.push_back(Store); 3787 // Increment the address by four for the next argument to store 3788 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3789 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3790 } 3791 3792 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3793 // is set. 3794 // The double arguments are stored to the VarArgsFrameIndex 3795 // on the stack. 3796 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3797 // Get an existing live-in vreg, or add a new one. 3798 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3799 if (!VReg) 3800 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3801 3802 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3803 SDValue Store = 3804 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3805 MemOps.push_back(Store); 3806 // Increment the address by eight for the next argument to store 3807 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3808 PtrVT); 3809 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3810 } 3811 } 3812 3813 if (!MemOps.empty()) 3814 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3815 3816 return Chain; 3817 } 3818 3819 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3820 // value to MVT::i64 and then truncate to the correct register size. 3821 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3822 EVT ObjectVT, SelectionDAG &DAG, 3823 SDValue ArgVal, 3824 const SDLoc &dl) const { 3825 if (Flags.isSExt()) 3826 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3827 DAG.getValueType(ObjectVT)); 3828 else if (Flags.isZExt()) 3829 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3830 DAG.getValueType(ObjectVT)); 3831 3832 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3833 } 3834 3835 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3836 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3837 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3838 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3839 // TODO: add description of PPC stack frame format, or at least some docs. 3840 // 3841 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3842 bool isLittleEndian = Subtarget.isLittleEndian(); 3843 MachineFunction &MF = DAG.getMachineFunction(); 3844 MachineFrameInfo &MFI = MF.getFrameInfo(); 3845 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3846 3847 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3848 "fastcc not supported on varargs functions"); 3849 3850 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3851 // Potential tail calls could cause overwriting of argument stack slots. 3852 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3853 (CallConv == CallingConv::Fast)); 3854 unsigned PtrByteSize = 8; 3855 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3856 3857 static const MCPhysReg GPR[] = { 3858 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3859 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3860 }; 3861 static const MCPhysReg VR[] = { 3862 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3863 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3864 }; 3865 3866 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3867 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3868 const unsigned Num_VR_Regs = array_lengthof(VR); 3869 3870 // Do a first pass over the arguments to determine whether the ABI 3871 // guarantees that our caller has allocated the parameter save area 3872 // on its stack frame. In the ELFv1 ABI, this is always the case; 3873 // in the ELFv2 ABI, it is true if this is a vararg function or if 3874 // any parameter is located in a stack slot. 3875 3876 bool HasParameterArea = !isELFv2ABI || isVarArg; 3877 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3878 unsigned NumBytes = LinkageSize; 3879 unsigned AvailableFPRs = Num_FPR_Regs; 3880 unsigned AvailableVRs = Num_VR_Regs; 3881 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3882 if (Ins[i].Flags.isNest()) 3883 continue; 3884 3885 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3886 PtrByteSize, LinkageSize, ParamAreaSize, 3887 NumBytes, AvailableFPRs, AvailableVRs)) 3888 HasParameterArea = true; 3889 } 3890 3891 // Add DAG nodes to load the arguments or copy them out of registers. On 3892 // entry to a function on PPC, the arguments start after the linkage area, 3893 // although the first ones are often in registers. 3894 3895 unsigned ArgOffset = LinkageSize; 3896 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3897 SmallVector<SDValue, 8> MemOps; 3898 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3899 unsigned CurArgIdx = 0; 3900 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3901 SDValue ArgVal; 3902 bool needsLoad = false; 3903 EVT ObjectVT = Ins[ArgNo].VT; 3904 EVT OrigVT = Ins[ArgNo].ArgVT; 3905 unsigned ObjSize = ObjectVT.getStoreSize(); 3906 unsigned ArgSize = ObjSize; 3907 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3908 if (Ins[ArgNo].isOrigArg()) { 3909 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3910 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3911 } 3912 // We re-align the argument offset for each argument, except when using the 3913 // fast calling convention, when we need to make sure we do that only when 3914 // we'll actually use a stack slot. 3915 unsigned CurArgOffset; 3916 Align Alignment; 3917 auto ComputeArgOffset = [&]() { 3918 /* Respect alignment of argument on the stack. */ 3919 Alignment = 3920 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3921 ArgOffset = alignTo(ArgOffset, Alignment); 3922 CurArgOffset = ArgOffset; 3923 }; 3924 3925 if (CallConv != CallingConv::Fast) { 3926 ComputeArgOffset(); 3927 3928 /* Compute GPR index associated with argument offset. */ 3929 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3930 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3931 } 3932 3933 // FIXME the codegen can be much improved in some cases. 3934 // We do not have to keep everything in memory. 3935 if (Flags.isByVal()) { 3936 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3937 3938 if (CallConv == CallingConv::Fast) 3939 ComputeArgOffset(); 3940 3941 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3942 ObjSize = Flags.getByValSize(); 3943 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3944 // Empty aggregate parameters do not take up registers. Examples: 3945 // struct { } a; 3946 // union { } b; 3947 // int c[0]; 3948 // etc. However, we have to provide a place-holder in InVals, so 3949 // pretend we have an 8-byte item at the current address for that 3950 // purpose. 3951 if (!ObjSize) { 3952 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3953 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3954 InVals.push_back(FIN); 3955 continue; 3956 } 3957 3958 // Create a stack object covering all stack doublewords occupied 3959 // by the argument. If the argument is (fully or partially) on 3960 // the stack, or if the argument is fully in registers but the 3961 // caller has allocated the parameter save anyway, we can refer 3962 // directly to the caller's stack frame. Otherwise, create a 3963 // local copy in our own frame. 3964 int FI; 3965 if (HasParameterArea || 3966 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3967 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3968 else 3969 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3970 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3971 3972 // Handle aggregates smaller than 8 bytes. 3973 if (ObjSize < PtrByteSize) { 3974 // The value of the object is its address, which differs from the 3975 // address of the enclosing doubleword on big-endian systems. 3976 SDValue Arg = FIN; 3977 if (!isLittleEndian) { 3978 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3979 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3980 } 3981 InVals.push_back(Arg); 3982 3983 if (GPR_idx != Num_GPR_Regs) { 3984 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3985 FuncInfo->addLiveInAttr(VReg, Flags); 3986 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3987 SDValue Store; 3988 3989 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3990 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3991 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3992 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3993 MachinePointerInfo(&*FuncArg), ObjType); 3994 } else { 3995 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3996 // store the whole register as-is to the parameter save area 3997 // slot. 3998 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3999 MachinePointerInfo(&*FuncArg)); 4000 } 4001 4002 MemOps.push_back(Store); 4003 } 4004 // Whether we copied from a register or not, advance the offset 4005 // into the parameter save area by a full doubleword. 4006 ArgOffset += PtrByteSize; 4007 continue; 4008 } 4009 4010 // The value of the object is its address, which is the address of 4011 // its first stack doubleword. 4012 InVals.push_back(FIN); 4013 4014 // Store whatever pieces of the object are in registers to memory. 4015 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4016 if (GPR_idx == Num_GPR_Regs) 4017 break; 4018 4019 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4020 FuncInfo->addLiveInAttr(VReg, Flags); 4021 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4022 SDValue Addr = FIN; 4023 if (j) { 4024 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4025 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4026 } 4027 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4028 MachinePointerInfo(&*FuncArg, j)); 4029 MemOps.push_back(Store); 4030 ++GPR_idx; 4031 } 4032 ArgOffset += ArgSize; 4033 continue; 4034 } 4035 4036 switch (ObjectVT.getSimpleVT().SimpleTy) { 4037 default: llvm_unreachable("Unhandled argument type!"); 4038 case MVT::i1: 4039 case MVT::i32: 4040 case MVT::i64: 4041 if (Flags.isNest()) { 4042 // The 'nest' parameter, if any, is passed in R11. 4043 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4044 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4045 4046 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4047 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4048 4049 break; 4050 } 4051 4052 // These can be scalar arguments or elements of an integer array type 4053 // passed directly. Clang may use those instead of "byval" aggregate 4054 // types to avoid forcing arguments to memory unnecessarily. 4055 if (GPR_idx != Num_GPR_Regs) { 4056 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4057 FuncInfo->addLiveInAttr(VReg, Flags); 4058 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4059 4060 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4061 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4062 // value to MVT::i64 and then truncate to the correct register size. 4063 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4064 } else { 4065 if (CallConv == CallingConv::Fast) 4066 ComputeArgOffset(); 4067 4068 needsLoad = true; 4069 ArgSize = PtrByteSize; 4070 } 4071 if (CallConv != CallingConv::Fast || needsLoad) 4072 ArgOffset += 8; 4073 break; 4074 4075 case MVT::f32: 4076 case MVT::f64: 4077 // These can be scalar arguments or elements of a float array type 4078 // passed directly. The latter are used to implement ELFv2 homogenous 4079 // float aggregates. 4080 if (FPR_idx != Num_FPR_Regs) { 4081 unsigned VReg; 4082 4083 if (ObjectVT == MVT::f32) 4084 VReg = MF.addLiveIn(FPR[FPR_idx], 4085 Subtarget.hasP8Vector() 4086 ? &PPC::VSSRCRegClass 4087 : &PPC::F4RCRegClass); 4088 else 4089 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4090 ? &PPC::VSFRCRegClass 4091 : &PPC::F8RCRegClass); 4092 4093 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4094 ++FPR_idx; 4095 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4096 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4097 // once we support fp <-> gpr moves. 4098 4099 // This can only ever happen in the presence of f32 array types, 4100 // since otherwise we never run out of FPRs before running out 4101 // of GPRs. 4102 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4103 FuncInfo->addLiveInAttr(VReg, Flags); 4104 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4105 4106 if (ObjectVT == MVT::f32) { 4107 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4108 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4109 DAG.getConstant(32, dl, MVT::i32)); 4110 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4111 } 4112 4113 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4114 } else { 4115 if (CallConv == CallingConv::Fast) 4116 ComputeArgOffset(); 4117 4118 needsLoad = true; 4119 } 4120 4121 // When passing an array of floats, the array occupies consecutive 4122 // space in the argument area; only round up to the next doubleword 4123 // at the end of the array. Otherwise, each float takes 8 bytes. 4124 if (CallConv != CallingConv::Fast || needsLoad) { 4125 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4126 ArgOffset += ArgSize; 4127 if (Flags.isInConsecutiveRegsLast()) 4128 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4129 } 4130 break; 4131 case MVT::v4f32: 4132 case MVT::v4i32: 4133 case MVT::v8i16: 4134 case MVT::v16i8: 4135 case MVT::v2f64: 4136 case MVT::v2i64: 4137 case MVT::v1i128: 4138 case MVT::f128: 4139 // These can be scalar arguments or elements of a vector array type 4140 // passed directly. The latter are used to implement ELFv2 homogenous 4141 // vector aggregates. 4142 if (VR_idx != Num_VR_Regs) { 4143 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4144 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4145 ++VR_idx; 4146 } else { 4147 if (CallConv == CallingConv::Fast) 4148 ComputeArgOffset(); 4149 needsLoad = true; 4150 } 4151 if (CallConv != CallingConv::Fast || needsLoad) 4152 ArgOffset += 16; 4153 break; 4154 } 4155 4156 // We need to load the argument to a virtual register if we determined 4157 // above that we ran out of physical registers of the appropriate type. 4158 if (needsLoad) { 4159 if (ObjSize < ArgSize && !isLittleEndian) 4160 CurArgOffset += ArgSize - ObjSize; 4161 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4162 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4163 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4164 } 4165 4166 InVals.push_back(ArgVal); 4167 } 4168 4169 // Area that is at least reserved in the caller of this function. 4170 unsigned MinReservedArea; 4171 if (HasParameterArea) 4172 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4173 else 4174 MinReservedArea = LinkageSize; 4175 4176 // Set the size that is at least reserved in caller of this function. Tail 4177 // call optimized functions' reserved stack space needs to be aligned so that 4178 // taking the difference between two stack areas will result in an aligned 4179 // stack. 4180 MinReservedArea = 4181 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4182 FuncInfo->setMinReservedArea(MinReservedArea); 4183 4184 // If the function takes variable number of arguments, make a frame index for 4185 // the start of the first vararg value... for expansion of llvm.va_start. 4186 // On ELFv2ABI spec, it writes: 4187 // C programs that are intended to be *portable* across different compilers 4188 // and architectures must use the header file <stdarg.h> to deal with variable 4189 // argument lists. 4190 if (isVarArg && MFI.hasVAStart()) { 4191 int Depth = ArgOffset; 4192 4193 FuncInfo->setVarArgsFrameIndex( 4194 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4195 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4196 4197 // If this function is vararg, store any remaining integer argument regs 4198 // to their spots on the stack so that they may be loaded by dereferencing 4199 // the result of va_next. 4200 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4201 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4202 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4203 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4204 SDValue Store = 4205 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4206 MemOps.push_back(Store); 4207 // Increment the address by four for the next argument to store 4208 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4209 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4210 } 4211 } 4212 4213 if (!MemOps.empty()) 4214 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4215 4216 return Chain; 4217 } 4218 4219 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4220 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4221 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4222 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4223 // TODO: add description of PPC stack frame format, or at least some docs. 4224 // 4225 MachineFunction &MF = DAG.getMachineFunction(); 4226 MachineFrameInfo &MFI = MF.getFrameInfo(); 4227 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4228 4229 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4230 bool isPPC64 = PtrVT == MVT::i64; 4231 // Potential tail calls could cause overwriting of argument stack slots. 4232 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4233 (CallConv == CallingConv::Fast)); 4234 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4235 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4236 unsigned ArgOffset = LinkageSize; 4237 // Area that is at least reserved in caller of this function. 4238 unsigned MinReservedArea = ArgOffset; 4239 4240 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4241 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4242 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4243 }; 4244 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4245 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4246 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4247 }; 4248 static const MCPhysReg VR[] = { 4249 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4250 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4251 }; 4252 4253 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4254 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4255 const unsigned Num_VR_Regs = array_lengthof( VR); 4256 4257 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4258 4259 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4260 4261 // In 32-bit non-varargs functions, the stack space for vectors is after the 4262 // stack space for non-vectors. We do not use this space unless we have 4263 // too many vectors to fit in registers, something that only occurs in 4264 // constructed examples:), but we have to walk the arglist to figure 4265 // that out...for the pathological case, compute VecArgOffset as the 4266 // start of the vector parameter area. Computing VecArgOffset is the 4267 // entire point of the following loop. 4268 unsigned VecArgOffset = ArgOffset; 4269 if (!isVarArg && !isPPC64) { 4270 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4271 ++ArgNo) { 4272 EVT ObjectVT = Ins[ArgNo].VT; 4273 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4274 4275 if (Flags.isByVal()) { 4276 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4277 unsigned ObjSize = Flags.getByValSize(); 4278 unsigned ArgSize = 4279 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4280 VecArgOffset += ArgSize; 4281 continue; 4282 } 4283 4284 switch(ObjectVT.getSimpleVT().SimpleTy) { 4285 default: llvm_unreachable("Unhandled argument type!"); 4286 case MVT::i1: 4287 case MVT::i32: 4288 case MVT::f32: 4289 VecArgOffset += 4; 4290 break; 4291 case MVT::i64: // PPC64 4292 case MVT::f64: 4293 // FIXME: We are guaranteed to be !isPPC64 at this point. 4294 // Does MVT::i64 apply? 4295 VecArgOffset += 8; 4296 break; 4297 case MVT::v4f32: 4298 case MVT::v4i32: 4299 case MVT::v8i16: 4300 case MVT::v16i8: 4301 // Nothing to do, we're only looking at Nonvector args here. 4302 break; 4303 } 4304 } 4305 } 4306 // We've found where the vector parameter area in memory is. Skip the 4307 // first 12 parameters; these don't use that memory. 4308 VecArgOffset = ((VecArgOffset+15)/16)*16; 4309 VecArgOffset += 12*16; 4310 4311 // Add DAG nodes to load the arguments or copy them out of registers. On 4312 // entry to a function on PPC, the arguments start after the linkage area, 4313 // although the first ones are often in registers. 4314 4315 SmallVector<SDValue, 8> MemOps; 4316 unsigned nAltivecParamsAtEnd = 0; 4317 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4318 unsigned CurArgIdx = 0; 4319 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4320 SDValue ArgVal; 4321 bool needsLoad = false; 4322 EVT ObjectVT = Ins[ArgNo].VT; 4323 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4324 unsigned ArgSize = ObjSize; 4325 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4326 if (Ins[ArgNo].isOrigArg()) { 4327 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4328 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4329 } 4330 unsigned CurArgOffset = ArgOffset; 4331 4332 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4333 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4334 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4335 if (isVarArg || isPPC64) { 4336 MinReservedArea = ((MinReservedArea+15)/16)*16; 4337 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4338 Flags, 4339 PtrByteSize); 4340 } else nAltivecParamsAtEnd++; 4341 } else 4342 // Calculate min reserved area. 4343 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4344 Flags, 4345 PtrByteSize); 4346 4347 // FIXME the codegen can be much improved in some cases. 4348 // We do not have to keep everything in memory. 4349 if (Flags.isByVal()) { 4350 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4351 4352 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4353 ObjSize = Flags.getByValSize(); 4354 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4355 // Objects of size 1 and 2 are right justified, everything else is 4356 // left justified. This means the memory address is adjusted forwards. 4357 if (ObjSize==1 || ObjSize==2) { 4358 CurArgOffset = CurArgOffset + (4 - ObjSize); 4359 } 4360 // The value of the object is its address. 4361 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4362 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4363 InVals.push_back(FIN); 4364 if (ObjSize==1 || ObjSize==2) { 4365 if (GPR_idx != Num_GPR_Regs) { 4366 unsigned VReg; 4367 if (isPPC64) 4368 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4369 else 4370 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4371 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4372 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4373 SDValue Store = 4374 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4375 MachinePointerInfo(&*FuncArg), ObjType); 4376 MemOps.push_back(Store); 4377 ++GPR_idx; 4378 } 4379 4380 ArgOffset += PtrByteSize; 4381 4382 continue; 4383 } 4384 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4385 // Store whatever pieces of the object are in registers 4386 // to memory. ArgOffset will be the address of the beginning 4387 // of the object. 4388 if (GPR_idx != Num_GPR_Regs) { 4389 unsigned VReg; 4390 if (isPPC64) 4391 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4392 else 4393 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4394 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4395 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4396 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4397 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4398 MachinePointerInfo(&*FuncArg, j)); 4399 MemOps.push_back(Store); 4400 ++GPR_idx; 4401 ArgOffset += PtrByteSize; 4402 } else { 4403 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4404 break; 4405 } 4406 } 4407 continue; 4408 } 4409 4410 switch (ObjectVT.getSimpleVT().SimpleTy) { 4411 default: llvm_unreachable("Unhandled argument type!"); 4412 case MVT::i1: 4413 case MVT::i32: 4414 if (!isPPC64) { 4415 if (GPR_idx != Num_GPR_Regs) { 4416 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4417 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4418 4419 if (ObjectVT == MVT::i1) 4420 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4421 4422 ++GPR_idx; 4423 } else { 4424 needsLoad = true; 4425 ArgSize = PtrByteSize; 4426 } 4427 // All int arguments reserve stack space in the Darwin ABI. 4428 ArgOffset += PtrByteSize; 4429 break; 4430 } 4431 LLVM_FALLTHROUGH; 4432 case MVT::i64: // PPC64 4433 if (GPR_idx != Num_GPR_Regs) { 4434 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4435 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4436 4437 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4438 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4439 // value to MVT::i64 and then truncate to the correct register size. 4440 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4441 4442 ++GPR_idx; 4443 } else { 4444 needsLoad = true; 4445 ArgSize = PtrByteSize; 4446 } 4447 // All int arguments reserve stack space in the Darwin ABI. 4448 ArgOffset += 8; 4449 break; 4450 4451 case MVT::f32: 4452 case MVT::f64: 4453 // Every 4 bytes of argument space consumes one of the GPRs available for 4454 // argument passing. 4455 if (GPR_idx != Num_GPR_Regs) { 4456 ++GPR_idx; 4457 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4458 ++GPR_idx; 4459 } 4460 if (FPR_idx != Num_FPR_Regs) { 4461 unsigned VReg; 4462 4463 if (ObjectVT == MVT::f32) 4464 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4465 else 4466 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4467 4468 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4469 ++FPR_idx; 4470 } else { 4471 needsLoad = true; 4472 } 4473 4474 // All FP arguments reserve stack space in the Darwin ABI. 4475 ArgOffset += isPPC64 ? 8 : ObjSize; 4476 break; 4477 case MVT::v4f32: 4478 case MVT::v4i32: 4479 case MVT::v8i16: 4480 case MVT::v16i8: 4481 // Note that vector arguments in registers don't reserve stack space, 4482 // except in varargs functions. 4483 if (VR_idx != Num_VR_Regs) { 4484 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4485 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4486 if (isVarArg) { 4487 while ((ArgOffset % 16) != 0) { 4488 ArgOffset += PtrByteSize; 4489 if (GPR_idx != Num_GPR_Regs) 4490 GPR_idx++; 4491 } 4492 ArgOffset += 16; 4493 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4494 } 4495 ++VR_idx; 4496 } else { 4497 if (!isVarArg && !isPPC64) { 4498 // Vectors go after all the nonvectors. 4499 CurArgOffset = VecArgOffset; 4500 VecArgOffset += 16; 4501 } else { 4502 // Vectors are aligned. 4503 ArgOffset = ((ArgOffset+15)/16)*16; 4504 CurArgOffset = ArgOffset; 4505 ArgOffset += 16; 4506 } 4507 needsLoad = true; 4508 } 4509 break; 4510 } 4511 4512 // We need to load the argument to a virtual register if we determined above 4513 // that we ran out of physical registers of the appropriate type. 4514 if (needsLoad) { 4515 int FI = MFI.CreateFixedObject(ObjSize, 4516 CurArgOffset + (ArgSize - ObjSize), 4517 isImmutable); 4518 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4519 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4520 } 4521 4522 InVals.push_back(ArgVal); 4523 } 4524 4525 // Allow for Altivec parameters at the end, if needed. 4526 if (nAltivecParamsAtEnd) { 4527 MinReservedArea = ((MinReservedArea+15)/16)*16; 4528 MinReservedArea += 16*nAltivecParamsAtEnd; 4529 } 4530 4531 // Area that is at least reserved in the caller of this function. 4532 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4533 4534 // Set the size that is at least reserved in caller of this function. Tail 4535 // call optimized functions' reserved stack space needs to be aligned so that 4536 // taking the difference between two stack areas will result in an aligned 4537 // stack. 4538 MinReservedArea = 4539 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4540 FuncInfo->setMinReservedArea(MinReservedArea); 4541 4542 // If the function takes variable number of arguments, make a frame index for 4543 // the start of the first vararg value... for expansion of llvm.va_start. 4544 if (isVarArg) { 4545 int Depth = ArgOffset; 4546 4547 FuncInfo->setVarArgsFrameIndex( 4548 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4549 Depth, true)); 4550 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4551 4552 // If this function is vararg, store any remaining integer argument regs 4553 // to their spots on the stack so that they may be loaded by dereferencing 4554 // the result of va_next. 4555 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4556 unsigned VReg; 4557 4558 if (isPPC64) 4559 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4560 else 4561 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4562 4563 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4564 SDValue Store = 4565 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4566 MemOps.push_back(Store); 4567 // Increment the address by four for the next argument to store 4568 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4569 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4570 } 4571 } 4572 4573 if (!MemOps.empty()) 4574 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4575 4576 return Chain; 4577 } 4578 4579 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4580 /// adjusted to accommodate the arguments for the tailcall. 4581 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4582 unsigned ParamSize) { 4583 4584 if (!isTailCall) return 0; 4585 4586 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4587 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4588 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4589 // Remember only if the new adjustment is bigger. 4590 if (SPDiff < FI->getTailCallSPDelta()) 4591 FI->setTailCallSPDelta(SPDiff); 4592 4593 return SPDiff; 4594 } 4595 4596 static bool isFunctionGlobalAddress(SDValue Callee); 4597 4598 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4599 const TargetMachine &TM) { 4600 // It does not make sense to call callsShareTOCBase() with a caller that 4601 // is PC Relative since PC Relative callers do not have a TOC. 4602 #ifndef NDEBUG 4603 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4604 assert(!STICaller->isUsingPCRelativeCalls() && 4605 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4606 #endif 4607 4608 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4609 // don't have enough information to determine if the caller and callee share 4610 // the same TOC base, so we have to pessimistically assume they don't for 4611 // correctness. 4612 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4613 if (!G) 4614 return false; 4615 4616 const GlobalValue *GV = G->getGlobal(); 4617 4618 // If the callee is preemptable, then the static linker will use a plt-stub 4619 // which saves the toc to the stack, and needs a nop after the call 4620 // instruction to convert to a toc-restore. 4621 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4622 return false; 4623 4624 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4625 // We may need a TOC restore in the situation where the caller requires a 4626 // valid TOC but the callee is PC Relative and does not. 4627 const Function *F = dyn_cast<Function>(GV); 4628 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4629 4630 // If we have an Alias we can try to get the function from there. 4631 if (Alias) { 4632 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4633 F = dyn_cast<Function>(GlobalObj); 4634 } 4635 4636 // If we still have no valid function pointer we do not have enough 4637 // information to determine if the callee uses PC Relative calls so we must 4638 // assume that it does. 4639 if (!F) 4640 return false; 4641 4642 // If the callee uses PC Relative we cannot guarantee that the callee won't 4643 // clobber the TOC of the caller and so we must assume that the two 4644 // functions do not share a TOC base. 4645 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4646 if (STICallee->isUsingPCRelativeCalls()) 4647 return false; 4648 4649 // The medium and large code models are expected to provide a sufficiently 4650 // large TOC to provide all data addressing needs of a module with a 4651 // single TOC. 4652 if (CodeModel::Medium == TM.getCodeModel() || 4653 CodeModel::Large == TM.getCodeModel()) 4654 return true; 4655 4656 // Otherwise we need to ensure callee and caller are in the same section, 4657 // since the linker may allocate multiple TOCs, and we don't know which 4658 // sections will belong to the same TOC base. 4659 if (!GV->isStrongDefinitionForLinker()) 4660 return false; 4661 4662 // Any explicitly-specified sections and section prefixes must also match. 4663 // Also, if we're using -ffunction-sections, then each function is always in 4664 // a different section (the same is true for COMDAT functions). 4665 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4666 GV->getSection() != Caller->getSection()) 4667 return false; 4668 if (const auto *F = dyn_cast<Function>(GV)) { 4669 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4670 return false; 4671 } 4672 4673 return true; 4674 } 4675 4676 static bool 4677 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4678 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4679 assert(Subtarget.is64BitELFABI()); 4680 4681 const unsigned PtrByteSize = 8; 4682 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4683 4684 static const MCPhysReg GPR[] = { 4685 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4686 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4687 }; 4688 static const MCPhysReg VR[] = { 4689 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4690 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4691 }; 4692 4693 const unsigned NumGPRs = array_lengthof(GPR); 4694 const unsigned NumFPRs = 13; 4695 const unsigned NumVRs = array_lengthof(VR); 4696 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4697 4698 unsigned NumBytes = LinkageSize; 4699 unsigned AvailableFPRs = NumFPRs; 4700 unsigned AvailableVRs = NumVRs; 4701 4702 for (const ISD::OutputArg& Param : Outs) { 4703 if (Param.Flags.isNest()) continue; 4704 4705 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4706 LinkageSize, ParamAreaSize, NumBytes, 4707 AvailableFPRs, AvailableVRs)) 4708 return true; 4709 } 4710 return false; 4711 } 4712 4713 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4714 if (CB.arg_size() != CallerFn->arg_size()) 4715 return false; 4716 4717 auto CalleeArgIter = CB.arg_begin(); 4718 auto CalleeArgEnd = CB.arg_end(); 4719 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4720 4721 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4722 const Value* CalleeArg = *CalleeArgIter; 4723 const Value* CallerArg = &(*CallerArgIter); 4724 if (CalleeArg == CallerArg) 4725 continue; 4726 4727 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4728 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4729 // } 4730 // 1st argument of callee is undef and has the same type as caller. 4731 if (CalleeArg->getType() == CallerArg->getType() && 4732 isa<UndefValue>(CalleeArg)) 4733 continue; 4734 4735 return false; 4736 } 4737 4738 return true; 4739 } 4740 4741 // Returns true if TCO is possible between the callers and callees 4742 // calling conventions. 4743 static bool 4744 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4745 CallingConv::ID CalleeCC) { 4746 // Tail calls are possible with fastcc and ccc. 4747 auto isTailCallableCC = [] (CallingConv::ID CC){ 4748 return CC == CallingConv::C || CC == CallingConv::Fast; 4749 }; 4750 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4751 return false; 4752 4753 // We can safely tail call both fastcc and ccc callees from a c calling 4754 // convention caller. If the caller is fastcc, we may have less stack space 4755 // than a non-fastcc caller with the same signature so disable tail-calls in 4756 // that case. 4757 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4758 } 4759 4760 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4761 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4762 const SmallVectorImpl<ISD::OutputArg> &Outs, 4763 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4764 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4765 4766 if (DisableSCO && !TailCallOpt) return false; 4767 4768 // Variadic argument functions are not supported. 4769 if (isVarArg) return false; 4770 4771 auto &Caller = DAG.getMachineFunction().getFunction(); 4772 // Check that the calling conventions are compatible for tco. 4773 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4774 return false; 4775 4776 // Caller contains any byval parameter is not supported. 4777 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4778 return false; 4779 4780 // Callee contains any byval parameter is not supported, too. 4781 // Note: This is a quick work around, because in some cases, e.g. 4782 // caller's stack size > callee's stack size, we are still able to apply 4783 // sibling call optimization. For example, gcc is able to do SCO for caller1 4784 // in the following example, but not for caller2. 4785 // struct test { 4786 // long int a; 4787 // char ary[56]; 4788 // } gTest; 4789 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4790 // b->a = v.a; 4791 // return 0; 4792 // } 4793 // void caller1(struct test a, struct test c, struct test *b) { 4794 // callee(gTest, b); } 4795 // void caller2(struct test *b) { callee(gTest, b); } 4796 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4797 return false; 4798 4799 // If callee and caller use different calling conventions, we cannot pass 4800 // parameters on stack since offsets for the parameter area may be different. 4801 if (Caller.getCallingConv() != CalleeCC && 4802 needStackSlotPassParameters(Subtarget, Outs)) 4803 return false; 4804 4805 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4806 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4807 // callee potentially have different TOC bases then we cannot tail call since 4808 // we need to restore the TOC pointer after the call. 4809 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4810 // We cannot guarantee this for indirect calls or calls to external functions. 4811 // When PC-Relative addressing is used, the concept of the TOC is no longer 4812 // applicable so this check is not required. 4813 // Check first for indirect calls. 4814 if (!Subtarget.isUsingPCRelativeCalls() && 4815 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4816 return false; 4817 4818 // Check if we share the TOC base. 4819 if (!Subtarget.isUsingPCRelativeCalls() && 4820 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4821 return false; 4822 4823 // TCO allows altering callee ABI, so we don't have to check further. 4824 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4825 return true; 4826 4827 if (DisableSCO) return false; 4828 4829 // If callee use the same argument list that caller is using, then we can 4830 // apply SCO on this case. If it is not, then we need to check if callee needs 4831 // stack for passing arguments. 4832 // PC Relative tail calls may not have a CallBase. 4833 // If there is no CallBase we cannot verify if we have the same argument 4834 // list so assume that we don't have the same argument list. 4835 if (CB && !hasSameArgumentList(&Caller, *CB) && 4836 needStackSlotPassParameters(Subtarget, Outs)) 4837 return false; 4838 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4839 return false; 4840 4841 return true; 4842 } 4843 4844 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4845 /// for tail call optimization. Targets which want to do tail call 4846 /// optimization should implement this function. 4847 bool 4848 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4849 CallingConv::ID CalleeCC, 4850 bool isVarArg, 4851 const SmallVectorImpl<ISD::InputArg> &Ins, 4852 SelectionDAG& DAG) const { 4853 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4854 return false; 4855 4856 // Variable argument functions are not supported. 4857 if (isVarArg) 4858 return false; 4859 4860 MachineFunction &MF = DAG.getMachineFunction(); 4861 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4862 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4863 // Functions containing by val parameters are not supported. 4864 for (unsigned i = 0; i != Ins.size(); i++) { 4865 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4866 if (Flags.isByVal()) return false; 4867 } 4868 4869 // Non-PIC/GOT tail calls are supported. 4870 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4871 return true; 4872 4873 // At the moment we can only do local tail calls (in same module, hidden 4874 // or protected) if we are generating PIC. 4875 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4876 return G->getGlobal()->hasHiddenVisibility() 4877 || G->getGlobal()->hasProtectedVisibility(); 4878 } 4879 4880 return false; 4881 } 4882 4883 /// isCallCompatibleAddress - Return the immediate to use if the specified 4884 /// 32-bit value is representable in the immediate field of a BxA instruction. 4885 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4886 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4887 if (!C) return nullptr; 4888 4889 int Addr = C->getZExtValue(); 4890 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4891 SignExtend32<26>(Addr) != Addr) 4892 return nullptr; // Top 6 bits have to be sext of immediate. 4893 4894 return DAG 4895 .getConstant( 4896 (int)C->getZExtValue() >> 2, SDLoc(Op), 4897 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4898 .getNode(); 4899 } 4900 4901 namespace { 4902 4903 struct TailCallArgumentInfo { 4904 SDValue Arg; 4905 SDValue FrameIdxOp; 4906 int FrameIdx = 0; 4907 4908 TailCallArgumentInfo() = default; 4909 }; 4910 4911 } // end anonymous namespace 4912 4913 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4914 static void StoreTailCallArgumentsToStackSlot( 4915 SelectionDAG &DAG, SDValue Chain, 4916 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4917 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4918 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4919 SDValue Arg = TailCallArgs[i].Arg; 4920 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4921 int FI = TailCallArgs[i].FrameIdx; 4922 // Store relative to framepointer. 4923 MemOpChains.push_back(DAG.getStore( 4924 Chain, dl, Arg, FIN, 4925 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4926 } 4927 } 4928 4929 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4930 /// the appropriate stack slot for the tail call optimized function call. 4931 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4932 SDValue OldRetAddr, SDValue OldFP, 4933 int SPDiff, const SDLoc &dl) { 4934 if (SPDiff) { 4935 // Calculate the new stack slot for the return address. 4936 MachineFunction &MF = DAG.getMachineFunction(); 4937 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4938 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4939 bool isPPC64 = Subtarget.isPPC64(); 4940 int SlotSize = isPPC64 ? 8 : 4; 4941 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4942 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4943 NewRetAddrLoc, true); 4944 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4945 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4946 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4947 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4948 } 4949 return Chain; 4950 } 4951 4952 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4953 /// the position of the argument. 4954 static void 4955 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4956 SDValue Arg, int SPDiff, unsigned ArgOffset, 4957 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4958 int Offset = ArgOffset + SPDiff; 4959 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4960 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4961 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4962 SDValue FIN = DAG.getFrameIndex(FI, VT); 4963 TailCallArgumentInfo Info; 4964 Info.Arg = Arg; 4965 Info.FrameIdxOp = FIN; 4966 Info.FrameIdx = FI; 4967 TailCallArguments.push_back(Info); 4968 } 4969 4970 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4971 /// stack slot. Returns the chain as result and the loaded frame pointers in 4972 /// LROpOut/FPOpout. Used when tail calling. 4973 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4974 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4975 SDValue &FPOpOut, const SDLoc &dl) const { 4976 if (SPDiff) { 4977 // Load the LR and FP stack slot for later adjusting. 4978 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4979 LROpOut = getReturnAddrFrameIndex(DAG); 4980 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4981 Chain = SDValue(LROpOut.getNode(), 1); 4982 } 4983 return Chain; 4984 } 4985 4986 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4987 /// by "Src" to address "Dst" of size "Size". Alignment information is 4988 /// specified by the specific parameter attribute. The copy will be passed as 4989 /// a byval function parameter. 4990 /// Sometimes what we are copying is the end of a larger object, the part that 4991 /// does not fit in registers. 4992 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4993 SDValue Chain, ISD::ArgFlagsTy Flags, 4994 SelectionDAG &DAG, const SDLoc &dl) { 4995 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4996 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4997 Flags.getNonZeroByValAlign(), false, false, false, 4998 MachinePointerInfo(), MachinePointerInfo()); 4999 } 5000 5001 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5002 /// tail calls. 5003 static void LowerMemOpCallTo( 5004 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5005 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5006 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5007 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5008 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5009 if (!isTailCall) { 5010 if (isVector) { 5011 SDValue StackPtr; 5012 if (isPPC64) 5013 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5014 else 5015 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5016 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5017 DAG.getConstant(ArgOffset, dl, PtrVT)); 5018 } 5019 MemOpChains.push_back( 5020 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5021 // Calculate and remember argument location. 5022 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5023 TailCallArguments); 5024 } 5025 5026 static void 5027 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5028 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5029 SDValue FPOp, 5030 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5031 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5032 // might overwrite each other in case of tail call optimization. 5033 SmallVector<SDValue, 8> MemOpChains2; 5034 // Do not flag preceding copytoreg stuff together with the following stuff. 5035 InFlag = SDValue(); 5036 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5037 MemOpChains2, dl); 5038 if (!MemOpChains2.empty()) 5039 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5040 5041 // Store the return address to the appropriate stack slot. 5042 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5043 5044 // Emit callseq_end just before tailcall node. 5045 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5046 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5047 InFlag = Chain.getValue(1); 5048 } 5049 5050 // Is this global address that of a function that can be called by name? (as 5051 // opposed to something that must hold a descriptor for an indirect call). 5052 static bool isFunctionGlobalAddress(SDValue Callee) { 5053 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5054 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5055 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5056 return false; 5057 5058 return G->getGlobal()->getValueType()->isFunctionTy(); 5059 } 5060 5061 return false; 5062 } 5063 5064 SDValue PPCTargetLowering::LowerCallResult( 5065 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5066 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5067 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5068 SmallVector<CCValAssign, 16> RVLocs; 5069 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5070 *DAG.getContext()); 5071 5072 CCRetInfo.AnalyzeCallResult( 5073 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5074 ? RetCC_PPC_Cold 5075 : RetCC_PPC); 5076 5077 // Copy all of the result registers out of their specified physreg. 5078 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5079 CCValAssign &VA = RVLocs[i]; 5080 assert(VA.isRegLoc() && "Can only return in registers!"); 5081 5082 SDValue Val; 5083 5084 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5085 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5086 InFlag); 5087 Chain = Lo.getValue(1); 5088 InFlag = Lo.getValue(2); 5089 VA = RVLocs[++i]; // skip ahead to next loc 5090 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5091 InFlag); 5092 Chain = Hi.getValue(1); 5093 InFlag = Hi.getValue(2); 5094 if (!Subtarget.isLittleEndian()) 5095 std::swap (Lo, Hi); 5096 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5097 } else { 5098 Val = DAG.getCopyFromReg(Chain, dl, 5099 VA.getLocReg(), VA.getLocVT(), InFlag); 5100 Chain = Val.getValue(1); 5101 InFlag = Val.getValue(2); 5102 } 5103 5104 switch (VA.getLocInfo()) { 5105 default: llvm_unreachable("Unknown loc info!"); 5106 case CCValAssign::Full: break; 5107 case CCValAssign::AExt: 5108 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5109 break; 5110 case CCValAssign::ZExt: 5111 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5112 DAG.getValueType(VA.getValVT())); 5113 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5114 break; 5115 case CCValAssign::SExt: 5116 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5117 DAG.getValueType(VA.getValVT())); 5118 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5119 break; 5120 } 5121 5122 InVals.push_back(Val); 5123 } 5124 5125 return Chain; 5126 } 5127 5128 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5129 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5130 // PatchPoint calls are not indirect. 5131 if (isPatchPoint) 5132 return false; 5133 5134 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5135 return false; 5136 5137 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5138 // becuase the immediate function pointer points to a descriptor instead of 5139 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5140 // pointer immediate points to the global entry point, while the BLA would 5141 // need to jump to the local entry point (see rL211174). 5142 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5143 isBLACompatibleAddress(Callee, DAG)) 5144 return false; 5145 5146 return true; 5147 } 5148 5149 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5150 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5151 return Subtarget.isAIXABI() || 5152 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5153 } 5154 5155 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5156 const Function &Caller, 5157 const SDValue &Callee, 5158 const PPCSubtarget &Subtarget, 5159 const TargetMachine &TM) { 5160 if (CFlags.IsTailCall) 5161 return PPCISD::TC_RETURN; 5162 5163 // This is a call through a function pointer. 5164 if (CFlags.IsIndirect) { 5165 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5166 // indirect calls. The save of the caller's TOC pointer to the stack will be 5167 // inserted into the DAG as part of call lowering. The restore of the TOC 5168 // pointer is modeled by using a pseudo instruction for the call opcode that 5169 // represents the 2 instruction sequence of an indirect branch and link, 5170 // immediately followed by a load of the TOC pointer from the the stack save 5171 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5172 // as it is not saved or used. 5173 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5174 : PPCISD::BCTRL; 5175 } 5176 5177 if (Subtarget.isUsingPCRelativeCalls()) { 5178 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5179 return PPCISD::CALL_NOTOC; 5180 } 5181 5182 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5183 // immediately following the call instruction if the caller and callee may 5184 // have different TOC bases. At link time if the linker determines the calls 5185 // may not share a TOC base, the call is redirected to a trampoline inserted 5186 // by the linker. The trampoline will (among other things) save the callers 5187 // TOC pointer at an ABI designated offset in the linkage area and the linker 5188 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5189 // into gpr2. 5190 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5191 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5192 : PPCISD::CALL_NOP; 5193 5194 return PPCISD::CALL; 5195 } 5196 5197 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5198 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5199 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5200 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5201 return SDValue(Dest, 0); 5202 5203 // Returns true if the callee is local, and false otherwise. 5204 auto isLocalCallee = [&]() { 5205 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5206 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5207 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5208 5209 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5210 !dyn_cast_or_null<GlobalIFunc>(GV); 5211 }; 5212 5213 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5214 // a static relocation model causes some versions of GNU LD (2.17.50, at 5215 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5216 // built with secure-PLT. 5217 bool UsePlt = 5218 Subtarget.is32BitELFABI() && !isLocalCallee() && 5219 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5220 5221 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5222 const TargetMachine &TM = Subtarget.getTargetMachine(); 5223 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5224 MCSymbolXCOFF *S = 5225 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5226 5227 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5228 return DAG.getMCSymbol(S, PtrVT); 5229 }; 5230 5231 if (isFunctionGlobalAddress(Callee)) { 5232 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5233 5234 if (Subtarget.isAIXABI()) { 5235 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5236 return getAIXFuncEntryPointSymbolSDNode(GV); 5237 } 5238 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5239 UsePlt ? PPCII::MO_PLT : 0); 5240 } 5241 5242 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5243 const char *SymName = S->getSymbol(); 5244 if (Subtarget.isAIXABI()) { 5245 // If there exists a user-declared function whose name is the same as the 5246 // ExternalSymbol's, then we pick up the user-declared version. 5247 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5248 if (const Function *F = 5249 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5250 return getAIXFuncEntryPointSymbolSDNode(F); 5251 5252 // On AIX, direct function calls reference the symbol for the function's 5253 // entry point, which is named by prepending a "." before the function's 5254 // C-linkage name. A Qualname is returned here because an external 5255 // function entry point is a csect with XTY_ER property. 5256 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5257 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5258 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5259 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5260 SectionKind::getMetadata()); 5261 return Sec->getQualNameSymbol(); 5262 }; 5263 5264 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5265 } 5266 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5267 UsePlt ? PPCII::MO_PLT : 0); 5268 } 5269 5270 // No transformation needed. 5271 assert(Callee.getNode() && "What no callee?"); 5272 return Callee; 5273 } 5274 5275 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5276 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5277 "Expected a CALLSEQ_STARTSDNode."); 5278 5279 // The last operand is the chain, except when the node has glue. If the node 5280 // has glue, then the last operand is the glue, and the chain is the second 5281 // last operand. 5282 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5283 if (LastValue.getValueType() != MVT::Glue) 5284 return LastValue; 5285 5286 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5287 } 5288 5289 // Creates the node that moves a functions address into the count register 5290 // to prepare for an indirect call instruction. 5291 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5292 SDValue &Glue, SDValue &Chain, 5293 const SDLoc &dl) { 5294 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5295 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5296 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5297 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5298 // The glue is the second value produced. 5299 Glue = Chain.getValue(1); 5300 } 5301 5302 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5303 SDValue &Glue, SDValue &Chain, 5304 SDValue CallSeqStart, 5305 const CallBase *CB, const SDLoc &dl, 5306 bool hasNest, 5307 const PPCSubtarget &Subtarget) { 5308 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5309 // entry point, but to the function descriptor (the function entry point 5310 // address is part of the function descriptor though). 5311 // The function descriptor is a three doubleword structure with the 5312 // following fields: function entry point, TOC base address and 5313 // environment pointer. 5314 // Thus for a call through a function pointer, the following actions need 5315 // to be performed: 5316 // 1. Save the TOC of the caller in the TOC save area of its stack 5317 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5318 // 2. Load the address of the function entry point from the function 5319 // descriptor. 5320 // 3. Load the TOC of the callee from the function descriptor into r2. 5321 // 4. Load the environment pointer from the function descriptor into 5322 // r11. 5323 // 5. Branch to the function entry point address. 5324 // 6. On return of the callee, the TOC of the caller needs to be 5325 // restored (this is done in FinishCall()). 5326 // 5327 // The loads are scheduled at the beginning of the call sequence, and the 5328 // register copies are flagged together to ensure that no other 5329 // operations can be scheduled in between. E.g. without flagging the 5330 // copies together, a TOC access in the caller could be scheduled between 5331 // the assignment of the callee TOC and the branch to the callee, which leads 5332 // to incorrect code. 5333 5334 // Start by loading the function address from the descriptor. 5335 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5336 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5337 ? (MachineMemOperand::MODereferenceable | 5338 MachineMemOperand::MOInvariant) 5339 : MachineMemOperand::MONone; 5340 5341 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5342 5343 // Registers used in building the DAG. 5344 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5345 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5346 5347 // Offsets of descriptor members. 5348 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5349 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5350 5351 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5352 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5353 5354 // One load for the functions entry point address. 5355 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5356 Alignment, MMOFlags); 5357 5358 // One for loading the TOC anchor for the module that contains the called 5359 // function. 5360 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5361 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5362 SDValue TOCPtr = 5363 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5364 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5365 5366 // One for loading the environment pointer. 5367 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5368 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5369 SDValue LoadEnvPtr = 5370 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5371 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5372 5373 5374 // Then copy the newly loaded TOC anchor to the TOC pointer. 5375 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5376 Chain = TOCVal.getValue(0); 5377 Glue = TOCVal.getValue(1); 5378 5379 // If the function call has an explicit 'nest' parameter, it takes the 5380 // place of the environment pointer. 5381 assert((!hasNest || !Subtarget.isAIXABI()) && 5382 "Nest parameter is not supported on AIX."); 5383 if (!hasNest) { 5384 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5385 Chain = EnvVal.getValue(0); 5386 Glue = EnvVal.getValue(1); 5387 } 5388 5389 // The rest of the indirect call sequence is the same as the non-descriptor 5390 // DAG. 5391 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5392 } 5393 5394 static void 5395 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5396 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5397 SelectionDAG &DAG, 5398 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5399 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5400 const PPCSubtarget &Subtarget) { 5401 const bool IsPPC64 = Subtarget.isPPC64(); 5402 // MVT for a general purpose register. 5403 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5404 5405 // First operand is always the chain. 5406 Ops.push_back(Chain); 5407 5408 // If it's a direct call pass the callee as the second operand. 5409 if (!CFlags.IsIndirect) 5410 Ops.push_back(Callee); 5411 else { 5412 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5413 5414 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5415 // on the stack (this would have been done in `LowerCall_64SVR4` or 5416 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5417 // represents both the indirect branch and a load that restores the TOC 5418 // pointer from the linkage area. The operand for the TOC restore is an add 5419 // of the TOC save offset to the stack pointer. This must be the second 5420 // operand: after the chain input but before any other variadic arguments. 5421 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5422 // saved or used. 5423 if (isTOCSaveRestoreRequired(Subtarget)) { 5424 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5425 5426 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5427 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5428 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5429 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5430 Ops.push_back(AddTOC); 5431 } 5432 5433 // Add the register used for the environment pointer. 5434 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5435 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5436 RegVT)); 5437 5438 5439 // Add CTR register as callee so a bctr can be emitted later. 5440 if (CFlags.IsTailCall) 5441 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5442 } 5443 5444 // If this is a tail call add stack pointer delta. 5445 if (CFlags.IsTailCall) 5446 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5447 5448 // Add argument registers to the end of the list so that they are known live 5449 // into the call. 5450 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5451 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5452 RegsToPass[i].second.getValueType())); 5453 5454 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5455 // no way to mark dependencies as implicit here. 5456 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5457 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5458 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5459 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5460 5461 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5462 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5463 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5464 5465 // Add a register mask operand representing the call-preserved registers. 5466 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5467 const uint32_t *Mask = 5468 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5469 assert(Mask && "Missing call preserved mask for calling convention"); 5470 Ops.push_back(DAG.getRegisterMask(Mask)); 5471 5472 // If the glue is valid, it is the last operand. 5473 if (Glue.getNode()) 5474 Ops.push_back(Glue); 5475 } 5476 5477 SDValue PPCTargetLowering::FinishCall( 5478 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5479 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5480 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5481 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5482 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5483 5484 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5485 Subtarget.isAIXABI()) 5486 setUsesTOCBasePtr(DAG); 5487 5488 unsigned CallOpc = 5489 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5490 Subtarget, DAG.getTarget()); 5491 5492 if (!CFlags.IsIndirect) 5493 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5494 else if (Subtarget.usesFunctionDescriptors()) 5495 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5496 dl, CFlags.HasNest, Subtarget); 5497 else 5498 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5499 5500 // Build the operand list for the call instruction. 5501 SmallVector<SDValue, 8> Ops; 5502 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5503 SPDiff, Subtarget); 5504 5505 // Emit tail call. 5506 if (CFlags.IsTailCall) { 5507 // Indirect tail call when using PC Relative calls do not have the same 5508 // constraints. 5509 assert(((Callee.getOpcode() == ISD::Register && 5510 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5511 Callee.getOpcode() == ISD::TargetExternalSymbol || 5512 Callee.getOpcode() == ISD::TargetGlobalAddress || 5513 isa<ConstantSDNode>(Callee) || 5514 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5515 "Expecting a global address, external symbol, absolute value, " 5516 "register or an indirect tail call when PC Relative calls are " 5517 "used."); 5518 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5519 assert(CallOpc == PPCISD::TC_RETURN && 5520 "Unexpected call opcode for a tail call."); 5521 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5522 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5523 } 5524 5525 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5526 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5527 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5528 Glue = Chain.getValue(1); 5529 5530 // When performing tail call optimization the callee pops its arguments off 5531 // the stack. Account for this here so these bytes can be pushed back on in 5532 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5533 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5534 getTargetMachine().Options.GuaranteedTailCallOpt) 5535 ? NumBytes 5536 : 0; 5537 5538 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5539 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5540 Glue, dl); 5541 Glue = Chain.getValue(1); 5542 5543 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5544 DAG, InVals); 5545 } 5546 5547 SDValue 5548 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5549 SmallVectorImpl<SDValue> &InVals) const { 5550 SelectionDAG &DAG = CLI.DAG; 5551 SDLoc &dl = CLI.DL; 5552 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5553 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5554 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5555 SDValue Chain = CLI.Chain; 5556 SDValue Callee = CLI.Callee; 5557 bool &isTailCall = CLI.IsTailCall; 5558 CallingConv::ID CallConv = CLI.CallConv; 5559 bool isVarArg = CLI.IsVarArg; 5560 bool isPatchPoint = CLI.IsPatchPoint; 5561 const CallBase *CB = CLI.CB; 5562 5563 if (isTailCall) { 5564 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5565 isTailCall = false; 5566 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5567 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5568 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5569 else 5570 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5571 Ins, DAG); 5572 if (isTailCall) { 5573 ++NumTailCalls; 5574 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5575 ++NumSiblingCalls; 5576 5577 // PC Relative calls no longer guarantee that the callee is a Global 5578 // Address Node. The callee could be an indirect tail call in which 5579 // case the SDValue for the callee could be a load (to load the address 5580 // of a function pointer) or it may be a register copy (to move the 5581 // address of the callee from a function parameter into a virtual 5582 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5583 assert((Subtarget.isUsingPCRelativeCalls() || 5584 isa<GlobalAddressSDNode>(Callee)) && 5585 "Callee should be an llvm::Function object."); 5586 5587 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5588 << "\nTCO callee: "); 5589 LLVM_DEBUG(Callee.dump()); 5590 } 5591 } 5592 5593 if (!isTailCall && CB && CB->isMustTailCall()) 5594 report_fatal_error("failed to perform tail call elimination on a call " 5595 "site marked musttail"); 5596 5597 // When long calls (i.e. indirect calls) are always used, calls are always 5598 // made via function pointer. If we have a function name, first translate it 5599 // into a pointer. 5600 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5601 !isTailCall) 5602 Callee = LowerGlobalAddress(Callee, DAG); 5603 5604 CallFlags CFlags( 5605 CallConv, isTailCall, isVarArg, isPatchPoint, 5606 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5607 // hasNest 5608 Subtarget.is64BitELFABI() && 5609 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5610 CLI.NoMerge); 5611 5612 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5613 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5614 InVals, CB); 5615 5616 if (Subtarget.isSVR4ABI()) 5617 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5618 InVals, CB); 5619 5620 if (Subtarget.isAIXABI()) 5621 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5622 InVals, CB); 5623 5624 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5625 InVals, CB); 5626 } 5627 5628 SDValue PPCTargetLowering::LowerCall_32SVR4( 5629 SDValue Chain, SDValue Callee, CallFlags CFlags, 5630 const SmallVectorImpl<ISD::OutputArg> &Outs, 5631 const SmallVectorImpl<SDValue> &OutVals, 5632 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5633 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5634 const CallBase *CB) const { 5635 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5636 // of the 32-bit SVR4 ABI stack frame layout. 5637 5638 const CallingConv::ID CallConv = CFlags.CallConv; 5639 const bool IsVarArg = CFlags.IsVarArg; 5640 const bool IsTailCall = CFlags.IsTailCall; 5641 5642 assert((CallConv == CallingConv::C || 5643 CallConv == CallingConv::Cold || 5644 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5645 5646 const Align PtrAlign(4); 5647 5648 MachineFunction &MF = DAG.getMachineFunction(); 5649 5650 // Mark this function as potentially containing a function that contains a 5651 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5652 // and restoring the callers stack pointer in this functions epilog. This is 5653 // done because by tail calling the called function might overwrite the value 5654 // in this function's (MF) stack pointer stack slot 0(SP). 5655 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5656 CallConv == CallingConv::Fast) 5657 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5658 5659 // Count how many bytes are to be pushed on the stack, including the linkage 5660 // area, parameter list area and the part of the local variable space which 5661 // contains copies of aggregates which are passed by value. 5662 5663 // Assign locations to all of the outgoing arguments. 5664 SmallVector<CCValAssign, 16> ArgLocs; 5665 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5666 5667 // Reserve space for the linkage area on the stack. 5668 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5669 PtrAlign); 5670 if (useSoftFloat()) 5671 CCInfo.PreAnalyzeCallOperands(Outs); 5672 5673 if (IsVarArg) { 5674 // Handle fixed and variable vector arguments differently. 5675 // Fixed vector arguments go into registers as long as registers are 5676 // available. Variable vector arguments always go into memory. 5677 unsigned NumArgs = Outs.size(); 5678 5679 for (unsigned i = 0; i != NumArgs; ++i) { 5680 MVT ArgVT = Outs[i].VT; 5681 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5682 bool Result; 5683 5684 if (Outs[i].IsFixed) { 5685 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5686 CCInfo); 5687 } else { 5688 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5689 ArgFlags, CCInfo); 5690 } 5691 5692 if (Result) { 5693 #ifndef NDEBUG 5694 errs() << "Call operand #" << i << " has unhandled type " 5695 << EVT(ArgVT).getEVTString() << "\n"; 5696 #endif 5697 llvm_unreachable(nullptr); 5698 } 5699 } 5700 } else { 5701 // All arguments are treated the same. 5702 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5703 } 5704 CCInfo.clearWasPPCF128(); 5705 5706 // Assign locations to all of the outgoing aggregate by value arguments. 5707 SmallVector<CCValAssign, 16> ByValArgLocs; 5708 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5709 5710 // Reserve stack space for the allocations in CCInfo. 5711 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5712 5713 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5714 5715 // Size of the linkage area, parameter list area and the part of the local 5716 // space variable where copies of aggregates which are passed by value are 5717 // stored. 5718 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5719 5720 // Calculate by how many bytes the stack has to be adjusted in case of tail 5721 // call optimization. 5722 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5723 5724 // Adjust the stack pointer for the new arguments... 5725 // These operations are automatically eliminated by the prolog/epilog pass 5726 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5727 SDValue CallSeqStart = Chain; 5728 5729 // Load the return address and frame pointer so it can be moved somewhere else 5730 // later. 5731 SDValue LROp, FPOp; 5732 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5733 5734 // Set up a copy of the stack pointer for use loading and storing any 5735 // arguments that may not fit in the registers available for argument 5736 // passing. 5737 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5738 5739 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5740 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5741 SmallVector<SDValue, 8> MemOpChains; 5742 5743 bool seenFloatArg = false; 5744 // Walk the register/memloc assignments, inserting copies/loads. 5745 // i - Tracks the index into the list of registers allocated for the call 5746 // RealArgIdx - Tracks the index into the list of actual function arguments 5747 // j - Tracks the index into the list of byval arguments 5748 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5749 i != e; 5750 ++i, ++RealArgIdx) { 5751 CCValAssign &VA = ArgLocs[i]; 5752 SDValue Arg = OutVals[RealArgIdx]; 5753 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5754 5755 if (Flags.isByVal()) { 5756 // Argument is an aggregate which is passed by value, thus we need to 5757 // create a copy of it in the local variable space of the current stack 5758 // frame (which is the stack frame of the caller) and pass the address of 5759 // this copy to the callee. 5760 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5761 CCValAssign &ByValVA = ByValArgLocs[j++]; 5762 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5763 5764 // Memory reserved in the local variable space of the callers stack frame. 5765 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5766 5767 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5768 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5769 StackPtr, PtrOff); 5770 5771 // Create a copy of the argument in the local area of the current 5772 // stack frame. 5773 SDValue MemcpyCall = 5774 CreateCopyOfByValArgument(Arg, PtrOff, 5775 CallSeqStart.getNode()->getOperand(0), 5776 Flags, DAG, dl); 5777 5778 // This must go outside the CALLSEQ_START..END. 5779 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5780 SDLoc(MemcpyCall)); 5781 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5782 NewCallSeqStart.getNode()); 5783 Chain = CallSeqStart = NewCallSeqStart; 5784 5785 // Pass the address of the aggregate copy on the stack either in a 5786 // physical register or in the parameter list area of the current stack 5787 // frame to the callee. 5788 Arg = PtrOff; 5789 } 5790 5791 // When useCRBits() is true, there can be i1 arguments. 5792 // It is because getRegisterType(MVT::i1) => MVT::i1, 5793 // and for other integer types getRegisterType() => MVT::i32. 5794 // Extend i1 and ensure callee will get i32. 5795 if (Arg.getValueType() == MVT::i1) 5796 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5797 dl, MVT::i32, Arg); 5798 5799 if (VA.isRegLoc()) { 5800 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5801 // Put argument in a physical register. 5802 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5803 bool IsLE = Subtarget.isLittleEndian(); 5804 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5805 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5806 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5807 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5808 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5809 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5810 SVal.getValue(0))); 5811 } else 5812 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5813 } else { 5814 // Put argument in the parameter list area of the current stack frame. 5815 assert(VA.isMemLoc()); 5816 unsigned LocMemOffset = VA.getLocMemOffset(); 5817 5818 if (!IsTailCall) { 5819 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5820 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5821 StackPtr, PtrOff); 5822 5823 MemOpChains.push_back( 5824 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5825 } else { 5826 // Calculate and remember argument location. 5827 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5828 TailCallArguments); 5829 } 5830 } 5831 } 5832 5833 if (!MemOpChains.empty()) 5834 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5835 5836 // Build a sequence of copy-to-reg nodes chained together with token chain 5837 // and flag operands which copy the outgoing args into the appropriate regs. 5838 SDValue InFlag; 5839 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5840 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5841 RegsToPass[i].second, InFlag); 5842 InFlag = Chain.getValue(1); 5843 } 5844 5845 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5846 // registers. 5847 if (IsVarArg) { 5848 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5849 SDValue Ops[] = { Chain, InFlag }; 5850 5851 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5852 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5853 5854 InFlag = Chain.getValue(1); 5855 } 5856 5857 if (IsTailCall) 5858 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5859 TailCallArguments); 5860 5861 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5862 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5863 } 5864 5865 // Copy an argument into memory, being careful to do this outside the 5866 // call sequence for the call to which the argument belongs. 5867 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5868 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5869 SelectionDAG &DAG, const SDLoc &dl) const { 5870 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5871 CallSeqStart.getNode()->getOperand(0), 5872 Flags, DAG, dl); 5873 // The MEMCPY must go outside the CALLSEQ_START..END. 5874 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5875 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5876 SDLoc(MemcpyCall)); 5877 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5878 NewCallSeqStart.getNode()); 5879 return NewCallSeqStart; 5880 } 5881 5882 SDValue PPCTargetLowering::LowerCall_64SVR4( 5883 SDValue Chain, SDValue Callee, CallFlags CFlags, 5884 const SmallVectorImpl<ISD::OutputArg> &Outs, 5885 const SmallVectorImpl<SDValue> &OutVals, 5886 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5887 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5888 const CallBase *CB) const { 5889 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5890 bool isLittleEndian = Subtarget.isLittleEndian(); 5891 unsigned NumOps = Outs.size(); 5892 bool IsSibCall = false; 5893 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5894 5895 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5896 unsigned PtrByteSize = 8; 5897 5898 MachineFunction &MF = DAG.getMachineFunction(); 5899 5900 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5901 IsSibCall = true; 5902 5903 // Mark this function as potentially containing a function that contains a 5904 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5905 // and restoring the callers stack pointer in this functions epilog. This is 5906 // done because by tail calling the called function might overwrite the value 5907 // in this function's (MF) stack pointer stack slot 0(SP). 5908 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5909 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5910 5911 assert(!(IsFastCall && CFlags.IsVarArg) && 5912 "fastcc not supported on varargs functions"); 5913 5914 // Count how many bytes are to be pushed on the stack, including the linkage 5915 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5916 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5917 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5918 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5919 unsigned NumBytes = LinkageSize; 5920 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5921 5922 static const MCPhysReg GPR[] = { 5923 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5924 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5925 }; 5926 static const MCPhysReg VR[] = { 5927 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5928 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5929 }; 5930 5931 const unsigned NumGPRs = array_lengthof(GPR); 5932 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5933 const unsigned NumVRs = array_lengthof(VR); 5934 5935 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5936 // can be passed to the callee in registers. 5937 // For the fast calling convention, there is another check below. 5938 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5939 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5940 if (!HasParameterArea) { 5941 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5942 unsigned AvailableFPRs = NumFPRs; 5943 unsigned AvailableVRs = NumVRs; 5944 unsigned NumBytesTmp = NumBytes; 5945 for (unsigned i = 0; i != NumOps; ++i) { 5946 if (Outs[i].Flags.isNest()) continue; 5947 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5948 PtrByteSize, LinkageSize, ParamAreaSize, 5949 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5950 HasParameterArea = true; 5951 } 5952 } 5953 5954 // When using the fast calling convention, we don't provide backing for 5955 // arguments that will be in registers. 5956 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5957 5958 // Avoid allocating parameter area for fastcc functions if all the arguments 5959 // can be passed in the registers. 5960 if (IsFastCall) 5961 HasParameterArea = false; 5962 5963 // Add up all the space actually used. 5964 for (unsigned i = 0; i != NumOps; ++i) { 5965 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5966 EVT ArgVT = Outs[i].VT; 5967 EVT OrigVT = Outs[i].ArgVT; 5968 5969 if (Flags.isNest()) 5970 continue; 5971 5972 if (IsFastCall) { 5973 if (Flags.isByVal()) { 5974 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5975 if (NumGPRsUsed > NumGPRs) 5976 HasParameterArea = true; 5977 } else { 5978 switch (ArgVT.getSimpleVT().SimpleTy) { 5979 default: llvm_unreachable("Unexpected ValueType for argument!"); 5980 case MVT::i1: 5981 case MVT::i32: 5982 case MVT::i64: 5983 if (++NumGPRsUsed <= NumGPRs) 5984 continue; 5985 break; 5986 case MVT::v4i32: 5987 case MVT::v8i16: 5988 case MVT::v16i8: 5989 case MVT::v2f64: 5990 case MVT::v2i64: 5991 case MVT::v1i128: 5992 case MVT::f128: 5993 if (++NumVRsUsed <= NumVRs) 5994 continue; 5995 break; 5996 case MVT::v4f32: 5997 if (++NumVRsUsed <= NumVRs) 5998 continue; 5999 break; 6000 case MVT::f32: 6001 case MVT::f64: 6002 if (++NumFPRsUsed <= NumFPRs) 6003 continue; 6004 break; 6005 } 6006 HasParameterArea = true; 6007 } 6008 } 6009 6010 /* Respect alignment of argument on the stack. */ 6011 auto Alignement = 6012 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6013 NumBytes = alignTo(NumBytes, Alignement); 6014 6015 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6016 if (Flags.isInConsecutiveRegsLast()) 6017 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6018 } 6019 6020 unsigned NumBytesActuallyUsed = NumBytes; 6021 6022 // In the old ELFv1 ABI, 6023 // the prolog code of the callee may store up to 8 GPR argument registers to 6024 // the stack, allowing va_start to index over them in memory if its varargs. 6025 // Because we cannot tell if this is needed on the caller side, we have to 6026 // conservatively assume that it is needed. As such, make sure we have at 6027 // least enough stack space for the caller to store the 8 GPRs. 6028 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6029 // really requires memory operands, e.g. a vararg function. 6030 if (HasParameterArea) 6031 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6032 else 6033 NumBytes = LinkageSize; 6034 6035 // Tail call needs the stack to be aligned. 6036 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6037 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6038 6039 int SPDiff = 0; 6040 6041 // Calculate by how many bytes the stack has to be adjusted in case of tail 6042 // call optimization. 6043 if (!IsSibCall) 6044 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6045 6046 // To protect arguments on the stack from being clobbered in a tail call, 6047 // force all the loads to happen before doing any other lowering. 6048 if (CFlags.IsTailCall) 6049 Chain = DAG.getStackArgumentTokenFactor(Chain); 6050 6051 // Adjust the stack pointer for the new arguments... 6052 // These operations are automatically eliminated by the prolog/epilog pass 6053 if (!IsSibCall) 6054 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6055 SDValue CallSeqStart = Chain; 6056 6057 // Load the return address and frame pointer so it can be move somewhere else 6058 // later. 6059 SDValue LROp, FPOp; 6060 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6061 6062 // Set up a copy of the stack pointer for use loading and storing any 6063 // arguments that may not fit in the registers available for argument 6064 // passing. 6065 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6066 6067 // Figure out which arguments are going to go in registers, and which in 6068 // memory. Also, if this is a vararg function, floating point operations 6069 // must be stored to our stack, and loaded into integer regs as well, if 6070 // any integer regs are available for argument passing. 6071 unsigned ArgOffset = LinkageSize; 6072 6073 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6074 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6075 6076 SmallVector<SDValue, 8> MemOpChains; 6077 for (unsigned i = 0; i != NumOps; ++i) { 6078 SDValue Arg = OutVals[i]; 6079 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6080 EVT ArgVT = Outs[i].VT; 6081 EVT OrigVT = Outs[i].ArgVT; 6082 6083 // PtrOff will be used to store the current argument to the stack if a 6084 // register cannot be found for it. 6085 SDValue PtrOff; 6086 6087 // We re-align the argument offset for each argument, except when using the 6088 // fast calling convention, when we need to make sure we do that only when 6089 // we'll actually use a stack slot. 6090 auto ComputePtrOff = [&]() { 6091 /* Respect alignment of argument on the stack. */ 6092 auto Alignment = 6093 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6094 ArgOffset = alignTo(ArgOffset, Alignment); 6095 6096 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6097 6098 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6099 }; 6100 6101 if (!IsFastCall) { 6102 ComputePtrOff(); 6103 6104 /* Compute GPR index associated with argument offset. */ 6105 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6106 GPR_idx = std::min(GPR_idx, NumGPRs); 6107 } 6108 6109 // Promote integers to 64-bit values. 6110 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6111 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6112 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6113 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6114 } 6115 6116 // FIXME memcpy is used way more than necessary. Correctness first. 6117 // Note: "by value" is code for passing a structure by value, not 6118 // basic types. 6119 if (Flags.isByVal()) { 6120 // Note: Size includes alignment padding, so 6121 // struct x { short a; char b; } 6122 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6123 // These are the proper values we need for right-justifying the 6124 // aggregate in a parameter register. 6125 unsigned Size = Flags.getByValSize(); 6126 6127 // An empty aggregate parameter takes up no storage and no 6128 // registers. 6129 if (Size == 0) 6130 continue; 6131 6132 if (IsFastCall) 6133 ComputePtrOff(); 6134 6135 // All aggregates smaller than 8 bytes must be passed right-justified. 6136 if (Size==1 || Size==2 || Size==4) { 6137 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6138 if (GPR_idx != NumGPRs) { 6139 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6140 MachinePointerInfo(), VT); 6141 MemOpChains.push_back(Load.getValue(1)); 6142 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6143 6144 ArgOffset += PtrByteSize; 6145 continue; 6146 } 6147 } 6148 6149 if (GPR_idx == NumGPRs && Size < 8) { 6150 SDValue AddPtr = PtrOff; 6151 if (!isLittleEndian) { 6152 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6153 PtrOff.getValueType()); 6154 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6155 } 6156 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6157 CallSeqStart, 6158 Flags, DAG, dl); 6159 ArgOffset += PtrByteSize; 6160 continue; 6161 } 6162 // Copy entire object into memory. There are cases where gcc-generated 6163 // code assumes it is there, even if it could be put entirely into 6164 // registers. (This is not what the doc says.) 6165 6166 // FIXME: The above statement is likely due to a misunderstanding of the 6167 // documents. All arguments must be copied into the parameter area BY 6168 // THE CALLEE in the event that the callee takes the address of any 6169 // formal argument. That has not yet been implemented. However, it is 6170 // reasonable to use the stack area as a staging area for the register 6171 // load. 6172 6173 // Skip this for small aggregates, as we will use the same slot for a 6174 // right-justified copy, below. 6175 if (Size >= 8) 6176 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6177 CallSeqStart, 6178 Flags, DAG, dl); 6179 6180 // When a register is available, pass a small aggregate right-justified. 6181 if (Size < 8 && GPR_idx != NumGPRs) { 6182 // The easiest way to get this right-justified in a register 6183 // is to copy the structure into the rightmost portion of a 6184 // local variable slot, then load the whole slot into the 6185 // register. 6186 // FIXME: The memcpy seems to produce pretty awful code for 6187 // small aggregates, particularly for packed ones. 6188 // FIXME: It would be preferable to use the slot in the 6189 // parameter save area instead of a new local variable. 6190 SDValue AddPtr = PtrOff; 6191 if (!isLittleEndian) { 6192 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6193 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6194 } 6195 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6196 CallSeqStart, 6197 Flags, DAG, dl); 6198 6199 // Load the slot into the register. 6200 SDValue Load = 6201 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6202 MemOpChains.push_back(Load.getValue(1)); 6203 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6204 6205 // Done with this argument. 6206 ArgOffset += PtrByteSize; 6207 continue; 6208 } 6209 6210 // For aggregates larger than PtrByteSize, copy the pieces of the 6211 // object that fit into registers from the parameter save area. 6212 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6213 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6214 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6215 if (GPR_idx != NumGPRs) { 6216 SDValue Load = 6217 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6218 MemOpChains.push_back(Load.getValue(1)); 6219 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6220 ArgOffset += PtrByteSize; 6221 } else { 6222 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6223 break; 6224 } 6225 } 6226 continue; 6227 } 6228 6229 switch (Arg.getSimpleValueType().SimpleTy) { 6230 default: llvm_unreachable("Unexpected ValueType for argument!"); 6231 case MVT::i1: 6232 case MVT::i32: 6233 case MVT::i64: 6234 if (Flags.isNest()) { 6235 // The 'nest' parameter, if any, is passed in R11. 6236 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6237 break; 6238 } 6239 6240 // These can be scalar arguments or elements of an integer array type 6241 // passed directly. Clang may use those instead of "byval" aggregate 6242 // types to avoid forcing arguments to memory unnecessarily. 6243 if (GPR_idx != NumGPRs) { 6244 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6245 } else { 6246 if (IsFastCall) 6247 ComputePtrOff(); 6248 6249 assert(HasParameterArea && 6250 "Parameter area must exist to pass an argument in memory."); 6251 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6252 true, CFlags.IsTailCall, false, MemOpChains, 6253 TailCallArguments, dl); 6254 if (IsFastCall) 6255 ArgOffset += PtrByteSize; 6256 } 6257 if (!IsFastCall) 6258 ArgOffset += PtrByteSize; 6259 break; 6260 case MVT::f32: 6261 case MVT::f64: { 6262 // These can be scalar arguments or elements of a float array type 6263 // passed directly. The latter are used to implement ELFv2 homogenous 6264 // float aggregates. 6265 6266 // Named arguments go into FPRs first, and once they overflow, the 6267 // remaining arguments go into GPRs and then the parameter save area. 6268 // Unnamed arguments for vararg functions always go to GPRs and 6269 // then the parameter save area. For now, put all arguments to vararg 6270 // routines always in both locations (FPR *and* GPR or stack slot). 6271 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6272 bool NeededLoad = false; 6273 6274 // First load the argument into the next available FPR. 6275 if (FPR_idx != NumFPRs) 6276 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6277 6278 // Next, load the argument into GPR or stack slot if needed. 6279 if (!NeedGPROrStack) 6280 ; 6281 else if (GPR_idx != NumGPRs && !IsFastCall) { 6282 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6283 // once we support fp <-> gpr moves. 6284 6285 // In the non-vararg case, this can only ever happen in the 6286 // presence of f32 array types, since otherwise we never run 6287 // out of FPRs before running out of GPRs. 6288 SDValue ArgVal; 6289 6290 // Double values are always passed in a single GPR. 6291 if (Arg.getValueType() != MVT::f32) { 6292 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6293 6294 // Non-array float values are extended and passed in a GPR. 6295 } else if (!Flags.isInConsecutiveRegs()) { 6296 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6297 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6298 6299 // If we have an array of floats, we collect every odd element 6300 // together with its predecessor into one GPR. 6301 } else if (ArgOffset % PtrByteSize != 0) { 6302 SDValue Lo, Hi; 6303 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6304 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6305 if (!isLittleEndian) 6306 std::swap(Lo, Hi); 6307 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6308 6309 // The final element, if even, goes into the first half of a GPR. 6310 } else if (Flags.isInConsecutiveRegsLast()) { 6311 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6312 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6313 if (!isLittleEndian) 6314 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6315 DAG.getConstant(32, dl, MVT::i32)); 6316 6317 // Non-final even elements are skipped; they will be handled 6318 // together the with subsequent argument on the next go-around. 6319 } else 6320 ArgVal = SDValue(); 6321 6322 if (ArgVal.getNode()) 6323 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6324 } else { 6325 if (IsFastCall) 6326 ComputePtrOff(); 6327 6328 // Single-precision floating-point values are mapped to the 6329 // second (rightmost) word of the stack doubleword. 6330 if (Arg.getValueType() == MVT::f32 && 6331 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6332 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6333 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6334 } 6335 6336 assert(HasParameterArea && 6337 "Parameter area must exist to pass an argument in memory."); 6338 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6339 true, CFlags.IsTailCall, false, MemOpChains, 6340 TailCallArguments, dl); 6341 6342 NeededLoad = true; 6343 } 6344 // When passing an array of floats, the array occupies consecutive 6345 // space in the argument area; only round up to the next doubleword 6346 // at the end of the array. Otherwise, each float takes 8 bytes. 6347 if (!IsFastCall || NeededLoad) { 6348 ArgOffset += (Arg.getValueType() == MVT::f32 && 6349 Flags.isInConsecutiveRegs()) ? 4 : 8; 6350 if (Flags.isInConsecutiveRegsLast()) 6351 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6352 } 6353 break; 6354 } 6355 case MVT::v4f32: 6356 case MVT::v4i32: 6357 case MVT::v8i16: 6358 case MVT::v16i8: 6359 case MVT::v2f64: 6360 case MVT::v2i64: 6361 case MVT::v1i128: 6362 case MVT::f128: 6363 // These can be scalar arguments or elements of a vector array type 6364 // passed directly. The latter are used to implement ELFv2 homogenous 6365 // vector aggregates. 6366 6367 // For a varargs call, named arguments go into VRs or on the stack as 6368 // usual; unnamed arguments always go to the stack or the corresponding 6369 // GPRs when within range. For now, we always put the value in both 6370 // locations (or even all three). 6371 if (CFlags.IsVarArg) { 6372 assert(HasParameterArea && 6373 "Parameter area must exist if we have a varargs call."); 6374 // We could elide this store in the case where the object fits 6375 // entirely in R registers. Maybe later. 6376 SDValue Store = 6377 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6378 MemOpChains.push_back(Store); 6379 if (VR_idx != NumVRs) { 6380 SDValue Load = 6381 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6382 MemOpChains.push_back(Load.getValue(1)); 6383 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6384 } 6385 ArgOffset += 16; 6386 for (unsigned i=0; i<16; i+=PtrByteSize) { 6387 if (GPR_idx == NumGPRs) 6388 break; 6389 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6390 DAG.getConstant(i, dl, PtrVT)); 6391 SDValue Load = 6392 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6393 MemOpChains.push_back(Load.getValue(1)); 6394 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6395 } 6396 break; 6397 } 6398 6399 // Non-varargs Altivec params go into VRs or on the stack. 6400 if (VR_idx != NumVRs) { 6401 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6402 } else { 6403 if (IsFastCall) 6404 ComputePtrOff(); 6405 6406 assert(HasParameterArea && 6407 "Parameter area must exist to pass an argument in memory."); 6408 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6409 true, CFlags.IsTailCall, true, MemOpChains, 6410 TailCallArguments, dl); 6411 if (IsFastCall) 6412 ArgOffset += 16; 6413 } 6414 6415 if (!IsFastCall) 6416 ArgOffset += 16; 6417 break; 6418 } 6419 } 6420 6421 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6422 "mismatch in size of parameter area"); 6423 (void)NumBytesActuallyUsed; 6424 6425 if (!MemOpChains.empty()) 6426 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6427 6428 // Check if this is an indirect call (MTCTR/BCTRL). 6429 // See prepareDescriptorIndirectCall and buildCallOperands for more 6430 // information about calls through function pointers in the 64-bit SVR4 ABI. 6431 if (CFlags.IsIndirect) { 6432 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6433 // caller in the TOC save area. 6434 if (isTOCSaveRestoreRequired(Subtarget)) { 6435 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6436 // Load r2 into a virtual register and store it to the TOC save area. 6437 setUsesTOCBasePtr(DAG); 6438 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6439 // TOC save area offset. 6440 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6441 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6442 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6443 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6444 MachinePointerInfo::getStack( 6445 DAG.getMachineFunction(), TOCSaveOffset)); 6446 } 6447 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6448 // This does not mean the MTCTR instruction must use R12; it's easier 6449 // to model this as an extra parameter, so do that. 6450 if (isELFv2ABI && !CFlags.IsPatchPoint) 6451 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6452 } 6453 6454 // Build a sequence of copy-to-reg nodes chained together with token chain 6455 // and flag operands which copy the outgoing args into the appropriate regs. 6456 SDValue InFlag; 6457 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6458 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6459 RegsToPass[i].second, InFlag); 6460 InFlag = Chain.getValue(1); 6461 } 6462 6463 if (CFlags.IsTailCall && !IsSibCall) 6464 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6465 TailCallArguments); 6466 6467 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6468 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6469 } 6470 6471 SDValue PPCTargetLowering::LowerCall_Darwin( 6472 SDValue Chain, SDValue Callee, CallFlags CFlags, 6473 const SmallVectorImpl<ISD::OutputArg> &Outs, 6474 const SmallVectorImpl<SDValue> &OutVals, 6475 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6476 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6477 const CallBase *CB) const { 6478 unsigned NumOps = Outs.size(); 6479 6480 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6481 bool isPPC64 = PtrVT == MVT::i64; 6482 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6483 6484 MachineFunction &MF = DAG.getMachineFunction(); 6485 6486 // Mark this function as potentially containing a function that contains a 6487 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6488 // and restoring the callers stack pointer in this functions epilog. This is 6489 // done because by tail calling the called function might overwrite the value 6490 // in this function's (MF) stack pointer stack slot 0(SP). 6491 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6492 CFlags.CallConv == CallingConv::Fast) 6493 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6494 6495 // Count how many bytes are to be pushed on the stack, including the linkage 6496 // area, and parameter passing area. We start with 24/48 bytes, which is 6497 // prereserved space for [SP][CR][LR][3 x unused]. 6498 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6499 unsigned NumBytes = LinkageSize; 6500 6501 // Add up all the space actually used. 6502 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6503 // they all go in registers, but we must reserve stack space for them for 6504 // possible use by the caller. In varargs or 64-bit calls, parameters are 6505 // assigned stack space in order, with padding so Altivec parameters are 6506 // 16-byte aligned. 6507 unsigned nAltivecParamsAtEnd = 0; 6508 for (unsigned i = 0; i != NumOps; ++i) { 6509 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6510 EVT ArgVT = Outs[i].VT; 6511 // Varargs Altivec parameters are padded to a 16 byte boundary. 6512 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6513 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6514 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6515 if (!CFlags.IsVarArg && !isPPC64) { 6516 // Non-varargs Altivec parameters go after all the non-Altivec 6517 // parameters; handle those later so we know how much padding we need. 6518 nAltivecParamsAtEnd++; 6519 continue; 6520 } 6521 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6522 NumBytes = ((NumBytes+15)/16)*16; 6523 } 6524 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6525 } 6526 6527 // Allow for Altivec parameters at the end, if needed. 6528 if (nAltivecParamsAtEnd) { 6529 NumBytes = ((NumBytes+15)/16)*16; 6530 NumBytes += 16*nAltivecParamsAtEnd; 6531 } 6532 6533 // The prolog code of the callee may store up to 8 GPR argument registers to 6534 // the stack, allowing va_start to index over them in memory if its varargs. 6535 // Because we cannot tell if this is needed on the caller side, we have to 6536 // conservatively assume that it is needed. As such, make sure we have at 6537 // least enough stack space for the caller to store the 8 GPRs. 6538 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6539 6540 // Tail call needs the stack to be aligned. 6541 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6542 CFlags.CallConv == CallingConv::Fast) 6543 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6544 6545 // Calculate by how many bytes the stack has to be adjusted in case of tail 6546 // call optimization. 6547 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6548 6549 // To protect arguments on the stack from being clobbered in a tail call, 6550 // force all the loads to happen before doing any other lowering. 6551 if (CFlags.IsTailCall) 6552 Chain = DAG.getStackArgumentTokenFactor(Chain); 6553 6554 // Adjust the stack pointer for the new arguments... 6555 // These operations are automatically eliminated by the prolog/epilog pass 6556 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6557 SDValue CallSeqStart = Chain; 6558 6559 // Load the return address and frame pointer so it can be move somewhere else 6560 // later. 6561 SDValue LROp, FPOp; 6562 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6563 6564 // Set up a copy of the stack pointer for use loading and storing any 6565 // arguments that may not fit in the registers available for argument 6566 // passing. 6567 SDValue StackPtr; 6568 if (isPPC64) 6569 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6570 else 6571 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6572 6573 // Figure out which arguments are going to go in registers, and which in 6574 // memory. Also, if this is a vararg function, floating point operations 6575 // must be stored to our stack, and loaded into integer regs as well, if 6576 // any integer regs are available for argument passing. 6577 unsigned ArgOffset = LinkageSize; 6578 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6579 6580 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6581 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6582 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6583 }; 6584 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6585 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6586 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6587 }; 6588 static const MCPhysReg VR[] = { 6589 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6590 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6591 }; 6592 const unsigned NumGPRs = array_lengthof(GPR_32); 6593 const unsigned NumFPRs = 13; 6594 const unsigned NumVRs = array_lengthof(VR); 6595 6596 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6597 6598 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6599 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6600 6601 SmallVector<SDValue, 8> MemOpChains; 6602 for (unsigned i = 0; i != NumOps; ++i) { 6603 SDValue Arg = OutVals[i]; 6604 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6605 6606 // PtrOff will be used to store the current argument to the stack if a 6607 // register cannot be found for it. 6608 SDValue PtrOff; 6609 6610 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6611 6612 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6613 6614 // On PPC64, promote integers to 64-bit values. 6615 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6616 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6617 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6618 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6619 } 6620 6621 // FIXME memcpy is used way more than necessary. Correctness first. 6622 // Note: "by value" is code for passing a structure by value, not 6623 // basic types. 6624 if (Flags.isByVal()) { 6625 unsigned Size = Flags.getByValSize(); 6626 // Very small objects are passed right-justified. Everything else is 6627 // passed left-justified. 6628 if (Size==1 || Size==2) { 6629 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6630 if (GPR_idx != NumGPRs) { 6631 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6632 MachinePointerInfo(), VT); 6633 MemOpChains.push_back(Load.getValue(1)); 6634 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6635 6636 ArgOffset += PtrByteSize; 6637 } else { 6638 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6639 PtrOff.getValueType()); 6640 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6641 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6642 CallSeqStart, 6643 Flags, DAG, dl); 6644 ArgOffset += PtrByteSize; 6645 } 6646 continue; 6647 } 6648 // Copy entire object into memory. There are cases where gcc-generated 6649 // code assumes it is there, even if it could be put entirely into 6650 // registers. (This is not what the doc says.) 6651 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6652 CallSeqStart, 6653 Flags, DAG, dl); 6654 6655 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6656 // copy the pieces of the object that fit into registers from the 6657 // parameter save area. 6658 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6659 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6660 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6661 if (GPR_idx != NumGPRs) { 6662 SDValue Load = 6663 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6664 MemOpChains.push_back(Load.getValue(1)); 6665 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6666 ArgOffset += PtrByteSize; 6667 } else { 6668 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6669 break; 6670 } 6671 } 6672 continue; 6673 } 6674 6675 switch (Arg.getSimpleValueType().SimpleTy) { 6676 default: llvm_unreachable("Unexpected ValueType for argument!"); 6677 case MVT::i1: 6678 case MVT::i32: 6679 case MVT::i64: 6680 if (GPR_idx != NumGPRs) { 6681 if (Arg.getValueType() == MVT::i1) 6682 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6683 6684 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6685 } else { 6686 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6687 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6688 TailCallArguments, dl); 6689 } 6690 ArgOffset += PtrByteSize; 6691 break; 6692 case MVT::f32: 6693 case MVT::f64: 6694 if (FPR_idx != NumFPRs) { 6695 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6696 6697 if (CFlags.IsVarArg) { 6698 SDValue Store = 6699 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6700 MemOpChains.push_back(Store); 6701 6702 // Float varargs are always shadowed in available integer registers 6703 if (GPR_idx != NumGPRs) { 6704 SDValue Load = 6705 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6706 MemOpChains.push_back(Load.getValue(1)); 6707 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6708 } 6709 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6710 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6711 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6712 SDValue Load = 6713 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6714 MemOpChains.push_back(Load.getValue(1)); 6715 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6716 } 6717 } else { 6718 // If we have any FPRs remaining, we may also have GPRs remaining. 6719 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6720 // GPRs. 6721 if (GPR_idx != NumGPRs) 6722 ++GPR_idx; 6723 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6724 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6725 ++GPR_idx; 6726 } 6727 } else 6728 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6729 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6730 TailCallArguments, dl); 6731 if (isPPC64) 6732 ArgOffset += 8; 6733 else 6734 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6735 break; 6736 case MVT::v4f32: 6737 case MVT::v4i32: 6738 case MVT::v8i16: 6739 case MVT::v16i8: 6740 if (CFlags.IsVarArg) { 6741 // These go aligned on the stack, or in the corresponding R registers 6742 // when within range. The Darwin PPC ABI doc claims they also go in 6743 // V registers; in fact gcc does this only for arguments that are 6744 // prototyped, not for those that match the ... We do it for all 6745 // arguments, seems to work. 6746 while (ArgOffset % 16 !=0) { 6747 ArgOffset += PtrByteSize; 6748 if (GPR_idx != NumGPRs) 6749 GPR_idx++; 6750 } 6751 // We could elide this store in the case where the object fits 6752 // entirely in R registers. Maybe later. 6753 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6754 DAG.getConstant(ArgOffset, dl, PtrVT)); 6755 SDValue Store = 6756 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6757 MemOpChains.push_back(Store); 6758 if (VR_idx != NumVRs) { 6759 SDValue Load = 6760 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6761 MemOpChains.push_back(Load.getValue(1)); 6762 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6763 } 6764 ArgOffset += 16; 6765 for (unsigned i=0; i<16; i+=PtrByteSize) { 6766 if (GPR_idx == NumGPRs) 6767 break; 6768 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6769 DAG.getConstant(i, dl, PtrVT)); 6770 SDValue Load = 6771 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6772 MemOpChains.push_back(Load.getValue(1)); 6773 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6774 } 6775 break; 6776 } 6777 6778 // Non-varargs Altivec params generally go in registers, but have 6779 // stack space allocated at the end. 6780 if (VR_idx != NumVRs) { 6781 // Doesn't have GPR space allocated. 6782 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6783 } else if (nAltivecParamsAtEnd==0) { 6784 // We are emitting Altivec params in order. 6785 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6786 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6787 TailCallArguments, dl); 6788 ArgOffset += 16; 6789 } 6790 break; 6791 } 6792 } 6793 // If all Altivec parameters fit in registers, as they usually do, 6794 // they get stack space following the non-Altivec parameters. We 6795 // don't track this here because nobody below needs it. 6796 // If there are more Altivec parameters than fit in registers emit 6797 // the stores here. 6798 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6799 unsigned j = 0; 6800 // Offset is aligned; skip 1st 12 params which go in V registers. 6801 ArgOffset = ((ArgOffset+15)/16)*16; 6802 ArgOffset += 12*16; 6803 for (unsigned i = 0; i != NumOps; ++i) { 6804 SDValue Arg = OutVals[i]; 6805 EVT ArgType = Outs[i].VT; 6806 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6807 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6808 if (++j > NumVRs) { 6809 SDValue PtrOff; 6810 // We are emitting Altivec params in order. 6811 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6812 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6813 TailCallArguments, dl); 6814 ArgOffset += 16; 6815 } 6816 } 6817 } 6818 } 6819 6820 if (!MemOpChains.empty()) 6821 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6822 6823 // On Darwin, R12 must contain the address of an indirect callee. This does 6824 // not mean the MTCTR instruction must use R12; it's easier to model this as 6825 // an extra parameter, so do that. 6826 if (CFlags.IsIndirect) { 6827 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6828 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6829 PPC::R12), Callee)); 6830 } 6831 6832 // Build a sequence of copy-to-reg nodes chained together with token chain 6833 // and flag operands which copy the outgoing args into the appropriate regs. 6834 SDValue InFlag; 6835 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6836 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6837 RegsToPass[i].second, InFlag); 6838 InFlag = Chain.getValue(1); 6839 } 6840 6841 if (CFlags.IsTailCall) 6842 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6843 TailCallArguments); 6844 6845 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6846 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6847 } 6848 6849 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6850 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6851 CCState &State) { 6852 6853 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6854 State.getMachineFunction().getSubtarget()); 6855 const bool IsPPC64 = Subtarget.isPPC64(); 6856 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6857 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6858 6859 assert((!ValVT.isInteger() || 6860 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6861 "Integer argument exceeds register size: should have been legalized"); 6862 6863 if (ValVT == MVT::f128) 6864 report_fatal_error("f128 is unimplemented on AIX."); 6865 6866 if (ArgFlags.isNest()) 6867 report_fatal_error("Nest arguments are unimplemented."); 6868 6869 if (ValVT.isVector() || LocVT.isVector()) 6870 report_fatal_error("Vector arguments are unimplemented on AIX."); 6871 6872 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6873 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6874 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6875 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6876 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6877 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6878 6879 if (ArgFlags.isByVal()) { 6880 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6881 report_fatal_error("Pass-by-value arguments with alignment greater than " 6882 "register width are not supported."); 6883 6884 const unsigned ByValSize = ArgFlags.getByValSize(); 6885 6886 // An empty aggregate parameter takes up no storage and no registers, 6887 // but needs a MemLoc for a stack slot for the formal arguments side. 6888 if (ByValSize == 0) { 6889 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6890 State.getNextStackOffset(), RegVT, 6891 LocInfo)); 6892 return false; 6893 } 6894 6895 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6896 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6897 for (const unsigned E = Offset + StackSize; Offset < E; 6898 Offset += PtrAlign.value()) { 6899 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6900 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6901 else { 6902 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6903 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6904 LocInfo)); 6905 break; 6906 } 6907 } 6908 return false; 6909 } 6910 6911 // Arguments always reserve parameter save area. 6912 switch (ValVT.SimpleTy) { 6913 default: 6914 report_fatal_error("Unhandled value type for argument."); 6915 case MVT::i64: 6916 // i64 arguments should have been split to i32 for PPC32. 6917 assert(IsPPC64 && "PPC32 should have split i64 values."); 6918 LLVM_FALLTHROUGH; 6919 case MVT::i1: 6920 case MVT::i32: { 6921 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6922 // AIX integer arguments are always passed in register width. 6923 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6924 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6925 : CCValAssign::LocInfo::ZExt; 6926 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6927 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6928 else 6929 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6930 6931 return false; 6932 } 6933 case MVT::f32: 6934 case MVT::f64: { 6935 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6936 const unsigned StoreSize = LocVT.getStoreSize(); 6937 // Floats are always 4-byte aligned in the PSA on AIX. 6938 // This includes f64 in 64-bit mode for ABI compatibility. 6939 const unsigned Offset = 6940 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6941 unsigned FReg = State.AllocateReg(FPR); 6942 if (FReg) 6943 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6944 6945 // Reserve and initialize GPRs or initialize the PSA as required. 6946 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6947 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6948 assert(FReg && "An FPR should be available when a GPR is reserved."); 6949 if (State.isVarArg()) { 6950 // Successfully reserved GPRs are only initialized for vararg calls. 6951 // Custom handling is required for: 6952 // f64 in PPC32 needs to be split into 2 GPRs. 6953 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6954 State.addLoc( 6955 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6956 } 6957 } else { 6958 // If there are insufficient GPRs, the PSA needs to be initialized. 6959 // Initialization occurs even if an FPR was initialized for 6960 // compatibility with the AIX XL compiler. The full memory for the 6961 // argument will be initialized even if a prior word is saved in GPR. 6962 // A custom memLoc is used when the argument also passes in FPR so 6963 // that the callee handling can skip over it easily. 6964 State.addLoc( 6965 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6966 LocInfo) 6967 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6968 break; 6969 } 6970 } 6971 6972 return false; 6973 } 6974 } 6975 return true; 6976 } 6977 6978 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6979 bool IsPPC64) { 6980 assert((IsPPC64 || SVT != MVT::i64) && 6981 "i64 should have been split for 32-bit codegen."); 6982 6983 switch (SVT) { 6984 default: 6985 report_fatal_error("Unexpected value type for formal argument"); 6986 case MVT::i1: 6987 case MVT::i32: 6988 case MVT::i64: 6989 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6990 case MVT::f32: 6991 return &PPC::F4RCRegClass; 6992 case MVT::f64: 6993 return &PPC::F8RCRegClass; 6994 } 6995 } 6996 6997 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6998 SelectionDAG &DAG, SDValue ArgValue, 6999 MVT LocVT, const SDLoc &dl) { 7000 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7001 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7002 7003 if (Flags.isSExt()) 7004 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7005 DAG.getValueType(ValVT)); 7006 else if (Flags.isZExt()) 7007 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7008 DAG.getValueType(ValVT)); 7009 7010 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7011 } 7012 7013 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7014 const unsigned LASize = FL->getLinkageSize(); 7015 7016 if (PPC::GPRCRegClass.contains(Reg)) { 7017 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7018 "Reg must be a valid argument register!"); 7019 return LASize + 4 * (Reg - PPC::R3); 7020 } 7021 7022 if (PPC::G8RCRegClass.contains(Reg)) { 7023 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7024 "Reg must be a valid argument register!"); 7025 return LASize + 8 * (Reg - PPC::X3); 7026 } 7027 7028 llvm_unreachable("Only general purpose registers expected."); 7029 } 7030 7031 // AIX ABI Stack Frame Layout: 7032 // 7033 // Low Memory +--------------------------------------------+ 7034 // SP +---> | Back chain | ---+ 7035 // | +--------------------------------------------+ | 7036 // | | Saved Condition Register | | 7037 // | +--------------------------------------------+ | 7038 // | | Saved Linkage Register | | 7039 // | +--------------------------------------------+ | Linkage Area 7040 // | | Reserved for compilers | | 7041 // | +--------------------------------------------+ | 7042 // | | Reserved for binders | | 7043 // | +--------------------------------------------+ | 7044 // | | Saved TOC pointer | ---+ 7045 // | +--------------------------------------------+ 7046 // | | Parameter save area | 7047 // | +--------------------------------------------+ 7048 // | | Alloca space | 7049 // | +--------------------------------------------+ 7050 // | | Local variable space | 7051 // | +--------------------------------------------+ 7052 // | | Float/int conversion temporary | 7053 // | +--------------------------------------------+ 7054 // | | Save area for AltiVec registers | 7055 // | +--------------------------------------------+ 7056 // | | AltiVec alignment padding | 7057 // | +--------------------------------------------+ 7058 // | | Save area for VRSAVE register | 7059 // | +--------------------------------------------+ 7060 // | | Save area for General Purpose registers | 7061 // | +--------------------------------------------+ 7062 // | | Save area for Floating Point registers | 7063 // | +--------------------------------------------+ 7064 // +---- | Back chain | 7065 // High Memory +--------------------------------------------+ 7066 // 7067 // Specifications: 7068 // AIX 7.2 Assembler Language Reference 7069 // Subroutine linkage convention 7070 7071 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7072 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7073 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7074 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7075 7076 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7077 CallConv == CallingConv::Fast) && 7078 "Unexpected calling convention!"); 7079 7080 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7081 report_fatal_error("Tail call support is unimplemented on AIX."); 7082 7083 if (useSoftFloat()) 7084 report_fatal_error("Soft float support is unimplemented on AIX."); 7085 7086 const PPCSubtarget &Subtarget = 7087 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7088 7089 const bool IsPPC64 = Subtarget.isPPC64(); 7090 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7091 7092 // Assign locations to all of the incoming arguments. 7093 SmallVector<CCValAssign, 16> ArgLocs; 7094 MachineFunction &MF = DAG.getMachineFunction(); 7095 MachineFrameInfo &MFI = MF.getFrameInfo(); 7096 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7097 7098 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7099 // Reserve space for the linkage area on the stack. 7100 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7101 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7102 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7103 7104 SmallVector<SDValue, 8> MemOps; 7105 7106 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7107 CCValAssign &VA = ArgLocs[I++]; 7108 MVT LocVT = VA.getLocVT(); 7109 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7110 7111 // For compatibility with the AIX XL compiler, the float args in the 7112 // parameter save area are initialized even if the argument is available 7113 // in register. The caller is required to initialize both the register 7114 // and memory, however, the callee can choose to expect it in either. 7115 // The memloc is dismissed here because the argument is retrieved from 7116 // the register. 7117 if (VA.isMemLoc() && VA.needsCustom()) 7118 continue; 7119 7120 if (Flags.isByVal() && VA.isMemLoc()) { 7121 const unsigned Size = 7122 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7123 PtrByteSize); 7124 const int FI = MF.getFrameInfo().CreateFixedObject( 7125 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7126 /* IsAliased */ true); 7127 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7128 InVals.push_back(FIN); 7129 7130 continue; 7131 } 7132 7133 if (Flags.isByVal()) { 7134 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7135 7136 const MCPhysReg ArgReg = VA.getLocReg(); 7137 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7138 7139 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7140 report_fatal_error("Over aligned byvals not supported yet."); 7141 7142 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7143 const int FI = MF.getFrameInfo().CreateFixedObject( 7144 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7145 /* IsAliased */ true); 7146 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7147 InVals.push_back(FIN); 7148 7149 // Add live ins for all the RegLocs for the same ByVal. 7150 const TargetRegisterClass *RegClass = 7151 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7152 7153 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7154 unsigned Offset) { 7155 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7156 // Since the callers side has left justified the aggregate in the 7157 // register, we can simply store the entire register into the stack 7158 // slot. 7159 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7160 // The store to the fixedstack object is needed becuase accessing a 7161 // field of the ByVal will use a gep and load. Ideally we will optimize 7162 // to extracting the value from the register directly, and elide the 7163 // stores when the arguments address is not taken, but that will need to 7164 // be future work. 7165 SDValue Store = DAG.getStore( 7166 CopyFrom.getValue(1), dl, CopyFrom, 7167 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7168 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7169 7170 MemOps.push_back(Store); 7171 }; 7172 7173 unsigned Offset = 0; 7174 HandleRegLoc(VA.getLocReg(), Offset); 7175 Offset += PtrByteSize; 7176 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7177 Offset += PtrByteSize) { 7178 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7179 "RegLocs should be for ByVal argument."); 7180 7181 const CCValAssign RL = ArgLocs[I++]; 7182 HandleRegLoc(RL.getLocReg(), Offset); 7183 } 7184 7185 if (Offset != StackSize) { 7186 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7187 "Expected MemLoc for remaining bytes."); 7188 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7189 // Consume the MemLoc.The InVal has already been emitted, so nothing 7190 // more needs to be done. 7191 ++I; 7192 } 7193 7194 continue; 7195 } 7196 7197 EVT ValVT = VA.getValVT(); 7198 if (VA.isRegLoc() && !VA.needsCustom()) { 7199 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7200 unsigned VReg = 7201 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7202 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7203 if (ValVT.isScalarInteger() && 7204 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7205 ArgValue = 7206 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7207 } 7208 InVals.push_back(ArgValue); 7209 continue; 7210 } 7211 if (VA.isMemLoc()) { 7212 const unsigned LocSize = LocVT.getStoreSize(); 7213 const unsigned ValSize = ValVT.getStoreSize(); 7214 assert((ValSize <= LocSize) && 7215 "Object size is larger than size of MemLoc"); 7216 int CurArgOffset = VA.getLocMemOffset(); 7217 // Objects are right-justified because AIX is big-endian. 7218 if (LocSize > ValSize) 7219 CurArgOffset += LocSize - ValSize; 7220 // Potential tail calls could cause overwriting of argument stack slots. 7221 const bool IsImmutable = 7222 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7223 (CallConv == CallingConv::Fast)); 7224 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7225 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7226 SDValue ArgValue = 7227 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7228 InVals.push_back(ArgValue); 7229 continue; 7230 } 7231 } 7232 7233 // On AIX a minimum of 8 words is saved to the parameter save area. 7234 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7235 // Area that is at least reserved in the caller of this function. 7236 unsigned CallerReservedArea = 7237 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7238 7239 // Set the size that is at least reserved in caller of this function. Tail 7240 // call optimized function's reserved stack space needs to be aligned so 7241 // that taking the difference between two stack areas will result in an 7242 // aligned stack. 7243 CallerReservedArea = 7244 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7245 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7246 FuncInfo->setMinReservedArea(CallerReservedArea); 7247 7248 if (isVarArg) { 7249 FuncInfo->setVarArgsFrameIndex( 7250 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7251 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7252 7253 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7254 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7255 7256 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7257 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7258 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7259 7260 // The fixed integer arguments of a variadic function are stored to the 7261 // VarArgsFrameIndex on the stack so that they may be loaded by 7262 // dereferencing the result of va_next. 7263 for (unsigned GPRIndex = 7264 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7265 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7266 7267 const unsigned VReg = 7268 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7269 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7270 7271 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7272 SDValue Store = 7273 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7274 MemOps.push_back(Store); 7275 // Increment the address for the next argument to store. 7276 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7277 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7278 } 7279 } 7280 7281 if (!MemOps.empty()) 7282 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7283 7284 return Chain; 7285 } 7286 7287 SDValue PPCTargetLowering::LowerCall_AIX( 7288 SDValue Chain, SDValue Callee, CallFlags CFlags, 7289 const SmallVectorImpl<ISD::OutputArg> &Outs, 7290 const SmallVectorImpl<SDValue> &OutVals, 7291 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7292 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7293 const CallBase *CB) const { 7294 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7295 // AIX ABI stack frame layout. 7296 7297 assert((CFlags.CallConv == CallingConv::C || 7298 CFlags.CallConv == CallingConv::Cold || 7299 CFlags.CallConv == CallingConv::Fast) && 7300 "Unexpected calling convention!"); 7301 7302 if (CFlags.IsPatchPoint) 7303 report_fatal_error("This call type is unimplemented on AIX."); 7304 7305 const PPCSubtarget& Subtarget = 7306 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7307 if (Subtarget.hasAltivec()) 7308 report_fatal_error("Altivec support is unimplemented on AIX."); 7309 7310 MachineFunction &MF = DAG.getMachineFunction(); 7311 SmallVector<CCValAssign, 16> ArgLocs; 7312 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7313 *DAG.getContext()); 7314 7315 // Reserve space for the linkage save area (LSA) on the stack. 7316 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7317 // [SP][CR][LR][2 x reserved][TOC]. 7318 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7319 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7320 const bool IsPPC64 = Subtarget.isPPC64(); 7321 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7322 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7323 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7324 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7325 7326 // The prolog code of the callee may store up to 8 GPR argument registers to 7327 // the stack, allowing va_start to index over them in memory if the callee 7328 // is variadic. 7329 // Because we cannot tell if this is needed on the caller side, we have to 7330 // conservatively assume that it is needed. As such, make sure we have at 7331 // least enough stack space for the caller to store the 8 GPRs. 7332 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7333 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7334 CCInfo.getNextStackOffset()); 7335 7336 // Adjust the stack pointer for the new arguments... 7337 // These operations are automatically eliminated by the prolog/epilog pass. 7338 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7339 SDValue CallSeqStart = Chain; 7340 7341 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7342 SmallVector<SDValue, 8> MemOpChains; 7343 7344 // Set up a copy of the stack pointer for loading and storing any 7345 // arguments that may not fit in the registers available for argument 7346 // passing. 7347 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7348 : DAG.getRegister(PPC::R1, MVT::i32); 7349 7350 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7351 const unsigned ValNo = ArgLocs[I].getValNo(); 7352 SDValue Arg = OutVals[ValNo]; 7353 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7354 7355 if (Flags.isByVal()) { 7356 const unsigned ByValSize = Flags.getByValSize(); 7357 7358 // Nothing to do for zero-sized ByVals on the caller side. 7359 if (!ByValSize) { 7360 ++I; 7361 continue; 7362 } 7363 7364 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7365 return DAG.getExtLoad( 7366 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7367 (LoadOffset != 0) 7368 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7369 : Arg, 7370 MachinePointerInfo(), VT); 7371 }; 7372 7373 unsigned LoadOffset = 0; 7374 7375 // Initialize registers, which are fully occupied by the by-val argument. 7376 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7377 SDValue Load = GetLoad(PtrVT, LoadOffset); 7378 MemOpChains.push_back(Load.getValue(1)); 7379 LoadOffset += PtrByteSize; 7380 const CCValAssign &ByValVA = ArgLocs[I++]; 7381 assert(ByValVA.getValNo() == ValNo && 7382 "Unexpected location for pass-by-value argument."); 7383 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7384 } 7385 7386 if (LoadOffset == ByValSize) 7387 continue; 7388 7389 // There must be one more loc to handle the remainder. 7390 assert(ArgLocs[I].getValNo() == ValNo && 7391 "Expected additional location for by-value argument."); 7392 7393 if (ArgLocs[I].isMemLoc()) { 7394 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7395 const CCValAssign &ByValVA = ArgLocs[I++]; 7396 ISD::ArgFlagsTy MemcpyFlags = Flags; 7397 // Only memcpy the bytes that don't pass in register. 7398 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7399 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7400 (LoadOffset != 0) 7401 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7402 : Arg, 7403 DAG.getObjectPtrOffset(dl, StackPtr, 7404 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7405 CallSeqStart, MemcpyFlags, DAG, dl); 7406 continue; 7407 } 7408 7409 // Initialize the final register residue. 7410 // Any residue that occupies the final by-val arg register must be 7411 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7412 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7413 // 2 and 1 byte loads. 7414 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7415 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7416 "Unexpected register residue for by-value argument."); 7417 SDValue ResidueVal; 7418 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7419 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7420 const MVT VT = 7421 N == 1 ? MVT::i8 7422 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7423 SDValue Load = GetLoad(VT, LoadOffset); 7424 MemOpChains.push_back(Load.getValue(1)); 7425 LoadOffset += N; 7426 Bytes += N; 7427 7428 // By-val arguments are passed left-justfied in register. 7429 // Every load here needs to be shifted, otherwise a full register load 7430 // should have been used. 7431 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7432 "Unexpected load emitted during handling of pass-by-value " 7433 "argument."); 7434 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7435 EVT ShiftAmountTy = 7436 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7437 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7438 SDValue ShiftedLoad = 7439 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7440 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7441 ShiftedLoad) 7442 : ShiftedLoad; 7443 } 7444 7445 const CCValAssign &ByValVA = ArgLocs[I++]; 7446 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7447 continue; 7448 } 7449 7450 CCValAssign &VA = ArgLocs[I++]; 7451 const MVT LocVT = VA.getLocVT(); 7452 const MVT ValVT = VA.getValVT(); 7453 7454 switch (VA.getLocInfo()) { 7455 default: 7456 report_fatal_error("Unexpected argument extension type."); 7457 case CCValAssign::Full: 7458 break; 7459 case CCValAssign::ZExt: 7460 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7461 break; 7462 case CCValAssign::SExt: 7463 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7464 break; 7465 } 7466 7467 if (VA.isRegLoc() && !VA.needsCustom()) { 7468 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7469 continue; 7470 } 7471 7472 if (VA.isMemLoc()) { 7473 SDValue PtrOff = 7474 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7475 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7476 MemOpChains.push_back( 7477 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7478 7479 continue; 7480 } 7481 7482 // Custom handling is used for GPR initializations for vararg float 7483 // arguments. 7484 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7485 ValVT.isFloatingPoint() && LocVT.isInteger() && 7486 "Unexpected register handling for calling convention."); 7487 7488 SDValue ArgAsInt = 7489 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7490 7491 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7492 // f32 in 32-bit GPR 7493 // f64 in 64-bit GPR 7494 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7495 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7496 // f32 in 64-bit GPR. 7497 RegsToPass.push_back(std::make_pair( 7498 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7499 else { 7500 // f64 in two 32-bit GPRs 7501 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7502 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7503 "Unexpected custom register for argument!"); 7504 CCValAssign &GPR1 = VA; 7505 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7506 DAG.getConstant(32, dl, MVT::i8)); 7507 RegsToPass.push_back(std::make_pair( 7508 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7509 7510 if (I != E) { 7511 // If only 1 GPR was available, there will only be one custom GPR and 7512 // the argument will also pass in memory. 7513 CCValAssign &PeekArg = ArgLocs[I]; 7514 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7515 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7516 CCValAssign &GPR2 = ArgLocs[I++]; 7517 RegsToPass.push_back(std::make_pair( 7518 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7519 } 7520 } 7521 } 7522 } 7523 7524 if (!MemOpChains.empty()) 7525 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7526 7527 // For indirect calls, we need to save the TOC base to the stack for 7528 // restoration after the call. 7529 if (CFlags.IsIndirect) { 7530 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7531 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7532 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7533 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7534 const unsigned TOCSaveOffset = 7535 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7536 7537 setUsesTOCBasePtr(DAG); 7538 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7539 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7540 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7541 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7542 Chain = DAG.getStore( 7543 Val.getValue(1), dl, Val, AddPtr, 7544 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7545 } 7546 7547 // Build a sequence of copy-to-reg nodes chained together with token chain 7548 // and flag operands which copy the outgoing args into the appropriate regs. 7549 SDValue InFlag; 7550 for (auto Reg : RegsToPass) { 7551 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7552 InFlag = Chain.getValue(1); 7553 } 7554 7555 const int SPDiff = 0; 7556 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7557 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7558 } 7559 7560 bool 7561 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7562 MachineFunction &MF, bool isVarArg, 7563 const SmallVectorImpl<ISD::OutputArg> &Outs, 7564 LLVMContext &Context) const { 7565 SmallVector<CCValAssign, 16> RVLocs; 7566 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7567 return CCInfo.CheckReturn( 7568 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7569 ? RetCC_PPC_Cold 7570 : RetCC_PPC); 7571 } 7572 7573 SDValue 7574 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7575 bool isVarArg, 7576 const SmallVectorImpl<ISD::OutputArg> &Outs, 7577 const SmallVectorImpl<SDValue> &OutVals, 7578 const SDLoc &dl, SelectionDAG &DAG) const { 7579 SmallVector<CCValAssign, 16> RVLocs; 7580 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7581 *DAG.getContext()); 7582 CCInfo.AnalyzeReturn(Outs, 7583 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7584 ? RetCC_PPC_Cold 7585 : RetCC_PPC); 7586 7587 SDValue Flag; 7588 SmallVector<SDValue, 4> RetOps(1, Chain); 7589 7590 // Copy the result values into the output registers. 7591 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7592 CCValAssign &VA = RVLocs[i]; 7593 assert(VA.isRegLoc() && "Can only return in registers!"); 7594 7595 SDValue Arg = OutVals[RealResIdx]; 7596 7597 switch (VA.getLocInfo()) { 7598 default: llvm_unreachable("Unknown loc info!"); 7599 case CCValAssign::Full: break; 7600 case CCValAssign::AExt: 7601 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7602 break; 7603 case CCValAssign::ZExt: 7604 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7605 break; 7606 case CCValAssign::SExt: 7607 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7608 break; 7609 } 7610 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7611 bool isLittleEndian = Subtarget.isLittleEndian(); 7612 // Legalize ret f64 -> ret 2 x i32. 7613 SDValue SVal = 7614 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7615 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7616 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7617 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7618 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7619 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7620 Flag = Chain.getValue(1); 7621 VA = RVLocs[++i]; // skip ahead to next loc 7622 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7623 } else 7624 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7625 Flag = Chain.getValue(1); 7626 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7627 } 7628 7629 RetOps[0] = Chain; // Update chain. 7630 7631 // Add the flag if we have it. 7632 if (Flag.getNode()) 7633 RetOps.push_back(Flag); 7634 7635 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7636 } 7637 7638 SDValue 7639 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7640 SelectionDAG &DAG) const { 7641 SDLoc dl(Op); 7642 7643 // Get the correct type for integers. 7644 EVT IntVT = Op.getValueType(); 7645 7646 // Get the inputs. 7647 SDValue Chain = Op.getOperand(0); 7648 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7649 // Build a DYNAREAOFFSET node. 7650 SDValue Ops[2] = {Chain, FPSIdx}; 7651 SDVTList VTs = DAG.getVTList(IntVT); 7652 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7653 } 7654 7655 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7656 SelectionDAG &DAG) const { 7657 // When we pop the dynamic allocation we need to restore the SP link. 7658 SDLoc dl(Op); 7659 7660 // Get the correct type for pointers. 7661 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7662 7663 // Construct the stack pointer operand. 7664 bool isPPC64 = Subtarget.isPPC64(); 7665 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7666 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7667 7668 // Get the operands for the STACKRESTORE. 7669 SDValue Chain = Op.getOperand(0); 7670 SDValue SaveSP = Op.getOperand(1); 7671 7672 // Load the old link SP. 7673 SDValue LoadLinkSP = 7674 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7675 7676 // Restore the stack pointer. 7677 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7678 7679 // Store the old link SP. 7680 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7681 } 7682 7683 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7684 MachineFunction &MF = DAG.getMachineFunction(); 7685 bool isPPC64 = Subtarget.isPPC64(); 7686 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7687 7688 // Get current frame pointer save index. The users of this index will be 7689 // primarily DYNALLOC instructions. 7690 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7691 int RASI = FI->getReturnAddrSaveIndex(); 7692 7693 // If the frame pointer save index hasn't been defined yet. 7694 if (!RASI) { 7695 // Find out what the fix offset of the frame pointer save area. 7696 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7697 // Allocate the frame index for frame pointer save area. 7698 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7699 // Save the result. 7700 FI->setReturnAddrSaveIndex(RASI); 7701 } 7702 return DAG.getFrameIndex(RASI, PtrVT); 7703 } 7704 7705 SDValue 7706 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7707 MachineFunction &MF = DAG.getMachineFunction(); 7708 bool isPPC64 = Subtarget.isPPC64(); 7709 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7710 7711 // Get current frame pointer save index. The users of this index will be 7712 // primarily DYNALLOC instructions. 7713 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7714 int FPSI = FI->getFramePointerSaveIndex(); 7715 7716 // If the frame pointer save index hasn't been defined yet. 7717 if (!FPSI) { 7718 // Find out what the fix offset of the frame pointer save area. 7719 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7720 // Allocate the frame index for frame pointer save area. 7721 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7722 // Save the result. 7723 FI->setFramePointerSaveIndex(FPSI); 7724 } 7725 return DAG.getFrameIndex(FPSI, PtrVT); 7726 } 7727 7728 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7729 SelectionDAG &DAG) const { 7730 MachineFunction &MF = DAG.getMachineFunction(); 7731 // Get the inputs. 7732 SDValue Chain = Op.getOperand(0); 7733 SDValue Size = Op.getOperand(1); 7734 SDLoc dl(Op); 7735 7736 // Get the correct type for pointers. 7737 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7738 // Negate the size. 7739 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7740 DAG.getConstant(0, dl, PtrVT), Size); 7741 // Construct a node for the frame pointer save index. 7742 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7743 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7744 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7745 if (hasInlineStackProbe(MF)) 7746 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7747 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7748 } 7749 7750 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7751 SelectionDAG &DAG) const { 7752 MachineFunction &MF = DAG.getMachineFunction(); 7753 7754 bool isPPC64 = Subtarget.isPPC64(); 7755 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7756 7757 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7758 return DAG.getFrameIndex(FI, PtrVT); 7759 } 7760 7761 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7762 SelectionDAG &DAG) const { 7763 SDLoc DL(Op); 7764 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7765 DAG.getVTList(MVT::i32, MVT::Other), 7766 Op.getOperand(0), Op.getOperand(1)); 7767 } 7768 7769 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7770 SelectionDAG &DAG) const { 7771 SDLoc DL(Op); 7772 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7773 Op.getOperand(0), Op.getOperand(1)); 7774 } 7775 7776 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7777 7778 assert(Op.getValueType() == MVT::i1 && 7779 "Custom lowering only for i1 loads"); 7780 7781 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7782 7783 SDLoc dl(Op); 7784 LoadSDNode *LD = cast<LoadSDNode>(Op); 7785 7786 SDValue Chain = LD->getChain(); 7787 SDValue BasePtr = LD->getBasePtr(); 7788 MachineMemOperand *MMO = LD->getMemOperand(); 7789 7790 SDValue NewLD = 7791 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7792 BasePtr, MVT::i8, MMO); 7793 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7794 7795 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7796 return DAG.getMergeValues(Ops, dl); 7797 } 7798 7799 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7800 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7801 "Custom lowering only for i1 stores"); 7802 7803 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7804 7805 SDLoc dl(Op); 7806 StoreSDNode *ST = cast<StoreSDNode>(Op); 7807 7808 SDValue Chain = ST->getChain(); 7809 SDValue BasePtr = ST->getBasePtr(); 7810 SDValue Value = ST->getValue(); 7811 MachineMemOperand *MMO = ST->getMemOperand(); 7812 7813 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7814 Value); 7815 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7816 } 7817 7818 // FIXME: Remove this once the ANDI glue bug is fixed: 7819 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7820 assert(Op.getValueType() == MVT::i1 && 7821 "Custom lowering only for i1 results"); 7822 7823 SDLoc DL(Op); 7824 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7825 } 7826 7827 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7828 SelectionDAG &DAG) const { 7829 7830 // Implements a vector truncate that fits in a vector register as a shuffle. 7831 // We want to legalize vector truncates down to where the source fits in 7832 // a vector register (and target is therefore smaller than vector register 7833 // size). At that point legalization will try to custom lower the sub-legal 7834 // result and get here - where we can contain the truncate as a single target 7835 // operation. 7836 7837 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7838 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7839 // 7840 // We will implement it for big-endian ordering as this (where x denotes 7841 // undefined): 7842 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7843 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7844 // 7845 // The same operation in little-endian ordering will be: 7846 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7847 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7848 7849 assert(Op.getValueType().isVector() && "Vector type expected."); 7850 7851 SDLoc DL(Op); 7852 SDValue N1 = Op.getOperand(0); 7853 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7854 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7855 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7856 7857 EVT TrgVT = Op.getValueType(); 7858 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7859 EVT EltVT = TrgVT.getVectorElementType(); 7860 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7861 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7862 7863 // First list the elements we want to keep. 7864 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7865 SmallVector<int, 16> ShuffV; 7866 if (Subtarget.isLittleEndian()) 7867 for (unsigned i = 0; i < TrgNumElts; ++i) 7868 ShuffV.push_back(i * SizeMult); 7869 else 7870 for (unsigned i = 1; i <= TrgNumElts; ++i) 7871 ShuffV.push_back(i * SizeMult - 1); 7872 7873 // Populate the remaining elements with undefs. 7874 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7875 // ShuffV.push_back(i + WideNumElts); 7876 ShuffV.push_back(WideNumElts + 1); 7877 7878 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7879 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7880 } 7881 7882 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7883 /// possible. 7884 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7885 // Not FP, or using SPE? Not a fsel. 7886 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7887 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7888 return Op; 7889 7890 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7891 7892 EVT ResVT = Op.getValueType(); 7893 EVT CmpVT = Op.getOperand(0).getValueType(); 7894 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7895 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7896 SDLoc dl(Op); 7897 SDNodeFlags Flags = Op.getNode()->getFlags(); 7898 7899 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7900 // presence of infinities. 7901 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7902 switch (CC) { 7903 default: 7904 break; 7905 case ISD::SETOGT: 7906 case ISD::SETGT: 7907 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7908 case ISD::SETOLT: 7909 case ISD::SETLT: 7910 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7911 } 7912 } 7913 7914 // We might be able to do better than this under some circumstances, but in 7915 // general, fsel-based lowering of select is a finite-math-only optimization. 7916 // For more information, see section F.3 of the 2.06 ISA specification. 7917 // With ISA 3.0 7918 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7919 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7920 return Op; 7921 7922 // If the RHS of the comparison is a 0.0, we don't need to do the 7923 // subtraction at all. 7924 SDValue Sel1; 7925 if (isFloatingPointZero(RHS)) 7926 switch (CC) { 7927 default: break; // SETUO etc aren't handled by fsel. 7928 case ISD::SETNE: 7929 std::swap(TV, FV); 7930 LLVM_FALLTHROUGH; 7931 case ISD::SETEQ: 7932 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7933 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7934 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7935 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7936 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7937 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7938 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7939 case ISD::SETULT: 7940 case ISD::SETLT: 7941 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7942 LLVM_FALLTHROUGH; 7943 case ISD::SETOGE: 7944 case ISD::SETGE: 7945 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7946 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7947 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7948 case ISD::SETUGT: 7949 case ISD::SETGT: 7950 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7951 LLVM_FALLTHROUGH; 7952 case ISD::SETOLE: 7953 case ISD::SETLE: 7954 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7955 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7956 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7957 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7958 } 7959 7960 SDValue Cmp; 7961 switch (CC) { 7962 default: break; // SETUO etc aren't handled by fsel. 7963 case ISD::SETNE: 7964 std::swap(TV, FV); 7965 LLVM_FALLTHROUGH; 7966 case ISD::SETEQ: 7967 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7968 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7969 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7970 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7971 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7972 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7973 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7974 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7975 case ISD::SETULT: 7976 case ISD::SETLT: 7977 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7978 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7979 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7980 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7981 case ISD::SETOGE: 7982 case ISD::SETGE: 7983 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7984 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7985 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7986 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7987 case ISD::SETUGT: 7988 case ISD::SETGT: 7989 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7990 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7991 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7992 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7993 case ISD::SETOLE: 7994 case ISD::SETLE: 7995 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7996 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7997 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7998 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7999 } 8000 return Op; 8001 } 8002 8003 static unsigned getPPCStrictOpcode(unsigned Opc) { 8004 switch (Opc) { 8005 default: 8006 llvm_unreachable("No strict version of this opcode!"); 8007 case PPCISD::FCTIDZ: 8008 return PPCISD::STRICT_FCTIDZ; 8009 case PPCISD::FCTIWZ: 8010 return PPCISD::STRICT_FCTIWZ; 8011 case PPCISD::FCTIDUZ: 8012 return PPCISD::STRICT_FCTIDUZ; 8013 case PPCISD::FCTIWUZ: 8014 return PPCISD::STRICT_FCTIWUZ; 8015 case PPCISD::FCFID: 8016 return PPCISD::STRICT_FCFID; 8017 case PPCISD::FCFIDU: 8018 return PPCISD::STRICT_FCFIDU; 8019 case PPCISD::FCFIDS: 8020 return PPCISD::STRICT_FCFIDS; 8021 case PPCISD::FCFIDUS: 8022 return PPCISD::STRICT_FCFIDUS; 8023 } 8024 } 8025 8026 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8027 const PPCSubtarget &Subtarget) { 8028 SDLoc dl(Op); 8029 bool IsStrict = Op->isStrictFPOpcode(); 8030 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8031 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8032 // For strict nodes, source is the second operand. 8033 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8034 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8035 assert(Src.getValueType().isFloatingPoint()); 8036 if (Src.getValueType() == MVT::f32) { 8037 if (IsStrict) { 8038 Src = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f64, MVT::Other}, 8039 {Chain, Src}); 8040 Chain = Src.getValue(1); 8041 } else 8042 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8043 } 8044 SDValue Conv; 8045 unsigned Opc = ISD::DELETED_NODE; 8046 switch (Op.getSimpleValueType().SimpleTy) { 8047 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8048 case MVT::i32: 8049 Opc = IsSigned ? PPCISD::FCTIWZ 8050 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8051 break; 8052 case MVT::i64: 8053 assert((IsSigned || Subtarget.hasFPCVT()) && 8054 "i64 FP_TO_UINT is supported only with FPCVT"); 8055 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8056 } 8057 if (IsStrict) { 8058 Opc = getPPCStrictOpcode(Opc); 8059 Conv = DAG.getNode(Opc, dl, {MVT::f64, MVT::Other}, {Chain, Src}); 8060 } else { 8061 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8062 } 8063 return Conv; 8064 } 8065 8066 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8067 SelectionDAG &DAG, 8068 const SDLoc &dl) const { 8069 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8070 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8071 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8072 bool IsStrict = Op->isStrictFPOpcode(); 8073 8074 // Convert the FP value to an int value through memory. 8075 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8076 (IsSigned || Subtarget.hasFPCVT()); 8077 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8078 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8079 MachinePointerInfo MPI = 8080 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8081 8082 // Emit a store to the stack slot. 8083 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8084 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8085 if (i32Stack) { 8086 MachineFunction &MF = DAG.getMachineFunction(); 8087 Alignment = Align(4); 8088 MachineMemOperand *MMO = 8089 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8090 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8091 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8092 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8093 } else 8094 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8095 8096 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8097 // add in a bias on big endian. 8098 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8099 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8100 DAG.getConstant(4, dl, FIPtr.getValueType())); 8101 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8102 } 8103 8104 RLI.Chain = Chain; 8105 RLI.Ptr = FIPtr; 8106 RLI.MPI = MPI; 8107 RLI.Alignment = Alignment; 8108 } 8109 8110 /// Custom lowers floating point to integer conversions to use 8111 /// the direct move instructions available in ISA 2.07 to avoid the 8112 /// need for load/store combinations. 8113 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8114 SelectionDAG &DAG, 8115 const SDLoc &dl) const { 8116 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8117 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8118 if (Op->isStrictFPOpcode()) 8119 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8120 else 8121 return Mov; 8122 } 8123 8124 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8125 const SDLoc &dl) const { 8126 bool IsStrict = Op->isStrictFPOpcode(); 8127 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8128 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8129 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8130 // FP to INT conversions are legal for f128. 8131 if (Src.getValueType() == MVT::f128) 8132 return Op; 8133 8134 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8135 // PPC (the libcall is not available). 8136 if (Src.getValueType() == MVT::ppcf128 && !IsStrict) { 8137 if (Op.getValueType() == MVT::i32) { 8138 if (IsSigned) { 8139 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8140 DAG.getIntPtrConstant(0, dl)); 8141 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8142 DAG.getIntPtrConstant(1, dl)); 8143 8144 // Add the two halves of the long double in round-to-zero mode. 8145 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8146 8147 // Now use a smaller FP_TO_SINT. 8148 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8149 } else { 8150 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8151 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8152 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8153 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8154 // FIXME: generated code sucks. 8155 // TODO: Are there fast-math-flags to propagate to this FSUB? 8156 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp); 8157 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8158 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8159 DAG.getConstant(0x80000000, dl, MVT::i32)); 8160 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8161 return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE); 8162 } 8163 } 8164 8165 return SDValue(); 8166 } 8167 8168 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8169 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8170 8171 ReuseLoadInfo RLI; 8172 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8173 8174 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8175 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8176 } 8177 8178 // We're trying to insert a regular store, S, and then a load, L. If the 8179 // incoming value, O, is a load, we might just be able to have our load use the 8180 // address used by O. However, we don't know if anything else will store to 8181 // that address before we can load from it. To prevent this situation, we need 8182 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8183 // the same chain operand as O, we create a token factor from the chain results 8184 // of O and L, and we replace all uses of O's chain result with that token 8185 // factor (see spliceIntoChain below for this last part). 8186 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8187 ReuseLoadInfo &RLI, 8188 SelectionDAG &DAG, 8189 ISD::LoadExtType ET) const { 8190 // Conservatively skip reusing for constrained FP nodes. 8191 if (Op->isStrictFPOpcode()) 8192 return false; 8193 8194 SDLoc dl(Op); 8195 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8196 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8197 if (ET == ISD::NON_EXTLOAD && 8198 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8199 isOperationLegalOrCustom(Op.getOpcode(), 8200 Op.getOperand(0).getValueType())) { 8201 8202 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8203 return true; 8204 } 8205 8206 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8207 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8208 LD->isNonTemporal()) 8209 return false; 8210 if (LD->getMemoryVT() != MemVT) 8211 return false; 8212 8213 RLI.Ptr = LD->getBasePtr(); 8214 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8215 assert(LD->getAddressingMode() == ISD::PRE_INC && 8216 "Non-pre-inc AM on PPC?"); 8217 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8218 LD->getOffset()); 8219 } 8220 8221 RLI.Chain = LD->getChain(); 8222 RLI.MPI = LD->getPointerInfo(); 8223 RLI.IsDereferenceable = LD->isDereferenceable(); 8224 RLI.IsInvariant = LD->isInvariant(); 8225 RLI.Alignment = LD->getAlign(); 8226 RLI.AAInfo = LD->getAAInfo(); 8227 RLI.Ranges = LD->getRanges(); 8228 8229 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8230 return true; 8231 } 8232 8233 // Given the head of the old chain, ResChain, insert a token factor containing 8234 // it and NewResChain, and make users of ResChain now be users of that token 8235 // factor. 8236 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8237 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8238 SDValue NewResChain, 8239 SelectionDAG &DAG) const { 8240 if (!ResChain) 8241 return; 8242 8243 SDLoc dl(NewResChain); 8244 8245 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8246 NewResChain, DAG.getUNDEF(MVT::Other)); 8247 assert(TF.getNode() != NewResChain.getNode() && 8248 "A new TF really is required here"); 8249 8250 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8251 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8252 } 8253 8254 /// Analyze profitability of direct move 8255 /// prefer float load to int load plus direct move 8256 /// when there is no integer use of int load 8257 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8258 SDNode *Origin = Op.getOperand(0).getNode(); 8259 if (Origin->getOpcode() != ISD::LOAD) 8260 return true; 8261 8262 // If there is no LXSIBZX/LXSIHZX, like Power8, 8263 // prefer direct move if the memory size is 1 or 2 bytes. 8264 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8265 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8266 return true; 8267 8268 for (SDNode::use_iterator UI = Origin->use_begin(), 8269 UE = Origin->use_end(); 8270 UI != UE; ++UI) { 8271 8272 // Only look at the users of the loaded value. 8273 if (UI.getUse().get().getResNo() != 0) 8274 continue; 8275 8276 if (UI->getOpcode() != ISD::SINT_TO_FP && 8277 UI->getOpcode() != ISD::UINT_TO_FP && 8278 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8279 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8280 return true; 8281 } 8282 8283 return false; 8284 } 8285 8286 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8287 const PPCSubtarget &Subtarget, 8288 SDValue Chain = SDValue()) { 8289 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8290 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8291 SDLoc dl(Op); 8292 // If we have FCFIDS, then use it when converting to single-precision. 8293 // Otherwise, convert to double-precision and then round. 8294 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8295 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8296 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8297 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8298 if (Op->isStrictFPOpcode()) { 8299 if (!Chain) 8300 Chain = Op.getOperand(0); 8301 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, {ConvTy, MVT::Other}, 8302 {Chain, Src}); 8303 } else 8304 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8305 } 8306 8307 /// Custom lowers integer to floating point conversions to use 8308 /// the direct move instructions available in ISA 2.07 to avoid the 8309 /// need for load/store combinations. 8310 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8311 SelectionDAG &DAG, 8312 const SDLoc &dl) const { 8313 assert((Op.getValueType() == MVT::f32 || 8314 Op.getValueType() == MVT::f64) && 8315 "Invalid floating point type as target of conversion"); 8316 assert(Subtarget.hasFPCVT() && 8317 "Int to FP conversions with direct moves require FPCVT"); 8318 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8319 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8320 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8321 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8322 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8323 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8324 return convertIntToFP(Op, Mov, DAG, Subtarget); 8325 } 8326 8327 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8328 8329 EVT VecVT = Vec.getValueType(); 8330 assert(VecVT.isVector() && "Expected a vector type."); 8331 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8332 8333 EVT EltVT = VecVT.getVectorElementType(); 8334 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8335 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8336 8337 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8338 SmallVector<SDValue, 16> Ops(NumConcat); 8339 Ops[0] = Vec; 8340 SDValue UndefVec = DAG.getUNDEF(VecVT); 8341 for (unsigned i = 1; i < NumConcat; ++i) 8342 Ops[i] = UndefVec; 8343 8344 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8345 } 8346 8347 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8348 const SDLoc &dl) const { 8349 8350 unsigned Opc = Op.getOpcode(); 8351 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8352 "Unexpected conversion type"); 8353 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8354 "Supports conversions to v2f64/v4f32 only."); 8355 8356 bool SignedConv = Opc == ISD::SINT_TO_FP; 8357 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8358 8359 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8360 EVT WideVT = Wide.getValueType(); 8361 unsigned WideNumElts = WideVT.getVectorNumElements(); 8362 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8363 8364 SmallVector<int, 16> ShuffV; 8365 for (unsigned i = 0; i < WideNumElts; ++i) 8366 ShuffV.push_back(i + WideNumElts); 8367 8368 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8369 int SaveElts = FourEltRes ? 4 : 2; 8370 if (Subtarget.isLittleEndian()) 8371 for (int i = 0; i < SaveElts; i++) 8372 ShuffV[i * Stride] = i; 8373 else 8374 for (int i = 1; i <= SaveElts; i++) 8375 ShuffV[i * Stride - 1] = i - 1; 8376 8377 SDValue ShuffleSrc2 = 8378 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8379 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8380 8381 SDValue Extend; 8382 if (SignedConv) { 8383 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8384 EVT ExtVT = Op.getOperand(0).getValueType(); 8385 if (Subtarget.hasP9Altivec()) 8386 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8387 IntermediateVT.getVectorNumElements()); 8388 8389 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8390 DAG.getValueType(ExtVT)); 8391 } else 8392 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8393 8394 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8395 } 8396 8397 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8398 SelectionDAG &DAG) const { 8399 SDLoc dl(Op); 8400 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8401 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8402 bool IsStrict = Op->isStrictFPOpcode(); 8403 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8404 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8405 8406 EVT InVT = Src.getValueType(); 8407 EVT OutVT = Op.getValueType(); 8408 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8409 isOperationCustom(Op.getOpcode(), InVT)) 8410 return LowerINT_TO_FPVector(Op, DAG, dl); 8411 8412 // Conversions to f128 are legal. 8413 if (Op.getValueType() == MVT::f128) 8414 return Op; 8415 8416 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8417 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8418 return SDValue(); 8419 8420 if (Src.getValueType() == MVT::i1) 8421 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8422 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8423 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8424 8425 // If we have direct moves, we can do all the conversion, skip the store/load 8426 // however, without FPCVT we can't do most conversions. 8427 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8428 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8429 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8430 8431 assert((IsSigned || Subtarget.hasFPCVT()) && 8432 "UINT_TO_FP is supported only with FPCVT"); 8433 8434 if (Src.getValueType() == MVT::i64) { 8435 SDValue SINT = Src; 8436 // When converting to single-precision, we actually need to convert 8437 // to double-precision first and then round to single-precision. 8438 // To avoid double-rounding effects during that operation, we have 8439 // to prepare the input operand. Bits that might be truncated when 8440 // converting to double-precision are replaced by a bit that won't 8441 // be lost at this stage, but is below the single-precision rounding 8442 // position. 8443 // 8444 // However, if -enable-unsafe-fp-math is in effect, accept double 8445 // rounding to avoid the extra overhead. 8446 if (Op.getValueType() == MVT::f32 && 8447 !Subtarget.hasFPCVT() && 8448 !DAG.getTarget().Options.UnsafeFPMath) { 8449 8450 // Twiddle input to make sure the low 11 bits are zero. (If this 8451 // is the case, we are guaranteed the value will fit into the 53 bit 8452 // mantissa of an IEEE double-precision value without rounding.) 8453 // If any of those low 11 bits were not zero originally, make sure 8454 // bit 12 (value 2048) is set instead, so that the final rounding 8455 // to single-precision gets the correct result. 8456 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8457 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8458 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8459 Round, DAG.getConstant(2047, dl, MVT::i64)); 8460 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8461 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8462 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8463 8464 // However, we cannot use that value unconditionally: if the magnitude 8465 // of the input value is small, the bit-twiddling we did above might 8466 // end up visibly changing the output. Fortunately, in that case, we 8467 // don't need to twiddle bits since the original input will convert 8468 // exactly to double-precision floating-point already. Therefore, 8469 // construct a conditional to use the original value if the top 11 8470 // bits are all sign-bit copies, and use the rounded value computed 8471 // above otherwise. 8472 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8473 SINT, DAG.getConstant(53, dl, MVT::i32)); 8474 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8475 Cond, DAG.getConstant(1, dl, MVT::i64)); 8476 Cond = DAG.getSetCC( 8477 dl, 8478 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8479 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8480 8481 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8482 } 8483 8484 ReuseLoadInfo RLI; 8485 SDValue Bits; 8486 8487 MachineFunction &MF = DAG.getMachineFunction(); 8488 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8489 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8490 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8491 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8492 } else if (Subtarget.hasLFIWAX() && 8493 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8494 MachineMemOperand *MMO = 8495 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8496 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8497 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8498 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8499 DAG.getVTList(MVT::f64, MVT::Other), 8500 Ops, MVT::i32, MMO); 8501 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8502 } else if (Subtarget.hasFPCVT() && 8503 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8504 MachineMemOperand *MMO = 8505 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8506 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8507 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8508 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8509 DAG.getVTList(MVT::f64, MVT::Other), 8510 Ops, MVT::i32, MMO); 8511 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8512 } else if (((Subtarget.hasLFIWAX() && 8513 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8514 (Subtarget.hasFPCVT() && 8515 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8516 SINT.getOperand(0).getValueType() == MVT::i32) { 8517 MachineFrameInfo &MFI = MF.getFrameInfo(); 8518 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8519 8520 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8521 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8522 8523 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8524 MachinePointerInfo::getFixedStack( 8525 DAG.getMachineFunction(), FrameIdx)); 8526 Chain = Store; 8527 8528 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8529 "Expected an i32 store"); 8530 8531 RLI.Ptr = FIdx; 8532 RLI.Chain = Chain; 8533 RLI.MPI = 8534 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8535 RLI.Alignment = Align(4); 8536 8537 MachineMemOperand *MMO = 8538 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8539 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8540 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8541 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8542 PPCISD::LFIWZX : PPCISD::LFIWAX, 8543 dl, DAG.getVTList(MVT::f64, MVT::Other), 8544 Ops, MVT::i32, MMO); 8545 Chain = Bits.getValue(1); 8546 } else 8547 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8548 8549 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8550 if (IsStrict) 8551 Chain = FP.getValue(1); 8552 8553 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8554 if (IsStrict) 8555 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other}, 8556 {Chain, FP, DAG.getIntPtrConstant(0, dl)}); 8557 else 8558 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8559 DAG.getIntPtrConstant(0, dl)); 8560 } 8561 return FP; 8562 } 8563 8564 assert(Src.getValueType() == MVT::i32 && 8565 "Unhandled INT_TO_FP type in custom expander!"); 8566 // Since we only generate this in 64-bit mode, we can take advantage of 8567 // 64-bit registers. In particular, sign extend the input value into the 8568 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8569 // then lfd it and fcfid it. 8570 MachineFunction &MF = DAG.getMachineFunction(); 8571 MachineFrameInfo &MFI = MF.getFrameInfo(); 8572 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8573 8574 SDValue Ld; 8575 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8576 ReuseLoadInfo RLI; 8577 bool ReusingLoad; 8578 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8579 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8580 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8581 8582 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8583 MachinePointerInfo::getFixedStack( 8584 DAG.getMachineFunction(), FrameIdx)); 8585 Chain = Store; 8586 8587 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8588 "Expected an i32 store"); 8589 8590 RLI.Ptr = FIdx; 8591 RLI.Chain = Chain; 8592 RLI.MPI = 8593 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8594 RLI.Alignment = Align(4); 8595 } 8596 8597 MachineMemOperand *MMO = 8598 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8599 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8600 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8601 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8602 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8603 MVT::i32, MMO); 8604 Chain = Ld.getValue(1); 8605 if (ReusingLoad) 8606 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8607 } else { 8608 assert(Subtarget.isPPC64() && 8609 "i32->FP without LFIWAX supported only on PPC64"); 8610 8611 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8612 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8613 8614 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8615 8616 // STD the extended value into the stack slot. 8617 SDValue Store = DAG.getStore( 8618 Chain, dl, Ext64, FIdx, 8619 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8620 Chain = Store; 8621 8622 // Load the value as a double. 8623 Ld = DAG.getLoad( 8624 MVT::f64, dl, Chain, FIdx, 8625 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8626 Chain = Ld.getValue(1); 8627 } 8628 8629 // FCFID it and return it. 8630 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8631 if (IsStrict) 8632 Chain = FP.getValue(1); 8633 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8634 if (IsStrict) 8635 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other}, 8636 {Chain, FP, DAG.getIntPtrConstant(0, dl)}); 8637 else 8638 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8639 DAG.getIntPtrConstant(0, dl)); 8640 } 8641 return FP; 8642 } 8643 8644 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8645 SelectionDAG &DAG) const { 8646 SDLoc dl(Op); 8647 /* 8648 The rounding mode is in bits 30:31 of FPSR, and has the following 8649 settings: 8650 00 Round to nearest 8651 01 Round to 0 8652 10 Round to +inf 8653 11 Round to -inf 8654 8655 FLT_ROUNDS, on the other hand, expects the following: 8656 -1 Undefined 8657 0 Round to 0 8658 1 Round to nearest 8659 2 Round to +inf 8660 3 Round to -inf 8661 8662 To perform the conversion, we do: 8663 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8664 */ 8665 8666 MachineFunction &MF = DAG.getMachineFunction(); 8667 EVT VT = Op.getValueType(); 8668 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8669 8670 // Save FP Control Word to register 8671 SDValue Chain = Op.getOperand(0); 8672 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8673 Chain = MFFS.getValue(1); 8674 8675 // Save FP register to stack slot 8676 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8677 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8678 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8679 8680 // Load FP Control Word from low 32 bits of stack slot. 8681 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8682 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8683 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8684 Chain = CWD.getValue(1); 8685 8686 // Transform as necessary 8687 SDValue CWD1 = 8688 DAG.getNode(ISD::AND, dl, MVT::i32, 8689 CWD, DAG.getConstant(3, dl, MVT::i32)); 8690 SDValue CWD2 = 8691 DAG.getNode(ISD::SRL, dl, MVT::i32, 8692 DAG.getNode(ISD::AND, dl, MVT::i32, 8693 DAG.getNode(ISD::XOR, dl, MVT::i32, 8694 CWD, DAG.getConstant(3, dl, MVT::i32)), 8695 DAG.getConstant(3, dl, MVT::i32)), 8696 DAG.getConstant(1, dl, MVT::i32)); 8697 8698 SDValue RetVal = 8699 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8700 8701 RetVal = 8702 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8703 dl, VT, RetVal); 8704 8705 return DAG.getMergeValues({RetVal, Chain}, dl); 8706 } 8707 8708 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8709 EVT VT = Op.getValueType(); 8710 unsigned BitWidth = VT.getSizeInBits(); 8711 SDLoc dl(Op); 8712 assert(Op.getNumOperands() == 3 && 8713 VT == Op.getOperand(1).getValueType() && 8714 "Unexpected SHL!"); 8715 8716 // Expand into a bunch of logical ops. Note that these ops 8717 // depend on the PPC behavior for oversized shift amounts. 8718 SDValue Lo = Op.getOperand(0); 8719 SDValue Hi = Op.getOperand(1); 8720 SDValue Amt = Op.getOperand(2); 8721 EVT AmtVT = Amt.getValueType(); 8722 8723 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8724 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8725 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8726 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8727 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8728 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8729 DAG.getConstant(-BitWidth, dl, AmtVT)); 8730 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8731 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8732 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8733 SDValue OutOps[] = { OutLo, OutHi }; 8734 return DAG.getMergeValues(OutOps, dl); 8735 } 8736 8737 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8738 EVT VT = Op.getValueType(); 8739 SDLoc dl(Op); 8740 unsigned BitWidth = VT.getSizeInBits(); 8741 assert(Op.getNumOperands() == 3 && 8742 VT == Op.getOperand(1).getValueType() && 8743 "Unexpected SRL!"); 8744 8745 // Expand into a bunch of logical ops. Note that these ops 8746 // depend on the PPC behavior for oversized shift amounts. 8747 SDValue Lo = Op.getOperand(0); 8748 SDValue Hi = Op.getOperand(1); 8749 SDValue Amt = Op.getOperand(2); 8750 EVT AmtVT = Amt.getValueType(); 8751 8752 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8753 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8754 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8755 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8756 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8757 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8758 DAG.getConstant(-BitWidth, dl, AmtVT)); 8759 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8760 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8761 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8762 SDValue OutOps[] = { OutLo, OutHi }; 8763 return DAG.getMergeValues(OutOps, dl); 8764 } 8765 8766 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8767 SDLoc dl(Op); 8768 EVT VT = Op.getValueType(); 8769 unsigned BitWidth = VT.getSizeInBits(); 8770 assert(Op.getNumOperands() == 3 && 8771 VT == Op.getOperand(1).getValueType() && 8772 "Unexpected SRA!"); 8773 8774 // Expand into a bunch of logical ops, followed by a select_cc. 8775 SDValue Lo = Op.getOperand(0); 8776 SDValue Hi = Op.getOperand(1); 8777 SDValue Amt = Op.getOperand(2); 8778 EVT AmtVT = Amt.getValueType(); 8779 8780 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8781 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8782 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8783 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8784 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8785 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8786 DAG.getConstant(-BitWidth, dl, AmtVT)); 8787 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8788 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8789 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8790 Tmp4, Tmp6, ISD::SETLE); 8791 SDValue OutOps[] = { OutLo, OutHi }; 8792 return DAG.getMergeValues(OutOps, dl); 8793 } 8794 8795 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8796 SelectionDAG &DAG) const { 8797 SDLoc dl(Op); 8798 EVT VT = Op.getValueType(); 8799 unsigned BitWidth = VT.getSizeInBits(); 8800 8801 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8802 SDValue X = Op.getOperand(0); 8803 SDValue Y = Op.getOperand(1); 8804 SDValue Z = Op.getOperand(2); 8805 EVT AmtVT = Z.getValueType(); 8806 8807 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8808 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8809 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8810 // on PowerPC shift by BW being well defined. 8811 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8812 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8813 SDValue SubZ = 8814 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8815 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8816 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8817 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8818 } 8819 8820 //===----------------------------------------------------------------------===// 8821 // Vector related lowering. 8822 // 8823 8824 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8825 /// element size of SplatSize. Cast the result to VT. 8826 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8827 SelectionDAG &DAG, const SDLoc &dl) { 8828 static const MVT VTys[] = { // canonical VT to use for each size. 8829 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8830 }; 8831 8832 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8833 8834 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8835 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 8836 SplatSize = 1; 8837 Val = 0xFF; 8838 } 8839 8840 EVT CanonicalVT = VTys[SplatSize-1]; 8841 8842 // Build a canonical splat for this value. 8843 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8844 } 8845 8846 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8847 /// specified intrinsic ID. 8848 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8849 const SDLoc &dl, EVT DestVT = MVT::Other) { 8850 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8851 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8852 DAG.getConstant(IID, dl, MVT::i32), Op); 8853 } 8854 8855 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8856 /// specified intrinsic ID. 8857 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8858 SelectionDAG &DAG, const SDLoc &dl, 8859 EVT DestVT = MVT::Other) { 8860 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8861 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8862 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8863 } 8864 8865 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8866 /// specified intrinsic ID. 8867 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8868 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8869 EVT DestVT = MVT::Other) { 8870 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8871 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8872 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8873 } 8874 8875 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8876 /// amount. The result has the specified value type. 8877 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8878 SelectionDAG &DAG, const SDLoc &dl) { 8879 // Force LHS/RHS to be the right type. 8880 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8881 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8882 8883 int Ops[16]; 8884 for (unsigned i = 0; i != 16; ++i) 8885 Ops[i] = i + Amt; 8886 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8887 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8888 } 8889 8890 /// Do we have an efficient pattern in a .td file for this node? 8891 /// 8892 /// \param V - pointer to the BuildVectorSDNode being matched 8893 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8894 /// 8895 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8896 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8897 /// the opposite is true (expansion is beneficial) are: 8898 /// - The node builds a vector out of integers that are not 32 or 64-bits 8899 /// - The node builds a vector out of constants 8900 /// - The node is a "load-and-splat" 8901 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8902 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8903 bool HasDirectMove, 8904 bool HasP8Vector) { 8905 EVT VecVT = V->getValueType(0); 8906 bool RightType = VecVT == MVT::v2f64 || 8907 (HasP8Vector && VecVT == MVT::v4f32) || 8908 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8909 if (!RightType) 8910 return false; 8911 8912 bool IsSplat = true; 8913 bool IsLoad = false; 8914 SDValue Op0 = V->getOperand(0); 8915 8916 // This function is called in a block that confirms the node is not a constant 8917 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8918 // different constants. 8919 if (V->isConstant()) 8920 return false; 8921 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8922 if (V->getOperand(i).isUndef()) 8923 return false; 8924 // We want to expand nodes that represent load-and-splat even if the 8925 // loaded value is a floating point truncation or conversion to int. 8926 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8927 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8928 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8929 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8930 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8931 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8932 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8933 IsLoad = true; 8934 // If the operands are different or the input is not a load and has more 8935 // uses than just this BV node, then it isn't a splat. 8936 if (V->getOperand(i) != Op0 || 8937 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8938 IsSplat = false; 8939 } 8940 return !(IsSplat && IsLoad); 8941 } 8942 8943 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8944 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8945 8946 SDLoc dl(Op); 8947 SDValue Op0 = Op->getOperand(0); 8948 8949 if ((Op.getValueType() != MVT::f128) || 8950 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8951 (Op0.getOperand(0).getValueType() != MVT::i64) || 8952 (Op0.getOperand(1).getValueType() != MVT::i64)) 8953 return SDValue(); 8954 8955 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8956 Op0.getOperand(1)); 8957 } 8958 8959 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 8960 const SDValue *InputLoad = &Op; 8961 if (InputLoad->getOpcode() == ISD::BITCAST) 8962 InputLoad = &InputLoad->getOperand(0); 8963 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 8964 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 8965 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 8966 InputLoad = &InputLoad->getOperand(0); 8967 } 8968 if (InputLoad->getOpcode() != ISD::LOAD) 8969 return nullptr; 8970 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8971 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8972 } 8973 8974 // Convert the argument APFloat to a single precision APFloat if there is no 8975 // loss in information during the conversion to single precision APFloat and the 8976 // resulting number is not a denormal number. Return true if successful. 8977 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 8978 APFloat APFloatToConvert = ArgAPFloat; 8979 bool LosesInfo = true; 8980 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8981 &LosesInfo); 8982 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 8983 if (Success) 8984 ArgAPFloat = APFloatToConvert; 8985 return Success; 8986 } 8987 8988 // Bitcast the argument APInt to a double and convert it to a single precision 8989 // APFloat, bitcast the APFloat to an APInt and assign it to the original 8990 // argument if there is no loss in information during the conversion from 8991 // double to single precision APFloat and the resulting number is not a denormal 8992 // number. Return true if successful. 8993 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 8994 double DpValue = ArgAPInt.bitsToDouble(); 8995 APFloat APFloatDp(DpValue); 8996 bool Success = convertToNonDenormSingle(APFloatDp); 8997 if (Success) 8998 ArgAPInt = APFloatDp.bitcastToAPInt(); 8999 return Success; 9000 } 9001 9002 // If this is a case we can't handle, return null and let the default 9003 // expansion code take care of it. If we CAN select this case, and if it 9004 // selects to a single instruction, return Op. Otherwise, if we can codegen 9005 // this case more efficiently than a constant pool load, lower it to the 9006 // sequence of ops that should be used. 9007 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9008 SelectionDAG &DAG) const { 9009 SDLoc dl(Op); 9010 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9011 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9012 9013 // Check if this is a splat of a constant value. 9014 APInt APSplatBits, APSplatUndef; 9015 unsigned SplatBitSize; 9016 bool HasAnyUndefs; 9017 bool BVNIsConstantSplat = 9018 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9019 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9020 9021 // If it is a splat of a double, check if we can shrink it to a 32 bit 9022 // non-denormal float which when converted back to double gives us the same 9023 // double. This is to exploit the XXSPLTIDP instruction. 9024 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 9025 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 9026 convertToNonDenormSingle(APSplatBits)) { 9027 SDValue SplatNode = DAG.getNode( 9028 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9029 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9030 return DAG.getBitcast(Op.getValueType(), SplatNode); 9031 } 9032 9033 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9034 9035 bool IsPermutedLoad = false; 9036 const SDValue *InputLoad = 9037 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9038 // Handle load-and-splat patterns as we have instructions that will do this 9039 // in one go. 9040 if (InputLoad && DAG.isSplatValue(Op, true)) { 9041 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9042 9043 // We have handling for 4 and 8 byte elements. 9044 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9045 9046 // Checking for a single use of this load, we have to check for vector 9047 // width (128 bits) / ElementSize uses (since each operand of the 9048 // BUILD_VECTOR is a separate use of the value. 9049 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9050 ((Subtarget.hasVSX() && ElementSize == 64) || 9051 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9052 SDValue Ops[] = { 9053 LD->getChain(), // Chain 9054 LD->getBasePtr(), // Ptr 9055 DAG.getValueType(Op.getValueType()) // VT 9056 }; 9057 return 9058 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9059 DAG.getVTList(Op.getValueType(), MVT::Other), 9060 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9061 } 9062 } 9063 9064 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9065 // lowered to VSX instructions under certain conditions. 9066 // Without VSX, there is no pattern more efficient than expanding the node. 9067 if (Subtarget.hasVSX() && 9068 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9069 Subtarget.hasP8Vector())) 9070 return Op; 9071 return SDValue(); 9072 } 9073 9074 uint64_t SplatBits = APSplatBits.getZExtValue(); 9075 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9076 unsigned SplatSize = SplatBitSize / 8; 9077 9078 // First, handle single instruction cases. 9079 9080 // All zeros? 9081 if (SplatBits == 0) { 9082 // Canonicalize all zero vectors to be v4i32. 9083 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9084 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9085 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9086 } 9087 return Op; 9088 } 9089 9090 // We have XXSPLTIW for constant splats four bytes wide. 9091 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9092 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9093 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9094 // turned into a 4-byte splat of 0xABABABAB. 9095 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9096 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 9097 Op.getValueType(), DAG, dl); 9098 9099 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9100 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9101 dl); 9102 9103 // We have XXSPLTIB for constant splats one byte wide. 9104 if (Subtarget.hasP9Vector() && SplatSize == 1) 9105 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9106 dl); 9107 9108 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9109 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9110 (32-SplatBitSize)); 9111 if (SextVal >= -16 && SextVal <= 15) 9112 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9113 dl); 9114 9115 // Two instruction sequences. 9116 9117 // If this value is in the range [-32,30] and is even, use: 9118 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9119 // If this value is in the range [17,31] and is odd, use: 9120 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9121 // If this value is in the range [-31,-17] and is odd, use: 9122 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9123 // Note the last two are three-instruction sequences. 9124 if (SextVal >= -32 && SextVal <= 31) { 9125 // To avoid having these optimizations undone by constant folding, 9126 // we convert to a pseudo that will be expanded later into one of 9127 // the above forms. 9128 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9129 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9130 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9131 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9132 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9133 if (VT == Op.getValueType()) 9134 return RetVal; 9135 else 9136 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9137 } 9138 9139 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9140 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9141 // for fneg/fabs. 9142 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9143 // Make -1 and vspltisw -1: 9144 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9145 9146 // Make the VSLW intrinsic, computing 0x8000_0000. 9147 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9148 OnesV, DAG, dl); 9149 9150 // xor by OnesV to invert it. 9151 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9152 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9153 } 9154 9155 // Check to see if this is a wide variety of vsplti*, binop self cases. 9156 static const signed char SplatCsts[] = { 9157 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9158 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9159 }; 9160 9161 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9162 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9163 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9164 int i = SplatCsts[idx]; 9165 9166 // Figure out what shift amount will be used by altivec if shifted by i in 9167 // this splat size. 9168 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9169 9170 // vsplti + shl self. 9171 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9172 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9173 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9174 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9175 Intrinsic::ppc_altivec_vslw 9176 }; 9177 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9178 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9179 } 9180 9181 // vsplti + srl self. 9182 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9183 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9184 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9185 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9186 Intrinsic::ppc_altivec_vsrw 9187 }; 9188 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9189 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9190 } 9191 9192 // vsplti + sra self. 9193 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9194 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9195 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9196 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9197 Intrinsic::ppc_altivec_vsraw 9198 }; 9199 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9200 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9201 } 9202 9203 // vsplti + rol self. 9204 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9205 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9206 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9207 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9208 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9209 Intrinsic::ppc_altivec_vrlw 9210 }; 9211 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9212 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9213 } 9214 9215 // t = vsplti c, result = vsldoi t, t, 1 9216 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9217 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9218 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9219 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9220 } 9221 // t = vsplti c, result = vsldoi t, t, 2 9222 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9223 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9224 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9225 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9226 } 9227 // t = vsplti c, result = vsldoi t, t, 3 9228 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9229 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9230 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9231 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9232 } 9233 } 9234 9235 return SDValue(); 9236 } 9237 9238 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9239 /// the specified operations to build the shuffle. 9240 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9241 SDValue RHS, SelectionDAG &DAG, 9242 const SDLoc &dl) { 9243 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9244 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9245 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9246 9247 enum { 9248 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9249 OP_VMRGHW, 9250 OP_VMRGLW, 9251 OP_VSPLTISW0, 9252 OP_VSPLTISW1, 9253 OP_VSPLTISW2, 9254 OP_VSPLTISW3, 9255 OP_VSLDOI4, 9256 OP_VSLDOI8, 9257 OP_VSLDOI12 9258 }; 9259 9260 if (OpNum == OP_COPY) { 9261 if (LHSID == (1*9+2)*9+3) return LHS; 9262 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9263 return RHS; 9264 } 9265 9266 SDValue OpLHS, OpRHS; 9267 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9268 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9269 9270 int ShufIdxs[16]; 9271 switch (OpNum) { 9272 default: llvm_unreachable("Unknown i32 permute!"); 9273 case OP_VMRGHW: 9274 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9275 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9276 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9277 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9278 break; 9279 case OP_VMRGLW: 9280 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9281 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9282 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9283 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9284 break; 9285 case OP_VSPLTISW0: 9286 for (unsigned i = 0; i != 16; ++i) 9287 ShufIdxs[i] = (i&3)+0; 9288 break; 9289 case OP_VSPLTISW1: 9290 for (unsigned i = 0; i != 16; ++i) 9291 ShufIdxs[i] = (i&3)+4; 9292 break; 9293 case OP_VSPLTISW2: 9294 for (unsigned i = 0; i != 16; ++i) 9295 ShufIdxs[i] = (i&3)+8; 9296 break; 9297 case OP_VSPLTISW3: 9298 for (unsigned i = 0; i != 16; ++i) 9299 ShufIdxs[i] = (i&3)+12; 9300 break; 9301 case OP_VSLDOI4: 9302 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9303 case OP_VSLDOI8: 9304 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9305 case OP_VSLDOI12: 9306 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9307 } 9308 EVT VT = OpLHS.getValueType(); 9309 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9310 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9311 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9312 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9313 } 9314 9315 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9316 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9317 /// SDValue. 9318 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9319 SelectionDAG &DAG) const { 9320 const unsigned BytesInVector = 16; 9321 bool IsLE = Subtarget.isLittleEndian(); 9322 SDLoc dl(N); 9323 SDValue V1 = N->getOperand(0); 9324 SDValue V2 = N->getOperand(1); 9325 unsigned ShiftElts = 0, InsertAtByte = 0; 9326 bool Swap = false; 9327 9328 // Shifts required to get the byte we want at element 7. 9329 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9330 0, 15, 14, 13, 12, 11, 10, 9}; 9331 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9332 1, 2, 3, 4, 5, 6, 7, 8}; 9333 9334 ArrayRef<int> Mask = N->getMask(); 9335 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9336 9337 // For each mask element, find out if we're just inserting something 9338 // from V2 into V1 or vice versa. 9339 // Possible permutations inserting an element from V2 into V1: 9340 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9341 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9342 // ... 9343 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9344 // Inserting from V1 into V2 will be similar, except mask range will be 9345 // [16,31]. 9346 9347 bool FoundCandidate = false; 9348 // If both vector operands for the shuffle are the same vector, the mask 9349 // will contain only elements from the first one and the second one will be 9350 // undef. 9351 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9352 // Go through the mask of half-words to find an element that's being moved 9353 // from one vector to the other. 9354 for (unsigned i = 0; i < BytesInVector; ++i) { 9355 unsigned CurrentElement = Mask[i]; 9356 // If 2nd operand is undefined, we should only look for element 7 in the 9357 // Mask. 9358 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9359 continue; 9360 9361 bool OtherElementsInOrder = true; 9362 // Examine the other elements in the Mask to see if they're in original 9363 // order. 9364 for (unsigned j = 0; j < BytesInVector; ++j) { 9365 if (j == i) 9366 continue; 9367 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9368 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9369 // in which we always assume we're always picking from the 1st operand. 9370 int MaskOffset = 9371 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9372 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9373 OtherElementsInOrder = false; 9374 break; 9375 } 9376 } 9377 // If other elements are in original order, we record the number of shifts 9378 // we need to get the element we want into element 7. Also record which byte 9379 // in the vector we should insert into. 9380 if (OtherElementsInOrder) { 9381 // If 2nd operand is undefined, we assume no shifts and no swapping. 9382 if (V2.isUndef()) { 9383 ShiftElts = 0; 9384 Swap = false; 9385 } else { 9386 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9387 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9388 : BigEndianShifts[CurrentElement & 0xF]; 9389 Swap = CurrentElement < BytesInVector; 9390 } 9391 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9392 FoundCandidate = true; 9393 break; 9394 } 9395 } 9396 9397 if (!FoundCandidate) 9398 return SDValue(); 9399 9400 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9401 // optionally with VECSHL if shift is required. 9402 if (Swap) 9403 std::swap(V1, V2); 9404 if (V2.isUndef()) 9405 V2 = V1; 9406 if (ShiftElts) { 9407 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9408 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9409 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9410 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9411 } 9412 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9413 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9414 } 9415 9416 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9417 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9418 /// SDValue. 9419 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9420 SelectionDAG &DAG) const { 9421 const unsigned NumHalfWords = 8; 9422 const unsigned BytesInVector = NumHalfWords * 2; 9423 // Check that the shuffle is on half-words. 9424 if (!isNByteElemShuffleMask(N, 2, 1)) 9425 return SDValue(); 9426 9427 bool IsLE = Subtarget.isLittleEndian(); 9428 SDLoc dl(N); 9429 SDValue V1 = N->getOperand(0); 9430 SDValue V2 = N->getOperand(1); 9431 unsigned ShiftElts = 0, InsertAtByte = 0; 9432 bool Swap = false; 9433 9434 // Shifts required to get the half-word we want at element 3. 9435 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9436 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9437 9438 uint32_t Mask = 0; 9439 uint32_t OriginalOrderLow = 0x1234567; 9440 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9441 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9442 // 32-bit space, only need 4-bit nibbles per element. 9443 for (unsigned i = 0; i < NumHalfWords; ++i) { 9444 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9445 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9446 } 9447 9448 // For each mask element, find out if we're just inserting something 9449 // from V2 into V1 or vice versa. Possible permutations inserting an element 9450 // from V2 into V1: 9451 // X, 1, 2, 3, 4, 5, 6, 7 9452 // 0, X, 2, 3, 4, 5, 6, 7 9453 // 0, 1, X, 3, 4, 5, 6, 7 9454 // 0, 1, 2, X, 4, 5, 6, 7 9455 // 0, 1, 2, 3, X, 5, 6, 7 9456 // 0, 1, 2, 3, 4, X, 6, 7 9457 // 0, 1, 2, 3, 4, 5, X, 7 9458 // 0, 1, 2, 3, 4, 5, 6, X 9459 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9460 9461 bool FoundCandidate = false; 9462 // Go through the mask of half-words to find an element that's being moved 9463 // from one vector to the other. 9464 for (unsigned i = 0; i < NumHalfWords; ++i) { 9465 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9466 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9467 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9468 uint32_t TargetOrder = 0x0; 9469 9470 // If both vector operands for the shuffle are the same vector, the mask 9471 // will contain only elements from the first one and the second one will be 9472 // undef. 9473 if (V2.isUndef()) { 9474 ShiftElts = 0; 9475 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9476 TargetOrder = OriginalOrderLow; 9477 Swap = false; 9478 // Skip if not the correct element or mask of other elements don't equal 9479 // to our expected order. 9480 if (MaskOneElt == VINSERTHSrcElem && 9481 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9482 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9483 FoundCandidate = true; 9484 break; 9485 } 9486 } else { // If both operands are defined. 9487 // Target order is [8,15] if the current mask is between [0,7]. 9488 TargetOrder = 9489 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9490 // Skip if mask of other elements don't equal our expected order. 9491 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9492 // We only need the last 3 bits for the number of shifts. 9493 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9494 : BigEndianShifts[MaskOneElt & 0x7]; 9495 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9496 Swap = MaskOneElt < NumHalfWords; 9497 FoundCandidate = true; 9498 break; 9499 } 9500 } 9501 } 9502 9503 if (!FoundCandidate) 9504 return SDValue(); 9505 9506 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9507 // optionally with VECSHL if shift is required. 9508 if (Swap) 9509 std::swap(V1, V2); 9510 if (V2.isUndef()) 9511 V2 = V1; 9512 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9513 if (ShiftElts) { 9514 // Double ShiftElts because we're left shifting on v16i8 type. 9515 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9516 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9517 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9518 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9519 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9520 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9521 } 9522 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9523 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9524 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9525 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9526 } 9527 9528 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9529 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9530 /// return the default SDValue. 9531 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9532 SelectionDAG &DAG) const { 9533 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9534 // to v16i8. Peek through the bitcasts to get the actual operands. 9535 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9536 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9537 9538 auto ShuffleMask = SVN->getMask(); 9539 SDValue VecShuffle(SVN, 0); 9540 SDLoc DL(SVN); 9541 9542 // Check that we have a four byte shuffle. 9543 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9544 return SDValue(); 9545 9546 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9547 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9548 std::swap(LHS, RHS); 9549 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9550 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9551 } 9552 9553 // Ensure that the RHS is a vector of constants. 9554 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9555 if (!BVN) 9556 return SDValue(); 9557 9558 // Check if RHS is a splat of 4-bytes (or smaller). 9559 APInt APSplatValue, APSplatUndef; 9560 unsigned SplatBitSize; 9561 bool HasAnyUndefs; 9562 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9563 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9564 SplatBitSize > 32) 9565 return SDValue(); 9566 9567 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9568 // The instruction splats a constant C into two words of the source vector 9569 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9570 // Thus we check that the shuffle mask is the equivalent of 9571 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9572 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9573 // within each word are consecutive, so we only need to check the first byte. 9574 SDValue Index; 9575 bool IsLE = Subtarget.isLittleEndian(); 9576 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9577 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9578 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9579 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9580 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9581 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9582 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9583 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9584 else 9585 return SDValue(); 9586 9587 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9588 // for XXSPLTI32DX. 9589 unsigned SplatVal = APSplatValue.getZExtValue(); 9590 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9591 SplatVal |= (SplatVal << SplatBitSize); 9592 9593 SDValue SplatNode = DAG.getNode( 9594 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9595 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9596 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9597 } 9598 9599 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9600 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9601 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9602 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9603 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9604 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9605 assert(Op.getValueType() == MVT::v1i128 && 9606 "Only set v1i128 as custom, other type shouldn't reach here!"); 9607 SDLoc dl(Op); 9608 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9609 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9610 unsigned SHLAmt = N1.getConstantOperandVal(0); 9611 if (SHLAmt % 8 == 0) { 9612 SmallVector<int, 16> Mask(16, 0); 9613 std::iota(Mask.begin(), Mask.end(), 0); 9614 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9615 if (SDValue Shuffle = 9616 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9617 DAG.getUNDEF(MVT::v16i8), Mask)) 9618 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9619 } 9620 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9621 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9622 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9623 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9624 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9625 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9626 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9627 } 9628 9629 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9630 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9631 /// return the code it can be lowered into. Worst case, it can always be 9632 /// lowered into a vperm. 9633 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9634 SelectionDAG &DAG) const { 9635 SDLoc dl(Op); 9636 SDValue V1 = Op.getOperand(0); 9637 SDValue V2 = Op.getOperand(1); 9638 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9639 9640 // Any nodes that were combined in the target-independent combiner prior 9641 // to vector legalization will not be sent to the target combine. Try to 9642 // combine it here. 9643 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9644 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9645 return NewShuffle; 9646 Op = NewShuffle; 9647 SVOp = cast<ShuffleVectorSDNode>(Op); 9648 V1 = Op.getOperand(0); 9649 V2 = Op.getOperand(1); 9650 } 9651 EVT VT = Op.getValueType(); 9652 bool isLittleEndian = Subtarget.isLittleEndian(); 9653 9654 unsigned ShiftElts, InsertAtByte; 9655 bool Swap = false; 9656 9657 // If this is a load-and-splat, we can do that with a single instruction 9658 // in some cases. However if the load has multiple uses, we don't want to 9659 // combine it because that will just produce multiple loads. 9660 bool IsPermutedLoad = false; 9661 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9662 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9663 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9664 InputLoad->hasOneUse()) { 9665 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9666 int SplatIdx = 9667 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9668 9669 // The splat index for permuted loads will be in the left half of the vector 9670 // which is strictly wider than the loaded value by 8 bytes. So we need to 9671 // adjust the splat index to point to the correct address in memory. 9672 if (IsPermutedLoad) { 9673 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9674 SplatIdx += IsFourByte ? 2 : 1; 9675 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9676 "Splat of a value outside of the loaded memory"); 9677 } 9678 9679 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9680 // For 4-byte load-and-splat, we need Power9. 9681 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9682 uint64_t Offset = 0; 9683 if (IsFourByte) 9684 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9685 else 9686 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9687 9688 SDValue BasePtr = LD->getBasePtr(); 9689 if (Offset != 0) 9690 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9691 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9692 SDValue Ops[] = { 9693 LD->getChain(), // Chain 9694 BasePtr, // BasePtr 9695 DAG.getValueType(Op.getValueType()) // VT 9696 }; 9697 SDVTList VTL = 9698 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9699 SDValue LdSplt = 9700 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9701 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9702 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9703 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9704 return LdSplt; 9705 } 9706 } 9707 if (Subtarget.hasP9Vector() && 9708 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9709 isLittleEndian)) { 9710 if (Swap) 9711 std::swap(V1, V2); 9712 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9713 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9714 if (ShiftElts) { 9715 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9716 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9717 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9718 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9719 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9720 } 9721 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9722 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9723 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9724 } 9725 9726 if (Subtarget.hasPrefixInstrs()) { 9727 SDValue SplatInsertNode; 9728 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9729 return SplatInsertNode; 9730 } 9731 9732 if (Subtarget.hasP9Altivec()) { 9733 SDValue NewISDNode; 9734 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9735 return NewISDNode; 9736 9737 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9738 return NewISDNode; 9739 } 9740 9741 if (Subtarget.hasVSX() && 9742 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9743 if (Swap) 9744 std::swap(V1, V2); 9745 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9746 SDValue Conv2 = 9747 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9748 9749 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9750 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9751 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9752 } 9753 9754 if (Subtarget.hasVSX() && 9755 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9756 if (Swap) 9757 std::swap(V1, V2); 9758 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9759 SDValue Conv2 = 9760 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9761 9762 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9763 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9764 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9765 } 9766 9767 if (Subtarget.hasP9Vector()) { 9768 if (PPC::isXXBRHShuffleMask(SVOp)) { 9769 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9770 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9771 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9772 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9773 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9774 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9775 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9776 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9777 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9778 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9779 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9780 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9781 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9782 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9783 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9784 } 9785 } 9786 9787 if (Subtarget.hasVSX()) { 9788 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9789 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9790 9791 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9792 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9793 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9794 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9795 } 9796 9797 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9798 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9799 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9800 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9801 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9802 } 9803 } 9804 9805 // Cases that are handled by instructions that take permute immediates 9806 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9807 // selected by the instruction selector. 9808 if (V2.isUndef()) { 9809 if (PPC::isSplatShuffleMask(SVOp, 1) || 9810 PPC::isSplatShuffleMask(SVOp, 2) || 9811 PPC::isSplatShuffleMask(SVOp, 4) || 9812 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9813 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9814 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9815 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9816 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9817 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9818 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9819 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9820 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9821 (Subtarget.hasP8Altivec() && ( 9822 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9823 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9824 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9825 return Op; 9826 } 9827 } 9828 9829 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9830 // and produce a fixed permutation. If any of these match, do not lower to 9831 // VPERM. 9832 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9833 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9834 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9835 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9836 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9837 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9838 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9839 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9840 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9841 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9842 (Subtarget.hasP8Altivec() && ( 9843 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9844 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9845 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9846 return Op; 9847 9848 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9849 // perfect shuffle table to emit an optimal matching sequence. 9850 ArrayRef<int> PermMask = SVOp->getMask(); 9851 9852 unsigned PFIndexes[4]; 9853 bool isFourElementShuffle = true; 9854 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9855 unsigned EltNo = 8; // Start out undef. 9856 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9857 if (PermMask[i*4+j] < 0) 9858 continue; // Undef, ignore it. 9859 9860 unsigned ByteSource = PermMask[i*4+j]; 9861 if ((ByteSource & 3) != j) { 9862 isFourElementShuffle = false; 9863 break; 9864 } 9865 9866 if (EltNo == 8) { 9867 EltNo = ByteSource/4; 9868 } else if (EltNo != ByteSource/4) { 9869 isFourElementShuffle = false; 9870 break; 9871 } 9872 } 9873 PFIndexes[i] = EltNo; 9874 } 9875 9876 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9877 // perfect shuffle vector to determine if it is cost effective to do this as 9878 // discrete instructions, or whether we should use a vperm. 9879 // For now, we skip this for little endian until such time as we have a 9880 // little-endian perfect shuffle table. 9881 if (isFourElementShuffle && !isLittleEndian) { 9882 // Compute the index in the perfect shuffle table. 9883 unsigned PFTableIndex = 9884 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9885 9886 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9887 unsigned Cost = (PFEntry >> 30); 9888 9889 // Determining when to avoid vperm is tricky. Many things affect the cost 9890 // of vperm, particularly how many times the perm mask needs to be computed. 9891 // For example, if the perm mask can be hoisted out of a loop or is already 9892 // used (perhaps because there are multiple permutes with the same shuffle 9893 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9894 // the loop requires an extra register. 9895 // 9896 // As a compromise, we only emit discrete instructions if the shuffle can be 9897 // generated in 3 or fewer operations. When we have loop information 9898 // available, if this block is within a loop, we should avoid using vperm 9899 // for 3-operation perms and use a constant pool load instead. 9900 if (Cost < 3) 9901 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9902 } 9903 9904 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9905 // vector that will get spilled to the constant pool. 9906 if (V2.isUndef()) V2 = V1; 9907 9908 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9909 // that it is in input element units, not in bytes. Convert now. 9910 9911 // For little endian, the order of the input vectors is reversed, and 9912 // the permutation mask is complemented with respect to 31. This is 9913 // necessary to produce proper semantics with the big-endian-biased vperm 9914 // instruction. 9915 EVT EltVT = V1.getValueType().getVectorElementType(); 9916 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9917 9918 SmallVector<SDValue, 16> ResultMask; 9919 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9920 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9921 9922 for (unsigned j = 0; j != BytesPerElement; ++j) 9923 if (isLittleEndian) 9924 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9925 dl, MVT::i32)); 9926 else 9927 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9928 MVT::i32)); 9929 } 9930 9931 ShufflesHandledWithVPERM++; 9932 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9933 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9934 LLVM_DEBUG(SVOp->dump()); 9935 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9936 LLVM_DEBUG(VPermMask.dump()); 9937 9938 if (isLittleEndian) 9939 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9940 V2, V1, VPermMask); 9941 else 9942 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9943 V1, V2, VPermMask); 9944 } 9945 9946 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9947 /// vector comparison. If it is, return true and fill in Opc/isDot with 9948 /// information about the intrinsic. 9949 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9950 bool &isDot, const PPCSubtarget &Subtarget) { 9951 unsigned IntrinsicID = 9952 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9953 CompareOpc = -1; 9954 isDot = false; 9955 switch (IntrinsicID) { 9956 default: 9957 return false; 9958 // Comparison predicates. 9959 case Intrinsic::ppc_altivec_vcmpbfp_p: 9960 CompareOpc = 966; 9961 isDot = true; 9962 break; 9963 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9964 CompareOpc = 198; 9965 isDot = true; 9966 break; 9967 case Intrinsic::ppc_altivec_vcmpequb_p: 9968 CompareOpc = 6; 9969 isDot = true; 9970 break; 9971 case Intrinsic::ppc_altivec_vcmpequh_p: 9972 CompareOpc = 70; 9973 isDot = true; 9974 break; 9975 case Intrinsic::ppc_altivec_vcmpequw_p: 9976 CompareOpc = 134; 9977 isDot = true; 9978 break; 9979 case Intrinsic::ppc_altivec_vcmpequd_p: 9980 if (Subtarget.hasP8Altivec()) { 9981 CompareOpc = 199; 9982 isDot = true; 9983 } else 9984 return false; 9985 break; 9986 case Intrinsic::ppc_altivec_vcmpneb_p: 9987 case Intrinsic::ppc_altivec_vcmpneh_p: 9988 case Intrinsic::ppc_altivec_vcmpnew_p: 9989 case Intrinsic::ppc_altivec_vcmpnezb_p: 9990 case Intrinsic::ppc_altivec_vcmpnezh_p: 9991 case Intrinsic::ppc_altivec_vcmpnezw_p: 9992 if (Subtarget.hasP9Altivec()) { 9993 switch (IntrinsicID) { 9994 default: 9995 llvm_unreachable("Unknown comparison intrinsic."); 9996 case Intrinsic::ppc_altivec_vcmpneb_p: 9997 CompareOpc = 7; 9998 break; 9999 case Intrinsic::ppc_altivec_vcmpneh_p: 10000 CompareOpc = 71; 10001 break; 10002 case Intrinsic::ppc_altivec_vcmpnew_p: 10003 CompareOpc = 135; 10004 break; 10005 case Intrinsic::ppc_altivec_vcmpnezb_p: 10006 CompareOpc = 263; 10007 break; 10008 case Intrinsic::ppc_altivec_vcmpnezh_p: 10009 CompareOpc = 327; 10010 break; 10011 case Intrinsic::ppc_altivec_vcmpnezw_p: 10012 CompareOpc = 391; 10013 break; 10014 } 10015 isDot = true; 10016 } else 10017 return false; 10018 break; 10019 case Intrinsic::ppc_altivec_vcmpgefp_p: 10020 CompareOpc = 454; 10021 isDot = true; 10022 break; 10023 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10024 CompareOpc = 710; 10025 isDot = true; 10026 break; 10027 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10028 CompareOpc = 774; 10029 isDot = true; 10030 break; 10031 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10032 CompareOpc = 838; 10033 isDot = true; 10034 break; 10035 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10036 CompareOpc = 902; 10037 isDot = true; 10038 break; 10039 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10040 if (Subtarget.hasP8Altivec()) { 10041 CompareOpc = 967; 10042 isDot = true; 10043 } else 10044 return false; 10045 break; 10046 case Intrinsic::ppc_altivec_vcmpgtub_p: 10047 CompareOpc = 518; 10048 isDot = true; 10049 break; 10050 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10051 CompareOpc = 582; 10052 isDot = true; 10053 break; 10054 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10055 CompareOpc = 646; 10056 isDot = true; 10057 break; 10058 case Intrinsic::ppc_altivec_vcmpgtud_p: 10059 if (Subtarget.hasP8Altivec()) { 10060 CompareOpc = 711; 10061 isDot = true; 10062 } else 10063 return false; 10064 break; 10065 10066 // VSX predicate comparisons use the same infrastructure 10067 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10068 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10069 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10070 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10071 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10072 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10073 if (Subtarget.hasVSX()) { 10074 switch (IntrinsicID) { 10075 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10076 CompareOpc = 99; 10077 break; 10078 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10079 CompareOpc = 115; 10080 break; 10081 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10082 CompareOpc = 107; 10083 break; 10084 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10085 CompareOpc = 67; 10086 break; 10087 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10088 CompareOpc = 83; 10089 break; 10090 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10091 CompareOpc = 75; 10092 break; 10093 } 10094 isDot = true; 10095 } else 10096 return false; 10097 break; 10098 10099 // Normal Comparisons. 10100 case Intrinsic::ppc_altivec_vcmpbfp: 10101 CompareOpc = 966; 10102 break; 10103 case Intrinsic::ppc_altivec_vcmpeqfp: 10104 CompareOpc = 198; 10105 break; 10106 case Intrinsic::ppc_altivec_vcmpequb: 10107 CompareOpc = 6; 10108 break; 10109 case Intrinsic::ppc_altivec_vcmpequh: 10110 CompareOpc = 70; 10111 break; 10112 case Intrinsic::ppc_altivec_vcmpequw: 10113 CompareOpc = 134; 10114 break; 10115 case Intrinsic::ppc_altivec_vcmpequd: 10116 if (Subtarget.hasP8Altivec()) 10117 CompareOpc = 199; 10118 else 10119 return false; 10120 break; 10121 case Intrinsic::ppc_altivec_vcmpneb: 10122 case Intrinsic::ppc_altivec_vcmpneh: 10123 case Intrinsic::ppc_altivec_vcmpnew: 10124 case Intrinsic::ppc_altivec_vcmpnezb: 10125 case Intrinsic::ppc_altivec_vcmpnezh: 10126 case Intrinsic::ppc_altivec_vcmpnezw: 10127 if (Subtarget.hasP9Altivec()) 10128 switch (IntrinsicID) { 10129 default: 10130 llvm_unreachable("Unknown comparison intrinsic."); 10131 case Intrinsic::ppc_altivec_vcmpneb: 10132 CompareOpc = 7; 10133 break; 10134 case Intrinsic::ppc_altivec_vcmpneh: 10135 CompareOpc = 71; 10136 break; 10137 case Intrinsic::ppc_altivec_vcmpnew: 10138 CompareOpc = 135; 10139 break; 10140 case Intrinsic::ppc_altivec_vcmpnezb: 10141 CompareOpc = 263; 10142 break; 10143 case Intrinsic::ppc_altivec_vcmpnezh: 10144 CompareOpc = 327; 10145 break; 10146 case Intrinsic::ppc_altivec_vcmpnezw: 10147 CompareOpc = 391; 10148 break; 10149 } 10150 else 10151 return false; 10152 break; 10153 case Intrinsic::ppc_altivec_vcmpgefp: 10154 CompareOpc = 454; 10155 break; 10156 case Intrinsic::ppc_altivec_vcmpgtfp: 10157 CompareOpc = 710; 10158 break; 10159 case Intrinsic::ppc_altivec_vcmpgtsb: 10160 CompareOpc = 774; 10161 break; 10162 case Intrinsic::ppc_altivec_vcmpgtsh: 10163 CompareOpc = 838; 10164 break; 10165 case Intrinsic::ppc_altivec_vcmpgtsw: 10166 CompareOpc = 902; 10167 break; 10168 case Intrinsic::ppc_altivec_vcmpgtsd: 10169 if (Subtarget.hasP8Altivec()) 10170 CompareOpc = 967; 10171 else 10172 return false; 10173 break; 10174 case Intrinsic::ppc_altivec_vcmpgtub: 10175 CompareOpc = 518; 10176 break; 10177 case Intrinsic::ppc_altivec_vcmpgtuh: 10178 CompareOpc = 582; 10179 break; 10180 case Intrinsic::ppc_altivec_vcmpgtuw: 10181 CompareOpc = 646; 10182 break; 10183 case Intrinsic::ppc_altivec_vcmpgtud: 10184 if (Subtarget.hasP8Altivec()) 10185 CompareOpc = 711; 10186 else 10187 return false; 10188 break; 10189 } 10190 return true; 10191 } 10192 10193 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10194 /// lower, do it, otherwise return null. 10195 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10196 SelectionDAG &DAG) const { 10197 unsigned IntrinsicID = 10198 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10199 10200 SDLoc dl(Op); 10201 10202 if (IntrinsicID == Intrinsic::thread_pointer) { 10203 // Reads the thread pointer register, used for __builtin_thread_pointer. 10204 if (Subtarget.isPPC64()) 10205 return DAG.getRegister(PPC::X13, MVT::i64); 10206 return DAG.getRegister(PPC::R2, MVT::i32); 10207 } 10208 10209 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10210 // opcode number of the comparison. 10211 int CompareOpc; 10212 bool isDot; 10213 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10214 return SDValue(); // Don't custom lower most intrinsics. 10215 10216 // If this is a non-dot comparison, make the VCMP node and we are done. 10217 if (!isDot) { 10218 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10219 Op.getOperand(1), Op.getOperand(2), 10220 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10221 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10222 } 10223 10224 // Create the PPCISD altivec 'dot' comparison node. 10225 SDValue Ops[] = { 10226 Op.getOperand(2), // LHS 10227 Op.getOperand(3), // RHS 10228 DAG.getConstant(CompareOpc, dl, MVT::i32) 10229 }; 10230 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10231 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10232 10233 // Now that we have the comparison, emit a copy from the CR to a GPR. 10234 // This is flagged to the above dot comparison. 10235 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10236 DAG.getRegister(PPC::CR6, MVT::i32), 10237 CompNode.getValue(1)); 10238 10239 // Unpack the result based on how the target uses it. 10240 unsigned BitNo; // Bit # of CR6. 10241 bool InvertBit; // Invert result? 10242 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10243 default: // Can't happen, don't crash on invalid number though. 10244 case 0: // Return the value of the EQ bit of CR6. 10245 BitNo = 0; InvertBit = false; 10246 break; 10247 case 1: // Return the inverted value of the EQ bit of CR6. 10248 BitNo = 0; InvertBit = true; 10249 break; 10250 case 2: // Return the value of the LT bit of CR6. 10251 BitNo = 2; InvertBit = false; 10252 break; 10253 case 3: // Return the inverted value of the LT bit of CR6. 10254 BitNo = 2; InvertBit = true; 10255 break; 10256 } 10257 10258 // Shift the bit into the low position. 10259 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10260 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10261 // Isolate the bit. 10262 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10263 DAG.getConstant(1, dl, MVT::i32)); 10264 10265 // If we are supposed to, toggle the bit. 10266 if (InvertBit) 10267 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10268 DAG.getConstant(1, dl, MVT::i32)); 10269 return Flags; 10270 } 10271 10272 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10273 SelectionDAG &DAG) const { 10274 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10275 // the beginning of the argument list. 10276 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10277 SDLoc DL(Op); 10278 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10279 case Intrinsic::ppc_cfence: { 10280 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10281 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10282 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10283 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10284 Op.getOperand(ArgStart + 1)), 10285 Op.getOperand(0)), 10286 0); 10287 } 10288 default: 10289 break; 10290 } 10291 return SDValue(); 10292 } 10293 10294 // Lower scalar BSWAP64 to xxbrd. 10295 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10296 SDLoc dl(Op); 10297 // MTVSRDD 10298 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10299 Op.getOperand(0)); 10300 // XXBRD 10301 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10302 // MFVSRD 10303 int VectorIndex = 0; 10304 if (Subtarget.isLittleEndian()) 10305 VectorIndex = 1; 10306 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10307 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10308 return Op; 10309 } 10310 10311 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10312 // compared to a value that is atomically loaded (atomic loads zero-extend). 10313 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10314 SelectionDAG &DAG) const { 10315 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10316 "Expecting an atomic compare-and-swap here."); 10317 SDLoc dl(Op); 10318 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10319 EVT MemVT = AtomicNode->getMemoryVT(); 10320 if (MemVT.getSizeInBits() >= 32) 10321 return Op; 10322 10323 SDValue CmpOp = Op.getOperand(2); 10324 // If this is already correctly zero-extended, leave it alone. 10325 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10326 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10327 return Op; 10328 10329 // Clear the high bits of the compare operand. 10330 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10331 SDValue NewCmpOp = 10332 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10333 DAG.getConstant(MaskVal, dl, MVT::i32)); 10334 10335 // Replace the existing compare operand with the properly zero-extended one. 10336 SmallVector<SDValue, 4> Ops; 10337 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10338 Ops.push_back(AtomicNode->getOperand(i)); 10339 Ops[2] = NewCmpOp; 10340 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10341 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10342 auto NodeTy = 10343 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10344 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10345 } 10346 10347 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10348 SelectionDAG &DAG) const { 10349 SDLoc dl(Op); 10350 // Create a stack slot that is 16-byte aligned. 10351 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10352 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10353 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10354 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10355 10356 // Store the input value into Value#0 of the stack slot. 10357 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10358 MachinePointerInfo()); 10359 // Load it out. 10360 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10361 } 10362 10363 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10364 SelectionDAG &DAG) const { 10365 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10366 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10367 10368 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10369 // We have legal lowering for constant indices but not for variable ones. 10370 if (!C) 10371 return SDValue(); 10372 10373 EVT VT = Op.getValueType(); 10374 SDLoc dl(Op); 10375 SDValue V1 = Op.getOperand(0); 10376 SDValue V2 = Op.getOperand(1); 10377 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10378 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10379 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10380 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10381 unsigned InsertAtElement = C->getZExtValue(); 10382 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10383 if (Subtarget.isLittleEndian()) { 10384 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10385 } 10386 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10387 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10388 } 10389 return Op; 10390 } 10391 10392 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10393 SDLoc dl(Op); 10394 if (Op.getValueType() == MVT::v4i32) { 10395 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10396 10397 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10398 // +16 as shift amt. 10399 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10400 SDValue RHSSwap = // = vrlw RHS, 16 10401 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10402 10403 // Shrinkify inputs to v8i16. 10404 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10405 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10406 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10407 10408 // Low parts multiplied together, generating 32-bit results (we ignore the 10409 // top parts). 10410 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10411 LHS, RHS, DAG, dl, MVT::v4i32); 10412 10413 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10414 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10415 // Shift the high parts up 16 bits. 10416 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10417 Neg16, DAG, dl); 10418 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10419 } else if (Op.getValueType() == MVT::v16i8) { 10420 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10421 bool isLittleEndian = Subtarget.isLittleEndian(); 10422 10423 // Multiply the even 8-bit parts, producing 16-bit sums. 10424 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10425 LHS, RHS, DAG, dl, MVT::v8i16); 10426 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10427 10428 // Multiply the odd 8-bit parts, producing 16-bit sums. 10429 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10430 LHS, RHS, DAG, dl, MVT::v8i16); 10431 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10432 10433 // Merge the results together. Because vmuleub and vmuloub are 10434 // instructions with a big-endian bias, we must reverse the 10435 // element numbering and reverse the meaning of "odd" and "even" 10436 // when generating little endian code. 10437 int Ops[16]; 10438 for (unsigned i = 0; i != 8; ++i) { 10439 if (isLittleEndian) { 10440 Ops[i*2 ] = 2*i; 10441 Ops[i*2+1] = 2*i+16; 10442 } else { 10443 Ops[i*2 ] = 2*i+1; 10444 Ops[i*2+1] = 2*i+1+16; 10445 } 10446 } 10447 if (isLittleEndian) 10448 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10449 else 10450 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10451 } else { 10452 llvm_unreachable("Unknown mul to lower!"); 10453 } 10454 } 10455 10456 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10457 10458 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10459 10460 EVT VT = Op.getValueType(); 10461 assert(VT.isVector() && 10462 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10463 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10464 VT == MVT::v16i8) && 10465 "Unexpected vector element type!"); 10466 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10467 "Current subtarget doesn't support smax v2i64!"); 10468 10469 // For vector abs, it can be lowered to: 10470 // abs x 10471 // ==> 10472 // y = -x 10473 // smax(x, y) 10474 10475 SDLoc dl(Op); 10476 SDValue X = Op.getOperand(0); 10477 SDValue Zero = DAG.getConstant(0, dl, VT); 10478 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10479 10480 // SMAX patch https://reviews.llvm.org/D47332 10481 // hasn't landed yet, so use intrinsic first here. 10482 // TODO: Should use SMAX directly once SMAX patch landed 10483 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10484 if (VT == MVT::v2i64) 10485 BifID = Intrinsic::ppc_altivec_vmaxsd; 10486 else if (VT == MVT::v8i16) 10487 BifID = Intrinsic::ppc_altivec_vmaxsh; 10488 else if (VT == MVT::v16i8) 10489 BifID = Intrinsic::ppc_altivec_vmaxsb; 10490 10491 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10492 } 10493 10494 // Custom lowering for fpext vf32 to v2f64 10495 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10496 10497 assert(Op.getOpcode() == ISD::FP_EXTEND && 10498 "Should only be called for ISD::FP_EXTEND"); 10499 10500 // FIXME: handle extends from half precision float vectors on P9. 10501 // We only want to custom lower an extend from v2f32 to v2f64. 10502 if (Op.getValueType() != MVT::v2f64 || 10503 Op.getOperand(0).getValueType() != MVT::v2f32) 10504 return SDValue(); 10505 10506 SDLoc dl(Op); 10507 SDValue Op0 = Op.getOperand(0); 10508 10509 switch (Op0.getOpcode()) { 10510 default: 10511 return SDValue(); 10512 case ISD::EXTRACT_SUBVECTOR: { 10513 assert(Op0.getNumOperands() == 2 && 10514 isa<ConstantSDNode>(Op0->getOperand(1)) && 10515 "Node should have 2 operands with second one being a constant!"); 10516 10517 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10518 return SDValue(); 10519 10520 // Custom lower is only done for high or low doubleword. 10521 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10522 if (Idx % 2 != 0) 10523 return SDValue(); 10524 10525 // Since input is v4f32, at this point Idx is either 0 or 2. 10526 // Shift to get the doubleword position we want. 10527 int DWord = Idx >> 1; 10528 10529 // High and low word positions are different on little endian. 10530 if (Subtarget.isLittleEndian()) 10531 DWord ^= 0x1; 10532 10533 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10534 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10535 } 10536 case ISD::FADD: 10537 case ISD::FMUL: 10538 case ISD::FSUB: { 10539 SDValue NewLoad[2]; 10540 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10541 // Ensure both input are loads. 10542 SDValue LdOp = Op0.getOperand(i); 10543 if (LdOp.getOpcode() != ISD::LOAD) 10544 return SDValue(); 10545 // Generate new load node. 10546 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10547 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10548 NewLoad[i] = DAG.getMemIntrinsicNode( 10549 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10550 LD->getMemoryVT(), LD->getMemOperand()); 10551 } 10552 SDValue NewOp = 10553 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10554 NewLoad[1], Op0.getNode()->getFlags()); 10555 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10556 DAG.getConstant(0, dl, MVT::i32)); 10557 } 10558 case ISD::LOAD: { 10559 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10560 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10561 SDValue NewLd = DAG.getMemIntrinsicNode( 10562 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10563 LD->getMemoryVT(), LD->getMemOperand()); 10564 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10565 DAG.getConstant(0, dl, MVT::i32)); 10566 } 10567 } 10568 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10569 } 10570 10571 /// LowerOperation - Provide custom lowering hooks for some operations. 10572 /// 10573 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10574 switch (Op.getOpcode()) { 10575 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10576 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10577 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10578 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10579 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10580 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10581 case ISD::SETCC: return LowerSETCC(Op, DAG); 10582 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10583 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10584 10585 // Variable argument lowering. 10586 case ISD::VASTART: return LowerVASTART(Op, DAG); 10587 case ISD::VAARG: return LowerVAARG(Op, DAG); 10588 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10589 10590 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10591 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10592 case ISD::GET_DYNAMIC_AREA_OFFSET: 10593 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10594 10595 // Exception handling lowering. 10596 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10597 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10598 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10599 10600 case ISD::LOAD: return LowerLOAD(Op, DAG); 10601 case ISD::STORE: return LowerSTORE(Op, DAG); 10602 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10603 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10604 case ISD::STRICT_FP_TO_UINT: 10605 case ISD::STRICT_FP_TO_SINT: 10606 case ISD::FP_TO_UINT: 10607 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10608 case ISD::STRICT_UINT_TO_FP: 10609 case ISD::STRICT_SINT_TO_FP: 10610 case ISD::UINT_TO_FP: 10611 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10612 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10613 10614 // Lower 64-bit shifts. 10615 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10616 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10617 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10618 10619 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10620 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10621 10622 // Vector-related lowering. 10623 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10624 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10625 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10626 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10627 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10628 case ISD::MUL: return LowerMUL(Op, DAG); 10629 case ISD::ABS: return LowerABS(Op, DAG); 10630 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10631 case ISD::ROTL: return LowerROTL(Op, DAG); 10632 10633 // For counter-based loop handling. 10634 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10635 10636 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10637 10638 // Frame & Return address. 10639 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10640 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10641 10642 case ISD::INTRINSIC_VOID: 10643 return LowerINTRINSIC_VOID(Op, DAG); 10644 case ISD::BSWAP: 10645 return LowerBSWAP(Op, DAG); 10646 case ISD::ATOMIC_CMP_SWAP: 10647 return LowerATOMIC_CMP_SWAP(Op, DAG); 10648 } 10649 } 10650 10651 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10652 SmallVectorImpl<SDValue>&Results, 10653 SelectionDAG &DAG) const { 10654 SDLoc dl(N); 10655 switch (N->getOpcode()) { 10656 default: 10657 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10658 case ISD::READCYCLECOUNTER: { 10659 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10660 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10661 10662 Results.push_back( 10663 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10664 Results.push_back(RTB.getValue(2)); 10665 break; 10666 } 10667 case ISD::INTRINSIC_W_CHAIN: { 10668 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10669 Intrinsic::loop_decrement) 10670 break; 10671 10672 assert(N->getValueType(0) == MVT::i1 && 10673 "Unexpected result type for CTR decrement intrinsic"); 10674 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10675 N->getValueType(0)); 10676 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10677 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10678 N->getOperand(1)); 10679 10680 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10681 Results.push_back(NewInt.getValue(1)); 10682 break; 10683 } 10684 case ISD::VAARG: { 10685 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10686 return; 10687 10688 EVT VT = N->getValueType(0); 10689 10690 if (VT == MVT::i64) { 10691 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10692 10693 Results.push_back(NewNode); 10694 Results.push_back(NewNode.getValue(1)); 10695 } 10696 return; 10697 } 10698 case ISD::STRICT_FP_TO_SINT: 10699 case ISD::STRICT_FP_TO_UINT: 10700 case ISD::FP_TO_SINT: 10701 case ISD::FP_TO_UINT: 10702 // LowerFP_TO_INT() can only handle f32 and f64. 10703 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10704 MVT::ppcf128) 10705 return; 10706 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10707 return; 10708 case ISD::TRUNCATE: { 10709 EVT TrgVT = N->getValueType(0); 10710 EVT OpVT = N->getOperand(0).getValueType(); 10711 if (TrgVT.isVector() && 10712 isOperationCustom(N->getOpcode(), TrgVT) && 10713 OpVT.getSizeInBits() <= 128 && 10714 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10715 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10716 return; 10717 } 10718 case ISD::BITCAST: 10719 // Don't handle bitcast here. 10720 return; 10721 case ISD::FP_EXTEND: 10722 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10723 if (Lowered) 10724 Results.push_back(Lowered); 10725 return; 10726 } 10727 } 10728 10729 //===----------------------------------------------------------------------===// 10730 // Other Lowering Code 10731 //===----------------------------------------------------------------------===// 10732 10733 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10734 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10735 Function *Func = Intrinsic::getDeclaration(M, Id); 10736 return Builder.CreateCall(Func, {}); 10737 } 10738 10739 // The mappings for emitLeading/TrailingFence is taken from 10740 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10741 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10742 Instruction *Inst, 10743 AtomicOrdering Ord) const { 10744 if (Ord == AtomicOrdering::SequentiallyConsistent) 10745 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10746 if (isReleaseOrStronger(Ord)) 10747 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10748 return nullptr; 10749 } 10750 10751 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10752 Instruction *Inst, 10753 AtomicOrdering Ord) const { 10754 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10755 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10756 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10757 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10758 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10759 return Builder.CreateCall( 10760 Intrinsic::getDeclaration( 10761 Builder.GetInsertBlock()->getParent()->getParent(), 10762 Intrinsic::ppc_cfence, {Inst->getType()}), 10763 {Inst}); 10764 // FIXME: Can use isync for rmw operation. 10765 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10766 } 10767 return nullptr; 10768 } 10769 10770 MachineBasicBlock * 10771 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10772 unsigned AtomicSize, 10773 unsigned BinOpcode, 10774 unsigned CmpOpcode, 10775 unsigned CmpPred) const { 10776 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10777 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10778 10779 auto LoadMnemonic = PPC::LDARX; 10780 auto StoreMnemonic = PPC::STDCX; 10781 switch (AtomicSize) { 10782 default: 10783 llvm_unreachable("Unexpected size of atomic entity"); 10784 case 1: 10785 LoadMnemonic = PPC::LBARX; 10786 StoreMnemonic = PPC::STBCX; 10787 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10788 break; 10789 case 2: 10790 LoadMnemonic = PPC::LHARX; 10791 StoreMnemonic = PPC::STHCX; 10792 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10793 break; 10794 case 4: 10795 LoadMnemonic = PPC::LWARX; 10796 StoreMnemonic = PPC::STWCX; 10797 break; 10798 case 8: 10799 LoadMnemonic = PPC::LDARX; 10800 StoreMnemonic = PPC::STDCX; 10801 break; 10802 } 10803 10804 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10805 MachineFunction *F = BB->getParent(); 10806 MachineFunction::iterator It = ++BB->getIterator(); 10807 10808 Register dest = MI.getOperand(0).getReg(); 10809 Register ptrA = MI.getOperand(1).getReg(); 10810 Register ptrB = MI.getOperand(2).getReg(); 10811 Register incr = MI.getOperand(3).getReg(); 10812 DebugLoc dl = MI.getDebugLoc(); 10813 10814 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10815 MachineBasicBlock *loop2MBB = 10816 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10817 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10818 F->insert(It, loopMBB); 10819 if (CmpOpcode) 10820 F->insert(It, loop2MBB); 10821 F->insert(It, exitMBB); 10822 exitMBB->splice(exitMBB->begin(), BB, 10823 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10824 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10825 10826 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10827 Register TmpReg = (!BinOpcode) ? incr : 10828 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10829 : &PPC::GPRCRegClass); 10830 10831 // thisMBB: 10832 // ... 10833 // fallthrough --> loopMBB 10834 BB->addSuccessor(loopMBB); 10835 10836 // loopMBB: 10837 // l[wd]arx dest, ptr 10838 // add r0, dest, incr 10839 // st[wd]cx. r0, ptr 10840 // bne- loopMBB 10841 // fallthrough --> exitMBB 10842 10843 // For max/min... 10844 // loopMBB: 10845 // l[wd]arx dest, ptr 10846 // cmpl?[wd] incr, dest 10847 // bgt exitMBB 10848 // loop2MBB: 10849 // st[wd]cx. dest, ptr 10850 // bne- loopMBB 10851 // fallthrough --> exitMBB 10852 10853 BB = loopMBB; 10854 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10855 .addReg(ptrA).addReg(ptrB); 10856 if (BinOpcode) 10857 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10858 if (CmpOpcode) { 10859 // Signed comparisons of byte or halfword values must be sign-extended. 10860 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10861 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10862 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10863 ExtReg).addReg(dest); 10864 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10865 .addReg(incr).addReg(ExtReg); 10866 } else 10867 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10868 .addReg(incr).addReg(dest); 10869 10870 BuildMI(BB, dl, TII->get(PPC::BCC)) 10871 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10872 BB->addSuccessor(loop2MBB); 10873 BB->addSuccessor(exitMBB); 10874 BB = loop2MBB; 10875 } 10876 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10877 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10878 BuildMI(BB, dl, TII->get(PPC::BCC)) 10879 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10880 BB->addSuccessor(loopMBB); 10881 BB->addSuccessor(exitMBB); 10882 10883 // exitMBB: 10884 // ... 10885 BB = exitMBB; 10886 return BB; 10887 } 10888 10889 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10890 MachineInstr &MI, MachineBasicBlock *BB, 10891 bool is8bit, // operation 10892 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10893 // If we support part-word atomic mnemonics, just use them 10894 if (Subtarget.hasPartwordAtomics()) 10895 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10896 CmpPred); 10897 10898 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10899 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10900 // In 64 bit mode we have to use 64 bits for addresses, even though the 10901 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10902 // registers without caring whether they're 32 or 64, but here we're 10903 // doing actual arithmetic on the addresses. 10904 bool is64bit = Subtarget.isPPC64(); 10905 bool isLittleEndian = Subtarget.isLittleEndian(); 10906 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10907 10908 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10909 MachineFunction *F = BB->getParent(); 10910 MachineFunction::iterator It = ++BB->getIterator(); 10911 10912 Register dest = MI.getOperand(0).getReg(); 10913 Register ptrA = MI.getOperand(1).getReg(); 10914 Register ptrB = MI.getOperand(2).getReg(); 10915 Register incr = MI.getOperand(3).getReg(); 10916 DebugLoc dl = MI.getDebugLoc(); 10917 10918 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10919 MachineBasicBlock *loop2MBB = 10920 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10921 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10922 F->insert(It, loopMBB); 10923 if (CmpOpcode) 10924 F->insert(It, loop2MBB); 10925 F->insert(It, exitMBB); 10926 exitMBB->splice(exitMBB->begin(), BB, 10927 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10928 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10929 10930 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10931 const TargetRegisterClass *RC = 10932 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10933 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10934 10935 Register PtrReg = RegInfo.createVirtualRegister(RC); 10936 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10937 Register ShiftReg = 10938 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10939 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10940 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10941 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10942 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10943 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10944 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10945 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10946 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10947 Register Ptr1Reg; 10948 Register TmpReg = 10949 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10950 10951 // thisMBB: 10952 // ... 10953 // fallthrough --> loopMBB 10954 BB->addSuccessor(loopMBB); 10955 10956 // The 4-byte load must be aligned, while a char or short may be 10957 // anywhere in the word. Hence all this nasty bookkeeping code. 10958 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10959 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10960 // xori shift, shift1, 24 [16] 10961 // rlwinm ptr, ptr1, 0, 0, 29 10962 // slw incr2, incr, shift 10963 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10964 // slw mask, mask2, shift 10965 // loopMBB: 10966 // lwarx tmpDest, ptr 10967 // add tmp, tmpDest, incr2 10968 // andc tmp2, tmpDest, mask 10969 // and tmp3, tmp, mask 10970 // or tmp4, tmp3, tmp2 10971 // stwcx. tmp4, ptr 10972 // bne- loopMBB 10973 // fallthrough --> exitMBB 10974 // srw dest, tmpDest, shift 10975 if (ptrA != ZeroReg) { 10976 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10977 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10978 .addReg(ptrA) 10979 .addReg(ptrB); 10980 } else { 10981 Ptr1Reg = ptrB; 10982 } 10983 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10984 // mode. 10985 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10986 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10987 .addImm(3) 10988 .addImm(27) 10989 .addImm(is8bit ? 28 : 27); 10990 if (!isLittleEndian) 10991 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10992 .addReg(Shift1Reg) 10993 .addImm(is8bit ? 24 : 16); 10994 if (is64bit) 10995 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10996 .addReg(Ptr1Reg) 10997 .addImm(0) 10998 .addImm(61); 10999 else 11000 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11001 .addReg(Ptr1Reg) 11002 .addImm(0) 11003 .addImm(0) 11004 .addImm(29); 11005 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11006 if (is8bit) 11007 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11008 else { 11009 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11010 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11011 .addReg(Mask3Reg) 11012 .addImm(65535); 11013 } 11014 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11015 .addReg(Mask2Reg) 11016 .addReg(ShiftReg); 11017 11018 BB = loopMBB; 11019 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11020 .addReg(ZeroReg) 11021 .addReg(PtrReg); 11022 if (BinOpcode) 11023 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11024 .addReg(Incr2Reg) 11025 .addReg(TmpDestReg); 11026 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11027 .addReg(TmpDestReg) 11028 .addReg(MaskReg); 11029 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11030 if (CmpOpcode) { 11031 // For unsigned comparisons, we can directly compare the shifted values. 11032 // For signed comparisons we shift and sign extend. 11033 Register SReg = RegInfo.createVirtualRegister(GPRC); 11034 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11035 .addReg(TmpDestReg) 11036 .addReg(MaskReg); 11037 unsigned ValueReg = SReg; 11038 unsigned CmpReg = Incr2Reg; 11039 if (CmpOpcode == PPC::CMPW) { 11040 ValueReg = RegInfo.createVirtualRegister(GPRC); 11041 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11042 .addReg(SReg) 11043 .addReg(ShiftReg); 11044 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11045 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11046 .addReg(ValueReg); 11047 ValueReg = ValueSReg; 11048 CmpReg = incr; 11049 } 11050 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11051 .addReg(CmpReg) 11052 .addReg(ValueReg); 11053 BuildMI(BB, dl, TII->get(PPC::BCC)) 11054 .addImm(CmpPred) 11055 .addReg(PPC::CR0) 11056 .addMBB(exitMBB); 11057 BB->addSuccessor(loop2MBB); 11058 BB->addSuccessor(exitMBB); 11059 BB = loop2MBB; 11060 } 11061 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11062 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11063 .addReg(Tmp4Reg) 11064 .addReg(ZeroReg) 11065 .addReg(PtrReg); 11066 BuildMI(BB, dl, TII->get(PPC::BCC)) 11067 .addImm(PPC::PRED_NE) 11068 .addReg(PPC::CR0) 11069 .addMBB(loopMBB); 11070 BB->addSuccessor(loopMBB); 11071 BB->addSuccessor(exitMBB); 11072 11073 // exitMBB: 11074 // ... 11075 BB = exitMBB; 11076 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11077 .addReg(TmpDestReg) 11078 .addReg(ShiftReg); 11079 return BB; 11080 } 11081 11082 llvm::MachineBasicBlock * 11083 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11084 MachineBasicBlock *MBB) const { 11085 DebugLoc DL = MI.getDebugLoc(); 11086 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11087 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11088 11089 MachineFunction *MF = MBB->getParent(); 11090 MachineRegisterInfo &MRI = MF->getRegInfo(); 11091 11092 const BasicBlock *BB = MBB->getBasicBlock(); 11093 MachineFunction::iterator I = ++MBB->getIterator(); 11094 11095 Register DstReg = MI.getOperand(0).getReg(); 11096 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11097 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11098 Register mainDstReg = MRI.createVirtualRegister(RC); 11099 Register restoreDstReg = MRI.createVirtualRegister(RC); 11100 11101 MVT PVT = getPointerTy(MF->getDataLayout()); 11102 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11103 "Invalid Pointer Size!"); 11104 // For v = setjmp(buf), we generate 11105 // 11106 // thisMBB: 11107 // SjLjSetup mainMBB 11108 // bl mainMBB 11109 // v_restore = 1 11110 // b sinkMBB 11111 // 11112 // mainMBB: 11113 // buf[LabelOffset] = LR 11114 // v_main = 0 11115 // 11116 // sinkMBB: 11117 // v = phi(main, restore) 11118 // 11119 11120 MachineBasicBlock *thisMBB = MBB; 11121 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11122 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11123 MF->insert(I, mainMBB); 11124 MF->insert(I, sinkMBB); 11125 11126 MachineInstrBuilder MIB; 11127 11128 // Transfer the remainder of BB and its successor edges to sinkMBB. 11129 sinkMBB->splice(sinkMBB->begin(), MBB, 11130 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11131 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11132 11133 // Note that the structure of the jmp_buf used here is not compatible 11134 // with that used by libc, and is not designed to be. Specifically, it 11135 // stores only those 'reserved' registers that LLVM does not otherwise 11136 // understand how to spill. Also, by convention, by the time this 11137 // intrinsic is called, Clang has already stored the frame address in the 11138 // first slot of the buffer and stack address in the third. Following the 11139 // X86 target code, we'll store the jump address in the second slot. We also 11140 // need to save the TOC pointer (R2) to handle jumps between shared 11141 // libraries, and that will be stored in the fourth slot. The thread 11142 // identifier (R13) is not affected. 11143 11144 // thisMBB: 11145 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11146 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11147 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11148 11149 // Prepare IP either in reg. 11150 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11151 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11152 Register BufReg = MI.getOperand(1).getReg(); 11153 11154 if (Subtarget.is64BitELFABI()) { 11155 setUsesTOCBasePtr(*MBB->getParent()); 11156 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11157 .addReg(PPC::X2) 11158 .addImm(TOCOffset) 11159 .addReg(BufReg) 11160 .cloneMemRefs(MI); 11161 } 11162 11163 // Naked functions never have a base pointer, and so we use r1. For all 11164 // other functions, this decision must be delayed until during PEI. 11165 unsigned BaseReg; 11166 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11167 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11168 else 11169 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11170 11171 MIB = BuildMI(*thisMBB, MI, DL, 11172 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11173 .addReg(BaseReg) 11174 .addImm(BPOffset) 11175 .addReg(BufReg) 11176 .cloneMemRefs(MI); 11177 11178 // Setup 11179 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11180 MIB.addRegMask(TRI->getNoPreservedMask()); 11181 11182 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11183 11184 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11185 .addMBB(mainMBB); 11186 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11187 11188 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11189 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11190 11191 // mainMBB: 11192 // mainDstReg = 0 11193 MIB = 11194 BuildMI(mainMBB, DL, 11195 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11196 11197 // Store IP 11198 if (Subtarget.isPPC64()) { 11199 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11200 .addReg(LabelReg) 11201 .addImm(LabelOffset) 11202 .addReg(BufReg); 11203 } else { 11204 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11205 .addReg(LabelReg) 11206 .addImm(LabelOffset) 11207 .addReg(BufReg); 11208 } 11209 MIB.cloneMemRefs(MI); 11210 11211 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11212 mainMBB->addSuccessor(sinkMBB); 11213 11214 // sinkMBB: 11215 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11216 TII->get(PPC::PHI), DstReg) 11217 .addReg(mainDstReg).addMBB(mainMBB) 11218 .addReg(restoreDstReg).addMBB(thisMBB); 11219 11220 MI.eraseFromParent(); 11221 return sinkMBB; 11222 } 11223 11224 MachineBasicBlock * 11225 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11226 MachineBasicBlock *MBB) const { 11227 DebugLoc DL = MI.getDebugLoc(); 11228 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11229 11230 MachineFunction *MF = MBB->getParent(); 11231 MachineRegisterInfo &MRI = MF->getRegInfo(); 11232 11233 MVT PVT = getPointerTy(MF->getDataLayout()); 11234 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11235 "Invalid Pointer Size!"); 11236 11237 const TargetRegisterClass *RC = 11238 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11239 Register Tmp = MRI.createVirtualRegister(RC); 11240 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11241 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11242 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11243 unsigned BP = 11244 (PVT == MVT::i64) 11245 ? PPC::X30 11246 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11247 : PPC::R30); 11248 11249 MachineInstrBuilder MIB; 11250 11251 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11252 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11253 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11254 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11255 11256 Register BufReg = MI.getOperand(0).getReg(); 11257 11258 // Reload FP (the jumped-to function may not have had a 11259 // frame pointer, and if so, then its r31 will be restored 11260 // as necessary). 11261 if (PVT == MVT::i64) { 11262 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11263 .addImm(0) 11264 .addReg(BufReg); 11265 } else { 11266 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11267 .addImm(0) 11268 .addReg(BufReg); 11269 } 11270 MIB.cloneMemRefs(MI); 11271 11272 // Reload IP 11273 if (PVT == MVT::i64) { 11274 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11275 .addImm(LabelOffset) 11276 .addReg(BufReg); 11277 } else { 11278 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11279 .addImm(LabelOffset) 11280 .addReg(BufReg); 11281 } 11282 MIB.cloneMemRefs(MI); 11283 11284 // Reload SP 11285 if (PVT == MVT::i64) { 11286 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11287 .addImm(SPOffset) 11288 .addReg(BufReg); 11289 } else { 11290 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11291 .addImm(SPOffset) 11292 .addReg(BufReg); 11293 } 11294 MIB.cloneMemRefs(MI); 11295 11296 // Reload BP 11297 if (PVT == MVT::i64) { 11298 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11299 .addImm(BPOffset) 11300 .addReg(BufReg); 11301 } else { 11302 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11303 .addImm(BPOffset) 11304 .addReg(BufReg); 11305 } 11306 MIB.cloneMemRefs(MI); 11307 11308 // Reload TOC 11309 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11310 setUsesTOCBasePtr(*MBB->getParent()); 11311 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11312 .addImm(TOCOffset) 11313 .addReg(BufReg) 11314 .cloneMemRefs(MI); 11315 } 11316 11317 // Jump 11318 BuildMI(*MBB, MI, DL, 11319 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11320 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11321 11322 MI.eraseFromParent(); 11323 return MBB; 11324 } 11325 11326 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11327 // If the function specifically requests inline stack probes, emit them. 11328 if (MF.getFunction().hasFnAttribute("probe-stack")) 11329 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11330 "inline-asm"; 11331 return false; 11332 } 11333 11334 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11335 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11336 unsigned StackAlign = TFI->getStackAlignment(); 11337 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11338 "Unexpected stack alignment"); 11339 // The default stack probe size is 4096 if the function has no 11340 // stack-probe-size attribute. 11341 unsigned StackProbeSize = 4096; 11342 const Function &Fn = MF.getFunction(); 11343 if (Fn.hasFnAttribute("stack-probe-size")) 11344 Fn.getFnAttribute("stack-probe-size") 11345 .getValueAsString() 11346 .getAsInteger(0, StackProbeSize); 11347 // Round down to the stack alignment. 11348 StackProbeSize &= ~(StackAlign - 1); 11349 return StackProbeSize ? StackProbeSize : StackAlign; 11350 } 11351 11352 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11353 // into three phases. In the first phase, it uses pseudo instruction 11354 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11355 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11356 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11357 // MaxCallFrameSize so that it can calculate correct data area pointer. 11358 MachineBasicBlock * 11359 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11360 MachineBasicBlock *MBB) const { 11361 const bool isPPC64 = Subtarget.isPPC64(); 11362 MachineFunction *MF = MBB->getParent(); 11363 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11364 DebugLoc DL = MI.getDebugLoc(); 11365 const unsigned ProbeSize = getStackProbeSize(*MF); 11366 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11367 MachineRegisterInfo &MRI = MF->getRegInfo(); 11368 // The CFG of probing stack looks as 11369 // +-----+ 11370 // | MBB | 11371 // +--+--+ 11372 // | 11373 // +----v----+ 11374 // +--->+ TestMBB +---+ 11375 // | +----+----+ | 11376 // | | | 11377 // | +-----v----+ | 11378 // +---+ BlockMBB | | 11379 // +----------+ | 11380 // | 11381 // +---------+ | 11382 // | TailMBB +<--+ 11383 // +---------+ 11384 // In MBB, calculate previous frame pointer and final stack pointer. 11385 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11386 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11387 // TailMBB is spliced via \p MI. 11388 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11389 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11390 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11391 11392 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11393 MF->insert(MBBIter, TestMBB); 11394 MF->insert(MBBIter, BlockMBB); 11395 MF->insert(MBBIter, TailMBB); 11396 11397 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11398 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11399 11400 Register DstReg = MI.getOperand(0).getReg(); 11401 Register NegSizeReg = MI.getOperand(1).getReg(); 11402 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11403 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11404 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11405 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11406 11407 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11408 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11409 // NegSize. 11410 unsigned ProbeOpc; 11411 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11412 ProbeOpc = 11413 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11414 else 11415 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11416 // and NegSizeReg will be allocated in the same phyreg to avoid 11417 // redundant copy when NegSizeReg has only one use which is current MI and 11418 // will be replaced by PREPARE_PROBED_ALLOCA then. 11419 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11420 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11421 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11422 .addDef(ActualNegSizeReg) 11423 .addReg(NegSizeReg) 11424 .add(MI.getOperand(2)) 11425 .add(MI.getOperand(3)); 11426 11427 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11428 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11429 FinalStackPtr) 11430 .addReg(SPReg) 11431 .addReg(ActualNegSizeReg); 11432 11433 // Materialize a scratch register for update. 11434 int64_t NegProbeSize = -(int64_t)ProbeSize; 11435 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11436 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11437 if (!isInt<16>(NegProbeSize)) { 11438 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11439 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11440 .addImm(NegProbeSize >> 16); 11441 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11442 ScratchReg) 11443 .addReg(TempReg) 11444 .addImm(NegProbeSize & 0xFFFF); 11445 } else 11446 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11447 .addImm(NegProbeSize); 11448 11449 { 11450 // Probing leading residual part. 11451 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11452 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11453 .addReg(ActualNegSizeReg) 11454 .addReg(ScratchReg); 11455 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11456 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11457 .addReg(Div) 11458 .addReg(ScratchReg); 11459 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11460 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11461 .addReg(Mul) 11462 .addReg(ActualNegSizeReg); 11463 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11464 .addReg(FramePointer) 11465 .addReg(SPReg) 11466 .addReg(NegMod); 11467 } 11468 11469 { 11470 // Remaining part should be multiple of ProbeSize. 11471 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11472 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11473 .addReg(SPReg) 11474 .addReg(FinalStackPtr); 11475 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11476 .addImm(PPC::PRED_EQ) 11477 .addReg(CmpResult) 11478 .addMBB(TailMBB); 11479 TestMBB->addSuccessor(BlockMBB); 11480 TestMBB->addSuccessor(TailMBB); 11481 } 11482 11483 { 11484 // Touch the block. 11485 // |P...|P...|P... 11486 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11487 .addReg(FramePointer) 11488 .addReg(SPReg) 11489 .addReg(ScratchReg); 11490 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11491 BlockMBB->addSuccessor(TestMBB); 11492 } 11493 11494 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11495 // DYNAREAOFFSET pseudo instruction to get the future result. 11496 Register MaxCallFrameSizeReg = 11497 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11498 BuildMI(TailMBB, DL, 11499 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11500 MaxCallFrameSizeReg) 11501 .add(MI.getOperand(2)) 11502 .add(MI.getOperand(3)); 11503 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11504 .addReg(SPReg) 11505 .addReg(MaxCallFrameSizeReg); 11506 11507 // Splice instructions after MI to TailMBB. 11508 TailMBB->splice(TailMBB->end(), MBB, 11509 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11510 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11511 MBB->addSuccessor(TestMBB); 11512 11513 // Delete the pseudo instruction. 11514 MI.eraseFromParent(); 11515 11516 ++NumDynamicAllocaProbed; 11517 return TailMBB; 11518 } 11519 11520 MachineBasicBlock * 11521 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11522 MachineBasicBlock *BB) const { 11523 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11524 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11525 if (Subtarget.is64BitELFABI() && 11526 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11527 !Subtarget.isUsingPCRelativeCalls()) { 11528 // Call lowering should have added an r2 operand to indicate a dependence 11529 // on the TOC base pointer value. It can't however, because there is no 11530 // way to mark the dependence as implicit there, and so the stackmap code 11531 // will confuse it with a regular operand. Instead, add the dependence 11532 // here. 11533 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11534 } 11535 11536 return emitPatchPoint(MI, BB); 11537 } 11538 11539 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11540 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11541 return emitEHSjLjSetJmp(MI, BB); 11542 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11543 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11544 return emitEHSjLjLongJmp(MI, BB); 11545 } 11546 11547 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11548 11549 // To "insert" these instructions we actually have to insert their 11550 // control-flow patterns. 11551 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11552 MachineFunction::iterator It = ++BB->getIterator(); 11553 11554 MachineFunction *F = BB->getParent(); 11555 11556 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11557 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11558 MI.getOpcode() == PPC::SELECT_I8) { 11559 SmallVector<MachineOperand, 2> Cond; 11560 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11561 MI.getOpcode() == PPC::SELECT_CC_I8) 11562 Cond.push_back(MI.getOperand(4)); 11563 else 11564 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11565 Cond.push_back(MI.getOperand(1)); 11566 11567 DebugLoc dl = MI.getDebugLoc(); 11568 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11569 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11570 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11571 MI.getOpcode() == PPC::SELECT_CC_F8 || 11572 MI.getOpcode() == PPC::SELECT_CC_F16 || 11573 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11574 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11575 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11576 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11577 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11578 MI.getOpcode() == PPC::SELECT_CC_SPE || 11579 MI.getOpcode() == PPC::SELECT_F4 || 11580 MI.getOpcode() == PPC::SELECT_F8 || 11581 MI.getOpcode() == PPC::SELECT_F16 || 11582 MI.getOpcode() == PPC::SELECT_SPE || 11583 MI.getOpcode() == PPC::SELECT_SPE4 || 11584 MI.getOpcode() == PPC::SELECT_VRRC || 11585 MI.getOpcode() == PPC::SELECT_VSFRC || 11586 MI.getOpcode() == PPC::SELECT_VSSRC || 11587 MI.getOpcode() == PPC::SELECT_VSRC) { 11588 // The incoming instruction knows the destination vreg to set, the 11589 // condition code register to branch on, the true/false values to 11590 // select between, and a branch opcode to use. 11591 11592 // thisMBB: 11593 // ... 11594 // TrueVal = ... 11595 // cmpTY ccX, r1, r2 11596 // bCC copy1MBB 11597 // fallthrough --> copy0MBB 11598 MachineBasicBlock *thisMBB = BB; 11599 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11600 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11601 DebugLoc dl = MI.getDebugLoc(); 11602 F->insert(It, copy0MBB); 11603 F->insert(It, sinkMBB); 11604 11605 // Transfer the remainder of BB and its successor edges to sinkMBB. 11606 sinkMBB->splice(sinkMBB->begin(), BB, 11607 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11608 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11609 11610 // Next, add the true and fallthrough blocks as its successors. 11611 BB->addSuccessor(copy0MBB); 11612 BB->addSuccessor(sinkMBB); 11613 11614 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11615 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11616 MI.getOpcode() == PPC::SELECT_F16 || 11617 MI.getOpcode() == PPC::SELECT_SPE4 || 11618 MI.getOpcode() == PPC::SELECT_SPE || 11619 MI.getOpcode() == PPC::SELECT_VRRC || 11620 MI.getOpcode() == PPC::SELECT_VSFRC || 11621 MI.getOpcode() == PPC::SELECT_VSSRC || 11622 MI.getOpcode() == PPC::SELECT_VSRC) { 11623 BuildMI(BB, dl, TII->get(PPC::BC)) 11624 .addReg(MI.getOperand(1).getReg()) 11625 .addMBB(sinkMBB); 11626 } else { 11627 unsigned SelectPred = MI.getOperand(4).getImm(); 11628 BuildMI(BB, dl, TII->get(PPC::BCC)) 11629 .addImm(SelectPred) 11630 .addReg(MI.getOperand(1).getReg()) 11631 .addMBB(sinkMBB); 11632 } 11633 11634 // copy0MBB: 11635 // %FalseValue = ... 11636 // # fallthrough to sinkMBB 11637 BB = copy0MBB; 11638 11639 // Update machine-CFG edges 11640 BB->addSuccessor(sinkMBB); 11641 11642 // sinkMBB: 11643 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11644 // ... 11645 BB = sinkMBB; 11646 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11647 .addReg(MI.getOperand(3).getReg()) 11648 .addMBB(copy0MBB) 11649 .addReg(MI.getOperand(2).getReg()) 11650 .addMBB(thisMBB); 11651 } else if (MI.getOpcode() == PPC::ReadTB) { 11652 // To read the 64-bit time-base register on a 32-bit target, we read the 11653 // two halves. Should the counter have wrapped while it was being read, we 11654 // need to try again. 11655 // ... 11656 // readLoop: 11657 // mfspr Rx,TBU # load from TBU 11658 // mfspr Ry,TB # load from TB 11659 // mfspr Rz,TBU # load from TBU 11660 // cmpw crX,Rx,Rz # check if 'old'='new' 11661 // bne readLoop # branch if they're not equal 11662 // ... 11663 11664 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11665 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11666 DebugLoc dl = MI.getDebugLoc(); 11667 F->insert(It, readMBB); 11668 F->insert(It, sinkMBB); 11669 11670 // Transfer the remainder of BB and its successor edges to sinkMBB. 11671 sinkMBB->splice(sinkMBB->begin(), BB, 11672 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11673 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11674 11675 BB->addSuccessor(readMBB); 11676 BB = readMBB; 11677 11678 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11679 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11680 Register LoReg = MI.getOperand(0).getReg(); 11681 Register HiReg = MI.getOperand(1).getReg(); 11682 11683 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11684 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11685 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11686 11687 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11688 11689 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11690 .addReg(HiReg) 11691 .addReg(ReadAgainReg); 11692 BuildMI(BB, dl, TII->get(PPC::BCC)) 11693 .addImm(PPC::PRED_NE) 11694 .addReg(CmpReg) 11695 .addMBB(readMBB); 11696 11697 BB->addSuccessor(readMBB); 11698 BB->addSuccessor(sinkMBB); 11699 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11700 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11701 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11702 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11703 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11704 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11705 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11706 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11707 11708 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11709 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11710 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11711 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11712 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11713 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11714 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11715 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11716 11717 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11718 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11719 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11720 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11721 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11722 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11723 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11724 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11725 11726 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11727 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11728 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11729 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11730 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11731 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11732 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11733 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11734 11735 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11736 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11737 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11738 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11739 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11740 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11741 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11742 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11743 11744 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11745 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11746 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11747 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11748 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11749 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11750 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11751 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11752 11753 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11754 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11755 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11756 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11757 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11758 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11759 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11760 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11761 11762 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11763 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11764 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11765 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11766 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11767 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11768 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11769 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11770 11771 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11772 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11773 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11774 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11775 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11776 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11777 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11778 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11779 11780 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11781 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11782 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11783 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11784 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11785 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11787 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11788 11789 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11790 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11791 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11792 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11793 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11794 BB = EmitAtomicBinary(MI, BB, 4, 0); 11795 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11796 BB = EmitAtomicBinary(MI, BB, 8, 0); 11797 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11798 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11799 (Subtarget.hasPartwordAtomics() && 11800 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11801 (Subtarget.hasPartwordAtomics() && 11802 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11803 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11804 11805 auto LoadMnemonic = PPC::LDARX; 11806 auto StoreMnemonic = PPC::STDCX; 11807 switch (MI.getOpcode()) { 11808 default: 11809 llvm_unreachable("Compare and swap of unknown size"); 11810 case PPC::ATOMIC_CMP_SWAP_I8: 11811 LoadMnemonic = PPC::LBARX; 11812 StoreMnemonic = PPC::STBCX; 11813 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11814 break; 11815 case PPC::ATOMIC_CMP_SWAP_I16: 11816 LoadMnemonic = PPC::LHARX; 11817 StoreMnemonic = PPC::STHCX; 11818 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11819 break; 11820 case PPC::ATOMIC_CMP_SWAP_I32: 11821 LoadMnemonic = PPC::LWARX; 11822 StoreMnemonic = PPC::STWCX; 11823 break; 11824 case PPC::ATOMIC_CMP_SWAP_I64: 11825 LoadMnemonic = PPC::LDARX; 11826 StoreMnemonic = PPC::STDCX; 11827 break; 11828 } 11829 Register dest = MI.getOperand(0).getReg(); 11830 Register ptrA = MI.getOperand(1).getReg(); 11831 Register ptrB = MI.getOperand(2).getReg(); 11832 Register oldval = MI.getOperand(3).getReg(); 11833 Register newval = MI.getOperand(4).getReg(); 11834 DebugLoc dl = MI.getDebugLoc(); 11835 11836 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11837 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11838 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11839 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11840 F->insert(It, loop1MBB); 11841 F->insert(It, loop2MBB); 11842 F->insert(It, midMBB); 11843 F->insert(It, exitMBB); 11844 exitMBB->splice(exitMBB->begin(), BB, 11845 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11846 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11847 11848 // thisMBB: 11849 // ... 11850 // fallthrough --> loopMBB 11851 BB->addSuccessor(loop1MBB); 11852 11853 // loop1MBB: 11854 // l[bhwd]arx dest, ptr 11855 // cmp[wd] dest, oldval 11856 // bne- midMBB 11857 // loop2MBB: 11858 // st[bhwd]cx. newval, ptr 11859 // bne- loopMBB 11860 // b exitBB 11861 // midMBB: 11862 // st[bhwd]cx. dest, ptr 11863 // exitBB: 11864 BB = loop1MBB; 11865 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11866 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11867 .addReg(oldval) 11868 .addReg(dest); 11869 BuildMI(BB, dl, TII->get(PPC::BCC)) 11870 .addImm(PPC::PRED_NE) 11871 .addReg(PPC::CR0) 11872 .addMBB(midMBB); 11873 BB->addSuccessor(loop2MBB); 11874 BB->addSuccessor(midMBB); 11875 11876 BB = loop2MBB; 11877 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11878 .addReg(newval) 11879 .addReg(ptrA) 11880 .addReg(ptrB); 11881 BuildMI(BB, dl, TII->get(PPC::BCC)) 11882 .addImm(PPC::PRED_NE) 11883 .addReg(PPC::CR0) 11884 .addMBB(loop1MBB); 11885 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11886 BB->addSuccessor(loop1MBB); 11887 BB->addSuccessor(exitMBB); 11888 11889 BB = midMBB; 11890 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11891 .addReg(dest) 11892 .addReg(ptrA) 11893 .addReg(ptrB); 11894 BB->addSuccessor(exitMBB); 11895 11896 // exitMBB: 11897 // ... 11898 BB = exitMBB; 11899 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11900 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11901 // We must use 64-bit registers for addresses when targeting 64-bit, 11902 // since we're actually doing arithmetic on them. Other registers 11903 // can be 32-bit. 11904 bool is64bit = Subtarget.isPPC64(); 11905 bool isLittleEndian = Subtarget.isLittleEndian(); 11906 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11907 11908 Register dest = MI.getOperand(0).getReg(); 11909 Register ptrA = MI.getOperand(1).getReg(); 11910 Register ptrB = MI.getOperand(2).getReg(); 11911 Register oldval = MI.getOperand(3).getReg(); 11912 Register newval = MI.getOperand(4).getReg(); 11913 DebugLoc dl = MI.getDebugLoc(); 11914 11915 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11916 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11917 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11918 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11919 F->insert(It, loop1MBB); 11920 F->insert(It, loop2MBB); 11921 F->insert(It, midMBB); 11922 F->insert(It, exitMBB); 11923 exitMBB->splice(exitMBB->begin(), BB, 11924 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11925 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11926 11927 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11928 const TargetRegisterClass *RC = 11929 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11930 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11931 11932 Register PtrReg = RegInfo.createVirtualRegister(RC); 11933 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11934 Register ShiftReg = 11935 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11936 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11937 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11938 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11939 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11940 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11941 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11942 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11943 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11944 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11945 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11946 Register Ptr1Reg; 11947 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11948 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11949 // thisMBB: 11950 // ... 11951 // fallthrough --> loopMBB 11952 BB->addSuccessor(loop1MBB); 11953 11954 // The 4-byte load must be aligned, while a char or short may be 11955 // anywhere in the word. Hence all this nasty bookkeeping code. 11956 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11957 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11958 // xori shift, shift1, 24 [16] 11959 // rlwinm ptr, ptr1, 0, 0, 29 11960 // slw newval2, newval, shift 11961 // slw oldval2, oldval,shift 11962 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11963 // slw mask, mask2, shift 11964 // and newval3, newval2, mask 11965 // and oldval3, oldval2, mask 11966 // loop1MBB: 11967 // lwarx tmpDest, ptr 11968 // and tmp, tmpDest, mask 11969 // cmpw tmp, oldval3 11970 // bne- midMBB 11971 // loop2MBB: 11972 // andc tmp2, tmpDest, mask 11973 // or tmp4, tmp2, newval3 11974 // stwcx. tmp4, ptr 11975 // bne- loop1MBB 11976 // b exitBB 11977 // midMBB: 11978 // stwcx. tmpDest, ptr 11979 // exitBB: 11980 // srw dest, tmpDest, shift 11981 if (ptrA != ZeroReg) { 11982 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11983 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11984 .addReg(ptrA) 11985 .addReg(ptrB); 11986 } else { 11987 Ptr1Reg = ptrB; 11988 } 11989 11990 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11991 // mode. 11992 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11993 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11994 .addImm(3) 11995 .addImm(27) 11996 .addImm(is8bit ? 28 : 27); 11997 if (!isLittleEndian) 11998 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11999 .addReg(Shift1Reg) 12000 .addImm(is8bit ? 24 : 16); 12001 if (is64bit) 12002 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12003 .addReg(Ptr1Reg) 12004 .addImm(0) 12005 .addImm(61); 12006 else 12007 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12008 .addReg(Ptr1Reg) 12009 .addImm(0) 12010 .addImm(0) 12011 .addImm(29); 12012 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12013 .addReg(newval) 12014 .addReg(ShiftReg); 12015 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12016 .addReg(oldval) 12017 .addReg(ShiftReg); 12018 if (is8bit) 12019 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12020 else { 12021 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12022 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12023 .addReg(Mask3Reg) 12024 .addImm(65535); 12025 } 12026 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12027 .addReg(Mask2Reg) 12028 .addReg(ShiftReg); 12029 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12030 .addReg(NewVal2Reg) 12031 .addReg(MaskReg); 12032 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12033 .addReg(OldVal2Reg) 12034 .addReg(MaskReg); 12035 12036 BB = loop1MBB; 12037 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12038 .addReg(ZeroReg) 12039 .addReg(PtrReg); 12040 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12041 .addReg(TmpDestReg) 12042 .addReg(MaskReg); 12043 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12044 .addReg(TmpReg) 12045 .addReg(OldVal3Reg); 12046 BuildMI(BB, dl, TII->get(PPC::BCC)) 12047 .addImm(PPC::PRED_NE) 12048 .addReg(PPC::CR0) 12049 .addMBB(midMBB); 12050 BB->addSuccessor(loop2MBB); 12051 BB->addSuccessor(midMBB); 12052 12053 BB = loop2MBB; 12054 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12055 .addReg(TmpDestReg) 12056 .addReg(MaskReg); 12057 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12058 .addReg(Tmp2Reg) 12059 .addReg(NewVal3Reg); 12060 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12061 .addReg(Tmp4Reg) 12062 .addReg(ZeroReg) 12063 .addReg(PtrReg); 12064 BuildMI(BB, dl, TII->get(PPC::BCC)) 12065 .addImm(PPC::PRED_NE) 12066 .addReg(PPC::CR0) 12067 .addMBB(loop1MBB); 12068 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12069 BB->addSuccessor(loop1MBB); 12070 BB->addSuccessor(exitMBB); 12071 12072 BB = midMBB; 12073 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12074 .addReg(TmpDestReg) 12075 .addReg(ZeroReg) 12076 .addReg(PtrReg); 12077 BB->addSuccessor(exitMBB); 12078 12079 // exitMBB: 12080 // ... 12081 BB = exitMBB; 12082 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12083 .addReg(TmpReg) 12084 .addReg(ShiftReg); 12085 } else if (MI.getOpcode() == PPC::FADDrtz) { 12086 // This pseudo performs an FADD with rounding mode temporarily forced 12087 // to round-to-zero. We emit this via custom inserter since the FPSCR 12088 // is not modeled at the SelectionDAG level. 12089 Register Dest = MI.getOperand(0).getReg(); 12090 Register Src1 = MI.getOperand(1).getReg(); 12091 Register Src2 = MI.getOperand(2).getReg(); 12092 DebugLoc dl = MI.getDebugLoc(); 12093 12094 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12095 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12096 12097 // Save FPSCR value. 12098 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12099 12100 // Set rounding mode to round-to-zero. 12101 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12102 .addImm(31) 12103 .addReg(PPC::RM, RegState::ImplicitDefine); 12104 12105 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12106 .addImm(30) 12107 .addReg(PPC::RM, RegState::ImplicitDefine); 12108 12109 // Perform addition. 12110 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12111 12112 // Restore FPSCR value. 12113 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12114 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12115 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12116 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12117 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12118 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12119 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12120 ? PPC::ANDI8_rec 12121 : PPC::ANDI_rec; 12122 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12123 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12124 12125 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12126 Register Dest = RegInfo.createVirtualRegister( 12127 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12128 12129 DebugLoc Dl = MI.getDebugLoc(); 12130 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12131 .addReg(MI.getOperand(1).getReg()) 12132 .addImm(1); 12133 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12134 MI.getOperand(0).getReg()) 12135 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12136 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12137 DebugLoc Dl = MI.getDebugLoc(); 12138 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12139 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12140 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12141 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12142 MI.getOperand(0).getReg()) 12143 .addReg(CRReg); 12144 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12145 DebugLoc Dl = MI.getDebugLoc(); 12146 unsigned Imm = MI.getOperand(1).getImm(); 12147 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12148 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12149 MI.getOperand(0).getReg()) 12150 .addReg(PPC::CR0EQ); 12151 } else if (MI.getOpcode() == PPC::SETRNDi) { 12152 DebugLoc dl = MI.getDebugLoc(); 12153 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12154 12155 // Save FPSCR value. 12156 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12157 12158 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12159 // the following settings: 12160 // 00 Round to nearest 12161 // 01 Round to 0 12162 // 10 Round to +inf 12163 // 11 Round to -inf 12164 12165 // When the operand is immediate, using the two least significant bits of 12166 // the immediate to set the bits 62:63 of FPSCR. 12167 unsigned Mode = MI.getOperand(1).getImm(); 12168 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12169 .addImm(31) 12170 .addReg(PPC::RM, RegState::ImplicitDefine); 12171 12172 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12173 .addImm(30) 12174 .addReg(PPC::RM, RegState::ImplicitDefine); 12175 } else if (MI.getOpcode() == PPC::SETRND) { 12176 DebugLoc dl = MI.getDebugLoc(); 12177 12178 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12179 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12180 // If the target doesn't have DirectMove, we should use stack to do the 12181 // conversion, because the target doesn't have the instructions like mtvsrd 12182 // or mfvsrd to do this conversion directly. 12183 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12184 if (Subtarget.hasDirectMove()) { 12185 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12186 .addReg(SrcReg); 12187 } else { 12188 // Use stack to do the register copy. 12189 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12190 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12191 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12192 if (RC == &PPC::F8RCRegClass) { 12193 // Copy register from F8RCRegClass to G8RCRegclass. 12194 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12195 "Unsupported RegClass."); 12196 12197 StoreOp = PPC::STFD; 12198 LoadOp = PPC::LD; 12199 } else { 12200 // Copy register from G8RCRegClass to F8RCRegclass. 12201 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12202 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12203 "Unsupported RegClass."); 12204 } 12205 12206 MachineFrameInfo &MFI = F->getFrameInfo(); 12207 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12208 12209 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12210 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12211 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12212 MFI.getObjectAlign(FrameIdx)); 12213 12214 // Store the SrcReg into the stack. 12215 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12216 .addReg(SrcReg) 12217 .addImm(0) 12218 .addFrameIndex(FrameIdx) 12219 .addMemOperand(MMOStore); 12220 12221 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12222 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12223 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12224 MFI.getObjectAlign(FrameIdx)); 12225 12226 // Load from the stack where SrcReg is stored, and save to DestReg, 12227 // so we have done the RegClass conversion from RegClass::SrcReg to 12228 // RegClass::DestReg. 12229 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12230 .addImm(0) 12231 .addFrameIndex(FrameIdx) 12232 .addMemOperand(MMOLoad); 12233 } 12234 }; 12235 12236 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12237 12238 // Save FPSCR value. 12239 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12240 12241 // When the operand is gprc register, use two least significant bits of the 12242 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12243 // 12244 // copy OldFPSCRTmpReg, OldFPSCRReg 12245 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12246 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12247 // copy NewFPSCRReg, NewFPSCRTmpReg 12248 // mtfsf 255, NewFPSCRReg 12249 MachineOperand SrcOp = MI.getOperand(1); 12250 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12251 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12252 12253 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12254 12255 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12256 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12257 12258 // The first operand of INSERT_SUBREG should be a register which has 12259 // subregisters, we only care about its RegClass, so we should use an 12260 // IMPLICIT_DEF register. 12261 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12262 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12263 .addReg(ImDefReg) 12264 .add(SrcOp) 12265 .addImm(1); 12266 12267 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12268 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12269 .addReg(OldFPSCRTmpReg) 12270 .addReg(ExtSrcReg) 12271 .addImm(0) 12272 .addImm(62); 12273 12274 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12275 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12276 12277 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12278 // bits of FPSCR. 12279 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12280 .addImm(255) 12281 .addReg(NewFPSCRReg) 12282 .addImm(0) 12283 .addImm(0); 12284 } else if (MI.getOpcode() == PPC::SETFLM) { 12285 DebugLoc Dl = MI.getDebugLoc(); 12286 12287 // Result of setflm is previous FPSCR content, so we need to save it first. 12288 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12289 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12290 12291 // Put bits in 32:63 to FPSCR. 12292 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12293 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12294 .addImm(255) 12295 .addReg(NewFPSCRReg) 12296 .addImm(0) 12297 .addImm(0); 12298 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12299 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12300 return emitProbedAlloca(MI, BB); 12301 } else { 12302 llvm_unreachable("Unexpected instr type to insert"); 12303 } 12304 12305 MI.eraseFromParent(); // The pseudo instruction is gone now. 12306 return BB; 12307 } 12308 12309 //===----------------------------------------------------------------------===// 12310 // Target Optimization Hooks 12311 //===----------------------------------------------------------------------===// 12312 12313 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12314 // For the estimates, convergence is quadratic, so we essentially double the 12315 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12316 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12317 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12318 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12319 if (VT.getScalarType() == MVT::f64) 12320 RefinementSteps++; 12321 return RefinementSteps; 12322 } 12323 12324 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12325 int Enabled, int &RefinementSteps, 12326 bool &UseOneConstNR, 12327 bool Reciprocal) const { 12328 EVT VT = Operand.getValueType(); 12329 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12330 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12331 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12332 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12333 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12334 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12335 12336 // The Newton-Raphson computation with a single constant does not provide 12337 // enough accuracy on some CPUs. 12338 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12339 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12340 } 12341 return SDValue(); 12342 } 12343 12344 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12345 int Enabled, 12346 int &RefinementSteps) const { 12347 EVT VT = Operand.getValueType(); 12348 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12349 (VT == MVT::f64 && Subtarget.hasFRE()) || 12350 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12351 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12352 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12353 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12354 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12355 } 12356 return SDValue(); 12357 } 12358 12359 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12360 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12361 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12362 // enabled for division), this functionality is redundant with the default 12363 // combiner logic (once the division -> reciprocal/multiply transformation 12364 // has taken place). As a result, this matters more for older cores than for 12365 // newer ones. 12366 12367 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12368 // reciprocal if there are two or more FDIVs (for embedded cores with only 12369 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12370 switch (Subtarget.getCPUDirective()) { 12371 default: 12372 return 3; 12373 case PPC::DIR_440: 12374 case PPC::DIR_A2: 12375 case PPC::DIR_E500: 12376 case PPC::DIR_E500mc: 12377 case PPC::DIR_E5500: 12378 return 2; 12379 } 12380 } 12381 12382 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12383 // collapsed, and so we need to look through chains of them. 12384 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12385 int64_t& Offset, SelectionDAG &DAG) { 12386 if (DAG.isBaseWithConstantOffset(Loc)) { 12387 Base = Loc.getOperand(0); 12388 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12389 12390 // The base might itself be a base plus an offset, and if so, accumulate 12391 // that as well. 12392 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12393 } 12394 } 12395 12396 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12397 unsigned Bytes, int Dist, 12398 SelectionDAG &DAG) { 12399 if (VT.getSizeInBits() / 8 != Bytes) 12400 return false; 12401 12402 SDValue BaseLoc = Base->getBasePtr(); 12403 if (Loc.getOpcode() == ISD::FrameIndex) { 12404 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12405 return false; 12406 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12407 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12408 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12409 int FS = MFI.getObjectSize(FI); 12410 int BFS = MFI.getObjectSize(BFI); 12411 if (FS != BFS || FS != (int)Bytes) return false; 12412 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12413 } 12414 12415 SDValue Base1 = Loc, Base2 = BaseLoc; 12416 int64_t Offset1 = 0, Offset2 = 0; 12417 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12418 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12419 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12420 return true; 12421 12422 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12423 const GlobalValue *GV1 = nullptr; 12424 const GlobalValue *GV2 = nullptr; 12425 Offset1 = 0; 12426 Offset2 = 0; 12427 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12428 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12429 if (isGA1 && isGA2 && GV1 == GV2) 12430 return Offset1 == (Offset2 + Dist*Bytes); 12431 return false; 12432 } 12433 12434 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12435 // not enforce equality of the chain operands. 12436 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12437 unsigned Bytes, int Dist, 12438 SelectionDAG &DAG) { 12439 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12440 EVT VT = LS->getMemoryVT(); 12441 SDValue Loc = LS->getBasePtr(); 12442 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12443 } 12444 12445 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12446 EVT VT; 12447 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12448 default: return false; 12449 case Intrinsic::ppc_altivec_lvx: 12450 case Intrinsic::ppc_altivec_lvxl: 12451 case Intrinsic::ppc_vsx_lxvw4x: 12452 case Intrinsic::ppc_vsx_lxvw4x_be: 12453 VT = MVT::v4i32; 12454 break; 12455 case Intrinsic::ppc_vsx_lxvd2x: 12456 case Intrinsic::ppc_vsx_lxvd2x_be: 12457 VT = MVT::v2f64; 12458 break; 12459 case Intrinsic::ppc_altivec_lvebx: 12460 VT = MVT::i8; 12461 break; 12462 case Intrinsic::ppc_altivec_lvehx: 12463 VT = MVT::i16; 12464 break; 12465 case Intrinsic::ppc_altivec_lvewx: 12466 VT = MVT::i32; 12467 break; 12468 } 12469 12470 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12471 } 12472 12473 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12474 EVT VT; 12475 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12476 default: return false; 12477 case Intrinsic::ppc_altivec_stvx: 12478 case Intrinsic::ppc_altivec_stvxl: 12479 case Intrinsic::ppc_vsx_stxvw4x: 12480 VT = MVT::v4i32; 12481 break; 12482 case Intrinsic::ppc_vsx_stxvd2x: 12483 VT = MVT::v2f64; 12484 break; 12485 case Intrinsic::ppc_vsx_stxvw4x_be: 12486 VT = MVT::v4i32; 12487 break; 12488 case Intrinsic::ppc_vsx_stxvd2x_be: 12489 VT = MVT::v2f64; 12490 break; 12491 case Intrinsic::ppc_altivec_stvebx: 12492 VT = MVT::i8; 12493 break; 12494 case Intrinsic::ppc_altivec_stvehx: 12495 VT = MVT::i16; 12496 break; 12497 case Intrinsic::ppc_altivec_stvewx: 12498 VT = MVT::i32; 12499 break; 12500 } 12501 12502 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12503 } 12504 12505 return false; 12506 } 12507 12508 // Return true is there is a nearyby consecutive load to the one provided 12509 // (regardless of alignment). We search up and down the chain, looking though 12510 // token factors and other loads (but nothing else). As a result, a true result 12511 // indicates that it is safe to create a new consecutive load adjacent to the 12512 // load provided. 12513 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12514 SDValue Chain = LD->getChain(); 12515 EVT VT = LD->getMemoryVT(); 12516 12517 SmallSet<SDNode *, 16> LoadRoots; 12518 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12519 SmallSet<SDNode *, 16> Visited; 12520 12521 // First, search up the chain, branching to follow all token-factor operands. 12522 // If we find a consecutive load, then we're done, otherwise, record all 12523 // nodes just above the top-level loads and token factors. 12524 while (!Queue.empty()) { 12525 SDNode *ChainNext = Queue.pop_back_val(); 12526 if (!Visited.insert(ChainNext).second) 12527 continue; 12528 12529 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12530 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12531 return true; 12532 12533 if (!Visited.count(ChainLD->getChain().getNode())) 12534 Queue.push_back(ChainLD->getChain().getNode()); 12535 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12536 for (const SDUse &O : ChainNext->ops()) 12537 if (!Visited.count(O.getNode())) 12538 Queue.push_back(O.getNode()); 12539 } else 12540 LoadRoots.insert(ChainNext); 12541 } 12542 12543 // Second, search down the chain, starting from the top-level nodes recorded 12544 // in the first phase. These top-level nodes are the nodes just above all 12545 // loads and token factors. Starting with their uses, recursively look though 12546 // all loads (just the chain uses) and token factors to find a consecutive 12547 // load. 12548 Visited.clear(); 12549 Queue.clear(); 12550 12551 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12552 IE = LoadRoots.end(); I != IE; ++I) { 12553 Queue.push_back(*I); 12554 12555 while (!Queue.empty()) { 12556 SDNode *LoadRoot = Queue.pop_back_val(); 12557 if (!Visited.insert(LoadRoot).second) 12558 continue; 12559 12560 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12561 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12562 return true; 12563 12564 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12565 UE = LoadRoot->use_end(); UI != UE; ++UI) 12566 if (((isa<MemSDNode>(*UI) && 12567 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12568 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12569 Queue.push_back(*UI); 12570 } 12571 } 12572 12573 return false; 12574 } 12575 12576 /// This function is called when we have proved that a SETCC node can be replaced 12577 /// by subtraction (and other supporting instructions) so that the result of 12578 /// comparison is kept in a GPR instead of CR. This function is purely for 12579 /// codegen purposes and has some flags to guide the codegen process. 12580 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12581 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12582 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12583 12584 // Zero extend the operands to the largest legal integer. Originally, they 12585 // must be of a strictly smaller size. 12586 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12587 DAG.getConstant(Size, DL, MVT::i32)); 12588 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12589 DAG.getConstant(Size, DL, MVT::i32)); 12590 12591 // Swap if needed. Depends on the condition code. 12592 if (Swap) 12593 std::swap(Op0, Op1); 12594 12595 // Subtract extended integers. 12596 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12597 12598 // Move the sign bit to the least significant position and zero out the rest. 12599 // Now the least significant bit carries the result of original comparison. 12600 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12601 DAG.getConstant(Size - 1, DL, MVT::i32)); 12602 auto Final = Shifted; 12603 12604 // Complement the result if needed. Based on the condition code. 12605 if (Complement) 12606 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12607 DAG.getConstant(1, DL, MVT::i64)); 12608 12609 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12610 } 12611 12612 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12613 DAGCombinerInfo &DCI) const { 12614 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12615 12616 SelectionDAG &DAG = DCI.DAG; 12617 SDLoc DL(N); 12618 12619 // Size of integers being compared has a critical role in the following 12620 // analysis, so we prefer to do this when all types are legal. 12621 if (!DCI.isAfterLegalizeDAG()) 12622 return SDValue(); 12623 12624 // If all users of SETCC extend its value to a legal integer type 12625 // then we replace SETCC with a subtraction 12626 for (SDNode::use_iterator UI = N->use_begin(), 12627 UE = N->use_end(); UI != UE; ++UI) { 12628 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12629 return SDValue(); 12630 } 12631 12632 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12633 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12634 12635 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12636 12637 if (OpSize < Size) { 12638 switch (CC) { 12639 default: break; 12640 case ISD::SETULT: 12641 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12642 case ISD::SETULE: 12643 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12644 case ISD::SETUGT: 12645 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12646 case ISD::SETUGE: 12647 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12648 } 12649 } 12650 12651 return SDValue(); 12652 } 12653 12654 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12655 DAGCombinerInfo &DCI) const { 12656 SelectionDAG &DAG = DCI.DAG; 12657 SDLoc dl(N); 12658 12659 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12660 // If we're tracking CR bits, we need to be careful that we don't have: 12661 // trunc(binary-ops(zext(x), zext(y))) 12662 // or 12663 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12664 // such that we're unnecessarily moving things into GPRs when it would be 12665 // better to keep them in CR bits. 12666 12667 // Note that trunc here can be an actual i1 trunc, or can be the effective 12668 // truncation that comes from a setcc or select_cc. 12669 if (N->getOpcode() == ISD::TRUNCATE && 12670 N->getValueType(0) != MVT::i1) 12671 return SDValue(); 12672 12673 if (N->getOperand(0).getValueType() != MVT::i32 && 12674 N->getOperand(0).getValueType() != MVT::i64) 12675 return SDValue(); 12676 12677 if (N->getOpcode() == ISD::SETCC || 12678 N->getOpcode() == ISD::SELECT_CC) { 12679 // If we're looking at a comparison, then we need to make sure that the 12680 // high bits (all except for the first) don't matter the result. 12681 ISD::CondCode CC = 12682 cast<CondCodeSDNode>(N->getOperand( 12683 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12684 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12685 12686 if (ISD::isSignedIntSetCC(CC)) { 12687 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12688 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12689 return SDValue(); 12690 } else if (ISD::isUnsignedIntSetCC(CC)) { 12691 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12692 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12693 !DAG.MaskedValueIsZero(N->getOperand(1), 12694 APInt::getHighBitsSet(OpBits, OpBits-1))) 12695 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12696 : SDValue()); 12697 } else { 12698 // This is neither a signed nor an unsigned comparison, just make sure 12699 // that the high bits are equal. 12700 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12701 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12702 12703 // We don't really care about what is known about the first bit (if 12704 // anything), so clear it in all masks prior to comparing them. 12705 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12706 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12707 12708 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12709 return SDValue(); 12710 } 12711 } 12712 12713 // We now know that the higher-order bits are irrelevant, we just need to 12714 // make sure that all of the intermediate operations are bit operations, and 12715 // all inputs are extensions. 12716 if (N->getOperand(0).getOpcode() != ISD::AND && 12717 N->getOperand(0).getOpcode() != ISD::OR && 12718 N->getOperand(0).getOpcode() != ISD::XOR && 12719 N->getOperand(0).getOpcode() != ISD::SELECT && 12720 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12721 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12722 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12723 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12724 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12725 return SDValue(); 12726 12727 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12728 N->getOperand(1).getOpcode() != ISD::AND && 12729 N->getOperand(1).getOpcode() != ISD::OR && 12730 N->getOperand(1).getOpcode() != ISD::XOR && 12731 N->getOperand(1).getOpcode() != ISD::SELECT && 12732 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12733 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12734 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12735 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12736 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12737 return SDValue(); 12738 12739 SmallVector<SDValue, 4> Inputs; 12740 SmallVector<SDValue, 8> BinOps, PromOps; 12741 SmallPtrSet<SDNode *, 16> Visited; 12742 12743 for (unsigned i = 0; i < 2; ++i) { 12744 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12745 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12746 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12747 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12748 isa<ConstantSDNode>(N->getOperand(i))) 12749 Inputs.push_back(N->getOperand(i)); 12750 else 12751 BinOps.push_back(N->getOperand(i)); 12752 12753 if (N->getOpcode() == ISD::TRUNCATE) 12754 break; 12755 } 12756 12757 // Visit all inputs, collect all binary operations (and, or, xor and 12758 // select) that are all fed by extensions. 12759 while (!BinOps.empty()) { 12760 SDValue BinOp = BinOps.back(); 12761 BinOps.pop_back(); 12762 12763 if (!Visited.insert(BinOp.getNode()).second) 12764 continue; 12765 12766 PromOps.push_back(BinOp); 12767 12768 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12769 // The condition of the select is not promoted. 12770 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12771 continue; 12772 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12773 continue; 12774 12775 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12776 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12777 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12778 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12779 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12780 Inputs.push_back(BinOp.getOperand(i)); 12781 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12782 BinOp.getOperand(i).getOpcode() == ISD::OR || 12783 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12784 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12785 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12786 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12787 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12788 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12789 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12790 BinOps.push_back(BinOp.getOperand(i)); 12791 } else { 12792 // We have an input that is not an extension or another binary 12793 // operation; we'll abort this transformation. 12794 return SDValue(); 12795 } 12796 } 12797 } 12798 12799 // Make sure that this is a self-contained cluster of operations (which 12800 // is not quite the same thing as saying that everything has only one 12801 // use). 12802 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12803 if (isa<ConstantSDNode>(Inputs[i])) 12804 continue; 12805 12806 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12807 UE = Inputs[i].getNode()->use_end(); 12808 UI != UE; ++UI) { 12809 SDNode *User = *UI; 12810 if (User != N && !Visited.count(User)) 12811 return SDValue(); 12812 12813 // Make sure that we're not going to promote the non-output-value 12814 // operand(s) or SELECT or SELECT_CC. 12815 // FIXME: Although we could sometimes handle this, and it does occur in 12816 // practice that one of the condition inputs to the select is also one of 12817 // the outputs, we currently can't deal with this. 12818 if (User->getOpcode() == ISD::SELECT) { 12819 if (User->getOperand(0) == Inputs[i]) 12820 return SDValue(); 12821 } else if (User->getOpcode() == ISD::SELECT_CC) { 12822 if (User->getOperand(0) == Inputs[i] || 12823 User->getOperand(1) == Inputs[i]) 12824 return SDValue(); 12825 } 12826 } 12827 } 12828 12829 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12830 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12831 UE = PromOps[i].getNode()->use_end(); 12832 UI != UE; ++UI) { 12833 SDNode *User = *UI; 12834 if (User != N && !Visited.count(User)) 12835 return SDValue(); 12836 12837 // Make sure that we're not going to promote the non-output-value 12838 // operand(s) or SELECT or SELECT_CC. 12839 // FIXME: Although we could sometimes handle this, and it does occur in 12840 // practice that one of the condition inputs to the select is also one of 12841 // the outputs, we currently can't deal with this. 12842 if (User->getOpcode() == ISD::SELECT) { 12843 if (User->getOperand(0) == PromOps[i]) 12844 return SDValue(); 12845 } else if (User->getOpcode() == ISD::SELECT_CC) { 12846 if (User->getOperand(0) == PromOps[i] || 12847 User->getOperand(1) == PromOps[i]) 12848 return SDValue(); 12849 } 12850 } 12851 } 12852 12853 // Replace all inputs with the extension operand. 12854 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12855 // Constants may have users outside the cluster of to-be-promoted nodes, 12856 // and so we need to replace those as we do the promotions. 12857 if (isa<ConstantSDNode>(Inputs[i])) 12858 continue; 12859 else 12860 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12861 } 12862 12863 std::list<HandleSDNode> PromOpHandles; 12864 for (auto &PromOp : PromOps) 12865 PromOpHandles.emplace_back(PromOp); 12866 12867 // Replace all operations (these are all the same, but have a different 12868 // (i1) return type). DAG.getNode will validate that the types of 12869 // a binary operator match, so go through the list in reverse so that 12870 // we've likely promoted both operands first. Any intermediate truncations or 12871 // extensions disappear. 12872 while (!PromOpHandles.empty()) { 12873 SDValue PromOp = PromOpHandles.back().getValue(); 12874 PromOpHandles.pop_back(); 12875 12876 if (PromOp.getOpcode() == ISD::TRUNCATE || 12877 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12878 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12879 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12880 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12881 PromOp.getOperand(0).getValueType() != MVT::i1) { 12882 // The operand is not yet ready (see comment below). 12883 PromOpHandles.emplace_front(PromOp); 12884 continue; 12885 } 12886 12887 SDValue RepValue = PromOp.getOperand(0); 12888 if (isa<ConstantSDNode>(RepValue)) 12889 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12890 12891 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12892 continue; 12893 } 12894 12895 unsigned C; 12896 switch (PromOp.getOpcode()) { 12897 default: C = 0; break; 12898 case ISD::SELECT: C = 1; break; 12899 case ISD::SELECT_CC: C = 2; break; 12900 } 12901 12902 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12903 PromOp.getOperand(C).getValueType() != MVT::i1) || 12904 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12905 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12906 // The to-be-promoted operands of this node have not yet been 12907 // promoted (this should be rare because we're going through the 12908 // list backward, but if one of the operands has several users in 12909 // this cluster of to-be-promoted nodes, it is possible). 12910 PromOpHandles.emplace_front(PromOp); 12911 continue; 12912 } 12913 12914 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12915 PromOp.getNode()->op_end()); 12916 12917 // If there are any constant inputs, make sure they're replaced now. 12918 for (unsigned i = 0; i < 2; ++i) 12919 if (isa<ConstantSDNode>(Ops[C+i])) 12920 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12921 12922 DAG.ReplaceAllUsesOfValueWith(PromOp, 12923 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12924 } 12925 12926 // Now we're left with the initial truncation itself. 12927 if (N->getOpcode() == ISD::TRUNCATE) 12928 return N->getOperand(0); 12929 12930 // Otherwise, this is a comparison. The operands to be compared have just 12931 // changed type (to i1), but everything else is the same. 12932 return SDValue(N, 0); 12933 } 12934 12935 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12936 DAGCombinerInfo &DCI) const { 12937 SelectionDAG &DAG = DCI.DAG; 12938 SDLoc dl(N); 12939 12940 // If we're tracking CR bits, we need to be careful that we don't have: 12941 // zext(binary-ops(trunc(x), trunc(y))) 12942 // or 12943 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12944 // such that we're unnecessarily moving things into CR bits that can more 12945 // efficiently stay in GPRs. Note that if we're not certain that the high 12946 // bits are set as required by the final extension, we still may need to do 12947 // some masking to get the proper behavior. 12948 12949 // This same functionality is important on PPC64 when dealing with 12950 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12951 // the return values of functions. Because it is so similar, it is handled 12952 // here as well. 12953 12954 if (N->getValueType(0) != MVT::i32 && 12955 N->getValueType(0) != MVT::i64) 12956 return SDValue(); 12957 12958 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12959 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12960 return SDValue(); 12961 12962 if (N->getOperand(0).getOpcode() != ISD::AND && 12963 N->getOperand(0).getOpcode() != ISD::OR && 12964 N->getOperand(0).getOpcode() != ISD::XOR && 12965 N->getOperand(0).getOpcode() != ISD::SELECT && 12966 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12967 return SDValue(); 12968 12969 SmallVector<SDValue, 4> Inputs; 12970 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12971 SmallPtrSet<SDNode *, 16> Visited; 12972 12973 // Visit all inputs, collect all binary operations (and, or, xor and 12974 // select) that are all fed by truncations. 12975 while (!BinOps.empty()) { 12976 SDValue BinOp = BinOps.back(); 12977 BinOps.pop_back(); 12978 12979 if (!Visited.insert(BinOp.getNode()).second) 12980 continue; 12981 12982 PromOps.push_back(BinOp); 12983 12984 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12985 // The condition of the select is not promoted. 12986 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12987 continue; 12988 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12989 continue; 12990 12991 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12992 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12993 Inputs.push_back(BinOp.getOperand(i)); 12994 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12995 BinOp.getOperand(i).getOpcode() == ISD::OR || 12996 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12997 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12998 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12999 BinOps.push_back(BinOp.getOperand(i)); 13000 } else { 13001 // We have an input that is not a truncation or another binary 13002 // operation; we'll abort this transformation. 13003 return SDValue(); 13004 } 13005 } 13006 } 13007 13008 // The operands of a select that must be truncated when the select is 13009 // promoted because the operand is actually part of the to-be-promoted set. 13010 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13011 13012 // Make sure that this is a self-contained cluster of operations (which 13013 // is not quite the same thing as saying that everything has only one 13014 // use). 13015 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13016 if (isa<ConstantSDNode>(Inputs[i])) 13017 continue; 13018 13019 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13020 UE = Inputs[i].getNode()->use_end(); 13021 UI != UE; ++UI) { 13022 SDNode *User = *UI; 13023 if (User != N && !Visited.count(User)) 13024 return SDValue(); 13025 13026 // If we're going to promote the non-output-value operand(s) or SELECT or 13027 // SELECT_CC, record them for truncation. 13028 if (User->getOpcode() == ISD::SELECT) { 13029 if (User->getOperand(0) == Inputs[i]) 13030 SelectTruncOp[0].insert(std::make_pair(User, 13031 User->getOperand(0).getValueType())); 13032 } else if (User->getOpcode() == ISD::SELECT_CC) { 13033 if (User->getOperand(0) == Inputs[i]) 13034 SelectTruncOp[0].insert(std::make_pair(User, 13035 User->getOperand(0).getValueType())); 13036 if (User->getOperand(1) == Inputs[i]) 13037 SelectTruncOp[1].insert(std::make_pair(User, 13038 User->getOperand(1).getValueType())); 13039 } 13040 } 13041 } 13042 13043 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13044 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13045 UE = PromOps[i].getNode()->use_end(); 13046 UI != UE; ++UI) { 13047 SDNode *User = *UI; 13048 if (User != N && !Visited.count(User)) 13049 return SDValue(); 13050 13051 // If we're going to promote the non-output-value operand(s) or SELECT or 13052 // SELECT_CC, record them for truncation. 13053 if (User->getOpcode() == ISD::SELECT) { 13054 if (User->getOperand(0) == PromOps[i]) 13055 SelectTruncOp[0].insert(std::make_pair(User, 13056 User->getOperand(0).getValueType())); 13057 } else if (User->getOpcode() == ISD::SELECT_CC) { 13058 if (User->getOperand(0) == PromOps[i]) 13059 SelectTruncOp[0].insert(std::make_pair(User, 13060 User->getOperand(0).getValueType())); 13061 if (User->getOperand(1) == PromOps[i]) 13062 SelectTruncOp[1].insert(std::make_pair(User, 13063 User->getOperand(1).getValueType())); 13064 } 13065 } 13066 } 13067 13068 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13069 bool ReallyNeedsExt = false; 13070 if (N->getOpcode() != ISD::ANY_EXTEND) { 13071 // If all of the inputs are not already sign/zero extended, then 13072 // we'll still need to do that at the end. 13073 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13074 if (isa<ConstantSDNode>(Inputs[i])) 13075 continue; 13076 13077 unsigned OpBits = 13078 Inputs[i].getOperand(0).getValueSizeInBits(); 13079 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13080 13081 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13082 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13083 APInt::getHighBitsSet(OpBits, 13084 OpBits-PromBits))) || 13085 (N->getOpcode() == ISD::SIGN_EXTEND && 13086 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13087 (OpBits-(PromBits-1)))) { 13088 ReallyNeedsExt = true; 13089 break; 13090 } 13091 } 13092 } 13093 13094 // Replace all inputs, either with the truncation operand, or a 13095 // truncation or extension to the final output type. 13096 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13097 // Constant inputs need to be replaced with the to-be-promoted nodes that 13098 // use them because they might have users outside of the cluster of 13099 // promoted nodes. 13100 if (isa<ConstantSDNode>(Inputs[i])) 13101 continue; 13102 13103 SDValue InSrc = Inputs[i].getOperand(0); 13104 if (Inputs[i].getValueType() == N->getValueType(0)) 13105 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13106 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13107 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13108 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13109 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13110 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13111 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13112 else 13113 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13114 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13115 } 13116 13117 std::list<HandleSDNode> PromOpHandles; 13118 for (auto &PromOp : PromOps) 13119 PromOpHandles.emplace_back(PromOp); 13120 13121 // Replace all operations (these are all the same, but have a different 13122 // (promoted) return type). DAG.getNode will validate that the types of 13123 // a binary operator match, so go through the list in reverse so that 13124 // we've likely promoted both operands first. 13125 while (!PromOpHandles.empty()) { 13126 SDValue PromOp = PromOpHandles.back().getValue(); 13127 PromOpHandles.pop_back(); 13128 13129 unsigned C; 13130 switch (PromOp.getOpcode()) { 13131 default: C = 0; break; 13132 case ISD::SELECT: C = 1; break; 13133 case ISD::SELECT_CC: C = 2; break; 13134 } 13135 13136 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13137 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13138 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13139 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13140 // The to-be-promoted operands of this node have not yet been 13141 // promoted (this should be rare because we're going through the 13142 // list backward, but if one of the operands has several users in 13143 // this cluster of to-be-promoted nodes, it is possible). 13144 PromOpHandles.emplace_front(PromOp); 13145 continue; 13146 } 13147 13148 // For SELECT and SELECT_CC nodes, we do a similar check for any 13149 // to-be-promoted comparison inputs. 13150 if (PromOp.getOpcode() == ISD::SELECT || 13151 PromOp.getOpcode() == ISD::SELECT_CC) { 13152 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13153 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13154 (SelectTruncOp[1].count(PromOp.getNode()) && 13155 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13156 PromOpHandles.emplace_front(PromOp); 13157 continue; 13158 } 13159 } 13160 13161 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13162 PromOp.getNode()->op_end()); 13163 13164 // If this node has constant inputs, then they'll need to be promoted here. 13165 for (unsigned i = 0; i < 2; ++i) { 13166 if (!isa<ConstantSDNode>(Ops[C+i])) 13167 continue; 13168 if (Ops[C+i].getValueType() == N->getValueType(0)) 13169 continue; 13170 13171 if (N->getOpcode() == ISD::SIGN_EXTEND) 13172 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13173 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13174 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13175 else 13176 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13177 } 13178 13179 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13180 // truncate them again to the original value type. 13181 if (PromOp.getOpcode() == ISD::SELECT || 13182 PromOp.getOpcode() == ISD::SELECT_CC) { 13183 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13184 if (SI0 != SelectTruncOp[0].end()) 13185 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13186 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13187 if (SI1 != SelectTruncOp[1].end()) 13188 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13189 } 13190 13191 DAG.ReplaceAllUsesOfValueWith(PromOp, 13192 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13193 } 13194 13195 // Now we're left with the initial extension itself. 13196 if (!ReallyNeedsExt) 13197 return N->getOperand(0); 13198 13199 // To zero extend, just mask off everything except for the first bit (in the 13200 // i1 case). 13201 if (N->getOpcode() == ISD::ZERO_EXTEND) 13202 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13203 DAG.getConstant(APInt::getLowBitsSet( 13204 N->getValueSizeInBits(0), PromBits), 13205 dl, N->getValueType(0))); 13206 13207 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13208 "Invalid extension type"); 13209 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13210 SDValue ShiftCst = 13211 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13212 return DAG.getNode( 13213 ISD::SRA, dl, N->getValueType(0), 13214 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13215 ShiftCst); 13216 } 13217 13218 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13219 DAGCombinerInfo &DCI) const { 13220 assert(N->getOpcode() == ISD::SETCC && 13221 "Should be called with a SETCC node"); 13222 13223 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13224 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13225 SDValue LHS = N->getOperand(0); 13226 SDValue RHS = N->getOperand(1); 13227 13228 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13229 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13230 LHS.hasOneUse()) 13231 std::swap(LHS, RHS); 13232 13233 // x == 0-y --> x+y == 0 13234 // x != 0-y --> x+y != 0 13235 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13236 RHS.hasOneUse()) { 13237 SDLoc DL(N); 13238 SelectionDAG &DAG = DCI.DAG; 13239 EVT VT = N->getValueType(0); 13240 EVT OpVT = LHS.getValueType(); 13241 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13242 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13243 } 13244 } 13245 13246 return DAGCombineTruncBoolExt(N, DCI); 13247 } 13248 13249 // Is this an extending load from an f32 to an f64? 13250 static bool isFPExtLoad(SDValue Op) { 13251 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13252 return LD->getExtensionType() == ISD::EXTLOAD && 13253 Op.getValueType() == MVT::f64; 13254 return false; 13255 } 13256 13257 /// Reduces the number of fp-to-int conversion when building a vector. 13258 /// 13259 /// If this vector is built out of floating to integer conversions, 13260 /// transform it to a vector built out of floating point values followed by a 13261 /// single floating to integer conversion of the vector. 13262 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13263 /// becomes (fptosi (build_vector ($A, $B, ...))) 13264 SDValue PPCTargetLowering:: 13265 combineElementTruncationToVectorTruncation(SDNode *N, 13266 DAGCombinerInfo &DCI) const { 13267 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13268 "Should be called with a BUILD_VECTOR node"); 13269 13270 SelectionDAG &DAG = DCI.DAG; 13271 SDLoc dl(N); 13272 13273 SDValue FirstInput = N->getOperand(0); 13274 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13275 "The input operand must be an fp-to-int conversion."); 13276 13277 // This combine happens after legalization so the fp_to_[su]i nodes are 13278 // already converted to PPCSISD nodes. 13279 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13280 if (FirstConversion == PPCISD::FCTIDZ || 13281 FirstConversion == PPCISD::FCTIDUZ || 13282 FirstConversion == PPCISD::FCTIWZ || 13283 FirstConversion == PPCISD::FCTIWUZ) { 13284 bool IsSplat = true; 13285 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13286 FirstConversion == PPCISD::FCTIWUZ; 13287 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13288 SmallVector<SDValue, 4> Ops; 13289 EVT TargetVT = N->getValueType(0); 13290 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13291 SDValue NextOp = N->getOperand(i); 13292 if (NextOp.getOpcode() != PPCISD::MFVSR) 13293 return SDValue(); 13294 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13295 if (NextConversion != FirstConversion) 13296 return SDValue(); 13297 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13298 // This is not valid if the input was originally double precision. It is 13299 // also not profitable to do unless this is an extending load in which 13300 // case doing this combine will allow us to combine consecutive loads. 13301 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13302 return SDValue(); 13303 if (N->getOperand(i) != FirstInput) 13304 IsSplat = false; 13305 } 13306 13307 // If this is a splat, we leave it as-is since there will be only a single 13308 // fp-to-int conversion followed by a splat of the integer. This is better 13309 // for 32-bit and smaller ints and neutral for 64-bit ints. 13310 if (IsSplat) 13311 return SDValue(); 13312 13313 // Now that we know we have the right type of node, get its operands 13314 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13315 SDValue In = N->getOperand(i).getOperand(0); 13316 if (Is32Bit) { 13317 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13318 // here, we know that all inputs are extending loads so this is safe). 13319 if (In.isUndef()) 13320 Ops.push_back(DAG.getUNDEF(SrcVT)); 13321 else { 13322 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13323 MVT::f32, In.getOperand(0), 13324 DAG.getIntPtrConstant(1, dl)); 13325 Ops.push_back(Trunc); 13326 } 13327 } else 13328 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13329 } 13330 13331 unsigned Opcode; 13332 if (FirstConversion == PPCISD::FCTIDZ || 13333 FirstConversion == PPCISD::FCTIWZ) 13334 Opcode = ISD::FP_TO_SINT; 13335 else 13336 Opcode = ISD::FP_TO_UINT; 13337 13338 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13339 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13340 return DAG.getNode(Opcode, dl, TargetVT, BV); 13341 } 13342 return SDValue(); 13343 } 13344 13345 /// Reduce the number of loads when building a vector. 13346 /// 13347 /// Building a vector out of multiple loads can be converted to a load 13348 /// of the vector type if the loads are consecutive. If the loads are 13349 /// consecutive but in descending order, a shuffle is added at the end 13350 /// to reorder the vector. 13351 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13352 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13353 "Should be called with a BUILD_VECTOR node"); 13354 13355 SDLoc dl(N); 13356 13357 // Return early for non byte-sized type, as they can't be consecutive. 13358 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13359 return SDValue(); 13360 13361 bool InputsAreConsecutiveLoads = true; 13362 bool InputsAreReverseConsecutive = true; 13363 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13364 SDValue FirstInput = N->getOperand(0); 13365 bool IsRoundOfExtLoad = false; 13366 13367 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13368 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13369 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13370 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13371 } 13372 // Not a build vector of (possibly fp_rounded) loads. 13373 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13374 N->getNumOperands() == 1) 13375 return SDValue(); 13376 13377 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13378 // If any inputs are fp_round(extload), they all must be. 13379 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13380 return SDValue(); 13381 13382 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13383 N->getOperand(i); 13384 if (NextInput.getOpcode() != ISD::LOAD) 13385 return SDValue(); 13386 13387 SDValue PreviousInput = 13388 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13389 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13390 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13391 13392 // If any inputs are fp_round(extload), they all must be. 13393 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13394 return SDValue(); 13395 13396 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13397 InputsAreConsecutiveLoads = false; 13398 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13399 InputsAreReverseConsecutive = false; 13400 13401 // Exit early if the loads are neither consecutive nor reverse consecutive. 13402 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13403 return SDValue(); 13404 } 13405 13406 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13407 "The loads cannot be both consecutive and reverse consecutive."); 13408 13409 SDValue FirstLoadOp = 13410 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13411 SDValue LastLoadOp = 13412 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13413 N->getOperand(N->getNumOperands()-1); 13414 13415 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13416 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13417 if (InputsAreConsecutiveLoads) { 13418 assert(LD1 && "Input needs to be a LoadSDNode."); 13419 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13420 LD1->getBasePtr(), LD1->getPointerInfo(), 13421 LD1->getAlignment()); 13422 } 13423 if (InputsAreReverseConsecutive) { 13424 assert(LDL && "Input needs to be a LoadSDNode."); 13425 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13426 LDL->getBasePtr(), LDL->getPointerInfo(), 13427 LDL->getAlignment()); 13428 SmallVector<int, 16> Ops; 13429 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13430 Ops.push_back(i); 13431 13432 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13433 DAG.getUNDEF(N->getValueType(0)), Ops); 13434 } 13435 return SDValue(); 13436 } 13437 13438 // This function adds the required vector_shuffle needed to get 13439 // the elements of the vector extract in the correct position 13440 // as specified by the CorrectElems encoding. 13441 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13442 SDValue Input, uint64_t Elems, 13443 uint64_t CorrectElems) { 13444 SDLoc dl(N); 13445 13446 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13447 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13448 13449 // Knowing the element indices being extracted from the original 13450 // vector and the order in which they're being inserted, just put 13451 // them at element indices required for the instruction. 13452 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13453 if (DAG.getDataLayout().isLittleEndian()) 13454 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13455 else 13456 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13457 CorrectElems = CorrectElems >> 8; 13458 Elems = Elems >> 8; 13459 } 13460 13461 SDValue Shuffle = 13462 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13463 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13464 13465 EVT VT = N->getValueType(0); 13466 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13467 13468 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13469 Input.getValueType().getVectorElementType(), 13470 VT.getVectorNumElements()); 13471 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13472 DAG.getValueType(ExtVT)); 13473 } 13474 13475 // Look for build vector patterns where input operands come from sign 13476 // extended vector_extract elements of specific indices. If the correct indices 13477 // aren't used, add a vector shuffle to fix up the indices and create 13478 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13479 // during instruction selection. 13480 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13481 // This array encodes the indices that the vector sign extend instructions 13482 // extract from when extending from one type to another for both BE and LE. 13483 // The right nibble of each byte corresponds to the LE incides. 13484 // and the left nibble of each byte corresponds to the BE incides. 13485 // For example: 0x3074B8FC byte->word 13486 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13487 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13488 // For example: 0x000070F8 byte->double word 13489 // For LE: the allowed indices are: 0x0,0x8 13490 // For BE: the allowed indices are: 0x7,0xF 13491 uint64_t TargetElems[] = { 13492 0x3074B8FC, // b->w 13493 0x000070F8, // b->d 13494 0x10325476, // h->w 13495 0x00003074, // h->d 13496 0x00001032, // w->d 13497 }; 13498 13499 uint64_t Elems = 0; 13500 int Index; 13501 SDValue Input; 13502 13503 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13504 if (!Op) 13505 return false; 13506 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13507 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13508 return false; 13509 13510 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13511 // of the right width. 13512 SDValue Extract = Op.getOperand(0); 13513 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13514 Extract = Extract.getOperand(0); 13515 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13516 return false; 13517 13518 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13519 if (!ExtOp) 13520 return false; 13521 13522 Index = ExtOp->getZExtValue(); 13523 if (Input && Input != Extract.getOperand(0)) 13524 return false; 13525 13526 if (!Input) 13527 Input = Extract.getOperand(0); 13528 13529 Elems = Elems << 8; 13530 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13531 Elems |= Index; 13532 13533 return true; 13534 }; 13535 13536 // If the build vector operands aren't sign extended vector extracts, 13537 // of the same input vector, then return. 13538 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13539 if (!isSExtOfVecExtract(N->getOperand(i))) { 13540 return SDValue(); 13541 } 13542 } 13543 13544 // If the vector extract indicies are not correct, add the appropriate 13545 // vector_shuffle. 13546 int TgtElemArrayIdx; 13547 int InputSize = Input.getValueType().getScalarSizeInBits(); 13548 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13549 if (InputSize + OutputSize == 40) 13550 TgtElemArrayIdx = 0; 13551 else if (InputSize + OutputSize == 72) 13552 TgtElemArrayIdx = 1; 13553 else if (InputSize + OutputSize == 48) 13554 TgtElemArrayIdx = 2; 13555 else if (InputSize + OutputSize == 80) 13556 TgtElemArrayIdx = 3; 13557 else if (InputSize + OutputSize == 96) 13558 TgtElemArrayIdx = 4; 13559 else 13560 return SDValue(); 13561 13562 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13563 CorrectElems = DAG.getDataLayout().isLittleEndian() 13564 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13565 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13566 if (Elems != CorrectElems) { 13567 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13568 } 13569 13570 // Regular lowering will catch cases where a shuffle is not needed. 13571 return SDValue(); 13572 } 13573 13574 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13575 DAGCombinerInfo &DCI) const { 13576 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13577 "Should be called with a BUILD_VECTOR node"); 13578 13579 SelectionDAG &DAG = DCI.DAG; 13580 SDLoc dl(N); 13581 13582 if (!Subtarget.hasVSX()) 13583 return SDValue(); 13584 13585 // The target independent DAG combiner will leave a build_vector of 13586 // float-to-int conversions intact. We can generate MUCH better code for 13587 // a float-to-int conversion of a vector of floats. 13588 SDValue FirstInput = N->getOperand(0); 13589 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13590 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13591 if (Reduced) 13592 return Reduced; 13593 } 13594 13595 // If we're building a vector out of consecutive loads, just load that 13596 // vector type. 13597 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13598 if (Reduced) 13599 return Reduced; 13600 13601 // If we're building a vector out of extended elements from another vector 13602 // we have P9 vector integer extend instructions. The code assumes legal 13603 // input types (i.e. it can't handle things like v4i16) so do not run before 13604 // legalization. 13605 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13606 Reduced = combineBVOfVecSExt(N, DAG); 13607 if (Reduced) 13608 return Reduced; 13609 } 13610 13611 13612 if (N->getValueType(0) != MVT::v2f64) 13613 return SDValue(); 13614 13615 // Looking for: 13616 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13617 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13618 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13619 return SDValue(); 13620 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13621 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13622 return SDValue(); 13623 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13624 return SDValue(); 13625 13626 SDValue Ext1 = FirstInput.getOperand(0); 13627 SDValue Ext2 = N->getOperand(1).getOperand(0); 13628 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13629 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13630 return SDValue(); 13631 13632 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13633 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13634 if (!Ext1Op || !Ext2Op) 13635 return SDValue(); 13636 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13637 Ext1.getOperand(0) != Ext2.getOperand(0)) 13638 return SDValue(); 13639 13640 int FirstElem = Ext1Op->getZExtValue(); 13641 int SecondElem = Ext2Op->getZExtValue(); 13642 int SubvecIdx; 13643 if (FirstElem == 0 && SecondElem == 1) 13644 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13645 else if (FirstElem == 2 && SecondElem == 3) 13646 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13647 else 13648 return SDValue(); 13649 13650 SDValue SrcVec = Ext1.getOperand(0); 13651 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13652 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13653 return DAG.getNode(NodeType, dl, MVT::v2f64, 13654 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13655 } 13656 13657 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13658 DAGCombinerInfo &DCI) const { 13659 assert((N->getOpcode() == ISD::SINT_TO_FP || 13660 N->getOpcode() == ISD::UINT_TO_FP) && 13661 "Need an int -> FP conversion node here"); 13662 13663 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13664 return SDValue(); 13665 13666 SelectionDAG &DAG = DCI.DAG; 13667 SDLoc dl(N); 13668 SDValue Op(N, 0); 13669 13670 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13671 // from the hardware. 13672 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13673 return SDValue(); 13674 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13675 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13676 return SDValue(); 13677 13678 SDValue FirstOperand(Op.getOperand(0)); 13679 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13680 (FirstOperand.getValueType() == MVT::i8 || 13681 FirstOperand.getValueType() == MVT::i16); 13682 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13683 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13684 bool DstDouble = Op.getValueType() == MVT::f64; 13685 unsigned ConvOp = Signed ? 13686 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13687 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13688 SDValue WidthConst = 13689 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13690 dl, false); 13691 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13692 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13693 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13694 DAG.getVTList(MVT::f64, MVT::Other), 13695 Ops, MVT::i8, LDN->getMemOperand()); 13696 13697 // For signed conversion, we need to sign-extend the value in the VSR 13698 if (Signed) { 13699 SDValue ExtOps[] = { Ld, WidthConst }; 13700 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13701 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13702 } else 13703 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13704 } 13705 13706 13707 // For i32 intermediate values, unfortunately, the conversion functions 13708 // leave the upper 32 bits of the value are undefined. Within the set of 13709 // scalar instructions, we have no method for zero- or sign-extending the 13710 // value. Thus, we cannot handle i32 intermediate values here. 13711 if (Op.getOperand(0).getValueType() == MVT::i32) 13712 return SDValue(); 13713 13714 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13715 "UINT_TO_FP is supported only with FPCVT"); 13716 13717 // If we have FCFIDS, then use it when converting to single-precision. 13718 // Otherwise, convert to double-precision and then round. 13719 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13720 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13721 : PPCISD::FCFIDS) 13722 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13723 : PPCISD::FCFID); 13724 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13725 ? MVT::f32 13726 : MVT::f64; 13727 13728 // If we're converting from a float, to an int, and back to a float again, 13729 // then we don't need the store/load pair at all. 13730 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13731 Subtarget.hasFPCVT()) || 13732 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13733 SDValue Src = Op.getOperand(0).getOperand(0); 13734 if (Src.getValueType() == MVT::f32) { 13735 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13736 DCI.AddToWorklist(Src.getNode()); 13737 } else if (Src.getValueType() != MVT::f64) { 13738 // Make sure that we don't pick up a ppc_fp128 source value. 13739 return SDValue(); 13740 } 13741 13742 unsigned FCTOp = 13743 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13744 PPCISD::FCTIDUZ; 13745 13746 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13747 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13748 13749 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13750 FP = DAG.getNode(ISD::FP_ROUND, dl, 13751 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13752 DCI.AddToWorklist(FP.getNode()); 13753 } 13754 13755 return FP; 13756 } 13757 13758 return SDValue(); 13759 } 13760 13761 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13762 // builtins) into loads with swaps. 13763 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13764 DAGCombinerInfo &DCI) const { 13765 SelectionDAG &DAG = DCI.DAG; 13766 SDLoc dl(N); 13767 SDValue Chain; 13768 SDValue Base; 13769 MachineMemOperand *MMO; 13770 13771 switch (N->getOpcode()) { 13772 default: 13773 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13774 case ISD::LOAD: { 13775 LoadSDNode *LD = cast<LoadSDNode>(N); 13776 Chain = LD->getChain(); 13777 Base = LD->getBasePtr(); 13778 MMO = LD->getMemOperand(); 13779 // If the MMO suggests this isn't a load of a full vector, leave 13780 // things alone. For a built-in, we have to make the change for 13781 // correctness, so if there is a size problem that will be a bug. 13782 if (MMO->getSize() < 16) 13783 return SDValue(); 13784 break; 13785 } 13786 case ISD::INTRINSIC_W_CHAIN: { 13787 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13788 Chain = Intrin->getChain(); 13789 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13790 // us what we want. Get operand 2 instead. 13791 Base = Intrin->getOperand(2); 13792 MMO = Intrin->getMemOperand(); 13793 break; 13794 } 13795 } 13796 13797 MVT VecTy = N->getValueType(0).getSimpleVT(); 13798 13799 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13800 // aligned and the type is a vector with elements up to 4 bytes 13801 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13802 VecTy.getScalarSizeInBits() <= 32) { 13803 return SDValue(); 13804 } 13805 13806 SDValue LoadOps[] = { Chain, Base }; 13807 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13808 DAG.getVTList(MVT::v2f64, MVT::Other), 13809 LoadOps, MVT::v2f64, MMO); 13810 13811 DCI.AddToWorklist(Load.getNode()); 13812 Chain = Load.getValue(1); 13813 SDValue Swap = DAG.getNode( 13814 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13815 DCI.AddToWorklist(Swap.getNode()); 13816 13817 // Add a bitcast if the resulting load type doesn't match v2f64. 13818 if (VecTy != MVT::v2f64) { 13819 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13820 DCI.AddToWorklist(N.getNode()); 13821 // Package {bitcast value, swap's chain} to match Load's shape. 13822 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13823 N, Swap.getValue(1)); 13824 } 13825 13826 return Swap; 13827 } 13828 13829 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13830 // builtins) into stores with swaps. 13831 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13832 DAGCombinerInfo &DCI) const { 13833 SelectionDAG &DAG = DCI.DAG; 13834 SDLoc dl(N); 13835 SDValue Chain; 13836 SDValue Base; 13837 unsigned SrcOpnd; 13838 MachineMemOperand *MMO; 13839 13840 switch (N->getOpcode()) { 13841 default: 13842 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13843 case ISD::STORE: { 13844 StoreSDNode *ST = cast<StoreSDNode>(N); 13845 Chain = ST->getChain(); 13846 Base = ST->getBasePtr(); 13847 MMO = ST->getMemOperand(); 13848 SrcOpnd = 1; 13849 // If the MMO suggests this isn't a store of a full vector, leave 13850 // things alone. For a built-in, we have to make the change for 13851 // correctness, so if there is a size problem that will be a bug. 13852 if (MMO->getSize() < 16) 13853 return SDValue(); 13854 break; 13855 } 13856 case ISD::INTRINSIC_VOID: { 13857 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13858 Chain = Intrin->getChain(); 13859 // Intrin->getBasePtr() oddly does not get what we want. 13860 Base = Intrin->getOperand(3); 13861 MMO = Intrin->getMemOperand(); 13862 SrcOpnd = 2; 13863 break; 13864 } 13865 } 13866 13867 SDValue Src = N->getOperand(SrcOpnd); 13868 MVT VecTy = Src.getValueType().getSimpleVT(); 13869 13870 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13871 // aligned and the type is a vector with elements up to 4 bytes 13872 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13873 VecTy.getScalarSizeInBits() <= 32) { 13874 return SDValue(); 13875 } 13876 13877 // All stores are done as v2f64 and possible bit cast. 13878 if (VecTy != MVT::v2f64) { 13879 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13880 DCI.AddToWorklist(Src.getNode()); 13881 } 13882 13883 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13884 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13885 DCI.AddToWorklist(Swap.getNode()); 13886 Chain = Swap.getValue(1); 13887 SDValue StoreOps[] = { Chain, Swap, Base }; 13888 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13889 DAG.getVTList(MVT::Other), 13890 StoreOps, VecTy, MMO); 13891 DCI.AddToWorklist(Store.getNode()); 13892 return Store; 13893 } 13894 13895 // Handle DAG combine for STORE (FP_TO_INT F). 13896 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13897 DAGCombinerInfo &DCI) const { 13898 13899 SelectionDAG &DAG = DCI.DAG; 13900 SDLoc dl(N); 13901 unsigned Opcode = N->getOperand(1).getOpcode(); 13902 13903 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13904 && "Not a FP_TO_INT Instruction!"); 13905 13906 SDValue Val = N->getOperand(1).getOperand(0); 13907 EVT Op1VT = N->getOperand(1).getValueType(); 13908 EVT ResVT = Val.getValueType(); 13909 13910 // Floating point types smaller than 32 bits are not legal on Power. 13911 if (ResVT.getScalarSizeInBits() < 32) 13912 return SDValue(); 13913 13914 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13915 bool ValidTypeForStoreFltAsInt = 13916 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13917 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13918 13919 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 13920 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13921 return SDValue(); 13922 13923 // Extend f32 values to f64 13924 if (ResVT.getScalarSizeInBits() == 32) { 13925 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13926 DCI.AddToWorklist(Val.getNode()); 13927 } 13928 13929 // Set signed or unsigned conversion opcode. 13930 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13931 PPCISD::FP_TO_SINT_IN_VSR : 13932 PPCISD::FP_TO_UINT_IN_VSR; 13933 13934 Val = DAG.getNode(ConvOpcode, 13935 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13936 DCI.AddToWorklist(Val.getNode()); 13937 13938 // Set number of bytes being converted. 13939 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13940 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13941 DAG.getIntPtrConstant(ByteSize, dl, false), 13942 DAG.getValueType(Op1VT) }; 13943 13944 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13945 DAG.getVTList(MVT::Other), Ops, 13946 cast<StoreSDNode>(N)->getMemoryVT(), 13947 cast<StoreSDNode>(N)->getMemOperand()); 13948 13949 DCI.AddToWorklist(Val.getNode()); 13950 return Val; 13951 } 13952 13953 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 13954 // Check that the source of the element keeps flipping 13955 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 13956 bool PrevElemFromFirstVec = Mask[0] < NumElts; 13957 for (int i = 1, e = Mask.size(); i < e; i++) { 13958 if (PrevElemFromFirstVec && Mask[i] < NumElts) 13959 return false; 13960 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 13961 return false; 13962 PrevElemFromFirstVec = !PrevElemFromFirstVec; 13963 } 13964 return true; 13965 } 13966 13967 static bool isSplatBV(SDValue Op) { 13968 if (Op.getOpcode() != ISD::BUILD_VECTOR) 13969 return false; 13970 SDValue FirstOp; 13971 13972 // Find first non-undef input. 13973 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 13974 FirstOp = Op.getOperand(i); 13975 if (!FirstOp.isUndef()) 13976 break; 13977 } 13978 13979 // All inputs are undef or the same as the first non-undef input. 13980 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 13981 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 13982 return false; 13983 return true; 13984 } 13985 13986 static SDValue isScalarToVec(SDValue Op) { 13987 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 13988 return Op; 13989 if (Op.getOpcode() != ISD::BITCAST) 13990 return SDValue(); 13991 Op = Op.getOperand(0); 13992 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 13993 return Op; 13994 return SDValue(); 13995 } 13996 13997 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 13998 int LHSMaxIdx, int RHSMinIdx, 13999 int RHSMaxIdx, int HalfVec) { 14000 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14001 int Idx = ShuffV[i]; 14002 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14003 ShuffV[i] += HalfVec; 14004 } 14005 return; 14006 } 14007 14008 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14009 // the original is: 14010 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14011 // In such a case, just change the shuffle mask to extract the element 14012 // from the permuted index. 14013 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14014 SDLoc dl(OrigSToV); 14015 EVT VT = OrigSToV.getValueType(); 14016 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14017 "Expecting a SCALAR_TO_VECTOR here"); 14018 SDValue Input = OrigSToV.getOperand(0); 14019 14020 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14021 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14022 SDValue OrigVector = Input.getOperand(0); 14023 14024 // Can't handle non-const element indices or different vector types 14025 // for the input to the extract and the output of the scalar_to_vector. 14026 if (Idx && VT == OrigVector.getValueType()) { 14027 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14028 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14029 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14030 } 14031 } 14032 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14033 OrigSToV.getOperand(0)); 14034 } 14035 14036 // On little endian subtargets, combine shuffles such as: 14037 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14038 // into: 14039 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14040 // because the latter can be matched to a single instruction merge. 14041 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14042 // to put the value into element zero. Adjust the shuffle mask so that the 14043 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14044 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14045 SelectionDAG &DAG) const { 14046 SDValue LHS = SVN->getOperand(0); 14047 SDValue RHS = SVN->getOperand(1); 14048 auto Mask = SVN->getMask(); 14049 int NumElts = LHS.getValueType().getVectorNumElements(); 14050 SDValue Res(SVN, 0); 14051 SDLoc dl(SVN); 14052 14053 // None of these combines are useful on big endian systems since the ISA 14054 // already has a big endian bias. 14055 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14056 return Res; 14057 14058 // If this is not a shuffle of a shuffle and the first element comes from 14059 // the second vector, canonicalize to the commuted form. This will make it 14060 // more likely to match one of the single instruction patterns. 14061 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14062 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14063 std::swap(LHS, RHS); 14064 Res = DAG.getCommutedVectorShuffle(*SVN); 14065 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14066 } 14067 14068 // Adjust the shuffle mask if either input vector comes from a 14069 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14070 // form (to prevent the need for a swap). 14071 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14072 SDValue SToVLHS = isScalarToVec(LHS); 14073 SDValue SToVRHS = isScalarToVec(RHS); 14074 if (SToVLHS || SToVRHS) { 14075 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14076 : SToVRHS.getValueType().getVectorNumElements(); 14077 int NumEltsOut = ShuffV.size(); 14078 14079 // Initially assume that neither input is permuted. These will be adjusted 14080 // accordingly if either input is. 14081 int LHSMaxIdx = -1; 14082 int RHSMinIdx = -1; 14083 int RHSMaxIdx = -1; 14084 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14085 14086 // Get the permuted scalar to vector nodes for the source(s) that come from 14087 // ISD::SCALAR_TO_VECTOR. 14088 if (SToVLHS) { 14089 // Set up the values for the shuffle vector fixup. 14090 LHSMaxIdx = NumEltsOut / NumEltsIn; 14091 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14092 if (SToVLHS.getValueType() != LHS.getValueType()) 14093 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14094 LHS = SToVLHS; 14095 } 14096 if (SToVRHS) { 14097 RHSMinIdx = NumEltsOut; 14098 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14099 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14100 if (SToVRHS.getValueType() != RHS.getValueType()) 14101 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14102 RHS = SToVRHS; 14103 } 14104 14105 // Fix up the shuffle mask to reflect where the desired element actually is. 14106 // The minimum and maximum indices that correspond to element zero for both 14107 // the LHS and RHS are computed and will control which shuffle mask entries 14108 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14109 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14110 // HalfVec to refer to the corresponding element in the permuted vector. 14111 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14112 HalfVec); 14113 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14114 14115 // We may have simplified away the shuffle. We won't be able to do anything 14116 // further with it here. 14117 if (!isa<ShuffleVectorSDNode>(Res)) 14118 return Res; 14119 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14120 } 14121 14122 // The common case after we commuted the shuffle is that the RHS is a splat 14123 // and we have elements coming in from the splat at indices that are not 14124 // conducive to using a merge. 14125 // Example: 14126 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14127 if (!isSplatBV(RHS)) 14128 return Res; 14129 14130 // We are looking for a mask such that all even elements are from 14131 // one vector and all odd elements from the other. 14132 if (!isAlternatingShuffMask(Mask, NumElts)) 14133 return Res; 14134 14135 // Adjust the mask so we are pulling in the same index from the splat 14136 // as the index from the interesting vector in consecutive elements. 14137 // Example (even elements from first vector): 14138 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14139 if (Mask[0] < NumElts) 14140 for (int i = 1, e = Mask.size(); i < e; i += 2) 14141 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14142 // Example (odd elements from first vector): 14143 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14144 else 14145 for (int i = 0, e = Mask.size(); i < e; i += 2) 14146 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14147 14148 // If the RHS has undefs, we need to remove them since we may have created 14149 // a shuffle that adds those instead of the splat value. 14150 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14151 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14152 14153 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14154 return Res; 14155 } 14156 14157 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14158 LSBaseSDNode *LSBase, 14159 DAGCombinerInfo &DCI) const { 14160 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14161 "Not a reverse memop pattern!"); 14162 14163 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14164 auto Mask = SVN->getMask(); 14165 int i = 0; 14166 auto I = Mask.rbegin(); 14167 auto E = Mask.rend(); 14168 14169 for (; I != E; ++I) { 14170 if (*I != i) 14171 return false; 14172 i++; 14173 } 14174 return true; 14175 }; 14176 14177 SelectionDAG &DAG = DCI.DAG; 14178 EVT VT = SVN->getValueType(0); 14179 14180 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14181 return SDValue(); 14182 14183 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14184 // See comment in PPCVSXSwapRemoval.cpp. 14185 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14186 if (!Subtarget.hasP9Vector()) 14187 return SDValue(); 14188 14189 if(!IsElementReverse(SVN)) 14190 return SDValue(); 14191 14192 if (LSBase->getOpcode() == ISD::LOAD) { 14193 SDLoc dl(SVN); 14194 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14195 return DAG.getMemIntrinsicNode( 14196 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14197 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14198 } 14199 14200 if (LSBase->getOpcode() == ISD::STORE) { 14201 SDLoc dl(LSBase); 14202 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14203 LSBase->getBasePtr()}; 14204 return DAG.getMemIntrinsicNode( 14205 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14206 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14207 } 14208 14209 llvm_unreachable("Expected a load or store node here"); 14210 } 14211 14212 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14213 DAGCombinerInfo &DCI) const { 14214 SelectionDAG &DAG = DCI.DAG; 14215 SDLoc dl(N); 14216 switch (N->getOpcode()) { 14217 default: break; 14218 case ISD::ADD: 14219 return combineADD(N, DCI); 14220 case ISD::SHL: 14221 return combineSHL(N, DCI); 14222 case ISD::SRA: 14223 return combineSRA(N, DCI); 14224 case ISD::SRL: 14225 return combineSRL(N, DCI); 14226 case ISD::MUL: 14227 return combineMUL(N, DCI); 14228 case ISD::FMA: 14229 case PPCISD::FNMSUB: 14230 return combineFMALike(N, DCI); 14231 case PPCISD::SHL: 14232 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14233 return N->getOperand(0); 14234 break; 14235 case PPCISD::SRL: 14236 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14237 return N->getOperand(0); 14238 break; 14239 case PPCISD::SRA: 14240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14241 if (C->isNullValue() || // 0 >>s V -> 0. 14242 C->isAllOnesValue()) // -1 >>s V -> -1. 14243 return N->getOperand(0); 14244 } 14245 break; 14246 case ISD::SIGN_EXTEND: 14247 case ISD::ZERO_EXTEND: 14248 case ISD::ANY_EXTEND: 14249 return DAGCombineExtBoolTrunc(N, DCI); 14250 case ISD::TRUNCATE: 14251 return combineTRUNCATE(N, DCI); 14252 case ISD::SETCC: 14253 if (SDValue CSCC = combineSetCC(N, DCI)) 14254 return CSCC; 14255 LLVM_FALLTHROUGH; 14256 case ISD::SELECT_CC: 14257 return DAGCombineTruncBoolExt(N, DCI); 14258 case ISD::SINT_TO_FP: 14259 case ISD::UINT_TO_FP: 14260 return combineFPToIntToFP(N, DCI); 14261 case ISD::VECTOR_SHUFFLE: 14262 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14263 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14264 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14265 } 14266 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14267 case ISD::STORE: { 14268 14269 EVT Op1VT = N->getOperand(1).getValueType(); 14270 unsigned Opcode = N->getOperand(1).getOpcode(); 14271 14272 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14273 SDValue Val= combineStoreFPToInt(N, DCI); 14274 if (Val) 14275 return Val; 14276 } 14277 14278 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14279 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14280 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14281 if (Val) 14282 return Val; 14283 } 14284 14285 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14286 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14287 N->getOperand(1).getNode()->hasOneUse() && 14288 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14289 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14290 14291 // STBRX can only handle simple types and it makes no sense to store less 14292 // two bytes in byte-reversed order. 14293 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14294 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14295 break; 14296 14297 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14298 // Do an any-extend to 32-bits if this is a half-word input. 14299 if (BSwapOp.getValueType() == MVT::i16) 14300 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14301 14302 // If the type of BSWAP operand is wider than stored memory width 14303 // it need to be shifted to the right side before STBRX. 14304 if (Op1VT.bitsGT(mVT)) { 14305 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14306 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14307 DAG.getConstant(Shift, dl, MVT::i32)); 14308 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14309 if (Op1VT == MVT::i64) 14310 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14311 } 14312 14313 SDValue Ops[] = { 14314 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14315 }; 14316 return 14317 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14318 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14319 cast<StoreSDNode>(N)->getMemOperand()); 14320 } 14321 14322 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14323 // So it can increase the chance of CSE constant construction. 14324 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14325 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14326 // Need to sign-extended to 64-bits to handle negative values. 14327 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14328 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14329 MemVT.getSizeInBits()); 14330 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14331 14332 // DAG.getTruncStore() can't be used here because it doesn't accept 14333 // the general (base + offset) addressing mode. 14334 // So we use UpdateNodeOperands and setTruncatingStore instead. 14335 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14336 N->getOperand(3)); 14337 cast<StoreSDNode>(N)->setTruncatingStore(true); 14338 return SDValue(N, 0); 14339 } 14340 14341 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14342 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14343 if (Op1VT.isSimple()) { 14344 MVT StoreVT = Op1VT.getSimpleVT(); 14345 if (Subtarget.needsSwapsForVSXMemOps() && 14346 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14347 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14348 return expandVSXStoreForLE(N, DCI); 14349 } 14350 break; 14351 } 14352 case ISD::LOAD: { 14353 LoadSDNode *LD = cast<LoadSDNode>(N); 14354 EVT VT = LD->getValueType(0); 14355 14356 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14357 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14358 if (VT.isSimple()) { 14359 MVT LoadVT = VT.getSimpleVT(); 14360 if (Subtarget.needsSwapsForVSXMemOps() && 14361 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14362 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14363 return expandVSXLoadForLE(N, DCI); 14364 } 14365 14366 // We sometimes end up with a 64-bit integer load, from which we extract 14367 // two single-precision floating-point numbers. This happens with 14368 // std::complex<float>, and other similar structures, because of the way we 14369 // canonicalize structure copies. However, if we lack direct moves, 14370 // then the final bitcasts from the extracted integer values to the 14371 // floating-point numbers turn into store/load pairs. Even with direct moves, 14372 // just loading the two floating-point numbers is likely better. 14373 auto ReplaceTwoFloatLoad = [&]() { 14374 if (VT != MVT::i64) 14375 return false; 14376 14377 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14378 LD->isVolatile()) 14379 return false; 14380 14381 // We're looking for a sequence like this: 14382 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14383 // t16: i64 = srl t13, Constant:i32<32> 14384 // t17: i32 = truncate t16 14385 // t18: f32 = bitcast t17 14386 // t19: i32 = truncate t13 14387 // t20: f32 = bitcast t19 14388 14389 if (!LD->hasNUsesOfValue(2, 0)) 14390 return false; 14391 14392 auto UI = LD->use_begin(); 14393 while (UI.getUse().getResNo() != 0) ++UI; 14394 SDNode *Trunc = *UI++; 14395 while (UI.getUse().getResNo() != 0) ++UI; 14396 SDNode *RightShift = *UI; 14397 if (Trunc->getOpcode() != ISD::TRUNCATE) 14398 std::swap(Trunc, RightShift); 14399 14400 if (Trunc->getOpcode() != ISD::TRUNCATE || 14401 Trunc->getValueType(0) != MVT::i32 || 14402 !Trunc->hasOneUse()) 14403 return false; 14404 if (RightShift->getOpcode() != ISD::SRL || 14405 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14406 RightShift->getConstantOperandVal(1) != 32 || 14407 !RightShift->hasOneUse()) 14408 return false; 14409 14410 SDNode *Trunc2 = *RightShift->use_begin(); 14411 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14412 Trunc2->getValueType(0) != MVT::i32 || 14413 !Trunc2->hasOneUse()) 14414 return false; 14415 14416 SDNode *Bitcast = *Trunc->use_begin(); 14417 SDNode *Bitcast2 = *Trunc2->use_begin(); 14418 14419 if (Bitcast->getOpcode() != ISD::BITCAST || 14420 Bitcast->getValueType(0) != MVT::f32) 14421 return false; 14422 if (Bitcast2->getOpcode() != ISD::BITCAST || 14423 Bitcast2->getValueType(0) != MVT::f32) 14424 return false; 14425 14426 if (Subtarget.isLittleEndian()) 14427 std::swap(Bitcast, Bitcast2); 14428 14429 // Bitcast has the second float (in memory-layout order) and Bitcast2 14430 // has the first one. 14431 14432 SDValue BasePtr = LD->getBasePtr(); 14433 if (LD->isIndexed()) { 14434 assert(LD->getAddressingMode() == ISD::PRE_INC && 14435 "Non-pre-inc AM on PPC?"); 14436 BasePtr = 14437 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14438 LD->getOffset()); 14439 } 14440 14441 auto MMOFlags = 14442 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14443 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14444 LD->getPointerInfo(), LD->getAlignment(), 14445 MMOFlags, LD->getAAInfo()); 14446 SDValue AddPtr = 14447 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14448 BasePtr, DAG.getIntPtrConstant(4, dl)); 14449 SDValue FloatLoad2 = DAG.getLoad( 14450 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14451 LD->getPointerInfo().getWithOffset(4), 14452 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14453 14454 if (LD->isIndexed()) { 14455 // Note that DAGCombine should re-form any pre-increment load(s) from 14456 // what is produced here if that makes sense. 14457 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14458 } 14459 14460 DCI.CombineTo(Bitcast2, FloatLoad); 14461 DCI.CombineTo(Bitcast, FloatLoad2); 14462 14463 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14464 SDValue(FloatLoad2.getNode(), 1)); 14465 return true; 14466 }; 14467 14468 if (ReplaceTwoFloatLoad()) 14469 return SDValue(N, 0); 14470 14471 EVT MemVT = LD->getMemoryVT(); 14472 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14473 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14474 if (LD->isUnindexed() && VT.isVector() && 14475 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14476 // P8 and later hardware should just use LOAD. 14477 !Subtarget.hasP8Vector() && 14478 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14479 VT == MVT::v4f32))) && 14480 LD->getAlign() < ABIAlignment) { 14481 // This is a type-legal unaligned Altivec load. 14482 SDValue Chain = LD->getChain(); 14483 SDValue Ptr = LD->getBasePtr(); 14484 bool isLittleEndian = Subtarget.isLittleEndian(); 14485 14486 // This implements the loading of unaligned vectors as described in 14487 // the venerable Apple Velocity Engine overview. Specifically: 14488 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14489 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14490 // 14491 // The general idea is to expand a sequence of one or more unaligned 14492 // loads into an alignment-based permutation-control instruction (lvsl 14493 // or lvsr), a series of regular vector loads (which always truncate 14494 // their input address to an aligned address), and a series of 14495 // permutations. The results of these permutations are the requested 14496 // loaded values. The trick is that the last "extra" load is not taken 14497 // from the address you might suspect (sizeof(vector) bytes after the 14498 // last requested load), but rather sizeof(vector) - 1 bytes after the 14499 // last requested vector. The point of this is to avoid a page fault if 14500 // the base address happened to be aligned. This works because if the 14501 // base address is aligned, then adding less than a full vector length 14502 // will cause the last vector in the sequence to be (re)loaded. 14503 // Otherwise, the next vector will be fetched as you might suspect was 14504 // necessary. 14505 14506 // We might be able to reuse the permutation generation from 14507 // a different base address offset from this one by an aligned amount. 14508 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14509 // optimization later. 14510 Intrinsic::ID Intr, IntrLD, IntrPerm; 14511 MVT PermCntlTy, PermTy, LDTy; 14512 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14513 : Intrinsic::ppc_altivec_lvsl; 14514 IntrLD = Intrinsic::ppc_altivec_lvx; 14515 IntrPerm = Intrinsic::ppc_altivec_vperm; 14516 PermCntlTy = MVT::v16i8; 14517 PermTy = MVT::v4i32; 14518 LDTy = MVT::v4i32; 14519 14520 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14521 14522 // Create the new MMO for the new base load. It is like the original MMO, 14523 // but represents an area in memory almost twice the vector size centered 14524 // on the original address. If the address is unaligned, we might start 14525 // reading up to (sizeof(vector)-1) bytes below the address of the 14526 // original unaligned load. 14527 MachineFunction &MF = DAG.getMachineFunction(); 14528 MachineMemOperand *BaseMMO = 14529 MF.getMachineMemOperand(LD->getMemOperand(), 14530 -(long)MemVT.getStoreSize()+1, 14531 2*MemVT.getStoreSize()-1); 14532 14533 // Create the new base load. 14534 SDValue LDXIntID = 14535 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14536 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14537 SDValue BaseLoad = 14538 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14539 DAG.getVTList(PermTy, MVT::Other), 14540 BaseLoadOps, LDTy, BaseMMO); 14541 14542 // Note that the value of IncOffset (which is provided to the next 14543 // load's pointer info offset value, and thus used to calculate the 14544 // alignment), and the value of IncValue (which is actually used to 14545 // increment the pointer value) are different! This is because we 14546 // require the next load to appear to be aligned, even though it 14547 // is actually offset from the base pointer by a lesser amount. 14548 int IncOffset = VT.getSizeInBits() / 8; 14549 int IncValue = IncOffset; 14550 14551 // Walk (both up and down) the chain looking for another load at the real 14552 // (aligned) offset (the alignment of the other load does not matter in 14553 // this case). If found, then do not use the offset reduction trick, as 14554 // that will prevent the loads from being later combined (as they would 14555 // otherwise be duplicates). 14556 if (!findConsecutiveLoad(LD, DAG)) 14557 --IncValue; 14558 14559 SDValue Increment = 14560 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14561 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14562 14563 MachineMemOperand *ExtraMMO = 14564 MF.getMachineMemOperand(LD->getMemOperand(), 14565 1, 2*MemVT.getStoreSize()-1); 14566 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14567 SDValue ExtraLoad = 14568 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14569 DAG.getVTList(PermTy, MVT::Other), 14570 ExtraLoadOps, LDTy, ExtraMMO); 14571 14572 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14573 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14574 14575 // Because vperm has a big-endian bias, we must reverse the order 14576 // of the input vectors and complement the permute control vector 14577 // when generating little endian code. We have already handled the 14578 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14579 // and ExtraLoad here. 14580 SDValue Perm; 14581 if (isLittleEndian) 14582 Perm = BuildIntrinsicOp(IntrPerm, 14583 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14584 else 14585 Perm = BuildIntrinsicOp(IntrPerm, 14586 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14587 14588 if (VT != PermTy) 14589 Perm = Subtarget.hasAltivec() 14590 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14591 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14592 DAG.getTargetConstant(1, dl, MVT::i64)); 14593 // second argument is 1 because this rounding 14594 // is always exact. 14595 14596 // The output of the permutation is our loaded result, the TokenFactor is 14597 // our new chain. 14598 DCI.CombineTo(N, Perm, TF); 14599 return SDValue(N, 0); 14600 } 14601 } 14602 break; 14603 case ISD::INTRINSIC_WO_CHAIN: { 14604 bool isLittleEndian = Subtarget.isLittleEndian(); 14605 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14606 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14607 : Intrinsic::ppc_altivec_lvsl); 14608 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14609 SDValue Add = N->getOperand(1); 14610 14611 int Bits = 4 /* 16 byte alignment */; 14612 14613 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14614 APInt::getAllOnesValue(Bits /* alignment */) 14615 .zext(Add.getScalarValueSizeInBits()))) { 14616 SDNode *BasePtr = Add->getOperand(0).getNode(); 14617 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14618 UE = BasePtr->use_end(); 14619 UI != UE; ++UI) { 14620 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14621 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14622 IID) { 14623 // We've found another LVSL/LVSR, and this address is an aligned 14624 // multiple of that one. The results will be the same, so use the 14625 // one we've just found instead. 14626 14627 return SDValue(*UI, 0); 14628 } 14629 } 14630 } 14631 14632 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14633 SDNode *BasePtr = Add->getOperand(0).getNode(); 14634 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14635 UE = BasePtr->use_end(); UI != UE; ++UI) { 14636 if (UI->getOpcode() == ISD::ADD && 14637 isa<ConstantSDNode>(UI->getOperand(1)) && 14638 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14639 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14640 (1ULL << Bits) == 0) { 14641 SDNode *OtherAdd = *UI; 14642 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14643 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14644 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14645 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14646 return SDValue(*VI, 0); 14647 } 14648 } 14649 } 14650 } 14651 } 14652 } 14653 14654 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14655 // Expose the vabsduw/h/b opportunity for down stream 14656 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14657 (IID == Intrinsic::ppc_altivec_vmaxsw || 14658 IID == Intrinsic::ppc_altivec_vmaxsh || 14659 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14660 SDValue V1 = N->getOperand(1); 14661 SDValue V2 = N->getOperand(2); 14662 if ((V1.getSimpleValueType() == MVT::v4i32 || 14663 V1.getSimpleValueType() == MVT::v8i16 || 14664 V1.getSimpleValueType() == MVT::v16i8) && 14665 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14666 // (0-a, a) 14667 if (V1.getOpcode() == ISD::SUB && 14668 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14669 V1.getOperand(1) == V2) { 14670 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14671 } 14672 // (a, 0-a) 14673 if (V2.getOpcode() == ISD::SUB && 14674 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14675 V2.getOperand(1) == V1) { 14676 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14677 } 14678 // (x-y, y-x) 14679 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14680 V1.getOperand(0) == V2.getOperand(1) && 14681 V1.getOperand(1) == V2.getOperand(0)) { 14682 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14683 } 14684 } 14685 } 14686 } 14687 14688 break; 14689 case ISD::INTRINSIC_W_CHAIN: 14690 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14691 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14692 if (Subtarget.needsSwapsForVSXMemOps()) { 14693 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14694 default: 14695 break; 14696 case Intrinsic::ppc_vsx_lxvw4x: 14697 case Intrinsic::ppc_vsx_lxvd2x: 14698 return expandVSXLoadForLE(N, DCI); 14699 } 14700 } 14701 break; 14702 case ISD::INTRINSIC_VOID: 14703 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14704 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14705 if (Subtarget.needsSwapsForVSXMemOps()) { 14706 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14707 default: 14708 break; 14709 case Intrinsic::ppc_vsx_stxvw4x: 14710 case Intrinsic::ppc_vsx_stxvd2x: 14711 return expandVSXStoreForLE(N, DCI); 14712 } 14713 } 14714 break; 14715 case ISD::BSWAP: 14716 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14717 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14718 N->getOperand(0).hasOneUse() && 14719 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14720 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14721 N->getValueType(0) == MVT::i64))) { 14722 SDValue Load = N->getOperand(0); 14723 LoadSDNode *LD = cast<LoadSDNode>(Load); 14724 // Create the byte-swapping load. 14725 SDValue Ops[] = { 14726 LD->getChain(), // Chain 14727 LD->getBasePtr(), // Ptr 14728 DAG.getValueType(N->getValueType(0)) // VT 14729 }; 14730 SDValue BSLoad = 14731 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14732 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14733 MVT::i64 : MVT::i32, MVT::Other), 14734 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14735 14736 // If this is an i16 load, insert the truncate. 14737 SDValue ResVal = BSLoad; 14738 if (N->getValueType(0) == MVT::i16) 14739 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14740 14741 // First, combine the bswap away. This makes the value produced by the 14742 // load dead. 14743 DCI.CombineTo(N, ResVal); 14744 14745 // Next, combine the load away, we give it a bogus result value but a real 14746 // chain result. The result value is dead because the bswap is dead. 14747 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14748 14749 // Return N so it doesn't get rechecked! 14750 return SDValue(N, 0); 14751 } 14752 break; 14753 case PPCISD::VCMP: 14754 // If a VCMPo node already exists with exactly the same operands as this 14755 // node, use its result instead of this node (VCMPo computes both a CR6 and 14756 // a normal output). 14757 // 14758 if (!N->getOperand(0).hasOneUse() && 14759 !N->getOperand(1).hasOneUse() && 14760 !N->getOperand(2).hasOneUse()) { 14761 14762 // Scan all of the users of the LHS, looking for VCMPo's that match. 14763 SDNode *VCMPoNode = nullptr; 14764 14765 SDNode *LHSN = N->getOperand(0).getNode(); 14766 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14767 UI != E; ++UI) 14768 if (UI->getOpcode() == PPCISD::VCMPo && 14769 UI->getOperand(1) == N->getOperand(1) && 14770 UI->getOperand(2) == N->getOperand(2) && 14771 UI->getOperand(0) == N->getOperand(0)) { 14772 VCMPoNode = *UI; 14773 break; 14774 } 14775 14776 // If there is no VCMPo node, or if the flag value has a single use, don't 14777 // transform this. 14778 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14779 break; 14780 14781 // Look at the (necessarily single) use of the flag value. If it has a 14782 // chain, this transformation is more complex. Note that multiple things 14783 // could use the value result, which we should ignore. 14784 SDNode *FlagUser = nullptr; 14785 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14786 FlagUser == nullptr; ++UI) { 14787 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14788 SDNode *User = *UI; 14789 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14790 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14791 FlagUser = User; 14792 break; 14793 } 14794 } 14795 } 14796 14797 // If the user is a MFOCRF instruction, we know this is safe. 14798 // Otherwise we give up for right now. 14799 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14800 return SDValue(VCMPoNode, 0); 14801 } 14802 break; 14803 case ISD::BRCOND: { 14804 SDValue Cond = N->getOperand(1); 14805 SDValue Target = N->getOperand(2); 14806 14807 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14808 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14809 Intrinsic::loop_decrement) { 14810 14811 // We now need to make the intrinsic dead (it cannot be instruction 14812 // selected). 14813 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14814 assert(Cond.getNode()->hasOneUse() && 14815 "Counter decrement has more than one use"); 14816 14817 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14818 N->getOperand(0), Target); 14819 } 14820 } 14821 break; 14822 case ISD::BR_CC: { 14823 // If this is a branch on an altivec predicate comparison, lower this so 14824 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14825 // lowering is done pre-legalize, because the legalizer lowers the predicate 14826 // compare down to code that is difficult to reassemble. 14827 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14828 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14829 14830 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14831 // value. If so, pass-through the AND to get to the intrinsic. 14832 if (LHS.getOpcode() == ISD::AND && 14833 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14834 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14835 Intrinsic::loop_decrement && 14836 isa<ConstantSDNode>(LHS.getOperand(1)) && 14837 !isNullConstant(LHS.getOperand(1))) 14838 LHS = LHS.getOperand(0); 14839 14840 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14841 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14842 Intrinsic::loop_decrement && 14843 isa<ConstantSDNode>(RHS)) { 14844 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14845 "Counter decrement comparison is not EQ or NE"); 14846 14847 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14848 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14849 (CC == ISD::SETNE && !Val); 14850 14851 // We now need to make the intrinsic dead (it cannot be instruction 14852 // selected). 14853 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14854 assert(LHS.getNode()->hasOneUse() && 14855 "Counter decrement has more than one use"); 14856 14857 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14858 N->getOperand(0), N->getOperand(4)); 14859 } 14860 14861 int CompareOpc; 14862 bool isDot; 14863 14864 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14865 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14866 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14867 assert(isDot && "Can't compare against a vector result!"); 14868 14869 // If this is a comparison against something other than 0/1, then we know 14870 // that the condition is never/always true. 14871 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14872 if (Val != 0 && Val != 1) { 14873 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14874 return N->getOperand(0); 14875 // Always !=, turn it into an unconditional branch. 14876 return DAG.getNode(ISD::BR, dl, MVT::Other, 14877 N->getOperand(0), N->getOperand(4)); 14878 } 14879 14880 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14881 14882 // Create the PPCISD altivec 'dot' comparison node. 14883 SDValue Ops[] = { 14884 LHS.getOperand(2), // LHS of compare 14885 LHS.getOperand(3), // RHS of compare 14886 DAG.getConstant(CompareOpc, dl, MVT::i32) 14887 }; 14888 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14889 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14890 14891 // Unpack the result based on how the target uses it. 14892 PPC::Predicate CompOpc; 14893 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14894 default: // Can't happen, don't crash on invalid number though. 14895 case 0: // Branch on the value of the EQ bit of CR6. 14896 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14897 break; 14898 case 1: // Branch on the inverted value of the EQ bit of CR6. 14899 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14900 break; 14901 case 2: // Branch on the value of the LT bit of CR6. 14902 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14903 break; 14904 case 3: // Branch on the inverted value of the LT bit of CR6. 14905 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14906 break; 14907 } 14908 14909 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14910 DAG.getConstant(CompOpc, dl, MVT::i32), 14911 DAG.getRegister(PPC::CR6, MVT::i32), 14912 N->getOperand(4), CompNode.getValue(1)); 14913 } 14914 break; 14915 } 14916 case ISD::BUILD_VECTOR: 14917 return DAGCombineBuildVector(N, DCI); 14918 case ISD::ABS: 14919 return combineABS(N, DCI); 14920 case ISD::VSELECT: 14921 return combineVSelect(N, DCI); 14922 } 14923 14924 return SDValue(); 14925 } 14926 14927 SDValue 14928 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14929 SelectionDAG &DAG, 14930 SmallVectorImpl<SDNode *> &Created) const { 14931 // fold (sdiv X, pow2) 14932 EVT VT = N->getValueType(0); 14933 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14934 return SDValue(); 14935 if ((VT != MVT::i32 && VT != MVT::i64) || 14936 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14937 return SDValue(); 14938 14939 SDLoc DL(N); 14940 SDValue N0 = N->getOperand(0); 14941 14942 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14943 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14944 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14945 14946 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14947 Created.push_back(Op.getNode()); 14948 14949 if (IsNegPow2) { 14950 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14951 Created.push_back(Op.getNode()); 14952 } 14953 14954 return Op; 14955 } 14956 14957 //===----------------------------------------------------------------------===// 14958 // Inline Assembly Support 14959 //===----------------------------------------------------------------------===// 14960 14961 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14962 KnownBits &Known, 14963 const APInt &DemandedElts, 14964 const SelectionDAG &DAG, 14965 unsigned Depth) const { 14966 Known.resetAll(); 14967 switch (Op.getOpcode()) { 14968 default: break; 14969 case PPCISD::LBRX: { 14970 // lhbrx is known to have the top bits cleared out. 14971 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14972 Known.Zero = 0xFFFF0000; 14973 break; 14974 } 14975 case ISD::INTRINSIC_WO_CHAIN: { 14976 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14977 default: break; 14978 case Intrinsic::ppc_altivec_vcmpbfp_p: 14979 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14980 case Intrinsic::ppc_altivec_vcmpequb_p: 14981 case Intrinsic::ppc_altivec_vcmpequh_p: 14982 case Intrinsic::ppc_altivec_vcmpequw_p: 14983 case Intrinsic::ppc_altivec_vcmpequd_p: 14984 case Intrinsic::ppc_altivec_vcmpgefp_p: 14985 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14986 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14987 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14988 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14989 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14990 case Intrinsic::ppc_altivec_vcmpgtub_p: 14991 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14992 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14993 case Intrinsic::ppc_altivec_vcmpgtud_p: 14994 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14995 break; 14996 } 14997 } 14998 } 14999 } 15000 15001 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15002 switch (Subtarget.getCPUDirective()) { 15003 default: break; 15004 case PPC::DIR_970: 15005 case PPC::DIR_PWR4: 15006 case PPC::DIR_PWR5: 15007 case PPC::DIR_PWR5X: 15008 case PPC::DIR_PWR6: 15009 case PPC::DIR_PWR6X: 15010 case PPC::DIR_PWR7: 15011 case PPC::DIR_PWR8: 15012 case PPC::DIR_PWR9: 15013 case PPC::DIR_PWR10: 15014 case PPC::DIR_PWR_FUTURE: { 15015 if (!ML) 15016 break; 15017 15018 if (!DisableInnermostLoopAlign32) { 15019 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15020 // so that we can decrease cache misses and branch-prediction misses. 15021 // Actual alignment of the loop will depend on the hotness check and other 15022 // logic in alignBlocks. 15023 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15024 return Align(32); 15025 } 15026 15027 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15028 15029 // For small loops (between 5 and 8 instructions), align to a 32-byte 15030 // boundary so that the entire loop fits in one instruction-cache line. 15031 uint64_t LoopSize = 0; 15032 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15033 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15034 LoopSize += TII->getInstSizeInBytes(*J); 15035 if (LoopSize > 32) 15036 break; 15037 } 15038 15039 if (LoopSize > 16 && LoopSize <= 32) 15040 return Align(32); 15041 15042 break; 15043 } 15044 } 15045 15046 return TargetLowering::getPrefLoopAlignment(ML); 15047 } 15048 15049 /// getConstraintType - Given a constraint, return the type of 15050 /// constraint it is for this target. 15051 PPCTargetLowering::ConstraintType 15052 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15053 if (Constraint.size() == 1) { 15054 switch (Constraint[0]) { 15055 default: break; 15056 case 'b': 15057 case 'r': 15058 case 'f': 15059 case 'd': 15060 case 'v': 15061 case 'y': 15062 return C_RegisterClass; 15063 case 'Z': 15064 // FIXME: While Z does indicate a memory constraint, it specifically 15065 // indicates an r+r address (used in conjunction with the 'y' modifier 15066 // in the replacement string). Currently, we're forcing the base 15067 // register to be r0 in the asm printer (which is interpreted as zero) 15068 // and forming the complete address in the second register. This is 15069 // suboptimal. 15070 return C_Memory; 15071 } 15072 } else if (Constraint == "wc") { // individual CR bits. 15073 return C_RegisterClass; 15074 } else if (Constraint == "wa" || Constraint == "wd" || 15075 Constraint == "wf" || Constraint == "ws" || 15076 Constraint == "wi" || Constraint == "ww") { 15077 return C_RegisterClass; // VSX registers. 15078 } 15079 return TargetLowering::getConstraintType(Constraint); 15080 } 15081 15082 /// Examine constraint type and operand type and determine a weight value. 15083 /// This object must already have been set up with the operand type 15084 /// and the current alternative constraint selected. 15085 TargetLowering::ConstraintWeight 15086 PPCTargetLowering::getSingleConstraintMatchWeight( 15087 AsmOperandInfo &info, const char *constraint) const { 15088 ConstraintWeight weight = CW_Invalid; 15089 Value *CallOperandVal = info.CallOperandVal; 15090 // If we don't have a value, we can't do a match, 15091 // but allow it at the lowest weight. 15092 if (!CallOperandVal) 15093 return CW_Default; 15094 Type *type = CallOperandVal->getType(); 15095 15096 // Look at the constraint type. 15097 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15098 return CW_Register; // an individual CR bit. 15099 else if ((StringRef(constraint) == "wa" || 15100 StringRef(constraint) == "wd" || 15101 StringRef(constraint) == "wf") && 15102 type->isVectorTy()) 15103 return CW_Register; 15104 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15105 return CW_Register; // just hold 64-bit integers data. 15106 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15107 return CW_Register; 15108 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15109 return CW_Register; 15110 15111 switch (*constraint) { 15112 default: 15113 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15114 break; 15115 case 'b': 15116 if (type->isIntegerTy()) 15117 weight = CW_Register; 15118 break; 15119 case 'f': 15120 if (type->isFloatTy()) 15121 weight = CW_Register; 15122 break; 15123 case 'd': 15124 if (type->isDoubleTy()) 15125 weight = CW_Register; 15126 break; 15127 case 'v': 15128 if (type->isVectorTy()) 15129 weight = CW_Register; 15130 break; 15131 case 'y': 15132 weight = CW_Register; 15133 break; 15134 case 'Z': 15135 weight = CW_Memory; 15136 break; 15137 } 15138 return weight; 15139 } 15140 15141 std::pair<unsigned, const TargetRegisterClass *> 15142 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15143 StringRef Constraint, 15144 MVT VT) const { 15145 if (Constraint.size() == 1) { 15146 // GCC RS6000 Constraint Letters 15147 switch (Constraint[0]) { 15148 case 'b': // R1-R31 15149 if (VT == MVT::i64 && Subtarget.isPPC64()) 15150 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15151 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15152 case 'r': // R0-R31 15153 if (VT == MVT::i64 && Subtarget.isPPC64()) 15154 return std::make_pair(0U, &PPC::G8RCRegClass); 15155 return std::make_pair(0U, &PPC::GPRCRegClass); 15156 // 'd' and 'f' constraints are both defined to be "the floating point 15157 // registers", where one is for 32-bit and the other for 64-bit. We don't 15158 // really care overly much here so just give them all the same reg classes. 15159 case 'd': 15160 case 'f': 15161 if (Subtarget.hasSPE()) { 15162 if (VT == MVT::f32 || VT == MVT::i32) 15163 return std::make_pair(0U, &PPC::GPRCRegClass); 15164 if (VT == MVT::f64 || VT == MVT::i64) 15165 return std::make_pair(0U, &PPC::SPERCRegClass); 15166 } else { 15167 if (VT == MVT::f32 || VT == MVT::i32) 15168 return std::make_pair(0U, &PPC::F4RCRegClass); 15169 if (VT == MVT::f64 || VT == MVT::i64) 15170 return std::make_pair(0U, &PPC::F8RCRegClass); 15171 } 15172 break; 15173 case 'v': 15174 if (Subtarget.hasAltivec()) 15175 return std::make_pair(0U, &PPC::VRRCRegClass); 15176 break; 15177 case 'y': // crrc 15178 return std::make_pair(0U, &PPC::CRRCRegClass); 15179 } 15180 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15181 // An individual CR bit. 15182 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15183 } else if ((Constraint == "wa" || Constraint == "wd" || 15184 Constraint == "wf" || Constraint == "wi") && 15185 Subtarget.hasVSX()) { 15186 return std::make_pair(0U, &PPC::VSRCRegClass); 15187 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15188 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15189 return std::make_pair(0U, &PPC::VSSRCRegClass); 15190 else 15191 return std::make_pair(0U, &PPC::VSFRCRegClass); 15192 } 15193 15194 // If we name a VSX register, we can't defer to the base class because it 15195 // will not recognize the correct register (their names will be VSL{0-31} 15196 // and V{0-31} so they won't match). So we match them here. 15197 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15198 int VSNum = atoi(Constraint.data() + 3); 15199 assert(VSNum >= 0 && VSNum <= 63 && 15200 "Attempted to access a vsr out of range"); 15201 if (VSNum < 32) 15202 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15203 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15204 } 15205 std::pair<unsigned, const TargetRegisterClass *> R = 15206 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15207 15208 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15209 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15210 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15211 // register. 15212 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15213 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15214 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15215 PPC::GPRCRegClass.contains(R.first)) 15216 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15217 PPC::sub_32, &PPC::G8RCRegClass), 15218 &PPC::G8RCRegClass); 15219 15220 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15221 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15222 R.first = PPC::CR0; 15223 R.second = &PPC::CRRCRegClass; 15224 } 15225 15226 return R; 15227 } 15228 15229 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15230 /// vector. If it is invalid, don't add anything to Ops. 15231 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15232 std::string &Constraint, 15233 std::vector<SDValue>&Ops, 15234 SelectionDAG &DAG) const { 15235 SDValue Result; 15236 15237 // Only support length 1 constraints. 15238 if (Constraint.length() > 1) return; 15239 15240 char Letter = Constraint[0]; 15241 switch (Letter) { 15242 default: break; 15243 case 'I': 15244 case 'J': 15245 case 'K': 15246 case 'L': 15247 case 'M': 15248 case 'N': 15249 case 'O': 15250 case 'P': { 15251 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15252 if (!CST) return; // Must be an immediate to match. 15253 SDLoc dl(Op); 15254 int64_t Value = CST->getSExtValue(); 15255 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15256 // numbers are printed as such. 15257 switch (Letter) { 15258 default: llvm_unreachable("Unknown constraint letter!"); 15259 case 'I': // "I" is a signed 16-bit constant. 15260 if (isInt<16>(Value)) 15261 Result = DAG.getTargetConstant(Value, dl, TCVT); 15262 break; 15263 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15264 if (isShiftedUInt<16, 16>(Value)) 15265 Result = DAG.getTargetConstant(Value, dl, TCVT); 15266 break; 15267 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15268 if (isShiftedInt<16, 16>(Value)) 15269 Result = DAG.getTargetConstant(Value, dl, TCVT); 15270 break; 15271 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15272 if (isUInt<16>(Value)) 15273 Result = DAG.getTargetConstant(Value, dl, TCVT); 15274 break; 15275 case 'M': // "M" is a constant that is greater than 31. 15276 if (Value > 31) 15277 Result = DAG.getTargetConstant(Value, dl, TCVT); 15278 break; 15279 case 'N': // "N" is a positive constant that is an exact power of two. 15280 if (Value > 0 && isPowerOf2_64(Value)) 15281 Result = DAG.getTargetConstant(Value, dl, TCVT); 15282 break; 15283 case 'O': // "O" is the constant zero. 15284 if (Value == 0) 15285 Result = DAG.getTargetConstant(Value, dl, TCVT); 15286 break; 15287 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15288 if (isInt<16>(-Value)) 15289 Result = DAG.getTargetConstant(Value, dl, TCVT); 15290 break; 15291 } 15292 break; 15293 } 15294 } 15295 15296 if (Result.getNode()) { 15297 Ops.push_back(Result); 15298 return; 15299 } 15300 15301 // Handle standard constraint letters. 15302 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15303 } 15304 15305 // isLegalAddressingMode - Return true if the addressing mode represented 15306 // by AM is legal for this target, for a load/store of the specified type. 15307 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15308 const AddrMode &AM, Type *Ty, 15309 unsigned AS, 15310 Instruction *I) const { 15311 // Vector type r+i form is supported since power9 as DQ form. We don't check 15312 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15313 // imm form is preferred and the offset can be adjusted to use imm form later 15314 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15315 // max offset to check legal addressing mode, we should be a little aggressive 15316 // to contain other offsets for that LSRUse. 15317 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15318 return false; 15319 15320 // PPC allows a sign-extended 16-bit immediate field. 15321 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15322 return false; 15323 15324 // No global is ever allowed as a base. 15325 if (AM.BaseGV) 15326 return false; 15327 15328 // PPC only support r+r, 15329 switch (AM.Scale) { 15330 case 0: // "r+i" or just "i", depending on HasBaseReg. 15331 break; 15332 case 1: 15333 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15334 return false; 15335 // Otherwise we have r+r or r+i. 15336 break; 15337 case 2: 15338 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15339 return false; 15340 // Allow 2*r as r+r. 15341 break; 15342 default: 15343 // No other scales are supported. 15344 return false; 15345 } 15346 15347 return true; 15348 } 15349 15350 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15351 SelectionDAG &DAG) const { 15352 MachineFunction &MF = DAG.getMachineFunction(); 15353 MachineFrameInfo &MFI = MF.getFrameInfo(); 15354 MFI.setReturnAddressIsTaken(true); 15355 15356 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15357 return SDValue(); 15358 15359 SDLoc dl(Op); 15360 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15361 15362 // Make sure the function does not optimize away the store of the RA to 15363 // the stack. 15364 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15365 FuncInfo->setLRStoreRequired(); 15366 bool isPPC64 = Subtarget.isPPC64(); 15367 auto PtrVT = getPointerTy(MF.getDataLayout()); 15368 15369 if (Depth > 0) { 15370 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15371 SDValue Offset = 15372 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15373 isPPC64 ? MVT::i64 : MVT::i32); 15374 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15375 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15376 MachinePointerInfo()); 15377 } 15378 15379 // Just load the return address off the stack. 15380 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15381 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15382 MachinePointerInfo()); 15383 } 15384 15385 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15386 SelectionDAG &DAG) const { 15387 SDLoc dl(Op); 15388 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15389 15390 MachineFunction &MF = DAG.getMachineFunction(); 15391 MachineFrameInfo &MFI = MF.getFrameInfo(); 15392 MFI.setFrameAddressIsTaken(true); 15393 15394 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15395 bool isPPC64 = PtrVT == MVT::i64; 15396 15397 // Naked functions never have a frame pointer, and so we use r1. For all 15398 // other functions, this decision must be delayed until during PEI. 15399 unsigned FrameReg; 15400 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15401 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15402 else 15403 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15404 15405 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15406 PtrVT); 15407 while (Depth--) 15408 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15409 FrameAddr, MachinePointerInfo()); 15410 return FrameAddr; 15411 } 15412 15413 // FIXME? Maybe this could be a TableGen attribute on some registers and 15414 // this table could be generated automatically from RegInfo. 15415 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15416 const MachineFunction &MF) const { 15417 bool isPPC64 = Subtarget.isPPC64(); 15418 15419 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15420 if (!is64Bit && VT != LLT::scalar(32)) 15421 report_fatal_error("Invalid register global variable type"); 15422 15423 Register Reg = StringSwitch<Register>(RegName) 15424 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15425 .Case("r2", isPPC64 ? Register() : PPC::R2) 15426 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15427 .Default(Register()); 15428 15429 if (Reg) 15430 return Reg; 15431 report_fatal_error("Invalid register name global variable"); 15432 } 15433 15434 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15435 // 32-bit SVR4 ABI access everything as got-indirect. 15436 if (Subtarget.is32BitELFABI()) 15437 return true; 15438 15439 // AIX accesses everything indirectly through the TOC, which is similar to 15440 // the GOT. 15441 if (Subtarget.isAIXABI()) 15442 return true; 15443 15444 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15445 // If it is small or large code model, module locals are accessed 15446 // indirectly by loading their address from .toc/.got. 15447 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15448 return true; 15449 15450 // JumpTable and BlockAddress are accessed as got-indirect. 15451 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15452 return true; 15453 15454 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15455 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15456 15457 return false; 15458 } 15459 15460 bool 15461 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15462 // The PowerPC target isn't yet aware of offsets. 15463 return false; 15464 } 15465 15466 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15467 const CallInst &I, 15468 MachineFunction &MF, 15469 unsigned Intrinsic) const { 15470 switch (Intrinsic) { 15471 case Intrinsic::ppc_altivec_lvx: 15472 case Intrinsic::ppc_altivec_lvxl: 15473 case Intrinsic::ppc_altivec_lvebx: 15474 case Intrinsic::ppc_altivec_lvehx: 15475 case Intrinsic::ppc_altivec_lvewx: 15476 case Intrinsic::ppc_vsx_lxvd2x: 15477 case Intrinsic::ppc_vsx_lxvw4x: { 15478 EVT VT; 15479 switch (Intrinsic) { 15480 case Intrinsic::ppc_altivec_lvebx: 15481 VT = MVT::i8; 15482 break; 15483 case Intrinsic::ppc_altivec_lvehx: 15484 VT = MVT::i16; 15485 break; 15486 case Intrinsic::ppc_altivec_lvewx: 15487 VT = MVT::i32; 15488 break; 15489 case Intrinsic::ppc_vsx_lxvd2x: 15490 VT = MVT::v2f64; 15491 break; 15492 default: 15493 VT = MVT::v4i32; 15494 break; 15495 } 15496 15497 Info.opc = ISD::INTRINSIC_W_CHAIN; 15498 Info.memVT = VT; 15499 Info.ptrVal = I.getArgOperand(0); 15500 Info.offset = -VT.getStoreSize()+1; 15501 Info.size = 2*VT.getStoreSize()-1; 15502 Info.align = Align(1); 15503 Info.flags = MachineMemOperand::MOLoad; 15504 return true; 15505 } 15506 case Intrinsic::ppc_altivec_stvx: 15507 case Intrinsic::ppc_altivec_stvxl: 15508 case Intrinsic::ppc_altivec_stvebx: 15509 case Intrinsic::ppc_altivec_stvehx: 15510 case Intrinsic::ppc_altivec_stvewx: 15511 case Intrinsic::ppc_vsx_stxvd2x: 15512 case Intrinsic::ppc_vsx_stxvw4x: { 15513 EVT VT; 15514 switch (Intrinsic) { 15515 case Intrinsic::ppc_altivec_stvebx: 15516 VT = MVT::i8; 15517 break; 15518 case Intrinsic::ppc_altivec_stvehx: 15519 VT = MVT::i16; 15520 break; 15521 case Intrinsic::ppc_altivec_stvewx: 15522 VT = MVT::i32; 15523 break; 15524 case Intrinsic::ppc_vsx_stxvd2x: 15525 VT = MVT::v2f64; 15526 break; 15527 default: 15528 VT = MVT::v4i32; 15529 break; 15530 } 15531 15532 Info.opc = ISD::INTRINSIC_VOID; 15533 Info.memVT = VT; 15534 Info.ptrVal = I.getArgOperand(1); 15535 Info.offset = -VT.getStoreSize()+1; 15536 Info.size = 2*VT.getStoreSize()-1; 15537 Info.align = Align(1); 15538 Info.flags = MachineMemOperand::MOStore; 15539 return true; 15540 } 15541 default: 15542 break; 15543 } 15544 15545 return false; 15546 } 15547 15548 /// It returns EVT::Other if the type should be determined using generic 15549 /// target-independent logic. 15550 EVT PPCTargetLowering::getOptimalMemOpType( 15551 const MemOp &Op, const AttributeList &FuncAttributes) const { 15552 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15553 // We should use Altivec/VSX loads and stores when available. For unaligned 15554 // addresses, unaligned VSX loads are only fast starting with the P8. 15555 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15556 (Op.isAligned(Align(16)) || 15557 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15558 return MVT::v4i32; 15559 } 15560 15561 if (Subtarget.isPPC64()) { 15562 return MVT::i64; 15563 } 15564 15565 return MVT::i32; 15566 } 15567 15568 /// Returns true if it is beneficial to convert a load of a constant 15569 /// to just the constant itself. 15570 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15571 Type *Ty) const { 15572 assert(Ty->isIntegerTy()); 15573 15574 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15575 return !(BitSize == 0 || BitSize > 64); 15576 } 15577 15578 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15579 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15580 return false; 15581 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15582 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15583 return NumBits1 == 64 && NumBits2 == 32; 15584 } 15585 15586 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15587 if (!VT1.isInteger() || !VT2.isInteger()) 15588 return false; 15589 unsigned NumBits1 = VT1.getSizeInBits(); 15590 unsigned NumBits2 = VT2.getSizeInBits(); 15591 return NumBits1 == 64 && NumBits2 == 32; 15592 } 15593 15594 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15595 // Generally speaking, zexts are not free, but they are free when they can be 15596 // folded with other operations. 15597 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15598 EVT MemVT = LD->getMemoryVT(); 15599 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15600 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15601 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15602 LD->getExtensionType() == ISD::ZEXTLOAD)) 15603 return true; 15604 } 15605 15606 // FIXME: Add other cases... 15607 // - 32-bit shifts with a zext to i64 15608 // - zext after ctlz, bswap, etc. 15609 // - zext after and by a constant mask 15610 15611 return TargetLowering::isZExtFree(Val, VT2); 15612 } 15613 15614 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15615 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15616 "invalid fpext types"); 15617 // Extending to float128 is not free. 15618 if (DestVT == MVT::f128) 15619 return false; 15620 return true; 15621 } 15622 15623 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15624 return isInt<16>(Imm) || isUInt<16>(Imm); 15625 } 15626 15627 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15628 return isInt<16>(Imm) || isUInt<16>(Imm); 15629 } 15630 15631 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15632 unsigned, 15633 unsigned, 15634 MachineMemOperand::Flags, 15635 bool *Fast) const { 15636 if (DisablePPCUnaligned) 15637 return false; 15638 15639 // PowerPC supports unaligned memory access for simple non-vector types. 15640 // Although accessing unaligned addresses is not as efficient as accessing 15641 // aligned addresses, it is generally more efficient than manual expansion, 15642 // and generally only traps for software emulation when crossing page 15643 // boundaries. 15644 15645 if (!VT.isSimple()) 15646 return false; 15647 15648 if (VT.isFloatingPoint() && !VT.isVector() && 15649 !Subtarget.allowsUnalignedFPAccess()) 15650 return false; 15651 15652 if (VT.getSimpleVT().isVector()) { 15653 if (Subtarget.hasVSX()) { 15654 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15655 VT != MVT::v4f32 && VT != MVT::v4i32) 15656 return false; 15657 } else { 15658 return false; 15659 } 15660 } 15661 15662 if (VT == MVT::ppcf128) 15663 return false; 15664 15665 if (Fast) 15666 *Fast = true; 15667 15668 return true; 15669 } 15670 15671 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15672 EVT VT) const { 15673 return isFMAFasterThanFMulAndFAdd( 15674 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15675 } 15676 15677 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15678 Type *Ty) const { 15679 switch (Ty->getScalarType()->getTypeID()) { 15680 case Type::FloatTyID: 15681 case Type::DoubleTyID: 15682 return true; 15683 case Type::FP128TyID: 15684 return Subtarget.hasP9Vector(); 15685 default: 15686 return false; 15687 } 15688 } 15689 15690 // FIXME: add more patterns which are not profitable to hoist. 15691 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15692 if (!I->hasOneUse()) 15693 return true; 15694 15695 Instruction *User = I->user_back(); 15696 assert(User && "A single use instruction with no uses."); 15697 15698 switch (I->getOpcode()) { 15699 case Instruction::FMul: { 15700 // Don't break FMA, PowerPC prefers FMA. 15701 if (User->getOpcode() != Instruction::FSub && 15702 User->getOpcode() != Instruction::FAdd) 15703 return true; 15704 15705 const TargetOptions &Options = getTargetMachine().Options; 15706 const Function *F = I->getFunction(); 15707 const DataLayout &DL = F->getParent()->getDataLayout(); 15708 Type *Ty = User->getOperand(0)->getType(); 15709 15710 return !( 15711 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15712 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15713 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15714 } 15715 case Instruction::Load: { 15716 // Don't break "store (load float*)" pattern, this pattern will be combined 15717 // to "store (load int32)" in later InstCombine pass. See function 15718 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15719 // cycles than loading a 32 bit integer. 15720 LoadInst *LI = cast<LoadInst>(I); 15721 // For the loads that combineLoadToOperationType does nothing, like 15722 // ordered load, it should be profitable to hoist them. 15723 // For swifterror load, it can only be used for pointer to pointer type, so 15724 // later type check should get rid of this case. 15725 if (!LI->isUnordered()) 15726 return true; 15727 15728 if (User->getOpcode() != Instruction::Store) 15729 return true; 15730 15731 if (I->getType()->getTypeID() != Type::FloatTyID) 15732 return true; 15733 15734 return false; 15735 } 15736 default: 15737 return true; 15738 } 15739 return true; 15740 } 15741 15742 const MCPhysReg * 15743 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15744 // LR is a callee-save register, but we must treat it as clobbered by any call 15745 // site. Hence we include LR in the scratch registers, which are in turn added 15746 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15747 // to CTR, which is used by any indirect call. 15748 static const MCPhysReg ScratchRegs[] = { 15749 PPC::X12, PPC::LR8, PPC::CTR8, 0 15750 }; 15751 15752 return ScratchRegs; 15753 } 15754 15755 Register PPCTargetLowering::getExceptionPointerRegister( 15756 const Constant *PersonalityFn) const { 15757 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15758 } 15759 15760 Register PPCTargetLowering::getExceptionSelectorRegister( 15761 const Constant *PersonalityFn) const { 15762 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15763 } 15764 15765 bool 15766 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15767 EVT VT , unsigned DefinedValues) const { 15768 if (VT == MVT::v2i64) 15769 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15770 15771 if (Subtarget.hasVSX()) 15772 return true; 15773 15774 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15775 } 15776 15777 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15778 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15779 return TargetLowering::getSchedulingPreference(N); 15780 15781 return Sched::ILP; 15782 } 15783 15784 // Create a fast isel object. 15785 FastISel * 15786 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15787 const TargetLibraryInfo *LibInfo) const { 15788 return PPC::createFastISel(FuncInfo, LibInfo); 15789 } 15790 15791 // 'Inverted' means the FMA opcode after negating one multiplicand. 15792 // For example, (fma -a b c) = (fnmsub a b c) 15793 static unsigned invertFMAOpcode(unsigned Opc) { 15794 switch (Opc) { 15795 default: 15796 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15797 case ISD::FMA: 15798 return PPCISD::FNMSUB; 15799 case PPCISD::FNMSUB: 15800 return ISD::FMA; 15801 } 15802 } 15803 15804 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15805 bool LegalOps, bool OptForSize, 15806 NegatibleCost &Cost, 15807 unsigned Depth) const { 15808 if (Depth > SelectionDAG::MaxRecursionDepth) 15809 return SDValue(); 15810 15811 unsigned Opc = Op.getOpcode(); 15812 EVT VT = Op.getValueType(); 15813 SDNodeFlags Flags = Op.getNode()->getFlags(); 15814 15815 switch (Opc) { 15816 case PPCISD::FNMSUB: 15817 if (!Op.hasOneUse() || !isTypeLegal(VT)) 15818 break; 15819 15820 const TargetOptions &Options = getTargetMachine().Options; 15821 SDValue N0 = Op.getOperand(0); 15822 SDValue N1 = Op.getOperand(1); 15823 SDValue N2 = Op.getOperand(2); 15824 SDLoc Loc(Op); 15825 15826 NegatibleCost N2Cost = NegatibleCost::Expensive; 15827 SDValue NegN2 = 15828 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 15829 15830 if (!NegN2) 15831 return SDValue(); 15832 15833 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 15834 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 15835 // These transformations may change sign of zeroes. For example, 15836 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 15837 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 15838 // Try and choose the cheaper one to negate. 15839 NegatibleCost N0Cost = NegatibleCost::Expensive; 15840 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 15841 N0Cost, Depth + 1); 15842 15843 NegatibleCost N1Cost = NegatibleCost::Expensive; 15844 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 15845 N1Cost, Depth + 1); 15846 15847 if (NegN0 && N0Cost <= N1Cost) { 15848 Cost = std::min(N0Cost, N2Cost); 15849 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 15850 } else if (NegN1) { 15851 Cost = std::min(N1Cost, N2Cost); 15852 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 15853 } 15854 } 15855 15856 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 15857 if (isOperationLegal(ISD::FMA, VT)) { 15858 Cost = N2Cost; 15859 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 15860 } 15861 15862 break; 15863 } 15864 15865 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 15866 Cost, Depth); 15867 } 15868 15869 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15870 bool PPCTargetLowering::useLoadStackGuardNode() const { 15871 if (!Subtarget.isTargetLinux()) 15872 return TargetLowering::useLoadStackGuardNode(); 15873 return true; 15874 } 15875 15876 // Override to disable global variable loading on Linux. 15877 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15878 if (!Subtarget.isTargetLinux()) 15879 return TargetLowering::insertSSPDeclarations(M); 15880 } 15881 15882 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15883 bool ForCodeSize) const { 15884 if (!VT.isSimple() || !Subtarget.hasVSX()) 15885 return false; 15886 15887 switch(VT.getSimpleVT().SimpleTy) { 15888 default: 15889 // For FP types that are currently not supported by PPC backend, return 15890 // false. Examples: f16, f80. 15891 return false; 15892 case MVT::f32: 15893 case MVT::f64: 15894 if (Subtarget.hasPrefixInstrs()) { 15895 // With prefixed instructions, we can materialize anything that can be 15896 // represented with a 32-bit immediate, not just positive zero. 15897 APFloat APFloatOfImm = Imm; 15898 return convertToNonDenormSingle(APFloatOfImm); 15899 } 15900 LLVM_FALLTHROUGH; 15901 case MVT::ppcf128: 15902 return Imm.isPosZero(); 15903 } 15904 } 15905 15906 // For vector shift operation op, fold 15907 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15908 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15909 SelectionDAG &DAG) { 15910 SDValue N0 = N->getOperand(0); 15911 SDValue N1 = N->getOperand(1); 15912 EVT VT = N0.getValueType(); 15913 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15914 unsigned Opcode = N->getOpcode(); 15915 unsigned TargetOpcode; 15916 15917 switch (Opcode) { 15918 default: 15919 llvm_unreachable("Unexpected shift operation"); 15920 case ISD::SHL: 15921 TargetOpcode = PPCISD::SHL; 15922 break; 15923 case ISD::SRL: 15924 TargetOpcode = PPCISD::SRL; 15925 break; 15926 case ISD::SRA: 15927 TargetOpcode = PPCISD::SRA; 15928 break; 15929 } 15930 15931 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15932 N1->getOpcode() == ISD::AND) 15933 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15934 if (Mask->getZExtValue() == OpSizeInBits - 1) 15935 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15936 15937 return SDValue(); 15938 } 15939 15940 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15941 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15942 return Value; 15943 15944 SDValue N0 = N->getOperand(0); 15945 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15946 if (!Subtarget.isISA3_0() || 15947 N0.getOpcode() != ISD::SIGN_EXTEND || 15948 N0.getOperand(0).getValueType() != MVT::i32 || 15949 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15950 return SDValue(); 15951 15952 // We can't save an operation here if the value is already extended, and 15953 // the existing shift is easier to combine. 15954 SDValue ExtsSrc = N0.getOperand(0); 15955 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15956 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15957 return SDValue(); 15958 15959 SDLoc DL(N0); 15960 SDValue ShiftBy = SDValue(CN1, 0); 15961 // We want the shift amount to be i32 on the extswli, but the shift could 15962 // have an i64. 15963 if (ShiftBy.getValueType() == MVT::i64) 15964 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15965 15966 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15967 ShiftBy); 15968 } 15969 15970 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15971 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15972 return Value; 15973 15974 return SDValue(); 15975 } 15976 15977 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15978 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15979 return Value; 15980 15981 return SDValue(); 15982 } 15983 15984 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15985 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15986 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15987 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15988 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15989 const PPCSubtarget &Subtarget) { 15990 if (!Subtarget.isPPC64()) 15991 return SDValue(); 15992 15993 SDValue LHS = N->getOperand(0); 15994 SDValue RHS = N->getOperand(1); 15995 15996 auto isZextOfCompareWithConstant = [](SDValue Op) { 15997 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15998 Op.getValueType() != MVT::i64) 15999 return false; 16000 16001 SDValue Cmp = Op.getOperand(0); 16002 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16003 Cmp.getOperand(0).getValueType() != MVT::i64) 16004 return false; 16005 16006 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16007 int64_t NegConstant = 0 - Constant->getSExtValue(); 16008 // Due to the limitations of the addi instruction, 16009 // -C is required to be [-32768, 32767]. 16010 return isInt<16>(NegConstant); 16011 } 16012 16013 return false; 16014 }; 16015 16016 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16017 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16018 16019 // If there is a pattern, canonicalize a zext operand to the RHS. 16020 if (LHSHasPattern && !RHSHasPattern) 16021 std::swap(LHS, RHS); 16022 else if (!LHSHasPattern && !RHSHasPattern) 16023 return SDValue(); 16024 16025 SDLoc DL(N); 16026 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16027 SDValue Cmp = RHS.getOperand(0); 16028 SDValue Z = Cmp.getOperand(0); 16029 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16030 16031 assert(Constant && "Constant Should not be a null pointer."); 16032 int64_t NegConstant = 0 - Constant->getSExtValue(); 16033 16034 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16035 default: break; 16036 case ISD::SETNE: { 16037 // when C == 0 16038 // --> addze X, (addic Z, -1).carry 16039 // / 16040 // add X, (zext(setne Z, C))-- 16041 // \ when -32768 <= -C <= 32767 && C != 0 16042 // --> addze X, (addic (addi Z, -C), -1).carry 16043 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16044 DAG.getConstant(NegConstant, DL, MVT::i64)); 16045 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16046 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16047 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16048 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16049 SDValue(Addc.getNode(), 1)); 16050 } 16051 case ISD::SETEQ: { 16052 // when C == 0 16053 // --> addze X, (subfic Z, 0).carry 16054 // / 16055 // add X, (zext(sete Z, C))-- 16056 // \ when -32768 <= -C <= 32767 && C != 0 16057 // --> addze X, (subfic (addi Z, -C), 0).carry 16058 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16059 DAG.getConstant(NegConstant, DL, MVT::i64)); 16060 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16061 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16062 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16063 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16064 SDValue(Subc.getNode(), 1)); 16065 } 16066 } 16067 16068 return SDValue(); 16069 } 16070 16071 // Transform 16072 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16073 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16074 // In this case both C1 and C2 must be known constants. 16075 // C1+C2 must fit into a 34 bit signed integer. 16076 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16077 const PPCSubtarget &Subtarget) { 16078 if (!Subtarget.isUsingPCRelativeCalls()) 16079 return SDValue(); 16080 16081 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16082 // If we find that node try to cast the Global Address and the Constant. 16083 SDValue LHS = N->getOperand(0); 16084 SDValue RHS = N->getOperand(1); 16085 16086 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16087 std::swap(LHS, RHS); 16088 16089 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16090 return SDValue(); 16091 16092 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16093 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16094 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16095 16096 // Check that both casts succeeded. 16097 if (!GSDN || !ConstNode) 16098 return SDValue(); 16099 16100 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16101 SDLoc DL(GSDN); 16102 16103 // The signed int offset needs to fit in 34 bits. 16104 if (!isInt<34>(NewOffset)) 16105 return SDValue(); 16106 16107 // The new global address is a copy of the old global address except 16108 // that it has the updated Offset. 16109 SDValue GA = 16110 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16111 NewOffset, GSDN->getTargetFlags()); 16112 SDValue MatPCRel = 16113 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16114 return MatPCRel; 16115 } 16116 16117 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16118 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16119 return Value; 16120 16121 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16122 return Value; 16123 16124 return SDValue(); 16125 } 16126 16127 // Detect TRUNCATE operations on bitcasts of float128 values. 16128 // What we are looking for here is the situtation where we extract a subset 16129 // of bits from a 128 bit float. 16130 // This can be of two forms: 16131 // 1) BITCAST of f128 feeding TRUNCATE 16132 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16133 // The reason this is required is because we do not have a legal i128 type 16134 // and so we want to prevent having to store the f128 and then reload part 16135 // of it. 16136 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16137 DAGCombinerInfo &DCI) const { 16138 // If we are using CRBits then try that first. 16139 if (Subtarget.useCRBits()) { 16140 // Check if CRBits did anything and return that if it did. 16141 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16142 return CRTruncValue; 16143 } 16144 16145 SDLoc dl(N); 16146 SDValue Op0 = N->getOperand(0); 16147 16148 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16149 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16150 EVT VT = N->getValueType(0); 16151 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16152 return SDValue(); 16153 SDValue Sub = Op0.getOperand(0); 16154 if (Sub.getOpcode() == ISD::SUB) { 16155 SDValue SubOp0 = Sub.getOperand(0); 16156 SDValue SubOp1 = Sub.getOperand(1); 16157 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16158 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16159 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16160 SubOp1.getOperand(0), 16161 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16162 } 16163 } 16164 } 16165 16166 // Looking for a truncate of i128 to i64. 16167 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16168 return SDValue(); 16169 16170 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16171 16172 // SRL feeding TRUNCATE. 16173 if (Op0.getOpcode() == ISD::SRL) { 16174 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16175 // The right shift has to be by 64 bits. 16176 if (!ConstNode || ConstNode->getZExtValue() != 64) 16177 return SDValue(); 16178 16179 // Switch the element number to extract. 16180 EltToExtract = EltToExtract ? 0 : 1; 16181 // Update Op0 past the SRL. 16182 Op0 = Op0.getOperand(0); 16183 } 16184 16185 // BITCAST feeding a TRUNCATE possibly via SRL. 16186 if (Op0.getOpcode() == ISD::BITCAST && 16187 Op0.getValueType() == MVT::i128 && 16188 Op0.getOperand(0).getValueType() == MVT::f128) { 16189 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16190 return DCI.DAG.getNode( 16191 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16192 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16193 } 16194 return SDValue(); 16195 } 16196 16197 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16198 SelectionDAG &DAG = DCI.DAG; 16199 16200 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16201 if (!ConstOpOrElement) 16202 return SDValue(); 16203 16204 // An imul is usually smaller than the alternative sequence for legal type. 16205 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16206 isOperationLegal(ISD::MUL, N->getValueType(0))) 16207 return SDValue(); 16208 16209 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16210 switch (this->Subtarget.getCPUDirective()) { 16211 default: 16212 // TODO: enhance the condition for subtarget before pwr8 16213 return false; 16214 case PPC::DIR_PWR8: 16215 // type mul add shl 16216 // scalar 4 1 1 16217 // vector 7 2 2 16218 return true; 16219 case PPC::DIR_PWR9: 16220 case PPC::DIR_PWR10: 16221 case PPC::DIR_PWR_FUTURE: 16222 // type mul add shl 16223 // scalar 5 2 2 16224 // vector 7 2 2 16225 16226 // The cycle RATIO of related operations are showed as a table above. 16227 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16228 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16229 // are 4, it is always profitable; but for 3 instrs patterns 16230 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16231 // So we should only do it for vector type. 16232 return IsAddOne && IsNeg ? VT.isVector() : true; 16233 } 16234 }; 16235 16236 EVT VT = N->getValueType(0); 16237 SDLoc DL(N); 16238 16239 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16240 bool IsNeg = MulAmt.isNegative(); 16241 APInt MulAmtAbs = MulAmt.abs(); 16242 16243 if ((MulAmtAbs - 1).isPowerOf2()) { 16244 // (mul x, 2^N + 1) => (add (shl x, N), x) 16245 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16246 16247 if (!IsProfitable(IsNeg, true, VT)) 16248 return SDValue(); 16249 16250 SDValue Op0 = N->getOperand(0); 16251 SDValue Op1 = 16252 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16253 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16254 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16255 16256 if (!IsNeg) 16257 return Res; 16258 16259 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16260 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16261 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16262 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16263 16264 if (!IsProfitable(IsNeg, false, VT)) 16265 return SDValue(); 16266 16267 SDValue Op0 = N->getOperand(0); 16268 SDValue Op1 = 16269 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16270 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16271 16272 if (!IsNeg) 16273 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16274 else 16275 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16276 16277 } else { 16278 return SDValue(); 16279 } 16280 } 16281 16282 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16283 // in combiner since we need to check SD flags and other subtarget features. 16284 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16285 DAGCombinerInfo &DCI) const { 16286 SDValue N0 = N->getOperand(0); 16287 SDValue N1 = N->getOperand(1); 16288 SDValue N2 = N->getOperand(2); 16289 SDNodeFlags Flags = N->getFlags(); 16290 EVT VT = N->getValueType(0); 16291 SelectionDAG &DAG = DCI.DAG; 16292 const TargetOptions &Options = getTargetMachine().Options; 16293 unsigned Opc = N->getOpcode(); 16294 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16295 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16296 SDLoc Loc(N); 16297 16298 if (!isOperationLegal(ISD::FMA, VT)) 16299 return SDValue(); 16300 16301 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16302 // since (fnmsub a b c)=-0 while c-ab=+0. 16303 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16304 return SDValue(); 16305 16306 // (fma (fneg a) b c) => (fnmsub a b c) 16307 // (fnmsub (fneg a) b c) => (fma a b c) 16308 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16309 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16310 16311 // (fma a (fneg b) c) => (fnmsub a b c) 16312 // (fnmsub a (fneg b) c) => (fma a b c) 16313 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16314 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16315 16316 return SDValue(); 16317 } 16318 16319 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16320 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16321 if (!Subtarget.is64BitELFABI()) 16322 return false; 16323 16324 // If not a tail call then no need to proceed. 16325 if (!CI->isTailCall()) 16326 return false; 16327 16328 // If sibling calls have been disabled and tail-calls aren't guaranteed 16329 // there is no reason to duplicate. 16330 auto &TM = getTargetMachine(); 16331 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16332 return false; 16333 16334 // Can't tail call a function called indirectly, or if it has variadic args. 16335 const Function *Callee = CI->getCalledFunction(); 16336 if (!Callee || Callee->isVarArg()) 16337 return false; 16338 16339 // Make sure the callee and caller calling conventions are eligible for tco. 16340 const Function *Caller = CI->getParent()->getParent(); 16341 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16342 CI->getCallingConv())) 16343 return false; 16344 16345 // If the function is local then we have a good chance at tail-calling it 16346 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16347 } 16348 16349 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16350 if (!Subtarget.hasVSX()) 16351 return false; 16352 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16353 return true; 16354 return VT == MVT::f32 || VT == MVT::f64 || 16355 VT == MVT::v4f32 || VT == MVT::v2f64; 16356 } 16357 16358 bool PPCTargetLowering:: 16359 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16360 const Value *Mask = AndI.getOperand(1); 16361 // If the mask is suitable for andi. or andis. we should sink the and. 16362 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16363 // Can't handle constants wider than 64-bits. 16364 if (CI->getBitWidth() > 64) 16365 return false; 16366 int64_t ConstVal = CI->getZExtValue(); 16367 return isUInt<16>(ConstVal) || 16368 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16369 } 16370 16371 // For non-constant masks, we can always use the record-form and. 16372 return true; 16373 } 16374 16375 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16376 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16377 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16378 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16379 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16380 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16381 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16382 assert(Subtarget.hasP9Altivec() && 16383 "Only combine this when P9 altivec supported!"); 16384 EVT VT = N->getValueType(0); 16385 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16386 return SDValue(); 16387 16388 SelectionDAG &DAG = DCI.DAG; 16389 SDLoc dl(N); 16390 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16391 // Even for signed integers, if it's known to be positive (as signed 16392 // integer) due to zero-extended inputs. 16393 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16394 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16395 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16396 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16397 (SubOpcd1 == ISD::ZERO_EXTEND || 16398 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16399 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16400 N->getOperand(0)->getOperand(0), 16401 N->getOperand(0)->getOperand(1), 16402 DAG.getTargetConstant(0, dl, MVT::i32)); 16403 } 16404 16405 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16406 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16407 N->getOperand(0).hasOneUse()) { 16408 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16409 N->getOperand(0)->getOperand(0), 16410 N->getOperand(0)->getOperand(1), 16411 DAG.getTargetConstant(1, dl, MVT::i32)); 16412 } 16413 } 16414 16415 return SDValue(); 16416 } 16417 16418 // For type v4i32/v8ii16/v16i8, transform 16419 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16420 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16421 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16422 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16423 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16424 DAGCombinerInfo &DCI) const { 16425 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16426 assert(Subtarget.hasP9Altivec() && 16427 "Only combine this when P9 altivec supported!"); 16428 16429 SelectionDAG &DAG = DCI.DAG; 16430 SDLoc dl(N); 16431 SDValue Cond = N->getOperand(0); 16432 SDValue TrueOpnd = N->getOperand(1); 16433 SDValue FalseOpnd = N->getOperand(2); 16434 EVT VT = N->getOperand(1).getValueType(); 16435 16436 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16437 FalseOpnd.getOpcode() != ISD::SUB) 16438 return SDValue(); 16439 16440 // ABSD only available for type v4i32/v8i16/v16i8 16441 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16442 return SDValue(); 16443 16444 // At least to save one more dependent computation 16445 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16446 return SDValue(); 16447 16448 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16449 16450 // Can only handle unsigned comparison here 16451 switch (CC) { 16452 default: 16453 return SDValue(); 16454 case ISD::SETUGT: 16455 case ISD::SETUGE: 16456 break; 16457 case ISD::SETULT: 16458 case ISD::SETULE: 16459 std::swap(TrueOpnd, FalseOpnd); 16460 break; 16461 } 16462 16463 SDValue CmpOpnd1 = Cond.getOperand(0); 16464 SDValue CmpOpnd2 = Cond.getOperand(1); 16465 16466 // SETCC CmpOpnd1 CmpOpnd2 cond 16467 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16468 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16469 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16470 TrueOpnd.getOperand(1) == CmpOpnd2 && 16471 FalseOpnd.getOperand(0) == CmpOpnd2 && 16472 FalseOpnd.getOperand(1) == CmpOpnd1) { 16473 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16474 CmpOpnd1, CmpOpnd2, 16475 DAG.getTargetConstant(0, dl, MVT::i32)); 16476 } 16477 16478 return SDValue(); 16479 } 16480