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 // TODO - Remove this option if soft fp128 has been fully supported . 125 static cl::opt<bool> 126 EnableSoftFP128("enable-soft-fp128", 127 cl::desc("temp option to enable soft fp128"), 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 // EFPU2 APU only supports f32 155 if (!Subtarget.hasEFPU2()) 156 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 157 } else { 158 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 159 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 160 } 161 } 162 163 // Match BITREVERSE to customized fast code sequence in the td file. 164 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 165 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 166 167 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 168 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 169 170 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 171 for (MVT VT : MVT::integer_valuetypes()) { 172 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 173 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 174 } 175 176 if (Subtarget.isISA3_0()) { 177 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 178 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 179 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 180 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 181 } else { 182 // No extending loads from f16 or HW conversions back and forth. 183 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 184 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 185 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 186 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 187 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 188 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 189 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 190 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 191 } 192 193 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 194 195 // PowerPC has pre-inc load and store's. 196 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 197 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 198 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 199 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 200 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 201 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 204 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 205 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 206 if (!Subtarget.hasSPE()) { 207 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 208 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 209 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 210 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 211 } 212 213 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 214 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 215 for (MVT VT : ScalarIntVTs) { 216 setOperationAction(ISD::ADDC, VT, Legal); 217 setOperationAction(ISD::ADDE, VT, Legal); 218 setOperationAction(ISD::SUBC, VT, Legal); 219 setOperationAction(ISD::SUBE, VT, Legal); 220 } 221 222 if (Subtarget.useCRBits()) { 223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 224 225 if (isPPC64 || Subtarget.hasFPCVT()) { 226 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 227 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 228 isPPC64 ? MVT::i64 : MVT::i32); 229 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 230 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 231 isPPC64 ? MVT::i64 : MVT::i32); 232 233 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 234 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 235 isPPC64 ? MVT::i64 : MVT::i32); 236 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 237 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 238 isPPC64 ? MVT::i64 : MVT::i32); 239 240 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 241 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 242 isPPC64 ? MVT::i64 : MVT::i32); 243 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 244 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 245 isPPC64 ? MVT::i64 : MVT::i32); 246 247 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 248 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 249 isPPC64 ? MVT::i64 : MVT::i32); 250 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 251 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 252 isPPC64 ? MVT::i64 : MVT::i32); 253 } else { 254 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 255 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 256 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 257 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 258 } 259 260 // PowerPC does not support direct load/store of condition registers. 261 setOperationAction(ISD::LOAD, MVT::i1, Custom); 262 setOperationAction(ISD::STORE, MVT::i1, Custom); 263 264 // FIXME: Remove this once the ANDI glue bug is fixed: 265 if (ANDIGlueBug) 266 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 267 268 for (MVT VT : MVT::integer_valuetypes()) { 269 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 270 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 271 setTruncStoreAction(VT, MVT::i1, Expand); 272 } 273 274 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 275 } 276 277 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 278 // PPC (the libcall is not available). 279 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 280 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 281 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 282 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 283 284 // We do not currently implement these libm ops for PowerPC. 285 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 286 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 287 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 288 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 289 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 290 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 291 292 // PowerPC has no SREM/UREM instructions unless we are on P9 293 // On P9 we may use a hardware instruction to compute the remainder. 294 // When the result of both the remainder and the division is required it is 295 // more efficient to compute the remainder from the result of the division 296 // rather than use the remainder instruction. The instructions are legalized 297 // directly because the DivRemPairsPass performs the transformation at the IR 298 // level. 299 if (Subtarget.isISA3_0()) { 300 setOperationAction(ISD::SREM, MVT::i32, Legal); 301 setOperationAction(ISD::UREM, MVT::i32, Legal); 302 setOperationAction(ISD::SREM, MVT::i64, Legal); 303 setOperationAction(ISD::UREM, MVT::i64, Legal); 304 } else { 305 setOperationAction(ISD::SREM, MVT::i32, Expand); 306 setOperationAction(ISD::UREM, MVT::i32, Expand); 307 setOperationAction(ISD::SREM, MVT::i64, Expand); 308 setOperationAction(ISD::UREM, MVT::i64, Expand); 309 } 310 311 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 312 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 313 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 314 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 315 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 316 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 317 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 318 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 319 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 320 321 // Handle constrained floating-point operations of scalar. 322 // TODO: Handle SPE specific operation. 323 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 324 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 325 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 326 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 327 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 328 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 329 330 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 331 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 332 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 333 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 334 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 335 if (Subtarget.hasVSX()) { 336 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 337 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 338 } 339 340 if (Subtarget.hasFSQRT()) { 341 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 342 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 343 } 344 345 if (Subtarget.hasFPRND()) { 346 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 347 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 348 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 349 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 350 351 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 352 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 353 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 354 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 355 } 356 357 // We don't support sin/cos/sqrt/fmod/pow 358 setOperationAction(ISD::FSIN , MVT::f64, Expand); 359 setOperationAction(ISD::FCOS , MVT::f64, Expand); 360 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 361 setOperationAction(ISD::FREM , MVT::f64, Expand); 362 setOperationAction(ISD::FPOW , MVT::f64, Expand); 363 setOperationAction(ISD::FSIN , MVT::f32, Expand); 364 setOperationAction(ISD::FCOS , MVT::f32, Expand); 365 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 366 setOperationAction(ISD::FREM , MVT::f32, Expand); 367 setOperationAction(ISD::FPOW , MVT::f32, Expand); 368 if (Subtarget.hasSPE()) { 369 setOperationAction(ISD::FMA , MVT::f64, Expand); 370 setOperationAction(ISD::FMA , MVT::f32, Expand); 371 } else { 372 setOperationAction(ISD::FMA , MVT::f64, Legal); 373 setOperationAction(ISD::FMA , MVT::f32, Legal); 374 } 375 376 if (Subtarget.hasSPE()) 377 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 378 379 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 380 381 // If we're enabling GP optimizations, use hardware square root 382 if (!Subtarget.hasFSQRT() && 383 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 384 Subtarget.hasFRE())) 385 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 386 387 if (!Subtarget.hasFSQRT() && 388 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 389 Subtarget.hasFRES())) 390 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 391 392 if (Subtarget.hasFCPSGN()) { 393 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 394 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 395 } else { 396 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 397 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 398 } 399 400 if (Subtarget.hasFPRND()) { 401 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 402 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 403 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 404 setOperationAction(ISD::FROUND, MVT::f64, Legal); 405 406 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 407 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 408 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 409 setOperationAction(ISD::FROUND, MVT::f32, Legal); 410 } 411 412 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 413 // to speed up scalar BSWAP64. 414 // CTPOP or CTTZ were introduced in P8/P9 respectively 415 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 416 if (Subtarget.hasP9Vector()) 417 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 418 else 419 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 420 if (Subtarget.isISA3_0()) { 421 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 422 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 423 } else { 424 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 425 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 426 } 427 428 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 429 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 430 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 431 } else { 432 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 433 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 434 } 435 436 // PowerPC does not have ROTR 437 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 438 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 439 440 if (!Subtarget.useCRBits()) { 441 // PowerPC does not have Select 442 setOperationAction(ISD::SELECT, MVT::i32, Expand); 443 setOperationAction(ISD::SELECT, MVT::i64, Expand); 444 setOperationAction(ISD::SELECT, MVT::f32, Expand); 445 setOperationAction(ISD::SELECT, MVT::f64, Expand); 446 } 447 448 // PowerPC wants to turn select_cc of FP into fsel when possible. 449 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 450 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 451 452 // PowerPC wants to optimize integer setcc a bit 453 if (!Subtarget.useCRBits()) 454 setOperationAction(ISD::SETCC, MVT::i32, Custom); 455 456 if (Subtarget.hasFPU()) { 457 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 458 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 459 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 460 461 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 462 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 463 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 464 } 465 466 // PowerPC does not have BRCOND which requires SetCC 467 if (!Subtarget.useCRBits()) 468 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 469 470 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 471 472 if (Subtarget.hasSPE()) { 473 // SPE has built-in conversions 474 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 475 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 476 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 477 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 478 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 479 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 480 } else { 481 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 482 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 483 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 484 485 // PowerPC does not have [U|S]INT_TO_FP 486 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 487 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 488 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 489 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 490 } 491 492 if (Subtarget.hasDirectMove() && isPPC64) { 493 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 494 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 495 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 496 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 497 if (TM.Options.UnsafeFPMath) { 498 setOperationAction(ISD::LRINT, MVT::f64, Legal); 499 setOperationAction(ISD::LRINT, MVT::f32, Legal); 500 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 501 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 502 setOperationAction(ISD::LROUND, MVT::f64, Legal); 503 setOperationAction(ISD::LROUND, MVT::f32, Legal); 504 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 505 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 506 } 507 } else { 508 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 509 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 510 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 511 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 512 } 513 514 // We cannot sextinreg(i1). Expand to shifts. 515 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 516 517 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 518 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 519 // support continuation, user-level threading, and etc.. As a result, no 520 // other SjLj exception interfaces are implemented and please don't build 521 // your own exception handling based on them. 522 // LLVM/Clang supports zero-cost DWARF exception handling. 523 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 524 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 525 526 // We want to legalize GlobalAddress and ConstantPool nodes into the 527 // appropriate instructions to materialize the address. 528 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 529 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 530 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 531 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 532 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 533 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 534 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 535 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 536 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 537 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 538 539 // TRAP is legal. 540 setOperationAction(ISD::TRAP, MVT::Other, Legal); 541 542 // TRAMPOLINE is custom lowered. 543 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 544 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 545 546 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 547 setOperationAction(ISD::VASTART , MVT::Other, Custom); 548 549 if (Subtarget.is64BitELFABI()) { 550 // VAARG always uses double-word chunks, so promote anything smaller. 551 setOperationAction(ISD::VAARG, MVT::i1, Promote); 552 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 553 setOperationAction(ISD::VAARG, MVT::i8, Promote); 554 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 555 setOperationAction(ISD::VAARG, MVT::i16, Promote); 556 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 557 setOperationAction(ISD::VAARG, MVT::i32, Promote); 558 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 559 setOperationAction(ISD::VAARG, MVT::Other, Expand); 560 } else if (Subtarget.is32BitELFABI()) { 561 // VAARG is custom lowered with the 32-bit SVR4 ABI. 562 setOperationAction(ISD::VAARG, MVT::Other, Custom); 563 setOperationAction(ISD::VAARG, MVT::i64, Custom); 564 } else 565 setOperationAction(ISD::VAARG, MVT::Other, Expand); 566 567 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 568 if (Subtarget.is32BitELFABI()) 569 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 570 else 571 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 572 573 // Use the default implementation. 574 setOperationAction(ISD::VAEND , MVT::Other, Expand); 575 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 576 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 577 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 578 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 579 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 580 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 581 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 582 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 583 584 // We want to custom lower some of our intrinsics. 585 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 586 587 // To handle counter-based loop conditions. 588 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 589 590 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 591 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 592 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 593 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 594 595 // Comparisons that require checking two conditions. 596 if (Subtarget.hasSPE()) { 597 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 598 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 599 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 600 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 601 } 602 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 603 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 604 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 605 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 606 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 607 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 608 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 609 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 610 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 611 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 612 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 613 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 614 615 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 616 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 617 618 if (Subtarget.has64BitSupport()) { 619 // They also have instructions for converting between i64 and fp. 620 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 621 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 622 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 623 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 624 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 625 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 626 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 627 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 628 // This is just the low 32 bits of a (signed) fp->i64 conversion. 629 // We cannot do this with Promote because i64 is not a legal type. 630 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 631 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 632 633 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 634 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 635 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 636 } 637 } else { 638 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 639 if (Subtarget.hasSPE()) { 640 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 641 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 642 } else { 643 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 644 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 645 } 646 } 647 648 // With the instructions enabled under FPCVT, we can do everything. 649 if (Subtarget.hasFPCVT()) { 650 if (Subtarget.has64BitSupport()) { 651 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 652 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 653 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 654 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 655 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 656 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 657 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 658 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 659 } 660 661 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 662 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 663 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 664 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 665 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 666 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 667 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 668 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 669 } 670 671 if (Subtarget.use64BitRegs()) { 672 // 64-bit PowerPC implementations can support i64 types directly 673 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 674 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 675 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 676 // 64-bit PowerPC wants to expand i128 shifts itself. 677 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 678 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 679 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 680 } else { 681 // 32-bit PowerPC wants to expand i64 shifts itself. 682 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 683 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 684 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 685 } 686 687 // PowerPC has better expansions for funnel shifts than the generic 688 // TargetLowering::expandFunnelShift. 689 if (Subtarget.has64BitSupport()) { 690 setOperationAction(ISD::FSHL, MVT::i64, Custom); 691 setOperationAction(ISD::FSHR, MVT::i64, Custom); 692 } 693 setOperationAction(ISD::FSHL, MVT::i32, Custom); 694 setOperationAction(ISD::FSHR, MVT::i32, Custom); 695 696 if (Subtarget.hasVSX()) { 697 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 698 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 699 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 700 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 701 } 702 703 if (Subtarget.hasAltivec()) { 704 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 705 setOperationAction(ISD::SADDSAT, VT, Legal); 706 setOperationAction(ISD::SSUBSAT, VT, Legal); 707 setOperationAction(ISD::UADDSAT, VT, Legal); 708 setOperationAction(ISD::USUBSAT, VT, Legal); 709 } 710 // First set operation action for all vector types to expand. Then we 711 // will selectively turn on ones that can be effectively codegen'd. 712 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 713 // add/sub are legal for all supported vector VT's. 714 setOperationAction(ISD::ADD, VT, Legal); 715 setOperationAction(ISD::SUB, VT, Legal); 716 717 // For v2i64, these are only valid with P8Vector. This is corrected after 718 // the loop. 719 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 720 setOperationAction(ISD::SMAX, VT, Legal); 721 setOperationAction(ISD::SMIN, VT, Legal); 722 setOperationAction(ISD::UMAX, VT, Legal); 723 setOperationAction(ISD::UMIN, VT, Legal); 724 } 725 else { 726 setOperationAction(ISD::SMAX, VT, Expand); 727 setOperationAction(ISD::SMIN, VT, Expand); 728 setOperationAction(ISD::UMAX, VT, Expand); 729 setOperationAction(ISD::UMIN, VT, Expand); 730 } 731 732 if (Subtarget.hasVSX()) { 733 setOperationAction(ISD::FMAXNUM, VT, Legal); 734 setOperationAction(ISD::FMINNUM, VT, Legal); 735 } 736 737 // Vector instructions introduced in P8 738 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 739 setOperationAction(ISD::CTPOP, VT, Legal); 740 setOperationAction(ISD::CTLZ, VT, Legal); 741 } 742 else { 743 setOperationAction(ISD::CTPOP, VT, Expand); 744 setOperationAction(ISD::CTLZ, VT, Expand); 745 } 746 747 // Vector instructions introduced in P9 748 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 749 setOperationAction(ISD::CTTZ, VT, Legal); 750 else 751 setOperationAction(ISD::CTTZ, VT, Expand); 752 753 // We promote all shuffles to v16i8. 754 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 755 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 756 757 // We promote all non-typed operations to v4i32. 758 setOperationAction(ISD::AND , VT, Promote); 759 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 760 setOperationAction(ISD::OR , VT, Promote); 761 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 762 setOperationAction(ISD::XOR , VT, Promote); 763 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 764 setOperationAction(ISD::LOAD , VT, Promote); 765 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 766 setOperationAction(ISD::SELECT, VT, Promote); 767 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 768 setOperationAction(ISD::VSELECT, VT, Legal); 769 setOperationAction(ISD::SELECT_CC, VT, Promote); 770 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 771 setOperationAction(ISD::STORE, VT, Promote); 772 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 773 774 // No other operations are legal. 775 setOperationAction(ISD::MUL , VT, Expand); 776 setOperationAction(ISD::SDIV, VT, Expand); 777 setOperationAction(ISD::SREM, VT, Expand); 778 setOperationAction(ISD::UDIV, VT, Expand); 779 setOperationAction(ISD::UREM, VT, Expand); 780 setOperationAction(ISD::FDIV, VT, Expand); 781 setOperationAction(ISD::FREM, VT, Expand); 782 setOperationAction(ISD::FNEG, VT, Expand); 783 setOperationAction(ISD::FSQRT, VT, Expand); 784 setOperationAction(ISD::FLOG, VT, Expand); 785 setOperationAction(ISD::FLOG10, VT, Expand); 786 setOperationAction(ISD::FLOG2, VT, Expand); 787 setOperationAction(ISD::FEXP, VT, Expand); 788 setOperationAction(ISD::FEXP2, VT, Expand); 789 setOperationAction(ISD::FSIN, VT, Expand); 790 setOperationAction(ISD::FCOS, VT, Expand); 791 setOperationAction(ISD::FABS, VT, Expand); 792 setOperationAction(ISD::FFLOOR, VT, Expand); 793 setOperationAction(ISD::FCEIL, VT, Expand); 794 setOperationAction(ISD::FTRUNC, VT, Expand); 795 setOperationAction(ISD::FRINT, VT, Expand); 796 setOperationAction(ISD::FNEARBYINT, VT, Expand); 797 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 798 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 799 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 800 setOperationAction(ISD::MULHU, VT, Expand); 801 setOperationAction(ISD::MULHS, VT, Expand); 802 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 803 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 804 setOperationAction(ISD::UDIVREM, VT, Expand); 805 setOperationAction(ISD::SDIVREM, VT, Expand); 806 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 807 setOperationAction(ISD::FPOW, VT, Expand); 808 setOperationAction(ISD::BSWAP, VT, Expand); 809 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 810 setOperationAction(ISD::ROTL, VT, Expand); 811 setOperationAction(ISD::ROTR, VT, Expand); 812 813 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 814 setTruncStoreAction(VT, InnerVT, Expand); 815 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 816 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 817 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 818 } 819 } 820 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 821 if (!Subtarget.hasP8Vector()) { 822 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 823 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 824 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 825 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 826 } 827 828 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 829 // with merges, splats, etc. 830 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 831 832 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 833 // are cheap, so handle them before they get expanded to scalar. 834 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 835 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 836 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 837 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 838 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 839 840 setOperationAction(ISD::AND , MVT::v4i32, Legal); 841 setOperationAction(ISD::OR , MVT::v4i32, Legal); 842 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 843 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 844 setOperationAction(ISD::SELECT, MVT::v4i32, 845 Subtarget.useCRBits() ? Legal : Expand); 846 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 847 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 848 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 849 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 850 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 851 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 852 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 853 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 854 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 855 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 856 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 857 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 858 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 859 860 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 861 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 862 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 863 if (Subtarget.hasAltivec()) 864 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 865 setOperationAction(ISD::ROTL, VT, Legal); 866 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 867 if (Subtarget.hasP8Altivec()) 868 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 869 870 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 871 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 872 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 873 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 874 875 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 876 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 877 878 if (Subtarget.hasVSX()) { 879 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 880 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 881 } 882 883 if (Subtarget.hasP8Altivec()) 884 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 885 else 886 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 887 888 if (Subtarget.isISA3_1()) { 889 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 890 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 891 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 892 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 893 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 894 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 895 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 896 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 897 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 898 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 899 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 900 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 901 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 902 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 903 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 904 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 905 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 906 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 907 } 908 909 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 910 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 911 912 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 914 915 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 916 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 917 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 918 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 919 920 // Altivec does not contain unordered floating-point compare instructions 921 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 922 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 923 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 924 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 925 926 if (Subtarget.hasVSX()) { 927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 928 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 929 if (Subtarget.hasP8Vector()) { 930 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 931 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 932 } 933 if (Subtarget.hasDirectMove() && isPPC64) { 934 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 935 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 936 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 937 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 938 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 939 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 940 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 942 } 943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 944 945 // The nearbyint variants are not allowed to raise the inexact exception 946 // so we can only code-gen them with unsafe math. 947 if (TM.Options.UnsafeFPMath) { 948 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 949 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 950 } 951 952 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 953 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 954 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 955 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 956 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 957 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 958 setOperationAction(ISD::FROUND, MVT::f64, Legal); 959 setOperationAction(ISD::FRINT, MVT::f64, Legal); 960 961 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 962 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 963 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 964 setOperationAction(ISD::FROUND, MVT::f32, Legal); 965 setOperationAction(ISD::FRINT, MVT::f32, Legal); 966 967 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 968 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 969 970 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 971 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 972 973 // Share the Altivec comparison restrictions. 974 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 975 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 976 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 977 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 978 979 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 980 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 981 982 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 983 984 if (Subtarget.hasP8Vector()) 985 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 986 987 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 988 989 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 990 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 991 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 992 993 if (Subtarget.hasP8Altivec()) { 994 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 995 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 996 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 997 998 // 128 bit shifts can be accomplished via 3 instructions for SHL and 999 // SRL, but not for SRA because of the instructions available: 1000 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1001 // doing 1002 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1003 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1004 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1005 1006 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1007 } 1008 else { 1009 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1010 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1011 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1012 1013 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1014 1015 // VSX v2i64 only supports non-arithmetic operations. 1016 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1017 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1018 } 1019 1020 if (Subtarget.isISA3_1()) 1021 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1022 else 1023 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1024 1025 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1026 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1027 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1028 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1029 1030 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1031 1032 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1033 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1034 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1035 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1036 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1037 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1038 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1039 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1040 1041 // Custom handling for partial vectors of integers converted to 1042 // floating point. We already have optimal handling for v2i32 through 1043 // the DAG combine, so those aren't necessary. 1044 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1045 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1046 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1047 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1048 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1049 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1050 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1051 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1052 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1053 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1054 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1055 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1056 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1057 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1058 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1059 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1060 1061 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1062 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1063 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1064 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1065 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1066 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1067 1068 if (Subtarget.hasDirectMove()) 1069 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1070 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1071 1072 // Handle constrained floating-point operations of vector. 1073 // The predictor is `hasVSX` because altivec instruction has 1074 // no exception but VSX vector instruction has. 1075 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1076 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1077 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1078 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1079 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1080 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1081 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1082 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1083 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1084 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1085 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1086 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1087 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1088 1089 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1090 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1091 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1092 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1093 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1094 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1095 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1096 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1097 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1098 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1099 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1100 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1101 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1102 1103 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1104 } 1105 1106 if (Subtarget.hasP8Altivec()) { 1107 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1108 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1109 } 1110 1111 if (Subtarget.hasP9Vector()) { 1112 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1113 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1114 1115 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1116 // SRL, but not for SRA because of the instructions available: 1117 // VS{RL} and VS{RL}O. 1118 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1119 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1120 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1121 1122 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1123 setOperationAction(ISD::FADD, MVT::f128, Legal); 1124 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1125 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1126 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1127 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1128 // No extending loads to f128 on PPC. 1129 for (MVT FPT : MVT::fp_valuetypes()) 1130 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1131 setOperationAction(ISD::FMA, MVT::f128, Legal); 1132 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1133 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1134 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1135 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1136 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1137 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1138 1139 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1140 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1141 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1142 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1143 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1144 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1145 1146 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1147 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1148 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1149 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1150 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1151 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1152 // No implementation for these ops for PowerPC. 1153 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1154 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1155 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1156 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1157 setOperationAction(ISD::FREM, MVT::f128, Expand); 1158 1159 // Handle constrained floating-point operations of fp128 1160 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1161 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1162 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1163 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1164 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1165 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1166 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1167 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1168 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1169 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1170 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1171 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1172 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1173 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1174 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1175 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1176 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1177 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1178 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1179 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1180 } else if (Subtarget.hasAltivec() && EnableSoftFP128) { 1181 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1182 1183 for (MVT FPT : MVT::fp_valuetypes()) 1184 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1185 1186 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1187 setOperationAction(ISD::STORE, MVT::f128, Promote); 1188 1189 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1190 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1191 1192 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1193 // fp_to_uint and int_to_fp. 1194 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1195 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1196 1197 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1198 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1199 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1200 setOperationAction(ISD::FABS, MVT::f128, Expand); 1201 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1202 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1203 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1204 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1205 setOperationAction(ISD::FREM, MVT::f128, Expand); 1206 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1207 setOperationAction(ISD::FMA, MVT::f128, Expand); 1208 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1209 1210 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1211 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1212 1213 // Expand the fp_extend if the target type is fp128. 1214 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1215 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1216 1217 // Expand the fp_round if the source type is fp128. 1218 for (MVT VT : {MVT::f32, MVT::f64}) { 1219 setOperationAction(ISD::FP_ROUND, VT, Custom); 1220 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1221 } 1222 } 1223 1224 if (Subtarget.hasP9Altivec()) { 1225 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1226 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1227 1228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1235 } 1236 1237 if (Subtarget.isISA3_1()) { 1238 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 1239 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 1240 } 1241 } 1242 1243 if (Subtarget.pairedVectorMemops()) { 1244 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1245 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1246 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1247 } 1248 if (Subtarget.hasMMA()) { 1249 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1250 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1251 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1252 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1253 } 1254 1255 if (Subtarget.has64BitSupport()) 1256 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1257 1258 if (Subtarget.isISA3_1()) 1259 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1260 1261 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1262 1263 if (!isPPC64) { 1264 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1265 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1266 } 1267 1268 setBooleanContents(ZeroOrOneBooleanContent); 1269 1270 if (Subtarget.hasAltivec()) { 1271 // Altivec instructions set fields to all zeros or all ones. 1272 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1273 } 1274 1275 if (!isPPC64) { 1276 // These libcalls are not available in 32-bit. 1277 setLibcallName(RTLIB::SHL_I128, nullptr); 1278 setLibcallName(RTLIB::SRL_I128, nullptr); 1279 setLibcallName(RTLIB::SRA_I128, nullptr); 1280 } 1281 1282 if (!isPPC64) 1283 setMaxAtomicSizeInBitsSupported(32); 1284 1285 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1286 1287 // We have target-specific dag combine patterns for the following nodes: 1288 setTargetDAGCombine(ISD::ADD); 1289 setTargetDAGCombine(ISD::SHL); 1290 setTargetDAGCombine(ISD::SRA); 1291 setTargetDAGCombine(ISD::SRL); 1292 setTargetDAGCombine(ISD::MUL); 1293 setTargetDAGCombine(ISD::FMA); 1294 setTargetDAGCombine(ISD::SINT_TO_FP); 1295 setTargetDAGCombine(ISD::BUILD_VECTOR); 1296 if (Subtarget.hasFPCVT()) 1297 setTargetDAGCombine(ISD::UINT_TO_FP); 1298 setTargetDAGCombine(ISD::LOAD); 1299 setTargetDAGCombine(ISD::STORE); 1300 setTargetDAGCombine(ISD::BR_CC); 1301 if (Subtarget.useCRBits()) 1302 setTargetDAGCombine(ISD::BRCOND); 1303 setTargetDAGCombine(ISD::BSWAP); 1304 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1305 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1306 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1307 1308 setTargetDAGCombine(ISD::SIGN_EXTEND); 1309 setTargetDAGCombine(ISD::ZERO_EXTEND); 1310 setTargetDAGCombine(ISD::ANY_EXTEND); 1311 1312 setTargetDAGCombine(ISD::TRUNCATE); 1313 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1314 1315 1316 if (Subtarget.useCRBits()) { 1317 setTargetDAGCombine(ISD::TRUNCATE); 1318 setTargetDAGCombine(ISD::SETCC); 1319 setTargetDAGCombine(ISD::SELECT_CC); 1320 } 1321 1322 if (Subtarget.hasP9Altivec()) { 1323 setTargetDAGCombine(ISD::ABS); 1324 setTargetDAGCombine(ISD::VSELECT); 1325 } 1326 1327 setLibcallName(RTLIB::LOG_F128, "logf128"); 1328 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1329 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1330 setLibcallName(RTLIB::EXP_F128, "expf128"); 1331 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1332 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1333 setLibcallName(RTLIB::COS_F128, "cosf128"); 1334 setLibcallName(RTLIB::POW_F128, "powf128"); 1335 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1336 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1337 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1338 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1339 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1340 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1341 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1342 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1343 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1344 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1345 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1346 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1347 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1348 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1349 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1350 1351 // With 32 condition bits, we don't need to sink (and duplicate) compares 1352 // aggressively in CodeGenPrep. 1353 if (Subtarget.useCRBits()) { 1354 setHasMultipleConditionRegisters(); 1355 setJumpIsExpensive(); 1356 } 1357 1358 setMinFunctionAlignment(Align(4)); 1359 1360 switch (Subtarget.getCPUDirective()) { 1361 default: break; 1362 case PPC::DIR_970: 1363 case PPC::DIR_A2: 1364 case PPC::DIR_E500: 1365 case PPC::DIR_E500mc: 1366 case PPC::DIR_E5500: 1367 case PPC::DIR_PWR4: 1368 case PPC::DIR_PWR5: 1369 case PPC::DIR_PWR5X: 1370 case PPC::DIR_PWR6: 1371 case PPC::DIR_PWR6X: 1372 case PPC::DIR_PWR7: 1373 case PPC::DIR_PWR8: 1374 case PPC::DIR_PWR9: 1375 case PPC::DIR_PWR10: 1376 case PPC::DIR_PWR_FUTURE: 1377 setPrefLoopAlignment(Align(16)); 1378 setPrefFunctionAlignment(Align(16)); 1379 break; 1380 } 1381 1382 if (Subtarget.enableMachineScheduler()) 1383 setSchedulingPreference(Sched::Source); 1384 else 1385 setSchedulingPreference(Sched::Hybrid); 1386 1387 computeRegisterProperties(STI.getRegisterInfo()); 1388 1389 // The Freescale cores do better with aggressive inlining of memcpy and 1390 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1391 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1392 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1393 MaxStoresPerMemset = 32; 1394 MaxStoresPerMemsetOptSize = 16; 1395 MaxStoresPerMemcpy = 32; 1396 MaxStoresPerMemcpyOptSize = 8; 1397 MaxStoresPerMemmove = 32; 1398 MaxStoresPerMemmoveOptSize = 8; 1399 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1400 // The A2 also benefits from (very) aggressive inlining of memcpy and 1401 // friends. The overhead of a the function call, even when warm, can be 1402 // over one hundred cycles. 1403 MaxStoresPerMemset = 128; 1404 MaxStoresPerMemcpy = 128; 1405 MaxStoresPerMemmove = 128; 1406 MaxLoadsPerMemcmp = 128; 1407 } else { 1408 MaxLoadsPerMemcmp = 8; 1409 MaxLoadsPerMemcmpOptSize = 4; 1410 } 1411 1412 IsStrictFPEnabled = true; 1413 1414 // Let the subtarget (CPU) decide if a predictable select is more expensive 1415 // than the corresponding branch. This information is used in CGP to decide 1416 // when to convert selects into branches. 1417 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1418 } 1419 1420 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1421 /// the desired ByVal argument alignment. 1422 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1423 if (MaxAlign == MaxMaxAlign) 1424 return; 1425 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1426 if (MaxMaxAlign >= 32 && 1427 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1428 MaxAlign = Align(32); 1429 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1430 MaxAlign < 16) 1431 MaxAlign = Align(16); 1432 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1433 Align EltAlign; 1434 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1435 if (EltAlign > MaxAlign) 1436 MaxAlign = EltAlign; 1437 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1438 for (auto *EltTy : STy->elements()) { 1439 Align EltAlign; 1440 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1441 if (EltAlign > MaxAlign) 1442 MaxAlign = EltAlign; 1443 if (MaxAlign == MaxMaxAlign) 1444 break; 1445 } 1446 } 1447 } 1448 1449 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1450 /// function arguments in the caller parameter area. 1451 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1452 const DataLayout &DL) const { 1453 // 16byte and wider vectors are passed on 16byte boundary. 1454 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1455 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1456 if (Subtarget.hasAltivec()) 1457 getMaxByValAlign(Ty, Alignment, Align(16)); 1458 return Alignment.value(); 1459 } 1460 1461 bool PPCTargetLowering::useSoftFloat() const { 1462 return Subtarget.useSoftFloat(); 1463 } 1464 1465 bool PPCTargetLowering::hasSPE() const { 1466 return Subtarget.hasSPE(); 1467 } 1468 1469 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1470 return VT.isScalarInteger(); 1471 } 1472 1473 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1474 switch ((PPCISD::NodeType)Opcode) { 1475 case PPCISD::FIRST_NUMBER: break; 1476 case PPCISD::FSEL: return "PPCISD::FSEL"; 1477 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1478 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1479 case PPCISD::FCFID: return "PPCISD::FCFID"; 1480 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1481 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1482 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1483 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1484 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1485 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1486 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1487 case PPCISD::FP_TO_UINT_IN_VSR: 1488 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1489 case PPCISD::FP_TO_SINT_IN_VSR: 1490 return "PPCISD::FP_TO_SINT_IN_VSR"; 1491 case PPCISD::FRE: return "PPCISD::FRE"; 1492 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1493 case PPCISD::FTSQRT: 1494 return "PPCISD::FTSQRT"; 1495 case PPCISD::FSQRT: 1496 return "PPCISD::FSQRT"; 1497 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1498 case PPCISD::VPERM: return "PPCISD::VPERM"; 1499 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1500 case PPCISD::XXSPLTI_SP_TO_DP: 1501 return "PPCISD::XXSPLTI_SP_TO_DP"; 1502 case PPCISD::XXSPLTI32DX: 1503 return "PPCISD::XXSPLTI32DX"; 1504 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1505 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1506 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1507 case PPCISD::CMPB: return "PPCISD::CMPB"; 1508 case PPCISD::Hi: return "PPCISD::Hi"; 1509 case PPCISD::Lo: return "PPCISD::Lo"; 1510 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1511 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1512 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1513 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1514 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1515 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1516 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1517 case PPCISD::SRL: return "PPCISD::SRL"; 1518 case PPCISD::SRA: return "PPCISD::SRA"; 1519 case PPCISD::SHL: return "PPCISD::SHL"; 1520 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1521 case PPCISD::CALL: return "PPCISD::CALL"; 1522 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1523 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1524 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1525 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1526 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1527 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1528 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1529 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1530 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1531 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1532 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1533 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1534 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1535 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1536 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1537 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1538 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1539 case PPCISD::ANDI_rec_1_EQ_BIT: 1540 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1541 case PPCISD::ANDI_rec_1_GT_BIT: 1542 return "PPCISD::ANDI_rec_1_GT_BIT"; 1543 case PPCISD::VCMP: return "PPCISD::VCMP"; 1544 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1545 case PPCISD::LBRX: return "PPCISD::LBRX"; 1546 case PPCISD::STBRX: return "PPCISD::STBRX"; 1547 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1548 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1549 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1550 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1551 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1552 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1553 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1554 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1555 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1556 case PPCISD::ST_VSR_SCAL_INT: 1557 return "PPCISD::ST_VSR_SCAL_INT"; 1558 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1559 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1560 case PPCISD::BDZ: return "PPCISD::BDZ"; 1561 case PPCISD::MFFS: return "PPCISD::MFFS"; 1562 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1563 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1564 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1565 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1566 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1567 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1568 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1569 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1570 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1571 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1572 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1573 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1574 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1575 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX"; 1576 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1577 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1578 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1579 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1580 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1581 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1582 case PPCISD::PADDI_DTPREL: 1583 return "PPCISD::PADDI_DTPREL"; 1584 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1585 case PPCISD::SC: return "PPCISD::SC"; 1586 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1587 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1588 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1589 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1590 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1591 case PPCISD::VABSD: return "PPCISD::VABSD"; 1592 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1593 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1594 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1595 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1596 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1597 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1598 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1599 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1600 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1601 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1602 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1603 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1604 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1605 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1606 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1607 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1608 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1609 case PPCISD::STRICT_FADDRTZ: 1610 return "PPCISD::STRICT_FADDRTZ"; 1611 case PPCISD::STRICT_FCTIDZ: 1612 return "PPCISD::STRICT_FCTIDZ"; 1613 case PPCISD::STRICT_FCTIWZ: 1614 return "PPCISD::STRICT_FCTIWZ"; 1615 case PPCISD::STRICT_FCTIDUZ: 1616 return "PPCISD::STRICT_FCTIDUZ"; 1617 case PPCISD::STRICT_FCTIWUZ: 1618 return "PPCISD::STRICT_FCTIWUZ"; 1619 case PPCISD::STRICT_FCFID: 1620 return "PPCISD::STRICT_FCFID"; 1621 case PPCISD::STRICT_FCFIDU: 1622 return "PPCISD::STRICT_FCFIDU"; 1623 case PPCISD::STRICT_FCFIDS: 1624 return "PPCISD::STRICT_FCFIDS"; 1625 case PPCISD::STRICT_FCFIDUS: 1626 return "PPCISD::STRICT_FCFIDUS"; 1627 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1628 } 1629 return nullptr; 1630 } 1631 1632 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1633 EVT VT) const { 1634 if (!VT.isVector()) 1635 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1636 1637 return VT.changeVectorElementTypeToInteger(); 1638 } 1639 1640 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1641 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1642 return true; 1643 } 1644 1645 //===----------------------------------------------------------------------===// 1646 // Node matching predicates, for use by the tblgen matching code. 1647 //===----------------------------------------------------------------------===// 1648 1649 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1650 static bool isFloatingPointZero(SDValue Op) { 1651 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1652 return CFP->getValueAPF().isZero(); 1653 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1654 // Maybe this has already been legalized into the constant pool? 1655 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1656 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1657 return CFP->getValueAPF().isZero(); 1658 } 1659 return false; 1660 } 1661 1662 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1663 /// true if Op is undef or if it matches the specified value. 1664 static bool isConstantOrUndef(int Op, int Val) { 1665 return Op < 0 || Op == Val; 1666 } 1667 1668 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1669 /// VPKUHUM instruction. 1670 /// The ShuffleKind distinguishes between big-endian operations with 1671 /// two different inputs (0), either-endian operations with two identical 1672 /// inputs (1), and little-endian operations with two different inputs (2). 1673 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1674 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1675 SelectionDAG &DAG) { 1676 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1677 if (ShuffleKind == 0) { 1678 if (IsLE) 1679 return false; 1680 for (unsigned i = 0; i != 16; ++i) 1681 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1682 return false; 1683 } else if (ShuffleKind == 2) { 1684 if (!IsLE) 1685 return false; 1686 for (unsigned i = 0; i != 16; ++i) 1687 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1688 return false; 1689 } else if (ShuffleKind == 1) { 1690 unsigned j = IsLE ? 0 : 1; 1691 for (unsigned i = 0; i != 8; ++i) 1692 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1693 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1694 return false; 1695 } 1696 return true; 1697 } 1698 1699 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1700 /// VPKUWUM instruction. 1701 /// The ShuffleKind distinguishes between big-endian operations with 1702 /// two different inputs (0), either-endian operations with two identical 1703 /// inputs (1), and little-endian operations with two different inputs (2). 1704 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1705 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1706 SelectionDAG &DAG) { 1707 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1708 if (ShuffleKind == 0) { 1709 if (IsLE) 1710 return false; 1711 for (unsigned i = 0; i != 16; i += 2) 1712 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1713 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1714 return false; 1715 } else if (ShuffleKind == 2) { 1716 if (!IsLE) 1717 return false; 1718 for (unsigned i = 0; i != 16; i += 2) 1719 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1720 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1721 return false; 1722 } else if (ShuffleKind == 1) { 1723 unsigned j = IsLE ? 0 : 2; 1724 for (unsigned i = 0; i != 8; i += 2) 1725 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1726 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1727 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1728 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1729 return false; 1730 } 1731 return true; 1732 } 1733 1734 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1735 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1736 /// current subtarget. 1737 /// 1738 /// The ShuffleKind distinguishes between big-endian operations with 1739 /// two different inputs (0), either-endian operations with two identical 1740 /// inputs (1), and little-endian operations with two different inputs (2). 1741 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1742 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1743 SelectionDAG &DAG) { 1744 const PPCSubtarget& Subtarget = 1745 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1746 if (!Subtarget.hasP8Vector()) 1747 return false; 1748 1749 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1750 if (ShuffleKind == 0) { 1751 if (IsLE) 1752 return false; 1753 for (unsigned i = 0; i != 16; i += 4) 1754 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1755 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1756 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1757 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1758 return false; 1759 } else if (ShuffleKind == 2) { 1760 if (!IsLE) 1761 return false; 1762 for (unsigned i = 0; i != 16; i += 4) 1763 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1764 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1765 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1766 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1767 return false; 1768 } else if (ShuffleKind == 1) { 1769 unsigned j = IsLE ? 0 : 4; 1770 for (unsigned i = 0; i != 8; i += 4) 1771 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1772 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1773 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1774 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1775 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1776 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1777 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1778 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1779 return false; 1780 } 1781 return true; 1782 } 1783 1784 /// isVMerge - Common function, used to match vmrg* shuffles. 1785 /// 1786 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1787 unsigned LHSStart, unsigned RHSStart) { 1788 if (N->getValueType(0) != MVT::v16i8) 1789 return false; 1790 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1791 "Unsupported merge size!"); 1792 1793 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1794 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1795 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1796 LHSStart+j+i*UnitSize) || 1797 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1798 RHSStart+j+i*UnitSize)) 1799 return false; 1800 } 1801 return true; 1802 } 1803 1804 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1805 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1806 /// The ShuffleKind distinguishes between big-endian merges with two 1807 /// different inputs (0), either-endian merges with two identical inputs (1), 1808 /// and little-endian merges with two different inputs (2). For the latter, 1809 /// the input operands are swapped (see PPCInstrAltivec.td). 1810 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1811 unsigned ShuffleKind, SelectionDAG &DAG) { 1812 if (DAG.getDataLayout().isLittleEndian()) { 1813 if (ShuffleKind == 1) // unary 1814 return isVMerge(N, UnitSize, 0, 0); 1815 else if (ShuffleKind == 2) // swapped 1816 return isVMerge(N, UnitSize, 0, 16); 1817 else 1818 return false; 1819 } else { 1820 if (ShuffleKind == 1) // unary 1821 return isVMerge(N, UnitSize, 8, 8); 1822 else if (ShuffleKind == 0) // normal 1823 return isVMerge(N, UnitSize, 8, 24); 1824 else 1825 return false; 1826 } 1827 } 1828 1829 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1830 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1831 /// The ShuffleKind distinguishes between big-endian merges with two 1832 /// different inputs (0), either-endian merges with two identical inputs (1), 1833 /// and little-endian merges with two different inputs (2). For the latter, 1834 /// the input operands are swapped (see PPCInstrAltivec.td). 1835 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1836 unsigned ShuffleKind, SelectionDAG &DAG) { 1837 if (DAG.getDataLayout().isLittleEndian()) { 1838 if (ShuffleKind == 1) // unary 1839 return isVMerge(N, UnitSize, 8, 8); 1840 else if (ShuffleKind == 2) // swapped 1841 return isVMerge(N, UnitSize, 8, 24); 1842 else 1843 return false; 1844 } else { 1845 if (ShuffleKind == 1) // unary 1846 return isVMerge(N, UnitSize, 0, 0); 1847 else if (ShuffleKind == 0) // normal 1848 return isVMerge(N, UnitSize, 0, 16); 1849 else 1850 return false; 1851 } 1852 } 1853 1854 /** 1855 * Common function used to match vmrgew and vmrgow shuffles 1856 * 1857 * The indexOffset determines whether to look for even or odd words in 1858 * the shuffle mask. This is based on the of the endianness of the target 1859 * machine. 1860 * - Little Endian: 1861 * - Use offset of 0 to check for odd elements 1862 * - Use offset of 4 to check for even elements 1863 * - Big Endian: 1864 * - Use offset of 0 to check for even elements 1865 * - Use offset of 4 to check for odd elements 1866 * A detailed description of the vector element ordering for little endian and 1867 * big endian can be found at 1868 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1869 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1870 * compiler differences mean to you 1871 * 1872 * The mask to the shuffle vector instruction specifies the indices of the 1873 * elements from the two input vectors to place in the result. The elements are 1874 * numbered in array-access order, starting with the first vector. These vectors 1875 * are always of type v16i8, thus each vector will contain 16 elements of size 1876 * 8. More info on the shuffle vector can be found in the 1877 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1878 * Language Reference. 1879 * 1880 * The RHSStartValue indicates whether the same input vectors are used (unary) 1881 * or two different input vectors are used, based on the following: 1882 * - If the instruction uses the same vector for both inputs, the range of the 1883 * indices will be 0 to 15. In this case, the RHSStart value passed should 1884 * be 0. 1885 * - If the instruction has two different vectors then the range of the 1886 * indices will be 0 to 31. In this case, the RHSStart value passed should 1887 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1888 * to 31 specify elements in the second vector). 1889 * 1890 * \param[in] N The shuffle vector SD Node to analyze 1891 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1892 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1893 * vector to the shuffle_vector instruction 1894 * \return true iff this shuffle vector represents an even or odd word merge 1895 */ 1896 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1897 unsigned RHSStartValue) { 1898 if (N->getValueType(0) != MVT::v16i8) 1899 return false; 1900 1901 for (unsigned i = 0; i < 2; ++i) 1902 for (unsigned j = 0; j < 4; ++j) 1903 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1904 i*RHSStartValue+j+IndexOffset) || 1905 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1906 i*RHSStartValue+j+IndexOffset+8)) 1907 return false; 1908 return true; 1909 } 1910 1911 /** 1912 * Determine if the specified shuffle mask is suitable for the vmrgew or 1913 * vmrgow instructions. 1914 * 1915 * \param[in] N The shuffle vector SD Node to analyze 1916 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1917 * \param[in] ShuffleKind Identify the type of merge: 1918 * - 0 = big-endian merge with two different inputs; 1919 * - 1 = either-endian merge with two identical inputs; 1920 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1921 * little-endian merges). 1922 * \param[in] DAG The current SelectionDAG 1923 * \return true iff this shuffle mask 1924 */ 1925 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1926 unsigned ShuffleKind, SelectionDAG &DAG) { 1927 if (DAG.getDataLayout().isLittleEndian()) { 1928 unsigned indexOffset = CheckEven ? 4 : 0; 1929 if (ShuffleKind == 1) // Unary 1930 return isVMerge(N, indexOffset, 0); 1931 else if (ShuffleKind == 2) // swapped 1932 return isVMerge(N, indexOffset, 16); 1933 else 1934 return false; 1935 } 1936 else { 1937 unsigned indexOffset = CheckEven ? 0 : 4; 1938 if (ShuffleKind == 1) // Unary 1939 return isVMerge(N, indexOffset, 0); 1940 else if (ShuffleKind == 0) // Normal 1941 return isVMerge(N, indexOffset, 16); 1942 else 1943 return false; 1944 } 1945 return false; 1946 } 1947 1948 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1949 /// amount, otherwise return -1. 1950 /// The ShuffleKind distinguishes between big-endian operations with two 1951 /// different inputs (0), either-endian operations with two identical inputs 1952 /// (1), and little-endian operations with two different inputs (2). For the 1953 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1954 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1955 SelectionDAG &DAG) { 1956 if (N->getValueType(0) != MVT::v16i8) 1957 return -1; 1958 1959 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1960 1961 // Find the first non-undef value in the shuffle mask. 1962 unsigned i; 1963 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1964 /*search*/; 1965 1966 if (i == 16) return -1; // all undef. 1967 1968 // Otherwise, check to see if the rest of the elements are consecutively 1969 // numbered from this value. 1970 unsigned ShiftAmt = SVOp->getMaskElt(i); 1971 if (ShiftAmt < i) return -1; 1972 1973 ShiftAmt -= i; 1974 bool isLE = DAG.getDataLayout().isLittleEndian(); 1975 1976 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1977 // Check the rest of the elements to see if they are consecutive. 1978 for (++i; i != 16; ++i) 1979 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1980 return -1; 1981 } else if (ShuffleKind == 1) { 1982 // Check the rest of the elements to see if they are consecutive. 1983 for (++i; i != 16; ++i) 1984 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1985 return -1; 1986 } else 1987 return -1; 1988 1989 if (isLE) 1990 ShiftAmt = 16 - ShiftAmt; 1991 1992 return ShiftAmt; 1993 } 1994 1995 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1996 /// specifies a splat of a single element that is suitable for input to 1997 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1998 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1999 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 2000 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2001 2002 // The consecutive indices need to specify an element, not part of two 2003 // different elements. So abandon ship early if this isn't the case. 2004 if (N->getMaskElt(0) % EltSize != 0) 2005 return false; 2006 2007 // This is a splat operation if each element of the permute is the same, and 2008 // if the value doesn't reference the second vector. 2009 unsigned ElementBase = N->getMaskElt(0); 2010 2011 // FIXME: Handle UNDEF elements too! 2012 if (ElementBase >= 16) 2013 return false; 2014 2015 // Check that the indices are consecutive, in the case of a multi-byte element 2016 // splatted with a v16i8 mask. 2017 for (unsigned i = 1; i != EltSize; ++i) 2018 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2019 return false; 2020 2021 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2022 if (N->getMaskElt(i) < 0) continue; 2023 for (unsigned j = 0; j != EltSize; ++j) 2024 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2025 return false; 2026 } 2027 return true; 2028 } 2029 2030 /// Check that the mask is shuffling N byte elements. Within each N byte 2031 /// element of the mask, the indices could be either in increasing or 2032 /// decreasing order as long as they are consecutive. 2033 /// \param[in] N the shuffle vector SD Node to analyze 2034 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2035 /// Word/DoubleWord/QuadWord). 2036 /// \param[in] StepLen the delta indices number among the N byte element, if 2037 /// the mask is in increasing/decreasing order then it is 1/-1. 2038 /// \return true iff the mask is shuffling N byte elements. 2039 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2040 int StepLen) { 2041 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2042 "Unexpected element width."); 2043 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2044 2045 unsigned NumOfElem = 16 / Width; 2046 unsigned MaskVal[16]; // Width is never greater than 16 2047 for (unsigned i = 0; i < NumOfElem; ++i) { 2048 MaskVal[0] = N->getMaskElt(i * Width); 2049 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2050 return false; 2051 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2052 return false; 2053 } 2054 2055 for (unsigned int j = 1; j < Width; ++j) { 2056 MaskVal[j] = N->getMaskElt(i * Width + j); 2057 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2058 return false; 2059 } 2060 } 2061 } 2062 2063 return true; 2064 } 2065 2066 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2067 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2068 if (!isNByteElemShuffleMask(N, 4, 1)) 2069 return false; 2070 2071 // Now we look at mask elements 0,4,8,12 2072 unsigned M0 = N->getMaskElt(0) / 4; 2073 unsigned M1 = N->getMaskElt(4) / 4; 2074 unsigned M2 = N->getMaskElt(8) / 4; 2075 unsigned M3 = N->getMaskElt(12) / 4; 2076 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2077 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2078 2079 // Below, let H and L be arbitrary elements of the shuffle mask 2080 // where H is in the range [4,7] and L is in the range [0,3]. 2081 // H, 1, 2, 3 or L, 5, 6, 7 2082 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2083 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2084 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2085 InsertAtByte = IsLE ? 12 : 0; 2086 Swap = M0 < 4; 2087 return true; 2088 } 2089 // 0, H, 2, 3 or 4, L, 6, 7 2090 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2091 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2092 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2093 InsertAtByte = IsLE ? 8 : 4; 2094 Swap = M1 < 4; 2095 return true; 2096 } 2097 // 0, 1, H, 3 or 4, 5, L, 7 2098 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2099 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2100 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2101 InsertAtByte = IsLE ? 4 : 8; 2102 Swap = M2 < 4; 2103 return true; 2104 } 2105 // 0, 1, 2, H or 4, 5, 6, L 2106 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2107 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2108 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2109 InsertAtByte = IsLE ? 0 : 12; 2110 Swap = M3 < 4; 2111 return true; 2112 } 2113 2114 // If both vector operands for the shuffle are the same vector, the mask will 2115 // contain only elements from the first one and the second one will be undef. 2116 if (N->getOperand(1).isUndef()) { 2117 ShiftElts = 0; 2118 Swap = true; 2119 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2120 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2121 InsertAtByte = IsLE ? 12 : 0; 2122 return true; 2123 } 2124 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2125 InsertAtByte = IsLE ? 8 : 4; 2126 return true; 2127 } 2128 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2129 InsertAtByte = IsLE ? 4 : 8; 2130 return true; 2131 } 2132 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2133 InsertAtByte = IsLE ? 0 : 12; 2134 return true; 2135 } 2136 } 2137 2138 return false; 2139 } 2140 2141 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2142 bool &Swap, bool IsLE) { 2143 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2144 // Ensure each byte index of the word is consecutive. 2145 if (!isNByteElemShuffleMask(N, 4, 1)) 2146 return false; 2147 2148 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2149 unsigned M0 = N->getMaskElt(0) / 4; 2150 unsigned M1 = N->getMaskElt(4) / 4; 2151 unsigned M2 = N->getMaskElt(8) / 4; 2152 unsigned M3 = N->getMaskElt(12) / 4; 2153 2154 // If both vector operands for the shuffle are the same vector, the mask will 2155 // contain only elements from the first one and the second one will be undef. 2156 if (N->getOperand(1).isUndef()) { 2157 assert(M0 < 4 && "Indexing into an undef vector?"); 2158 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2159 return false; 2160 2161 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2162 Swap = false; 2163 return true; 2164 } 2165 2166 // Ensure each word index of the ShuffleVector Mask is consecutive. 2167 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2168 return false; 2169 2170 if (IsLE) { 2171 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2172 // Input vectors don't need to be swapped if the leading element 2173 // of the result is one of the 3 left elements of the second vector 2174 // (or if there is no shift to be done at all). 2175 Swap = false; 2176 ShiftElts = (8 - M0) % 8; 2177 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2178 // Input vectors need to be swapped if the leading element 2179 // of the result is one of the 3 left elements of the first vector 2180 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2181 Swap = true; 2182 ShiftElts = (4 - M0) % 4; 2183 } 2184 2185 return true; 2186 } else { // BE 2187 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2188 // Input vectors don't need to be swapped if the leading element 2189 // of the result is one of the 4 elements of the first vector. 2190 Swap = false; 2191 ShiftElts = M0; 2192 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2193 // Input vectors need to be swapped if the leading element 2194 // of the result is one of the 4 elements of the right vector. 2195 Swap = true; 2196 ShiftElts = M0 - 4; 2197 } 2198 2199 return true; 2200 } 2201 } 2202 2203 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2204 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2205 2206 if (!isNByteElemShuffleMask(N, Width, -1)) 2207 return false; 2208 2209 for (int i = 0; i < 16; i += Width) 2210 if (N->getMaskElt(i) != i + Width - 1) 2211 return false; 2212 2213 return true; 2214 } 2215 2216 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2217 return isXXBRShuffleMaskHelper(N, 2); 2218 } 2219 2220 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2221 return isXXBRShuffleMaskHelper(N, 4); 2222 } 2223 2224 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2225 return isXXBRShuffleMaskHelper(N, 8); 2226 } 2227 2228 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2229 return isXXBRShuffleMaskHelper(N, 16); 2230 } 2231 2232 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2233 /// if the inputs to the instruction should be swapped and set \p DM to the 2234 /// value for the immediate. 2235 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2236 /// AND element 0 of the result comes from the first input (LE) or second input 2237 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2238 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2239 /// mask. 2240 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2241 bool &Swap, bool IsLE) { 2242 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2243 2244 // Ensure each byte index of the double word is consecutive. 2245 if (!isNByteElemShuffleMask(N, 8, 1)) 2246 return false; 2247 2248 unsigned M0 = N->getMaskElt(0) / 8; 2249 unsigned M1 = N->getMaskElt(8) / 8; 2250 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2251 2252 // If both vector operands for the shuffle are the same vector, the mask will 2253 // contain only elements from the first one and the second one will be undef. 2254 if (N->getOperand(1).isUndef()) { 2255 if ((M0 | M1) < 2) { 2256 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2257 Swap = false; 2258 return true; 2259 } else 2260 return false; 2261 } 2262 2263 if (IsLE) { 2264 if (M0 > 1 && M1 < 2) { 2265 Swap = false; 2266 } else if (M0 < 2 && M1 > 1) { 2267 M0 = (M0 + 2) % 4; 2268 M1 = (M1 + 2) % 4; 2269 Swap = true; 2270 } else 2271 return false; 2272 2273 // Note: if control flow comes here that means Swap is already set above 2274 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2275 return true; 2276 } else { // BE 2277 if (M0 < 2 && M1 > 1) { 2278 Swap = false; 2279 } else if (M0 > 1 && M1 < 2) { 2280 M0 = (M0 + 2) % 4; 2281 M1 = (M1 + 2) % 4; 2282 Swap = true; 2283 } else 2284 return false; 2285 2286 // Note: if control flow comes here that means Swap is already set above 2287 DM = (M0 << 1) + (M1 & 1); 2288 return true; 2289 } 2290 } 2291 2292 2293 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2294 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2295 /// elements are counted from the left of the vector register). 2296 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2297 SelectionDAG &DAG) { 2298 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2299 assert(isSplatShuffleMask(SVOp, EltSize)); 2300 if (DAG.getDataLayout().isLittleEndian()) 2301 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2302 else 2303 return SVOp->getMaskElt(0) / EltSize; 2304 } 2305 2306 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2307 /// by using a vspltis[bhw] instruction of the specified element size, return 2308 /// the constant being splatted. The ByteSize field indicates the number of 2309 /// bytes of each element [124] -> [bhw]. 2310 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2311 SDValue OpVal(nullptr, 0); 2312 2313 // If ByteSize of the splat is bigger than the element size of the 2314 // build_vector, then we have a case where we are checking for a splat where 2315 // multiple elements of the buildvector are folded together into a single 2316 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2317 unsigned EltSize = 16/N->getNumOperands(); 2318 if (EltSize < ByteSize) { 2319 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2320 SDValue UniquedVals[4]; 2321 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2322 2323 // See if all of the elements in the buildvector agree across. 2324 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2325 if (N->getOperand(i).isUndef()) continue; 2326 // If the element isn't a constant, bail fully out. 2327 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2328 2329 if (!UniquedVals[i&(Multiple-1)].getNode()) 2330 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2331 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2332 return SDValue(); // no match. 2333 } 2334 2335 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2336 // either constant or undef values that are identical for each chunk. See 2337 // if these chunks can form into a larger vspltis*. 2338 2339 // Check to see if all of the leading entries are either 0 or -1. If 2340 // neither, then this won't fit into the immediate field. 2341 bool LeadingZero = true; 2342 bool LeadingOnes = true; 2343 for (unsigned i = 0; i != Multiple-1; ++i) { 2344 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2345 2346 LeadingZero &= isNullConstant(UniquedVals[i]); 2347 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2348 } 2349 // Finally, check the least significant entry. 2350 if (LeadingZero) { 2351 if (!UniquedVals[Multiple-1].getNode()) 2352 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2353 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2354 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2355 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2356 } 2357 if (LeadingOnes) { 2358 if (!UniquedVals[Multiple-1].getNode()) 2359 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2360 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2361 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2362 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2363 } 2364 2365 return SDValue(); 2366 } 2367 2368 // Check to see if this buildvec has a single non-undef value in its elements. 2369 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2370 if (N->getOperand(i).isUndef()) continue; 2371 if (!OpVal.getNode()) 2372 OpVal = N->getOperand(i); 2373 else if (OpVal != N->getOperand(i)) 2374 return SDValue(); 2375 } 2376 2377 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2378 2379 unsigned ValSizeInBytes = EltSize; 2380 uint64_t Value = 0; 2381 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2382 Value = CN->getZExtValue(); 2383 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2384 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2385 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2386 } 2387 2388 // If the splat value is larger than the element value, then we can never do 2389 // this splat. The only case that we could fit the replicated bits into our 2390 // immediate field for would be zero, and we prefer to use vxor for it. 2391 if (ValSizeInBytes < ByteSize) return SDValue(); 2392 2393 // If the element value is larger than the splat value, check if it consists 2394 // of a repeated bit pattern of size ByteSize. 2395 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2396 return SDValue(); 2397 2398 // Properly sign extend the value. 2399 int MaskVal = SignExtend32(Value, ByteSize * 8); 2400 2401 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2402 if (MaskVal == 0) return SDValue(); 2403 2404 // Finally, if this value fits in a 5 bit sext field, return it 2405 if (SignExtend32<5>(MaskVal) == MaskVal) 2406 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2407 return SDValue(); 2408 } 2409 2410 //===----------------------------------------------------------------------===// 2411 // Addressing Mode Selection 2412 //===----------------------------------------------------------------------===// 2413 2414 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2415 /// or 64-bit immediate, and if the value can be accurately represented as a 2416 /// sign extension from a 16-bit value. If so, this returns true and the 2417 /// immediate. 2418 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2419 if (!isa<ConstantSDNode>(N)) 2420 return false; 2421 2422 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2423 if (N->getValueType(0) == MVT::i32) 2424 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2425 else 2426 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2427 } 2428 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2429 return isIntS16Immediate(Op.getNode(), Imm); 2430 } 2431 2432 2433 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2434 /// be represented as an indexed [r+r] operation. 2435 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2436 SDValue &Index, 2437 SelectionDAG &DAG) const { 2438 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2439 UI != E; ++UI) { 2440 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2441 if (Memop->getMemoryVT() == MVT::f64) { 2442 Base = N.getOperand(0); 2443 Index = N.getOperand(1); 2444 return true; 2445 } 2446 } 2447 } 2448 return false; 2449 } 2450 2451 /// isIntS34Immediate - This method tests if value of node given can be 2452 /// accurately represented as a sign extension from a 34-bit value. If so, 2453 /// this returns true and the immediate. 2454 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2455 if (!isa<ConstantSDNode>(N)) 2456 return false; 2457 2458 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2459 return isInt<34>(Imm); 2460 } 2461 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2462 return isIntS34Immediate(Op.getNode(), Imm); 2463 } 2464 2465 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2466 /// can be represented as an indexed [r+r] operation. Returns false if it 2467 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2468 /// non-zero and N can be represented by a base register plus a signed 16-bit 2469 /// displacement, make a more precise judgement by checking (displacement % \p 2470 /// EncodingAlignment). 2471 bool PPCTargetLowering::SelectAddressRegReg( 2472 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2473 MaybeAlign EncodingAlignment) const { 2474 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2475 // a [pc+imm]. 2476 if (SelectAddressPCRel(N, Base)) 2477 return false; 2478 2479 int16_t Imm = 0; 2480 if (N.getOpcode() == ISD::ADD) { 2481 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2482 // SPE load/store can only handle 8-bit offsets. 2483 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2484 return true; 2485 if (isIntS16Immediate(N.getOperand(1), Imm) && 2486 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2487 return false; // r+i 2488 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2489 return false; // r+i 2490 2491 Base = N.getOperand(0); 2492 Index = N.getOperand(1); 2493 return true; 2494 } else if (N.getOpcode() == ISD::OR) { 2495 if (isIntS16Immediate(N.getOperand(1), Imm) && 2496 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2497 return false; // r+i can fold it if we can. 2498 2499 // If this is an or of disjoint bitfields, we can codegen this as an add 2500 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2501 // disjoint. 2502 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2503 2504 if (LHSKnown.Zero.getBoolValue()) { 2505 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2506 // If all of the bits are known zero on the LHS or RHS, the add won't 2507 // carry. 2508 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2509 Base = N.getOperand(0); 2510 Index = N.getOperand(1); 2511 return true; 2512 } 2513 } 2514 } 2515 2516 return false; 2517 } 2518 2519 // If we happen to be doing an i64 load or store into a stack slot that has 2520 // less than a 4-byte alignment, then the frame-index elimination may need to 2521 // use an indexed load or store instruction (because the offset may not be a 2522 // multiple of 4). The extra register needed to hold the offset comes from the 2523 // register scavenger, and it is possible that the scavenger will need to use 2524 // an emergency spill slot. As a result, we need to make sure that a spill slot 2525 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2526 // stack slot. 2527 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2528 // FIXME: This does not handle the LWA case. 2529 if (VT != MVT::i64) 2530 return; 2531 2532 // NOTE: We'll exclude negative FIs here, which come from argument 2533 // lowering, because there are no known test cases triggering this problem 2534 // using packed structures (or similar). We can remove this exclusion if 2535 // we find such a test case. The reason why this is so test-case driven is 2536 // because this entire 'fixup' is only to prevent crashes (from the 2537 // register scavenger) on not-really-valid inputs. For example, if we have: 2538 // %a = alloca i1 2539 // %b = bitcast i1* %a to i64* 2540 // store i64* a, i64 b 2541 // then the store should really be marked as 'align 1', but is not. If it 2542 // were marked as 'align 1' then the indexed form would have been 2543 // instruction-selected initially, and the problem this 'fixup' is preventing 2544 // won't happen regardless. 2545 if (FrameIdx < 0) 2546 return; 2547 2548 MachineFunction &MF = DAG.getMachineFunction(); 2549 MachineFrameInfo &MFI = MF.getFrameInfo(); 2550 2551 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2552 return; 2553 2554 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2555 FuncInfo->setHasNonRISpills(); 2556 } 2557 2558 /// Returns true if the address N can be represented by a base register plus 2559 /// a signed 16-bit displacement [r+imm], and if it is not better 2560 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2561 /// displacements that are multiples of that value. 2562 bool PPCTargetLowering::SelectAddressRegImm( 2563 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2564 MaybeAlign EncodingAlignment) const { 2565 // FIXME dl should come from parent load or store, not from address 2566 SDLoc dl(N); 2567 2568 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2569 // a [pc+imm]. 2570 if (SelectAddressPCRel(N, Base)) 2571 return false; 2572 2573 // If this can be more profitably realized as r+r, fail. 2574 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2575 return false; 2576 2577 if (N.getOpcode() == ISD::ADD) { 2578 int16_t imm = 0; 2579 if (isIntS16Immediate(N.getOperand(1), imm) && 2580 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2581 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2582 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2583 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2584 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2585 } else { 2586 Base = N.getOperand(0); 2587 } 2588 return true; // [r+i] 2589 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2590 // Match LOAD (ADD (X, Lo(G))). 2591 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2592 && "Cannot handle constant offsets yet!"); 2593 Disp = N.getOperand(1).getOperand(0); // The global address. 2594 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2595 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2596 Disp.getOpcode() == ISD::TargetConstantPool || 2597 Disp.getOpcode() == ISD::TargetJumpTable); 2598 Base = N.getOperand(0); 2599 return true; // [&g+r] 2600 } 2601 } else if (N.getOpcode() == ISD::OR) { 2602 int16_t imm = 0; 2603 if (isIntS16Immediate(N.getOperand(1), imm) && 2604 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2605 // If this is an or of disjoint bitfields, we can codegen this as an add 2606 // (for better address arithmetic) if the LHS and RHS of the OR are 2607 // provably disjoint. 2608 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2609 2610 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2611 // If all of the bits are known zero on the LHS or RHS, the add won't 2612 // carry. 2613 if (FrameIndexSDNode *FI = 2614 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2615 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2616 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2617 } else { 2618 Base = N.getOperand(0); 2619 } 2620 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2621 return true; 2622 } 2623 } 2624 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2625 // Loading from a constant address. 2626 2627 // If this address fits entirely in a 16-bit sext immediate field, codegen 2628 // this as "d, 0" 2629 int16_t Imm; 2630 if (isIntS16Immediate(CN, Imm) && 2631 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2632 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2633 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2634 CN->getValueType(0)); 2635 return true; 2636 } 2637 2638 // Handle 32-bit sext immediates with LIS + addr mode. 2639 if ((CN->getValueType(0) == MVT::i32 || 2640 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2641 (!EncodingAlignment || 2642 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2643 int Addr = (int)CN->getZExtValue(); 2644 2645 // Otherwise, break this down into an LIS + disp. 2646 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2647 2648 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2649 MVT::i32); 2650 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2651 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2652 return true; 2653 } 2654 } 2655 2656 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2657 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2658 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2659 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2660 } else 2661 Base = N; 2662 return true; // [r+0] 2663 } 2664 2665 /// Similar to the 16-bit case but for instructions that take a 34-bit 2666 /// displacement field (prefixed loads/stores). 2667 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2668 SDValue &Base, 2669 SelectionDAG &DAG) const { 2670 // Only on 64-bit targets. 2671 if (N.getValueType() != MVT::i64) 2672 return false; 2673 2674 SDLoc dl(N); 2675 int64_t Imm = 0; 2676 2677 if (N.getOpcode() == ISD::ADD) { 2678 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2679 return false; 2680 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2681 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2682 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2683 else 2684 Base = N.getOperand(0); 2685 return true; 2686 } 2687 2688 if (N.getOpcode() == ISD::OR) { 2689 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2690 return false; 2691 // If this is an or of disjoint bitfields, we can codegen this as an add 2692 // (for better address arithmetic) if the LHS and RHS of the OR are 2693 // provably disjoint. 2694 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2695 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2696 return false; 2697 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2698 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2699 else 2700 Base = N.getOperand(0); 2701 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2702 return true; 2703 } 2704 2705 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2706 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2707 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2708 return true; 2709 } 2710 2711 return false; 2712 } 2713 2714 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2715 /// represented as an indexed [r+r] operation. 2716 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2717 SDValue &Index, 2718 SelectionDAG &DAG) const { 2719 // Check to see if we can easily represent this as an [r+r] address. This 2720 // will fail if it thinks that the address is more profitably represented as 2721 // reg+imm, e.g. where imm = 0. 2722 if (SelectAddressRegReg(N, Base, Index, DAG)) 2723 return true; 2724 2725 // If the address is the result of an add, we will utilize the fact that the 2726 // address calculation includes an implicit add. However, we can reduce 2727 // register pressure if we do not materialize a constant just for use as the 2728 // index register. We only get rid of the add if it is not an add of a 2729 // value and a 16-bit signed constant and both have a single use. 2730 int16_t imm = 0; 2731 if (N.getOpcode() == ISD::ADD && 2732 (!isIntS16Immediate(N.getOperand(1), imm) || 2733 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2734 Base = N.getOperand(0); 2735 Index = N.getOperand(1); 2736 return true; 2737 } 2738 2739 // Otherwise, do it the hard way, using R0 as the base register. 2740 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2741 N.getValueType()); 2742 Index = N; 2743 return true; 2744 } 2745 2746 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2747 Ty *PCRelCand = dyn_cast<Ty>(N); 2748 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2749 } 2750 2751 /// Returns true if this address is a PC Relative address. 2752 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2753 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2754 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2755 // This is a materialize PC Relative node. Always select this as PC Relative. 2756 Base = N; 2757 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2758 return true; 2759 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2760 isValidPCRelNode<GlobalAddressSDNode>(N) || 2761 isValidPCRelNode<JumpTableSDNode>(N) || 2762 isValidPCRelNode<BlockAddressSDNode>(N)) 2763 return true; 2764 return false; 2765 } 2766 2767 /// Returns true if we should use a direct load into vector instruction 2768 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2769 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2770 2771 // If there are any other uses other than scalar to vector, then we should 2772 // keep it as a scalar load -> direct move pattern to prevent multiple 2773 // loads. 2774 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2775 if (!LD) 2776 return false; 2777 2778 EVT MemVT = LD->getMemoryVT(); 2779 if (!MemVT.isSimple()) 2780 return false; 2781 switch(MemVT.getSimpleVT().SimpleTy) { 2782 case MVT::i64: 2783 break; 2784 case MVT::i32: 2785 if (!ST.hasP8Vector()) 2786 return false; 2787 break; 2788 case MVT::i16: 2789 case MVT::i8: 2790 if (!ST.hasP9Vector()) 2791 return false; 2792 break; 2793 default: 2794 return false; 2795 } 2796 2797 SDValue LoadedVal(N, 0); 2798 if (!LoadedVal.hasOneUse()) 2799 return false; 2800 2801 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2802 UI != UE; ++UI) 2803 if (UI.getUse().get().getResNo() == 0 && 2804 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2805 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2806 return false; 2807 2808 return true; 2809 } 2810 2811 /// getPreIndexedAddressParts - returns true by value, base pointer and 2812 /// offset pointer and addressing mode by reference if the node's address 2813 /// can be legally represented as pre-indexed load / store address. 2814 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2815 SDValue &Offset, 2816 ISD::MemIndexedMode &AM, 2817 SelectionDAG &DAG) const { 2818 if (DisablePPCPreinc) return false; 2819 2820 bool isLoad = true; 2821 SDValue Ptr; 2822 EVT VT; 2823 unsigned Alignment; 2824 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2825 Ptr = LD->getBasePtr(); 2826 VT = LD->getMemoryVT(); 2827 Alignment = LD->getAlignment(); 2828 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2829 Ptr = ST->getBasePtr(); 2830 VT = ST->getMemoryVT(); 2831 Alignment = ST->getAlignment(); 2832 isLoad = false; 2833 } else 2834 return false; 2835 2836 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2837 // instructions because we can fold these into a more efficient instruction 2838 // instead, (such as LXSD). 2839 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2840 return false; 2841 } 2842 2843 // PowerPC doesn't have preinc load/store instructions for vectors 2844 if (VT.isVector()) 2845 return false; 2846 2847 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2848 // Common code will reject creating a pre-inc form if the base pointer 2849 // is a frame index, or if N is a store and the base pointer is either 2850 // the same as or a predecessor of the value being stored. Check for 2851 // those situations here, and try with swapped Base/Offset instead. 2852 bool Swap = false; 2853 2854 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2855 Swap = true; 2856 else if (!isLoad) { 2857 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2858 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2859 Swap = true; 2860 } 2861 2862 if (Swap) 2863 std::swap(Base, Offset); 2864 2865 AM = ISD::PRE_INC; 2866 return true; 2867 } 2868 2869 // LDU/STU can only handle immediates that are a multiple of 4. 2870 if (VT != MVT::i64) { 2871 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2872 return false; 2873 } else { 2874 // LDU/STU need an address with at least 4-byte alignment. 2875 if (Alignment < 4) 2876 return false; 2877 2878 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2879 return false; 2880 } 2881 2882 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2883 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2884 // sext i32 to i64 when addr mode is r+i. 2885 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2886 LD->getExtensionType() == ISD::SEXTLOAD && 2887 isa<ConstantSDNode>(Offset)) 2888 return false; 2889 } 2890 2891 AM = ISD::PRE_INC; 2892 return true; 2893 } 2894 2895 //===----------------------------------------------------------------------===// 2896 // LowerOperation implementation 2897 //===----------------------------------------------------------------------===// 2898 2899 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2900 /// and LoOpFlags to the target MO flags. 2901 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2902 unsigned &HiOpFlags, unsigned &LoOpFlags, 2903 const GlobalValue *GV = nullptr) { 2904 HiOpFlags = PPCII::MO_HA; 2905 LoOpFlags = PPCII::MO_LO; 2906 2907 // Don't use the pic base if not in PIC relocation model. 2908 if (IsPIC) { 2909 HiOpFlags |= PPCII::MO_PIC_FLAG; 2910 LoOpFlags |= PPCII::MO_PIC_FLAG; 2911 } 2912 } 2913 2914 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2915 SelectionDAG &DAG) { 2916 SDLoc DL(HiPart); 2917 EVT PtrVT = HiPart.getValueType(); 2918 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2919 2920 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2921 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2922 2923 // With PIC, the first instruction is actually "GR+hi(&G)". 2924 if (isPIC) 2925 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2926 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2927 2928 // Generate non-pic code that has direct accesses to the constant pool. 2929 // The address of the global is just (hi(&g)+lo(&g)). 2930 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2931 } 2932 2933 static void setUsesTOCBasePtr(MachineFunction &MF) { 2934 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2935 FuncInfo->setUsesTOCBasePtr(); 2936 } 2937 2938 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2939 setUsesTOCBasePtr(DAG.getMachineFunction()); 2940 } 2941 2942 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2943 SDValue GA) const { 2944 const bool Is64Bit = Subtarget.isPPC64(); 2945 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2946 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2947 : Subtarget.isAIXABI() 2948 ? DAG.getRegister(PPC::R2, VT) 2949 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2950 SDValue Ops[] = { GA, Reg }; 2951 return DAG.getMemIntrinsicNode( 2952 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2953 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2954 MachineMemOperand::MOLoad); 2955 } 2956 2957 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2958 SelectionDAG &DAG) const { 2959 EVT PtrVT = Op.getValueType(); 2960 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2961 const Constant *C = CP->getConstVal(); 2962 2963 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2964 // The actual address of the GlobalValue is stored in the TOC. 2965 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2966 if (Subtarget.isUsingPCRelativeCalls()) { 2967 SDLoc DL(CP); 2968 EVT Ty = getPointerTy(DAG.getDataLayout()); 2969 SDValue ConstPool = DAG.getTargetConstantPool( 2970 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2971 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2972 } 2973 setUsesTOCBasePtr(DAG); 2974 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2975 return getTOCEntry(DAG, SDLoc(CP), GA); 2976 } 2977 2978 unsigned MOHiFlag, MOLoFlag; 2979 bool IsPIC = isPositionIndependent(); 2980 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2981 2982 if (IsPIC && Subtarget.isSVR4ABI()) { 2983 SDValue GA = 2984 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2985 return getTOCEntry(DAG, SDLoc(CP), GA); 2986 } 2987 2988 SDValue CPIHi = 2989 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2990 SDValue CPILo = 2991 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2992 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2993 } 2994 2995 // For 64-bit PowerPC, prefer the more compact relative encodings. 2996 // This trades 32 bits per jump table entry for one or two instructions 2997 // on the jump site. 2998 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2999 if (isJumpTableRelative()) 3000 return MachineJumpTableInfo::EK_LabelDifference32; 3001 3002 return TargetLowering::getJumpTableEncoding(); 3003 } 3004 3005 bool PPCTargetLowering::isJumpTableRelative() const { 3006 if (UseAbsoluteJumpTables) 3007 return false; 3008 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3009 return true; 3010 return TargetLowering::isJumpTableRelative(); 3011 } 3012 3013 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3014 SelectionDAG &DAG) const { 3015 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3016 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3017 3018 switch (getTargetMachine().getCodeModel()) { 3019 case CodeModel::Small: 3020 case CodeModel::Medium: 3021 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3022 default: 3023 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3024 getPointerTy(DAG.getDataLayout())); 3025 } 3026 } 3027 3028 const MCExpr * 3029 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3030 unsigned JTI, 3031 MCContext &Ctx) const { 3032 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3033 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3034 3035 switch (getTargetMachine().getCodeModel()) { 3036 case CodeModel::Small: 3037 case CodeModel::Medium: 3038 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3039 default: 3040 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3041 } 3042 } 3043 3044 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3045 EVT PtrVT = Op.getValueType(); 3046 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3047 3048 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3049 if (Subtarget.isUsingPCRelativeCalls()) { 3050 SDLoc DL(JT); 3051 EVT Ty = getPointerTy(DAG.getDataLayout()); 3052 SDValue GA = 3053 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3054 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3055 return MatAddr; 3056 } 3057 3058 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3059 // The actual address of the GlobalValue is stored in the TOC. 3060 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3061 setUsesTOCBasePtr(DAG); 3062 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3063 return getTOCEntry(DAG, SDLoc(JT), GA); 3064 } 3065 3066 unsigned MOHiFlag, MOLoFlag; 3067 bool IsPIC = isPositionIndependent(); 3068 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3069 3070 if (IsPIC && Subtarget.isSVR4ABI()) { 3071 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3072 PPCII::MO_PIC_FLAG); 3073 return getTOCEntry(DAG, SDLoc(GA), GA); 3074 } 3075 3076 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3077 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3078 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3079 } 3080 3081 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3082 SelectionDAG &DAG) const { 3083 EVT PtrVT = Op.getValueType(); 3084 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3085 const BlockAddress *BA = BASDN->getBlockAddress(); 3086 3087 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3088 if (Subtarget.isUsingPCRelativeCalls()) { 3089 SDLoc DL(BASDN); 3090 EVT Ty = getPointerTy(DAG.getDataLayout()); 3091 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3092 PPCII::MO_PCREL_FLAG); 3093 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3094 return MatAddr; 3095 } 3096 3097 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3098 // The actual BlockAddress is stored in the TOC. 3099 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3100 setUsesTOCBasePtr(DAG); 3101 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3102 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3103 } 3104 3105 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3106 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3107 return getTOCEntry( 3108 DAG, SDLoc(BASDN), 3109 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3110 3111 unsigned MOHiFlag, MOLoFlag; 3112 bool IsPIC = isPositionIndependent(); 3113 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3114 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3115 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3116 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3117 } 3118 3119 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3120 SelectionDAG &DAG) const { 3121 if (Subtarget.isAIXABI()) 3122 return LowerGlobalTLSAddressAIX(Op, DAG); 3123 3124 return LowerGlobalTLSAddressLinux(Op, DAG); 3125 } 3126 3127 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3128 SelectionDAG &DAG) const { 3129 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3130 3131 if (DAG.getTarget().useEmulatedTLS()) 3132 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3133 3134 SDLoc dl(GA); 3135 const GlobalValue *GV = GA->getGlobal(); 3136 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3137 3138 // The general-dynamic model is the only access model supported for now, so 3139 // all the GlobalTLSAddress nodes are lowered with this model. 3140 // We need to generate two TOC entries, one for the variable offset, one for 3141 // the region handle. The global address for the TOC entry of the region 3142 // handle is created with the MO_TLSGD_FLAG flag so we can easily identify 3143 // this entry and add the right relocation. 3144 SDValue VariableOffsetTGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3145 SDValue RegionHandleTGA = 3146 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3147 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3148 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3149 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3150 RegionHandle); 3151 } 3152 3153 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3154 SelectionDAG &DAG) const { 3155 // FIXME: TLS addresses currently use medium model code sequences, 3156 // which is the most useful form. Eventually support for small and 3157 // large models could be added if users need it, at the cost of 3158 // additional complexity. 3159 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3160 if (DAG.getTarget().useEmulatedTLS()) 3161 return LowerToTLSEmulatedModel(GA, DAG); 3162 3163 SDLoc dl(GA); 3164 const GlobalValue *GV = GA->getGlobal(); 3165 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3166 bool is64bit = Subtarget.isPPC64(); 3167 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3168 PICLevel::Level picLevel = M->getPICLevel(); 3169 3170 const TargetMachine &TM = getTargetMachine(); 3171 TLSModel::Model Model = TM.getTLSModel(GV); 3172 3173 if (Model == TLSModel::LocalExec) { 3174 if (Subtarget.isUsingPCRelativeCalls()) { 3175 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3176 SDValue TGA = DAG.getTargetGlobalAddress( 3177 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3178 SDValue MatAddr = 3179 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3180 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3181 } 3182 3183 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3184 PPCII::MO_TPREL_HA); 3185 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3186 PPCII::MO_TPREL_LO); 3187 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3188 : DAG.getRegister(PPC::R2, MVT::i32); 3189 3190 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3191 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3192 } 3193 3194 if (Model == TLSModel::InitialExec) { 3195 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3196 SDValue TGA = DAG.getTargetGlobalAddress( 3197 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3198 SDValue TGATLS = DAG.getTargetGlobalAddress( 3199 GV, dl, PtrVT, 0, 3200 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3201 SDValue TPOffset; 3202 if (IsPCRel) { 3203 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3204 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3205 MachinePointerInfo()); 3206 } else { 3207 SDValue GOTPtr; 3208 if (is64bit) { 3209 setUsesTOCBasePtr(DAG); 3210 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3211 GOTPtr = 3212 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3213 } else { 3214 if (!TM.isPositionIndependent()) 3215 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3216 else if (picLevel == PICLevel::SmallPIC) 3217 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3218 else 3219 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3220 } 3221 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3222 } 3223 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3224 } 3225 3226 if (Model == TLSModel::GeneralDynamic) { 3227 if (Subtarget.isUsingPCRelativeCalls()) { 3228 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3229 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3230 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3231 } 3232 3233 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3234 SDValue GOTPtr; 3235 if (is64bit) { 3236 setUsesTOCBasePtr(DAG); 3237 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3238 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3239 GOTReg, TGA); 3240 } else { 3241 if (picLevel == PICLevel::SmallPIC) 3242 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3243 else 3244 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3245 } 3246 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3247 GOTPtr, TGA, TGA); 3248 } 3249 3250 if (Model == TLSModel::LocalDynamic) { 3251 if (Subtarget.isUsingPCRelativeCalls()) { 3252 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3253 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3254 SDValue MatPCRel = 3255 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3256 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3257 } 3258 3259 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3260 SDValue GOTPtr; 3261 if (is64bit) { 3262 setUsesTOCBasePtr(DAG); 3263 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3264 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3265 GOTReg, TGA); 3266 } else { 3267 if (picLevel == PICLevel::SmallPIC) 3268 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3269 else 3270 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3271 } 3272 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3273 PtrVT, GOTPtr, TGA, TGA); 3274 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3275 PtrVT, TLSAddr, TGA); 3276 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3277 } 3278 3279 llvm_unreachable("Unknown TLS model!"); 3280 } 3281 3282 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3283 SelectionDAG &DAG) const { 3284 EVT PtrVT = Op.getValueType(); 3285 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3286 SDLoc DL(GSDN); 3287 const GlobalValue *GV = GSDN->getGlobal(); 3288 3289 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3290 // The actual address of the GlobalValue is stored in the TOC. 3291 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3292 if (Subtarget.isUsingPCRelativeCalls()) { 3293 EVT Ty = getPointerTy(DAG.getDataLayout()); 3294 if (isAccessedAsGotIndirect(Op)) { 3295 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3296 PPCII::MO_PCREL_FLAG | 3297 PPCII::MO_GOT_FLAG); 3298 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3299 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3300 MachinePointerInfo()); 3301 return Load; 3302 } else { 3303 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3304 PPCII::MO_PCREL_FLAG); 3305 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3306 } 3307 } 3308 setUsesTOCBasePtr(DAG); 3309 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3310 return getTOCEntry(DAG, DL, GA); 3311 } 3312 3313 unsigned MOHiFlag, MOLoFlag; 3314 bool IsPIC = isPositionIndependent(); 3315 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3316 3317 if (IsPIC && Subtarget.isSVR4ABI()) { 3318 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3319 GSDN->getOffset(), 3320 PPCII::MO_PIC_FLAG); 3321 return getTOCEntry(DAG, DL, GA); 3322 } 3323 3324 SDValue GAHi = 3325 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3326 SDValue GALo = 3327 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3328 3329 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3330 } 3331 3332 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3333 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3334 SDLoc dl(Op); 3335 3336 if (Op.getValueType() == MVT::v2i64) { 3337 // When the operands themselves are v2i64 values, we need to do something 3338 // special because VSX has no underlying comparison operations for these. 3339 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3340 // Equality can be handled by casting to the legal type for Altivec 3341 // comparisons, everything else needs to be expanded. 3342 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3343 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3344 DAG.getSetCC(dl, MVT::v4i32, 3345 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3346 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3347 CC)); 3348 } 3349 3350 return SDValue(); 3351 } 3352 3353 // We handle most of these in the usual way. 3354 return Op; 3355 } 3356 3357 // If we're comparing for equality to zero, expose the fact that this is 3358 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3359 // fold the new nodes. 3360 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3361 return V; 3362 3363 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3364 // Leave comparisons against 0 and -1 alone for now, since they're usually 3365 // optimized. FIXME: revisit this when we can custom lower all setcc 3366 // optimizations. 3367 if (C->isAllOnesValue() || C->isNullValue()) 3368 return SDValue(); 3369 } 3370 3371 // If we have an integer seteq/setne, turn it into a compare against zero 3372 // by xor'ing the rhs with the lhs, which is faster than setting a 3373 // condition register, reading it back out, and masking the correct bit. The 3374 // normal approach here uses sub to do this instead of xor. Using xor exposes 3375 // the result to other bit-twiddling opportunities. 3376 EVT LHSVT = Op.getOperand(0).getValueType(); 3377 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3378 EVT VT = Op.getValueType(); 3379 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3380 Op.getOperand(1)); 3381 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3382 } 3383 return SDValue(); 3384 } 3385 3386 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3387 SDNode *Node = Op.getNode(); 3388 EVT VT = Node->getValueType(0); 3389 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3390 SDValue InChain = Node->getOperand(0); 3391 SDValue VAListPtr = Node->getOperand(1); 3392 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3393 SDLoc dl(Node); 3394 3395 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3396 3397 // gpr_index 3398 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3399 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3400 InChain = GprIndex.getValue(1); 3401 3402 if (VT == MVT::i64) { 3403 // Check if GprIndex is even 3404 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3405 DAG.getConstant(1, dl, MVT::i32)); 3406 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3407 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3408 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3409 DAG.getConstant(1, dl, MVT::i32)); 3410 // Align GprIndex to be even if it isn't 3411 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3412 GprIndex); 3413 } 3414 3415 // fpr index is 1 byte after gpr 3416 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3417 DAG.getConstant(1, dl, MVT::i32)); 3418 3419 // fpr 3420 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3421 FprPtr, MachinePointerInfo(SV), MVT::i8); 3422 InChain = FprIndex.getValue(1); 3423 3424 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3425 DAG.getConstant(8, dl, MVT::i32)); 3426 3427 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3428 DAG.getConstant(4, dl, MVT::i32)); 3429 3430 // areas 3431 SDValue OverflowArea = 3432 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3433 InChain = OverflowArea.getValue(1); 3434 3435 SDValue RegSaveArea = 3436 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3437 InChain = RegSaveArea.getValue(1); 3438 3439 // select overflow_area if index > 8 3440 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3441 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3442 3443 // adjustment constant gpr_index * 4/8 3444 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3445 VT.isInteger() ? GprIndex : FprIndex, 3446 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3447 MVT::i32)); 3448 3449 // OurReg = RegSaveArea + RegConstant 3450 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3451 RegConstant); 3452 3453 // Floating types are 32 bytes into RegSaveArea 3454 if (VT.isFloatingPoint()) 3455 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3456 DAG.getConstant(32, dl, MVT::i32)); 3457 3458 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3459 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3460 VT.isInteger() ? GprIndex : FprIndex, 3461 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3462 MVT::i32)); 3463 3464 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3465 VT.isInteger() ? VAListPtr : FprPtr, 3466 MachinePointerInfo(SV), MVT::i8); 3467 3468 // determine if we should load from reg_save_area or overflow_area 3469 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3470 3471 // increase overflow_area by 4/8 if gpr/fpr > 8 3472 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3473 DAG.getConstant(VT.isInteger() ? 4 : 8, 3474 dl, MVT::i32)); 3475 3476 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3477 OverflowAreaPlusN); 3478 3479 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3480 MachinePointerInfo(), MVT::i32); 3481 3482 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3483 } 3484 3485 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3486 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3487 3488 // We have to copy the entire va_list struct: 3489 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3490 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3491 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3492 false, true, false, MachinePointerInfo(), 3493 MachinePointerInfo()); 3494 } 3495 3496 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3497 SelectionDAG &DAG) const { 3498 if (Subtarget.isAIXABI()) 3499 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3500 3501 return Op.getOperand(0); 3502 } 3503 3504 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3505 SelectionDAG &DAG) const { 3506 if (Subtarget.isAIXABI()) 3507 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3508 3509 SDValue Chain = Op.getOperand(0); 3510 SDValue Trmp = Op.getOperand(1); // trampoline 3511 SDValue FPtr = Op.getOperand(2); // nested function 3512 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3513 SDLoc dl(Op); 3514 3515 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3516 bool isPPC64 = (PtrVT == MVT::i64); 3517 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3518 3519 TargetLowering::ArgListTy Args; 3520 TargetLowering::ArgListEntry Entry; 3521 3522 Entry.Ty = IntPtrTy; 3523 Entry.Node = Trmp; Args.push_back(Entry); 3524 3525 // TrampSize == (isPPC64 ? 48 : 40); 3526 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3527 isPPC64 ? MVT::i64 : MVT::i32); 3528 Args.push_back(Entry); 3529 3530 Entry.Node = FPtr; Args.push_back(Entry); 3531 Entry.Node = Nest; Args.push_back(Entry); 3532 3533 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3534 TargetLowering::CallLoweringInfo CLI(DAG); 3535 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3536 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3537 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3538 3539 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3540 return CallResult.second; 3541 } 3542 3543 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3544 MachineFunction &MF = DAG.getMachineFunction(); 3545 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3546 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3547 3548 SDLoc dl(Op); 3549 3550 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3551 // vastart just stores the address of the VarArgsFrameIndex slot into the 3552 // memory location argument. 3553 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3554 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3555 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3556 MachinePointerInfo(SV)); 3557 } 3558 3559 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3560 // We suppose the given va_list is already allocated. 3561 // 3562 // typedef struct { 3563 // char gpr; /* index into the array of 8 GPRs 3564 // * stored in the register save area 3565 // * gpr=0 corresponds to r3, 3566 // * gpr=1 to r4, etc. 3567 // */ 3568 // char fpr; /* index into the array of 8 FPRs 3569 // * stored in the register save area 3570 // * fpr=0 corresponds to f1, 3571 // * fpr=1 to f2, etc. 3572 // */ 3573 // char *overflow_arg_area; 3574 // /* location on stack that holds 3575 // * the next overflow argument 3576 // */ 3577 // char *reg_save_area; 3578 // /* where r3:r10 and f1:f8 (if saved) 3579 // * are stored 3580 // */ 3581 // } va_list[1]; 3582 3583 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3584 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3585 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3586 PtrVT); 3587 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3588 PtrVT); 3589 3590 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3591 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3592 3593 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3594 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3595 3596 uint64_t FPROffset = 1; 3597 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3598 3599 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3600 3601 // Store first byte : number of int regs 3602 SDValue firstStore = 3603 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3604 MachinePointerInfo(SV), MVT::i8); 3605 uint64_t nextOffset = FPROffset; 3606 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3607 ConstFPROffset); 3608 3609 // Store second byte : number of float regs 3610 SDValue secondStore = 3611 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3612 MachinePointerInfo(SV, nextOffset), MVT::i8); 3613 nextOffset += StackOffset; 3614 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3615 3616 // Store second word : arguments given on stack 3617 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3618 MachinePointerInfo(SV, nextOffset)); 3619 nextOffset += FrameOffset; 3620 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3621 3622 // Store third word : arguments given in registers 3623 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3624 MachinePointerInfo(SV, nextOffset)); 3625 } 3626 3627 /// FPR - The set of FP registers that should be allocated for arguments 3628 /// on Darwin and AIX. 3629 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3630 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3631 PPC::F11, PPC::F12, PPC::F13}; 3632 3633 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3634 /// the stack. 3635 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3636 unsigned PtrByteSize) { 3637 unsigned ArgSize = ArgVT.getStoreSize(); 3638 if (Flags.isByVal()) 3639 ArgSize = Flags.getByValSize(); 3640 3641 // Round up to multiples of the pointer size, except for array members, 3642 // which are always packed. 3643 if (!Flags.isInConsecutiveRegs()) 3644 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3645 3646 return ArgSize; 3647 } 3648 3649 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3650 /// on the stack. 3651 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3652 ISD::ArgFlagsTy Flags, 3653 unsigned PtrByteSize) { 3654 Align Alignment(PtrByteSize); 3655 3656 // Altivec parameters are padded to a 16 byte boundary. 3657 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3658 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3659 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3660 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3661 Alignment = Align(16); 3662 3663 // ByVal parameters are aligned as requested. 3664 if (Flags.isByVal()) { 3665 auto BVAlign = Flags.getNonZeroByValAlign(); 3666 if (BVAlign > PtrByteSize) { 3667 if (BVAlign.value() % PtrByteSize != 0) 3668 llvm_unreachable( 3669 "ByVal alignment is not a multiple of the pointer size"); 3670 3671 Alignment = BVAlign; 3672 } 3673 } 3674 3675 // Array members are always packed to their original alignment. 3676 if (Flags.isInConsecutiveRegs()) { 3677 // If the array member was split into multiple registers, the first 3678 // needs to be aligned to the size of the full type. (Except for 3679 // ppcf128, which is only aligned as its f64 components.) 3680 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3681 Alignment = Align(OrigVT.getStoreSize()); 3682 else 3683 Alignment = Align(ArgVT.getStoreSize()); 3684 } 3685 3686 return Alignment; 3687 } 3688 3689 /// CalculateStackSlotUsed - Return whether this argument will use its 3690 /// stack slot (instead of being passed in registers). ArgOffset, 3691 /// AvailableFPRs, and AvailableVRs must hold the current argument 3692 /// position, and will be updated to account for this argument. 3693 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3694 unsigned PtrByteSize, unsigned LinkageSize, 3695 unsigned ParamAreaSize, unsigned &ArgOffset, 3696 unsigned &AvailableFPRs, 3697 unsigned &AvailableVRs) { 3698 bool UseMemory = false; 3699 3700 // Respect alignment of argument on the stack. 3701 Align Alignment = 3702 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3703 ArgOffset = alignTo(ArgOffset, Alignment); 3704 // If there's no space left in the argument save area, we must 3705 // use memory (this check also catches zero-sized arguments). 3706 if (ArgOffset >= LinkageSize + ParamAreaSize) 3707 UseMemory = true; 3708 3709 // Allocate argument on the stack. 3710 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3711 if (Flags.isInConsecutiveRegsLast()) 3712 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3713 // If we overran the argument save area, we must use memory 3714 // (this check catches arguments passed partially in memory) 3715 if (ArgOffset > LinkageSize + ParamAreaSize) 3716 UseMemory = true; 3717 3718 // However, if the argument is actually passed in an FPR or a VR, 3719 // we don't use memory after all. 3720 if (!Flags.isByVal()) { 3721 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3722 if (AvailableFPRs > 0) { 3723 --AvailableFPRs; 3724 return false; 3725 } 3726 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3727 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3728 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3729 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3730 if (AvailableVRs > 0) { 3731 --AvailableVRs; 3732 return false; 3733 } 3734 } 3735 3736 return UseMemory; 3737 } 3738 3739 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3740 /// ensure minimum alignment required for target. 3741 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3742 unsigned NumBytes) { 3743 return alignTo(NumBytes, Lowering->getStackAlign()); 3744 } 3745 3746 SDValue PPCTargetLowering::LowerFormalArguments( 3747 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3748 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3749 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3750 if (Subtarget.isAIXABI()) 3751 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3752 InVals); 3753 if (Subtarget.is64BitELFABI()) 3754 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3755 InVals); 3756 assert(Subtarget.is32BitELFABI()); 3757 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3758 InVals); 3759 } 3760 3761 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3762 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3763 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3764 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3765 3766 // 32-bit SVR4 ABI Stack Frame Layout: 3767 // +-----------------------------------+ 3768 // +--> | Back chain | 3769 // | +-----------------------------------+ 3770 // | | Floating-point register save area | 3771 // | +-----------------------------------+ 3772 // | | General register save area | 3773 // | +-----------------------------------+ 3774 // | | CR save word | 3775 // | +-----------------------------------+ 3776 // | | VRSAVE save word | 3777 // | +-----------------------------------+ 3778 // | | Alignment padding | 3779 // | +-----------------------------------+ 3780 // | | Vector register save area | 3781 // | +-----------------------------------+ 3782 // | | Local variable space | 3783 // | +-----------------------------------+ 3784 // | | Parameter list area | 3785 // | +-----------------------------------+ 3786 // | | LR save word | 3787 // | +-----------------------------------+ 3788 // SP--> +--- | Back chain | 3789 // +-----------------------------------+ 3790 // 3791 // Specifications: 3792 // System V Application Binary Interface PowerPC Processor Supplement 3793 // AltiVec Technology Programming Interface Manual 3794 3795 MachineFunction &MF = DAG.getMachineFunction(); 3796 MachineFrameInfo &MFI = MF.getFrameInfo(); 3797 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3798 3799 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3800 // Potential tail calls could cause overwriting of argument stack slots. 3801 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3802 (CallConv == CallingConv::Fast)); 3803 const Align PtrAlign(4); 3804 3805 // Assign locations to all of the incoming arguments. 3806 SmallVector<CCValAssign, 16> ArgLocs; 3807 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3808 *DAG.getContext()); 3809 3810 // Reserve space for the linkage area on the stack. 3811 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3812 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3813 if (useSoftFloat()) 3814 CCInfo.PreAnalyzeFormalArguments(Ins); 3815 3816 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3817 CCInfo.clearWasPPCF128(); 3818 3819 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3820 CCValAssign &VA = ArgLocs[i]; 3821 3822 // Arguments stored in registers. 3823 if (VA.isRegLoc()) { 3824 const TargetRegisterClass *RC; 3825 EVT ValVT = VA.getValVT(); 3826 3827 switch (ValVT.getSimpleVT().SimpleTy) { 3828 default: 3829 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3830 case MVT::i1: 3831 case MVT::i32: 3832 RC = &PPC::GPRCRegClass; 3833 break; 3834 case MVT::f32: 3835 if (Subtarget.hasP8Vector()) 3836 RC = &PPC::VSSRCRegClass; 3837 else if (Subtarget.hasSPE()) 3838 RC = &PPC::GPRCRegClass; 3839 else 3840 RC = &PPC::F4RCRegClass; 3841 break; 3842 case MVT::f64: 3843 if (Subtarget.hasVSX()) 3844 RC = &PPC::VSFRCRegClass; 3845 else if (Subtarget.hasSPE()) 3846 // SPE passes doubles in GPR pairs. 3847 RC = &PPC::GPRCRegClass; 3848 else 3849 RC = &PPC::F8RCRegClass; 3850 break; 3851 case MVT::v16i8: 3852 case MVT::v8i16: 3853 case MVT::v4i32: 3854 RC = &PPC::VRRCRegClass; 3855 break; 3856 case MVT::v4f32: 3857 RC = &PPC::VRRCRegClass; 3858 break; 3859 case MVT::v2f64: 3860 case MVT::v2i64: 3861 RC = &PPC::VRRCRegClass; 3862 break; 3863 } 3864 3865 SDValue ArgValue; 3866 // Transform the arguments stored in physical registers into 3867 // virtual ones. 3868 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3869 assert(i + 1 < e && "No second half of double precision argument"); 3870 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3871 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3872 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3873 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3874 if (!Subtarget.isLittleEndian()) 3875 std::swap (ArgValueLo, ArgValueHi); 3876 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3877 ArgValueHi); 3878 } else { 3879 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3880 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3881 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3882 if (ValVT == MVT::i1) 3883 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3884 } 3885 3886 InVals.push_back(ArgValue); 3887 } else { 3888 // Argument stored in memory. 3889 assert(VA.isMemLoc()); 3890 3891 // Get the extended size of the argument type in stack 3892 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3893 // Get the actual size of the argument type 3894 unsigned ObjSize = VA.getValVT().getStoreSize(); 3895 unsigned ArgOffset = VA.getLocMemOffset(); 3896 // Stack objects in PPC32 are right justified. 3897 ArgOffset += ArgSize - ObjSize; 3898 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3899 3900 // Create load nodes to retrieve arguments from the stack. 3901 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3902 InVals.push_back( 3903 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3904 } 3905 } 3906 3907 // Assign locations to all of the incoming aggregate by value arguments. 3908 // Aggregates passed by value are stored in the local variable space of the 3909 // caller's stack frame, right above the parameter list area. 3910 SmallVector<CCValAssign, 16> ByValArgLocs; 3911 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3912 ByValArgLocs, *DAG.getContext()); 3913 3914 // Reserve stack space for the allocations in CCInfo. 3915 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3916 3917 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3918 3919 // Area that is at least reserved in the caller of this function. 3920 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3921 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3922 3923 // Set the size that is at least reserved in caller of this function. Tail 3924 // call optimized function's reserved stack space needs to be aligned so that 3925 // taking the difference between two stack areas will result in an aligned 3926 // stack. 3927 MinReservedArea = 3928 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3929 FuncInfo->setMinReservedArea(MinReservedArea); 3930 3931 SmallVector<SDValue, 8> MemOps; 3932 3933 // If the function takes variable number of arguments, make a frame index for 3934 // the start of the first vararg value... for expansion of llvm.va_start. 3935 if (isVarArg) { 3936 static const MCPhysReg GPArgRegs[] = { 3937 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3938 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3939 }; 3940 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3941 3942 static const MCPhysReg FPArgRegs[] = { 3943 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3944 PPC::F8 3945 }; 3946 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3947 3948 if (useSoftFloat() || hasSPE()) 3949 NumFPArgRegs = 0; 3950 3951 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3952 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3953 3954 // Make room for NumGPArgRegs and NumFPArgRegs. 3955 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3956 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3957 3958 FuncInfo->setVarArgsStackOffset( 3959 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3960 CCInfo.getNextStackOffset(), true)); 3961 3962 FuncInfo->setVarArgsFrameIndex( 3963 MFI.CreateStackObject(Depth, Align(8), false)); 3964 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3965 3966 // The fixed integer arguments of a variadic function are stored to the 3967 // VarArgsFrameIndex on the stack so that they may be loaded by 3968 // dereferencing the result of va_next. 3969 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3970 // Get an existing live-in vreg, or add a new one. 3971 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3972 if (!VReg) 3973 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3974 3975 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3976 SDValue Store = 3977 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3978 MemOps.push_back(Store); 3979 // Increment the address by four for the next argument to store 3980 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3981 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3982 } 3983 3984 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3985 // is set. 3986 // The double arguments are stored to the VarArgsFrameIndex 3987 // on the stack. 3988 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3989 // Get an existing live-in vreg, or add a new one. 3990 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3991 if (!VReg) 3992 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3993 3994 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3995 SDValue Store = 3996 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3997 MemOps.push_back(Store); 3998 // Increment the address by eight for the next argument to store 3999 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4000 PtrVT); 4001 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4002 } 4003 } 4004 4005 if (!MemOps.empty()) 4006 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4007 4008 return Chain; 4009 } 4010 4011 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4012 // value to MVT::i64 and then truncate to the correct register size. 4013 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4014 EVT ObjectVT, SelectionDAG &DAG, 4015 SDValue ArgVal, 4016 const SDLoc &dl) const { 4017 if (Flags.isSExt()) 4018 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4019 DAG.getValueType(ObjectVT)); 4020 else if (Flags.isZExt()) 4021 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4022 DAG.getValueType(ObjectVT)); 4023 4024 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4025 } 4026 4027 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4028 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4029 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4030 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4031 // TODO: add description of PPC stack frame format, or at least some docs. 4032 // 4033 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4034 bool isLittleEndian = Subtarget.isLittleEndian(); 4035 MachineFunction &MF = DAG.getMachineFunction(); 4036 MachineFrameInfo &MFI = MF.getFrameInfo(); 4037 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4038 4039 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4040 "fastcc not supported on varargs functions"); 4041 4042 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4043 // Potential tail calls could cause overwriting of argument stack slots. 4044 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4045 (CallConv == CallingConv::Fast)); 4046 unsigned PtrByteSize = 8; 4047 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4048 4049 static const MCPhysReg GPR[] = { 4050 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4051 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4052 }; 4053 static const MCPhysReg VR[] = { 4054 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4055 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4056 }; 4057 4058 const unsigned Num_GPR_Regs = array_lengthof(GPR); 4059 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4060 const unsigned Num_VR_Regs = array_lengthof(VR); 4061 4062 // Do a first pass over the arguments to determine whether the ABI 4063 // guarantees that our caller has allocated the parameter save area 4064 // on its stack frame. In the ELFv1 ABI, this is always the case; 4065 // in the ELFv2 ABI, it is true if this is a vararg function or if 4066 // any parameter is located in a stack slot. 4067 4068 bool HasParameterArea = !isELFv2ABI || isVarArg; 4069 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4070 unsigned NumBytes = LinkageSize; 4071 unsigned AvailableFPRs = Num_FPR_Regs; 4072 unsigned AvailableVRs = Num_VR_Regs; 4073 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4074 if (Ins[i].Flags.isNest()) 4075 continue; 4076 4077 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4078 PtrByteSize, LinkageSize, ParamAreaSize, 4079 NumBytes, AvailableFPRs, AvailableVRs)) 4080 HasParameterArea = true; 4081 } 4082 4083 // Add DAG nodes to load the arguments or copy them out of registers. On 4084 // entry to a function on PPC, the arguments start after the linkage area, 4085 // although the first ones are often in registers. 4086 4087 unsigned ArgOffset = LinkageSize; 4088 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4089 SmallVector<SDValue, 8> MemOps; 4090 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4091 unsigned CurArgIdx = 0; 4092 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4093 SDValue ArgVal; 4094 bool needsLoad = false; 4095 EVT ObjectVT = Ins[ArgNo].VT; 4096 EVT OrigVT = Ins[ArgNo].ArgVT; 4097 unsigned ObjSize = ObjectVT.getStoreSize(); 4098 unsigned ArgSize = ObjSize; 4099 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4100 if (Ins[ArgNo].isOrigArg()) { 4101 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4102 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4103 } 4104 // We re-align the argument offset for each argument, except when using the 4105 // fast calling convention, when we need to make sure we do that only when 4106 // we'll actually use a stack slot. 4107 unsigned CurArgOffset; 4108 Align Alignment; 4109 auto ComputeArgOffset = [&]() { 4110 /* Respect alignment of argument on the stack. */ 4111 Alignment = 4112 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4113 ArgOffset = alignTo(ArgOffset, Alignment); 4114 CurArgOffset = ArgOffset; 4115 }; 4116 4117 if (CallConv != CallingConv::Fast) { 4118 ComputeArgOffset(); 4119 4120 /* Compute GPR index associated with argument offset. */ 4121 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4122 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4123 } 4124 4125 // FIXME the codegen can be much improved in some cases. 4126 // We do not have to keep everything in memory. 4127 if (Flags.isByVal()) { 4128 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4129 4130 if (CallConv == CallingConv::Fast) 4131 ComputeArgOffset(); 4132 4133 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4134 ObjSize = Flags.getByValSize(); 4135 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4136 // Empty aggregate parameters do not take up registers. Examples: 4137 // struct { } a; 4138 // union { } b; 4139 // int c[0]; 4140 // etc. However, we have to provide a place-holder in InVals, so 4141 // pretend we have an 8-byte item at the current address for that 4142 // purpose. 4143 if (!ObjSize) { 4144 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4145 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4146 InVals.push_back(FIN); 4147 continue; 4148 } 4149 4150 // Create a stack object covering all stack doublewords occupied 4151 // by the argument. If the argument is (fully or partially) on 4152 // the stack, or if the argument is fully in registers but the 4153 // caller has allocated the parameter save anyway, we can refer 4154 // directly to the caller's stack frame. Otherwise, create a 4155 // local copy in our own frame. 4156 int FI; 4157 if (HasParameterArea || 4158 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4159 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4160 else 4161 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4162 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4163 4164 // Handle aggregates smaller than 8 bytes. 4165 if (ObjSize < PtrByteSize) { 4166 // The value of the object is its address, which differs from the 4167 // address of the enclosing doubleword on big-endian systems. 4168 SDValue Arg = FIN; 4169 if (!isLittleEndian) { 4170 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4171 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4172 } 4173 InVals.push_back(Arg); 4174 4175 if (GPR_idx != Num_GPR_Regs) { 4176 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4177 FuncInfo->addLiveInAttr(VReg, Flags); 4178 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4179 SDValue Store; 4180 4181 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4182 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4183 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4184 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4185 MachinePointerInfo(&*FuncArg), ObjType); 4186 } else { 4187 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4188 // store the whole register as-is to the parameter save area 4189 // slot. 4190 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4191 MachinePointerInfo(&*FuncArg)); 4192 } 4193 4194 MemOps.push_back(Store); 4195 } 4196 // Whether we copied from a register or not, advance the offset 4197 // into the parameter save area by a full doubleword. 4198 ArgOffset += PtrByteSize; 4199 continue; 4200 } 4201 4202 // The value of the object is its address, which is the address of 4203 // its first stack doubleword. 4204 InVals.push_back(FIN); 4205 4206 // Store whatever pieces of the object are in registers to memory. 4207 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4208 if (GPR_idx == Num_GPR_Regs) 4209 break; 4210 4211 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4212 FuncInfo->addLiveInAttr(VReg, Flags); 4213 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4214 SDValue Addr = FIN; 4215 if (j) { 4216 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4217 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4218 } 4219 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4220 MachinePointerInfo(&*FuncArg, j)); 4221 MemOps.push_back(Store); 4222 ++GPR_idx; 4223 } 4224 ArgOffset += ArgSize; 4225 continue; 4226 } 4227 4228 switch (ObjectVT.getSimpleVT().SimpleTy) { 4229 default: llvm_unreachable("Unhandled argument type!"); 4230 case MVT::i1: 4231 case MVT::i32: 4232 case MVT::i64: 4233 if (Flags.isNest()) { 4234 // The 'nest' parameter, if any, is passed in R11. 4235 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4236 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4237 4238 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4239 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4240 4241 break; 4242 } 4243 4244 // These can be scalar arguments or elements of an integer array type 4245 // passed directly. Clang may use those instead of "byval" aggregate 4246 // types to avoid forcing arguments to memory unnecessarily. 4247 if (GPR_idx != Num_GPR_Regs) { 4248 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4249 FuncInfo->addLiveInAttr(VReg, Flags); 4250 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4251 4252 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4253 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4254 // value to MVT::i64 and then truncate to the correct register size. 4255 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4256 } else { 4257 if (CallConv == CallingConv::Fast) 4258 ComputeArgOffset(); 4259 4260 needsLoad = true; 4261 ArgSize = PtrByteSize; 4262 } 4263 if (CallConv != CallingConv::Fast || needsLoad) 4264 ArgOffset += 8; 4265 break; 4266 4267 case MVT::f32: 4268 case MVT::f64: 4269 // These can be scalar arguments or elements of a float array type 4270 // passed directly. The latter are used to implement ELFv2 homogenous 4271 // float aggregates. 4272 if (FPR_idx != Num_FPR_Regs) { 4273 unsigned VReg; 4274 4275 if (ObjectVT == MVT::f32) 4276 VReg = MF.addLiveIn(FPR[FPR_idx], 4277 Subtarget.hasP8Vector() 4278 ? &PPC::VSSRCRegClass 4279 : &PPC::F4RCRegClass); 4280 else 4281 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4282 ? &PPC::VSFRCRegClass 4283 : &PPC::F8RCRegClass); 4284 4285 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4286 ++FPR_idx; 4287 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4288 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4289 // once we support fp <-> gpr moves. 4290 4291 // This can only ever happen in the presence of f32 array types, 4292 // since otherwise we never run out of FPRs before running out 4293 // of GPRs. 4294 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4295 FuncInfo->addLiveInAttr(VReg, Flags); 4296 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4297 4298 if (ObjectVT == MVT::f32) { 4299 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4300 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4301 DAG.getConstant(32, dl, MVT::i32)); 4302 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4303 } 4304 4305 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4306 } else { 4307 if (CallConv == CallingConv::Fast) 4308 ComputeArgOffset(); 4309 4310 needsLoad = true; 4311 } 4312 4313 // When passing an array of floats, the array occupies consecutive 4314 // space in the argument area; only round up to the next doubleword 4315 // at the end of the array. Otherwise, each float takes 8 bytes. 4316 if (CallConv != CallingConv::Fast || needsLoad) { 4317 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4318 ArgOffset += ArgSize; 4319 if (Flags.isInConsecutiveRegsLast()) 4320 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4321 } 4322 break; 4323 case MVT::v4f32: 4324 case MVT::v4i32: 4325 case MVT::v8i16: 4326 case MVT::v16i8: 4327 case MVT::v2f64: 4328 case MVT::v2i64: 4329 case MVT::v1i128: 4330 case MVT::f128: 4331 // These can be scalar arguments or elements of a vector array type 4332 // passed directly. The latter are used to implement ELFv2 homogenous 4333 // vector aggregates. 4334 if (VR_idx != Num_VR_Regs) { 4335 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4336 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4337 ++VR_idx; 4338 } else { 4339 if (CallConv == CallingConv::Fast) 4340 ComputeArgOffset(); 4341 needsLoad = true; 4342 } 4343 if (CallConv != CallingConv::Fast || needsLoad) 4344 ArgOffset += 16; 4345 break; 4346 } 4347 4348 // We need to load the argument to a virtual register if we determined 4349 // above that we ran out of physical registers of the appropriate type. 4350 if (needsLoad) { 4351 if (ObjSize < ArgSize && !isLittleEndian) 4352 CurArgOffset += ArgSize - ObjSize; 4353 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4354 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4355 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4356 } 4357 4358 InVals.push_back(ArgVal); 4359 } 4360 4361 // Area that is at least reserved in the caller of this function. 4362 unsigned MinReservedArea; 4363 if (HasParameterArea) 4364 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4365 else 4366 MinReservedArea = LinkageSize; 4367 4368 // Set the size that is at least reserved in caller of this function. Tail 4369 // call optimized functions' reserved stack space needs to be aligned so that 4370 // taking the difference between two stack areas will result in an aligned 4371 // stack. 4372 MinReservedArea = 4373 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4374 FuncInfo->setMinReservedArea(MinReservedArea); 4375 4376 // If the function takes variable number of arguments, make a frame index for 4377 // the start of the first vararg value... for expansion of llvm.va_start. 4378 // On ELFv2ABI spec, it writes: 4379 // C programs that are intended to be *portable* across different compilers 4380 // and architectures must use the header file <stdarg.h> to deal with variable 4381 // argument lists. 4382 if (isVarArg && MFI.hasVAStart()) { 4383 int Depth = ArgOffset; 4384 4385 FuncInfo->setVarArgsFrameIndex( 4386 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4387 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4388 4389 // If this function is vararg, store any remaining integer argument regs 4390 // to their spots on the stack so that they may be loaded by dereferencing 4391 // the result of va_next. 4392 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4393 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4394 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4395 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4396 SDValue Store = 4397 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4398 MemOps.push_back(Store); 4399 // Increment the address by four for the next argument to store 4400 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4401 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4402 } 4403 } 4404 4405 if (!MemOps.empty()) 4406 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4407 4408 return Chain; 4409 } 4410 4411 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4412 /// adjusted to accommodate the arguments for the tailcall. 4413 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4414 unsigned ParamSize) { 4415 4416 if (!isTailCall) return 0; 4417 4418 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4419 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4420 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4421 // Remember only if the new adjustment is bigger. 4422 if (SPDiff < FI->getTailCallSPDelta()) 4423 FI->setTailCallSPDelta(SPDiff); 4424 4425 return SPDiff; 4426 } 4427 4428 static bool isFunctionGlobalAddress(SDValue Callee); 4429 4430 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4431 const TargetMachine &TM) { 4432 // It does not make sense to call callsShareTOCBase() with a caller that 4433 // is PC Relative since PC Relative callers do not have a TOC. 4434 #ifndef NDEBUG 4435 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4436 assert(!STICaller->isUsingPCRelativeCalls() && 4437 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4438 #endif 4439 4440 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4441 // don't have enough information to determine if the caller and callee share 4442 // the same TOC base, so we have to pessimistically assume they don't for 4443 // correctness. 4444 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4445 if (!G) 4446 return false; 4447 4448 const GlobalValue *GV = G->getGlobal(); 4449 4450 // If the callee is preemptable, then the static linker will use a plt-stub 4451 // which saves the toc to the stack, and needs a nop after the call 4452 // instruction to convert to a toc-restore. 4453 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4454 return false; 4455 4456 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4457 // We may need a TOC restore in the situation where the caller requires a 4458 // valid TOC but the callee is PC Relative and does not. 4459 const Function *F = dyn_cast<Function>(GV); 4460 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4461 4462 // If we have an Alias we can try to get the function from there. 4463 if (Alias) { 4464 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4465 F = dyn_cast<Function>(GlobalObj); 4466 } 4467 4468 // If we still have no valid function pointer we do not have enough 4469 // information to determine if the callee uses PC Relative calls so we must 4470 // assume that it does. 4471 if (!F) 4472 return false; 4473 4474 // If the callee uses PC Relative we cannot guarantee that the callee won't 4475 // clobber the TOC of the caller and so we must assume that the two 4476 // functions do not share a TOC base. 4477 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4478 if (STICallee->isUsingPCRelativeCalls()) 4479 return false; 4480 4481 // If the GV is not a strong definition then we need to assume it can be 4482 // replaced by another function at link time. The function that replaces 4483 // it may not share the same TOC as the caller since the callee may be 4484 // replaced by a PC Relative version of the same function. 4485 if (!GV->isStrongDefinitionForLinker()) 4486 return false; 4487 4488 // The medium and large code models are expected to provide a sufficiently 4489 // large TOC to provide all data addressing needs of a module with a 4490 // single TOC. 4491 if (CodeModel::Medium == TM.getCodeModel() || 4492 CodeModel::Large == TM.getCodeModel()) 4493 return true; 4494 4495 // Any explicitly-specified sections and section prefixes must also match. 4496 // Also, if we're using -ffunction-sections, then each function is always in 4497 // a different section (the same is true for COMDAT functions). 4498 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4499 GV->getSection() != Caller->getSection()) 4500 return false; 4501 if (const auto *F = dyn_cast<Function>(GV)) { 4502 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4503 return false; 4504 } 4505 4506 return true; 4507 } 4508 4509 static bool 4510 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4511 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4512 assert(Subtarget.is64BitELFABI()); 4513 4514 const unsigned PtrByteSize = 8; 4515 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4516 4517 static const MCPhysReg GPR[] = { 4518 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4519 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4520 }; 4521 static const MCPhysReg VR[] = { 4522 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4523 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4524 }; 4525 4526 const unsigned NumGPRs = array_lengthof(GPR); 4527 const unsigned NumFPRs = 13; 4528 const unsigned NumVRs = array_lengthof(VR); 4529 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4530 4531 unsigned NumBytes = LinkageSize; 4532 unsigned AvailableFPRs = NumFPRs; 4533 unsigned AvailableVRs = NumVRs; 4534 4535 for (const ISD::OutputArg& Param : Outs) { 4536 if (Param.Flags.isNest()) continue; 4537 4538 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4539 LinkageSize, ParamAreaSize, NumBytes, 4540 AvailableFPRs, AvailableVRs)) 4541 return true; 4542 } 4543 return false; 4544 } 4545 4546 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4547 if (CB.arg_size() != CallerFn->arg_size()) 4548 return false; 4549 4550 auto CalleeArgIter = CB.arg_begin(); 4551 auto CalleeArgEnd = CB.arg_end(); 4552 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4553 4554 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4555 const Value* CalleeArg = *CalleeArgIter; 4556 const Value* CallerArg = &(*CallerArgIter); 4557 if (CalleeArg == CallerArg) 4558 continue; 4559 4560 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4561 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4562 // } 4563 // 1st argument of callee is undef and has the same type as caller. 4564 if (CalleeArg->getType() == CallerArg->getType() && 4565 isa<UndefValue>(CalleeArg)) 4566 continue; 4567 4568 return false; 4569 } 4570 4571 return true; 4572 } 4573 4574 // Returns true if TCO is possible between the callers and callees 4575 // calling conventions. 4576 static bool 4577 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4578 CallingConv::ID CalleeCC) { 4579 // Tail calls are possible with fastcc and ccc. 4580 auto isTailCallableCC = [] (CallingConv::ID CC){ 4581 return CC == CallingConv::C || CC == CallingConv::Fast; 4582 }; 4583 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4584 return false; 4585 4586 // We can safely tail call both fastcc and ccc callees from a c calling 4587 // convention caller. If the caller is fastcc, we may have less stack space 4588 // than a non-fastcc caller with the same signature so disable tail-calls in 4589 // that case. 4590 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4591 } 4592 4593 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4594 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4595 const SmallVectorImpl<ISD::OutputArg> &Outs, 4596 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4597 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4598 4599 if (DisableSCO && !TailCallOpt) return false; 4600 4601 // Variadic argument functions are not supported. 4602 if (isVarArg) return false; 4603 4604 auto &Caller = DAG.getMachineFunction().getFunction(); 4605 // Check that the calling conventions are compatible for tco. 4606 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4607 return false; 4608 4609 // Caller contains any byval parameter is not supported. 4610 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4611 return false; 4612 4613 // Callee contains any byval parameter is not supported, too. 4614 // Note: This is a quick work around, because in some cases, e.g. 4615 // caller's stack size > callee's stack size, we are still able to apply 4616 // sibling call optimization. For example, gcc is able to do SCO for caller1 4617 // in the following example, but not for caller2. 4618 // struct test { 4619 // long int a; 4620 // char ary[56]; 4621 // } gTest; 4622 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4623 // b->a = v.a; 4624 // return 0; 4625 // } 4626 // void caller1(struct test a, struct test c, struct test *b) { 4627 // callee(gTest, b); } 4628 // void caller2(struct test *b) { callee(gTest, b); } 4629 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4630 return false; 4631 4632 // If callee and caller use different calling conventions, we cannot pass 4633 // parameters on stack since offsets for the parameter area may be different. 4634 if (Caller.getCallingConv() != CalleeCC && 4635 needStackSlotPassParameters(Subtarget, Outs)) 4636 return false; 4637 4638 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4639 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4640 // callee potentially have different TOC bases then we cannot tail call since 4641 // we need to restore the TOC pointer after the call. 4642 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4643 // We cannot guarantee this for indirect calls or calls to external functions. 4644 // When PC-Relative addressing is used, the concept of the TOC is no longer 4645 // applicable so this check is not required. 4646 // Check first for indirect calls. 4647 if (!Subtarget.isUsingPCRelativeCalls() && 4648 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4649 return false; 4650 4651 // Check if we share the TOC base. 4652 if (!Subtarget.isUsingPCRelativeCalls() && 4653 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4654 return false; 4655 4656 // TCO allows altering callee ABI, so we don't have to check further. 4657 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4658 return true; 4659 4660 if (DisableSCO) return false; 4661 4662 // If callee use the same argument list that caller is using, then we can 4663 // apply SCO on this case. If it is not, then we need to check if callee needs 4664 // stack for passing arguments. 4665 // PC Relative tail calls may not have a CallBase. 4666 // If there is no CallBase we cannot verify if we have the same argument 4667 // list so assume that we don't have the same argument list. 4668 if (CB && !hasSameArgumentList(&Caller, *CB) && 4669 needStackSlotPassParameters(Subtarget, Outs)) 4670 return false; 4671 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4672 return false; 4673 4674 return true; 4675 } 4676 4677 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4678 /// for tail call optimization. Targets which want to do tail call 4679 /// optimization should implement this function. 4680 bool 4681 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4682 CallingConv::ID CalleeCC, 4683 bool isVarArg, 4684 const SmallVectorImpl<ISD::InputArg> &Ins, 4685 SelectionDAG& DAG) const { 4686 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4687 return false; 4688 4689 // Variable argument functions are not supported. 4690 if (isVarArg) 4691 return false; 4692 4693 MachineFunction &MF = DAG.getMachineFunction(); 4694 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4695 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4696 // Functions containing by val parameters are not supported. 4697 for (unsigned i = 0; i != Ins.size(); i++) { 4698 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4699 if (Flags.isByVal()) return false; 4700 } 4701 4702 // Non-PIC/GOT tail calls are supported. 4703 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4704 return true; 4705 4706 // At the moment we can only do local tail calls (in same module, hidden 4707 // or protected) if we are generating PIC. 4708 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4709 return G->getGlobal()->hasHiddenVisibility() 4710 || G->getGlobal()->hasProtectedVisibility(); 4711 } 4712 4713 return false; 4714 } 4715 4716 /// isCallCompatibleAddress - Return the immediate to use if the specified 4717 /// 32-bit value is representable in the immediate field of a BxA instruction. 4718 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4719 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4720 if (!C) return nullptr; 4721 4722 int Addr = C->getZExtValue(); 4723 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4724 SignExtend32<26>(Addr) != Addr) 4725 return nullptr; // Top 6 bits have to be sext of immediate. 4726 4727 return DAG 4728 .getConstant( 4729 (int)C->getZExtValue() >> 2, SDLoc(Op), 4730 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4731 .getNode(); 4732 } 4733 4734 namespace { 4735 4736 struct TailCallArgumentInfo { 4737 SDValue Arg; 4738 SDValue FrameIdxOp; 4739 int FrameIdx = 0; 4740 4741 TailCallArgumentInfo() = default; 4742 }; 4743 4744 } // end anonymous namespace 4745 4746 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4747 static void StoreTailCallArgumentsToStackSlot( 4748 SelectionDAG &DAG, SDValue Chain, 4749 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4750 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4751 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4752 SDValue Arg = TailCallArgs[i].Arg; 4753 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4754 int FI = TailCallArgs[i].FrameIdx; 4755 // Store relative to framepointer. 4756 MemOpChains.push_back(DAG.getStore( 4757 Chain, dl, Arg, FIN, 4758 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4759 } 4760 } 4761 4762 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4763 /// the appropriate stack slot for the tail call optimized function call. 4764 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4765 SDValue OldRetAddr, SDValue OldFP, 4766 int SPDiff, const SDLoc &dl) { 4767 if (SPDiff) { 4768 // Calculate the new stack slot for the return address. 4769 MachineFunction &MF = DAG.getMachineFunction(); 4770 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4771 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4772 bool isPPC64 = Subtarget.isPPC64(); 4773 int SlotSize = isPPC64 ? 8 : 4; 4774 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4775 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4776 NewRetAddrLoc, true); 4777 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4778 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4779 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4780 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4781 } 4782 return Chain; 4783 } 4784 4785 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4786 /// the position of the argument. 4787 static void 4788 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4789 SDValue Arg, int SPDiff, unsigned ArgOffset, 4790 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4791 int Offset = ArgOffset + SPDiff; 4792 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4793 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4794 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4795 SDValue FIN = DAG.getFrameIndex(FI, VT); 4796 TailCallArgumentInfo Info; 4797 Info.Arg = Arg; 4798 Info.FrameIdxOp = FIN; 4799 Info.FrameIdx = FI; 4800 TailCallArguments.push_back(Info); 4801 } 4802 4803 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4804 /// stack slot. Returns the chain as result and the loaded frame pointers in 4805 /// LROpOut/FPOpout. Used when tail calling. 4806 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4807 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4808 SDValue &FPOpOut, const SDLoc &dl) const { 4809 if (SPDiff) { 4810 // Load the LR and FP stack slot for later adjusting. 4811 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4812 LROpOut = getReturnAddrFrameIndex(DAG); 4813 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4814 Chain = SDValue(LROpOut.getNode(), 1); 4815 } 4816 return Chain; 4817 } 4818 4819 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4820 /// by "Src" to address "Dst" of size "Size". Alignment information is 4821 /// specified by the specific parameter attribute. The copy will be passed as 4822 /// a byval function parameter. 4823 /// Sometimes what we are copying is the end of a larger object, the part that 4824 /// does not fit in registers. 4825 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4826 SDValue Chain, ISD::ArgFlagsTy Flags, 4827 SelectionDAG &DAG, const SDLoc &dl) { 4828 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4829 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4830 Flags.getNonZeroByValAlign(), false, false, false, 4831 MachinePointerInfo(), MachinePointerInfo()); 4832 } 4833 4834 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4835 /// tail calls. 4836 static void LowerMemOpCallTo( 4837 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4838 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4839 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4840 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4841 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4842 if (!isTailCall) { 4843 if (isVector) { 4844 SDValue StackPtr; 4845 if (isPPC64) 4846 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4847 else 4848 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4849 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4850 DAG.getConstant(ArgOffset, dl, PtrVT)); 4851 } 4852 MemOpChains.push_back( 4853 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4854 // Calculate and remember argument location. 4855 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4856 TailCallArguments); 4857 } 4858 4859 static void 4860 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4861 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4862 SDValue FPOp, 4863 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4864 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4865 // might overwrite each other in case of tail call optimization. 4866 SmallVector<SDValue, 8> MemOpChains2; 4867 // Do not flag preceding copytoreg stuff together with the following stuff. 4868 InFlag = SDValue(); 4869 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4870 MemOpChains2, dl); 4871 if (!MemOpChains2.empty()) 4872 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4873 4874 // Store the return address to the appropriate stack slot. 4875 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4876 4877 // Emit callseq_end just before tailcall node. 4878 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4879 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4880 InFlag = Chain.getValue(1); 4881 } 4882 4883 // Is this global address that of a function that can be called by name? (as 4884 // opposed to something that must hold a descriptor for an indirect call). 4885 static bool isFunctionGlobalAddress(SDValue Callee) { 4886 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4887 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4888 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4889 return false; 4890 4891 return G->getGlobal()->getValueType()->isFunctionTy(); 4892 } 4893 4894 return false; 4895 } 4896 4897 SDValue PPCTargetLowering::LowerCallResult( 4898 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4899 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4900 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4901 SmallVector<CCValAssign, 16> RVLocs; 4902 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4903 *DAG.getContext()); 4904 4905 CCRetInfo.AnalyzeCallResult( 4906 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4907 ? RetCC_PPC_Cold 4908 : RetCC_PPC); 4909 4910 // Copy all of the result registers out of their specified physreg. 4911 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4912 CCValAssign &VA = RVLocs[i]; 4913 assert(VA.isRegLoc() && "Can only return in registers!"); 4914 4915 SDValue Val; 4916 4917 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4918 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4919 InFlag); 4920 Chain = Lo.getValue(1); 4921 InFlag = Lo.getValue(2); 4922 VA = RVLocs[++i]; // skip ahead to next loc 4923 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4924 InFlag); 4925 Chain = Hi.getValue(1); 4926 InFlag = Hi.getValue(2); 4927 if (!Subtarget.isLittleEndian()) 4928 std::swap (Lo, Hi); 4929 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 4930 } else { 4931 Val = DAG.getCopyFromReg(Chain, dl, 4932 VA.getLocReg(), VA.getLocVT(), InFlag); 4933 Chain = Val.getValue(1); 4934 InFlag = Val.getValue(2); 4935 } 4936 4937 switch (VA.getLocInfo()) { 4938 default: llvm_unreachable("Unknown loc info!"); 4939 case CCValAssign::Full: break; 4940 case CCValAssign::AExt: 4941 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4942 break; 4943 case CCValAssign::ZExt: 4944 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4945 DAG.getValueType(VA.getValVT())); 4946 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4947 break; 4948 case CCValAssign::SExt: 4949 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4950 DAG.getValueType(VA.getValVT())); 4951 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4952 break; 4953 } 4954 4955 InVals.push_back(Val); 4956 } 4957 4958 return Chain; 4959 } 4960 4961 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 4962 const PPCSubtarget &Subtarget, bool isPatchPoint) { 4963 // PatchPoint calls are not indirect. 4964 if (isPatchPoint) 4965 return false; 4966 4967 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 4968 return false; 4969 4970 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 4971 // becuase the immediate function pointer points to a descriptor instead of 4972 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 4973 // pointer immediate points to the global entry point, while the BLA would 4974 // need to jump to the local entry point (see rL211174). 4975 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 4976 isBLACompatibleAddress(Callee, DAG)) 4977 return false; 4978 4979 return true; 4980 } 4981 4982 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 4983 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 4984 return Subtarget.isAIXABI() || 4985 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 4986 } 4987 4988 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 4989 const Function &Caller, 4990 const SDValue &Callee, 4991 const PPCSubtarget &Subtarget, 4992 const TargetMachine &TM) { 4993 if (CFlags.IsTailCall) 4994 return PPCISD::TC_RETURN; 4995 4996 // This is a call through a function pointer. 4997 if (CFlags.IsIndirect) { 4998 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 4999 // indirect calls. The save of the caller's TOC pointer to the stack will be 5000 // inserted into the DAG as part of call lowering. The restore of the TOC 5001 // pointer is modeled by using a pseudo instruction for the call opcode that 5002 // represents the 2 instruction sequence of an indirect branch and link, 5003 // immediately followed by a load of the TOC pointer from the the stack save 5004 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5005 // as it is not saved or used. 5006 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5007 : PPCISD::BCTRL; 5008 } 5009 5010 if (Subtarget.isUsingPCRelativeCalls()) { 5011 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5012 return PPCISD::CALL_NOTOC; 5013 } 5014 5015 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5016 // immediately following the call instruction if the caller and callee may 5017 // have different TOC bases. At link time if the linker determines the calls 5018 // may not share a TOC base, the call is redirected to a trampoline inserted 5019 // by the linker. The trampoline will (among other things) save the callers 5020 // TOC pointer at an ABI designated offset in the linkage area and the linker 5021 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5022 // into gpr2. 5023 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5024 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5025 : PPCISD::CALL_NOP; 5026 5027 return PPCISD::CALL; 5028 } 5029 5030 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5031 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5032 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5033 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5034 return SDValue(Dest, 0); 5035 5036 // Returns true if the callee is local, and false otherwise. 5037 auto isLocalCallee = [&]() { 5038 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5039 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5040 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5041 5042 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5043 !dyn_cast_or_null<GlobalIFunc>(GV); 5044 }; 5045 5046 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5047 // a static relocation model causes some versions of GNU LD (2.17.50, at 5048 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5049 // built with secure-PLT. 5050 bool UsePlt = 5051 Subtarget.is32BitELFABI() && !isLocalCallee() && 5052 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5053 5054 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5055 const TargetMachine &TM = Subtarget.getTargetMachine(); 5056 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5057 MCSymbolXCOFF *S = 5058 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5059 5060 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5061 return DAG.getMCSymbol(S, PtrVT); 5062 }; 5063 5064 if (isFunctionGlobalAddress(Callee)) { 5065 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5066 5067 if (Subtarget.isAIXABI()) { 5068 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5069 return getAIXFuncEntryPointSymbolSDNode(GV); 5070 } 5071 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5072 UsePlt ? PPCII::MO_PLT : 0); 5073 } 5074 5075 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5076 const char *SymName = S->getSymbol(); 5077 if (Subtarget.isAIXABI()) { 5078 // If there exists a user-declared function whose name is the same as the 5079 // ExternalSymbol's, then we pick up the user-declared version. 5080 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5081 if (const Function *F = 5082 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5083 return getAIXFuncEntryPointSymbolSDNode(F); 5084 5085 // On AIX, direct function calls reference the symbol for the function's 5086 // entry point, which is named by prepending a "." before the function's 5087 // C-linkage name. A Qualname is returned here because an external 5088 // function entry point is a csect with XTY_ER property. 5089 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5090 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5091 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5092 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5093 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5094 return Sec->getQualNameSymbol(); 5095 }; 5096 5097 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5098 } 5099 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5100 UsePlt ? PPCII::MO_PLT : 0); 5101 } 5102 5103 // No transformation needed. 5104 assert(Callee.getNode() && "What no callee?"); 5105 return Callee; 5106 } 5107 5108 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5109 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5110 "Expected a CALLSEQ_STARTSDNode."); 5111 5112 // The last operand is the chain, except when the node has glue. If the node 5113 // has glue, then the last operand is the glue, and the chain is the second 5114 // last operand. 5115 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5116 if (LastValue.getValueType() != MVT::Glue) 5117 return LastValue; 5118 5119 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5120 } 5121 5122 // Creates the node that moves a functions address into the count register 5123 // to prepare for an indirect call instruction. 5124 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5125 SDValue &Glue, SDValue &Chain, 5126 const SDLoc &dl) { 5127 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5128 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5129 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5130 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5131 // The glue is the second value produced. 5132 Glue = Chain.getValue(1); 5133 } 5134 5135 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5136 SDValue &Glue, SDValue &Chain, 5137 SDValue CallSeqStart, 5138 const CallBase *CB, const SDLoc &dl, 5139 bool hasNest, 5140 const PPCSubtarget &Subtarget) { 5141 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5142 // entry point, but to the function descriptor (the function entry point 5143 // address is part of the function descriptor though). 5144 // The function descriptor is a three doubleword structure with the 5145 // following fields: function entry point, TOC base address and 5146 // environment pointer. 5147 // Thus for a call through a function pointer, the following actions need 5148 // to be performed: 5149 // 1. Save the TOC of the caller in the TOC save area of its stack 5150 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5151 // 2. Load the address of the function entry point from the function 5152 // descriptor. 5153 // 3. Load the TOC of the callee from the function descriptor into r2. 5154 // 4. Load the environment pointer from the function descriptor into 5155 // r11. 5156 // 5. Branch to the function entry point address. 5157 // 6. On return of the callee, the TOC of the caller needs to be 5158 // restored (this is done in FinishCall()). 5159 // 5160 // The loads are scheduled at the beginning of the call sequence, and the 5161 // register copies are flagged together to ensure that no other 5162 // operations can be scheduled in between. E.g. without flagging the 5163 // copies together, a TOC access in the caller could be scheduled between 5164 // the assignment of the callee TOC and the branch to the callee, which leads 5165 // to incorrect code. 5166 5167 // Start by loading the function address from the descriptor. 5168 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5169 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5170 ? (MachineMemOperand::MODereferenceable | 5171 MachineMemOperand::MOInvariant) 5172 : MachineMemOperand::MONone; 5173 5174 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5175 5176 // Registers used in building the DAG. 5177 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5178 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5179 5180 // Offsets of descriptor members. 5181 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5182 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5183 5184 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5185 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5186 5187 // One load for the functions entry point address. 5188 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5189 Alignment, MMOFlags); 5190 5191 // One for loading the TOC anchor for the module that contains the called 5192 // function. 5193 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5194 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5195 SDValue TOCPtr = 5196 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5197 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5198 5199 // One for loading the environment pointer. 5200 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5201 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5202 SDValue LoadEnvPtr = 5203 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5204 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5205 5206 5207 // Then copy the newly loaded TOC anchor to the TOC pointer. 5208 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5209 Chain = TOCVal.getValue(0); 5210 Glue = TOCVal.getValue(1); 5211 5212 // If the function call has an explicit 'nest' parameter, it takes the 5213 // place of the environment pointer. 5214 assert((!hasNest || !Subtarget.isAIXABI()) && 5215 "Nest parameter is not supported on AIX."); 5216 if (!hasNest) { 5217 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5218 Chain = EnvVal.getValue(0); 5219 Glue = EnvVal.getValue(1); 5220 } 5221 5222 // The rest of the indirect call sequence is the same as the non-descriptor 5223 // DAG. 5224 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5225 } 5226 5227 static void 5228 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5229 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5230 SelectionDAG &DAG, 5231 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5232 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5233 const PPCSubtarget &Subtarget) { 5234 const bool IsPPC64 = Subtarget.isPPC64(); 5235 // MVT for a general purpose register. 5236 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5237 5238 // First operand is always the chain. 5239 Ops.push_back(Chain); 5240 5241 // If it's a direct call pass the callee as the second operand. 5242 if (!CFlags.IsIndirect) 5243 Ops.push_back(Callee); 5244 else { 5245 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5246 5247 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5248 // on the stack (this would have been done in `LowerCall_64SVR4` or 5249 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5250 // represents both the indirect branch and a load that restores the TOC 5251 // pointer from the linkage area. The operand for the TOC restore is an add 5252 // of the TOC save offset to the stack pointer. This must be the second 5253 // operand: after the chain input but before any other variadic arguments. 5254 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5255 // saved or used. 5256 if (isTOCSaveRestoreRequired(Subtarget)) { 5257 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5258 5259 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5260 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5261 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5262 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5263 Ops.push_back(AddTOC); 5264 } 5265 5266 // Add the register used for the environment pointer. 5267 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5268 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5269 RegVT)); 5270 5271 5272 // Add CTR register as callee so a bctr can be emitted later. 5273 if (CFlags.IsTailCall) 5274 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5275 } 5276 5277 // If this is a tail call add stack pointer delta. 5278 if (CFlags.IsTailCall) 5279 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5280 5281 // Add argument registers to the end of the list so that they are known live 5282 // into the call. 5283 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5284 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5285 RegsToPass[i].second.getValueType())); 5286 5287 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5288 // no way to mark dependencies as implicit here. 5289 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5290 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5291 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5292 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5293 5294 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5295 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5296 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5297 5298 // Add a register mask operand representing the call-preserved registers. 5299 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5300 const uint32_t *Mask = 5301 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5302 assert(Mask && "Missing call preserved mask for calling convention"); 5303 Ops.push_back(DAG.getRegisterMask(Mask)); 5304 5305 // If the glue is valid, it is the last operand. 5306 if (Glue.getNode()) 5307 Ops.push_back(Glue); 5308 } 5309 5310 SDValue PPCTargetLowering::FinishCall( 5311 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5312 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5313 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5314 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5315 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5316 5317 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5318 Subtarget.isAIXABI()) 5319 setUsesTOCBasePtr(DAG); 5320 5321 unsigned CallOpc = 5322 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5323 Subtarget, DAG.getTarget()); 5324 5325 if (!CFlags.IsIndirect) 5326 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5327 else if (Subtarget.usesFunctionDescriptors()) 5328 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5329 dl, CFlags.HasNest, Subtarget); 5330 else 5331 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5332 5333 // Build the operand list for the call instruction. 5334 SmallVector<SDValue, 8> Ops; 5335 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5336 SPDiff, Subtarget); 5337 5338 // Emit tail call. 5339 if (CFlags.IsTailCall) { 5340 // Indirect tail call when using PC Relative calls do not have the same 5341 // constraints. 5342 assert(((Callee.getOpcode() == ISD::Register && 5343 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5344 Callee.getOpcode() == ISD::TargetExternalSymbol || 5345 Callee.getOpcode() == ISD::TargetGlobalAddress || 5346 isa<ConstantSDNode>(Callee) || 5347 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5348 "Expecting a global address, external symbol, absolute value, " 5349 "register or an indirect tail call when PC Relative calls are " 5350 "used."); 5351 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5352 assert(CallOpc == PPCISD::TC_RETURN && 5353 "Unexpected call opcode for a tail call."); 5354 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5355 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5356 } 5357 5358 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5359 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5360 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5361 Glue = Chain.getValue(1); 5362 5363 // When performing tail call optimization the callee pops its arguments off 5364 // the stack. Account for this here so these bytes can be pushed back on in 5365 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5366 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5367 getTargetMachine().Options.GuaranteedTailCallOpt) 5368 ? NumBytes 5369 : 0; 5370 5371 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5372 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5373 Glue, dl); 5374 Glue = Chain.getValue(1); 5375 5376 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5377 DAG, InVals); 5378 } 5379 5380 SDValue 5381 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5382 SmallVectorImpl<SDValue> &InVals) const { 5383 SelectionDAG &DAG = CLI.DAG; 5384 SDLoc &dl = CLI.DL; 5385 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5386 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5387 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5388 SDValue Chain = CLI.Chain; 5389 SDValue Callee = CLI.Callee; 5390 bool &isTailCall = CLI.IsTailCall; 5391 CallingConv::ID CallConv = CLI.CallConv; 5392 bool isVarArg = CLI.IsVarArg; 5393 bool isPatchPoint = CLI.IsPatchPoint; 5394 const CallBase *CB = CLI.CB; 5395 5396 if (isTailCall) { 5397 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5398 isTailCall = false; 5399 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5400 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5401 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5402 else 5403 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5404 Ins, DAG); 5405 if (isTailCall) { 5406 ++NumTailCalls; 5407 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5408 ++NumSiblingCalls; 5409 5410 // PC Relative calls no longer guarantee that the callee is a Global 5411 // Address Node. The callee could be an indirect tail call in which 5412 // case the SDValue for the callee could be a load (to load the address 5413 // of a function pointer) or it may be a register copy (to move the 5414 // address of the callee from a function parameter into a virtual 5415 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5416 assert((Subtarget.isUsingPCRelativeCalls() || 5417 isa<GlobalAddressSDNode>(Callee)) && 5418 "Callee should be an llvm::Function object."); 5419 5420 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5421 << "\nTCO callee: "); 5422 LLVM_DEBUG(Callee.dump()); 5423 } 5424 } 5425 5426 if (!isTailCall && CB && CB->isMustTailCall()) 5427 report_fatal_error("failed to perform tail call elimination on a call " 5428 "site marked musttail"); 5429 5430 // When long calls (i.e. indirect calls) are always used, calls are always 5431 // made via function pointer. If we have a function name, first translate it 5432 // into a pointer. 5433 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5434 !isTailCall) 5435 Callee = LowerGlobalAddress(Callee, DAG); 5436 5437 CallFlags CFlags( 5438 CallConv, isTailCall, isVarArg, isPatchPoint, 5439 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5440 // hasNest 5441 Subtarget.is64BitELFABI() && 5442 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5443 CLI.NoMerge); 5444 5445 if (Subtarget.isAIXABI()) 5446 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5447 InVals, CB); 5448 5449 assert(Subtarget.isSVR4ABI()); 5450 if (Subtarget.isPPC64()) 5451 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5452 InVals, CB); 5453 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5454 InVals, CB); 5455 } 5456 5457 SDValue PPCTargetLowering::LowerCall_32SVR4( 5458 SDValue Chain, SDValue Callee, CallFlags CFlags, 5459 const SmallVectorImpl<ISD::OutputArg> &Outs, 5460 const SmallVectorImpl<SDValue> &OutVals, 5461 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5462 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5463 const CallBase *CB) const { 5464 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5465 // of the 32-bit SVR4 ABI stack frame layout. 5466 5467 const CallingConv::ID CallConv = CFlags.CallConv; 5468 const bool IsVarArg = CFlags.IsVarArg; 5469 const bool IsTailCall = CFlags.IsTailCall; 5470 5471 assert((CallConv == CallingConv::C || 5472 CallConv == CallingConv::Cold || 5473 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5474 5475 const Align PtrAlign(4); 5476 5477 MachineFunction &MF = DAG.getMachineFunction(); 5478 5479 // Mark this function as potentially containing a function that contains a 5480 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5481 // and restoring the callers stack pointer in this functions epilog. This is 5482 // done because by tail calling the called function might overwrite the value 5483 // in this function's (MF) stack pointer stack slot 0(SP). 5484 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5485 CallConv == CallingConv::Fast) 5486 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5487 5488 // Count how many bytes are to be pushed on the stack, including the linkage 5489 // area, parameter list area and the part of the local variable space which 5490 // contains copies of aggregates which are passed by value. 5491 5492 // Assign locations to all of the outgoing arguments. 5493 SmallVector<CCValAssign, 16> ArgLocs; 5494 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5495 5496 // Reserve space for the linkage area on the stack. 5497 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5498 PtrAlign); 5499 if (useSoftFloat()) 5500 CCInfo.PreAnalyzeCallOperands(Outs); 5501 5502 if (IsVarArg) { 5503 // Handle fixed and variable vector arguments differently. 5504 // Fixed vector arguments go into registers as long as registers are 5505 // available. Variable vector arguments always go into memory. 5506 unsigned NumArgs = Outs.size(); 5507 5508 for (unsigned i = 0; i != NumArgs; ++i) { 5509 MVT ArgVT = Outs[i].VT; 5510 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5511 bool Result; 5512 5513 if (Outs[i].IsFixed) { 5514 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5515 CCInfo); 5516 } else { 5517 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5518 ArgFlags, CCInfo); 5519 } 5520 5521 if (Result) { 5522 #ifndef NDEBUG 5523 errs() << "Call operand #" << i << " has unhandled type " 5524 << EVT(ArgVT).getEVTString() << "\n"; 5525 #endif 5526 llvm_unreachable(nullptr); 5527 } 5528 } 5529 } else { 5530 // All arguments are treated the same. 5531 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5532 } 5533 CCInfo.clearWasPPCF128(); 5534 5535 // Assign locations to all of the outgoing aggregate by value arguments. 5536 SmallVector<CCValAssign, 16> ByValArgLocs; 5537 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5538 5539 // Reserve stack space for the allocations in CCInfo. 5540 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5541 5542 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5543 5544 // Size of the linkage area, parameter list area and the part of the local 5545 // space variable where copies of aggregates which are passed by value are 5546 // stored. 5547 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5548 5549 // Calculate by how many bytes the stack has to be adjusted in case of tail 5550 // call optimization. 5551 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5552 5553 // Adjust the stack pointer for the new arguments... 5554 // These operations are automatically eliminated by the prolog/epilog pass 5555 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5556 SDValue CallSeqStart = Chain; 5557 5558 // Load the return address and frame pointer so it can be moved somewhere else 5559 // later. 5560 SDValue LROp, FPOp; 5561 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5562 5563 // Set up a copy of the stack pointer for use loading and storing any 5564 // arguments that may not fit in the registers available for argument 5565 // passing. 5566 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5567 5568 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5569 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5570 SmallVector<SDValue, 8> MemOpChains; 5571 5572 bool seenFloatArg = false; 5573 // Walk the register/memloc assignments, inserting copies/loads. 5574 // i - Tracks the index into the list of registers allocated for the call 5575 // RealArgIdx - Tracks the index into the list of actual function arguments 5576 // j - Tracks the index into the list of byval arguments 5577 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5578 i != e; 5579 ++i, ++RealArgIdx) { 5580 CCValAssign &VA = ArgLocs[i]; 5581 SDValue Arg = OutVals[RealArgIdx]; 5582 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5583 5584 if (Flags.isByVal()) { 5585 // Argument is an aggregate which is passed by value, thus we need to 5586 // create a copy of it in the local variable space of the current stack 5587 // frame (which is the stack frame of the caller) and pass the address of 5588 // this copy to the callee. 5589 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5590 CCValAssign &ByValVA = ByValArgLocs[j++]; 5591 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5592 5593 // Memory reserved in the local variable space of the callers stack frame. 5594 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5595 5596 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5597 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5598 StackPtr, PtrOff); 5599 5600 // Create a copy of the argument in the local area of the current 5601 // stack frame. 5602 SDValue MemcpyCall = 5603 CreateCopyOfByValArgument(Arg, PtrOff, 5604 CallSeqStart.getNode()->getOperand(0), 5605 Flags, DAG, dl); 5606 5607 // This must go outside the CALLSEQ_START..END. 5608 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5609 SDLoc(MemcpyCall)); 5610 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5611 NewCallSeqStart.getNode()); 5612 Chain = CallSeqStart = NewCallSeqStart; 5613 5614 // Pass the address of the aggregate copy on the stack either in a 5615 // physical register or in the parameter list area of the current stack 5616 // frame to the callee. 5617 Arg = PtrOff; 5618 } 5619 5620 // When useCRBits() is true, there can be i1 arguments. 5621 // It is because getRegisterType(MVT::i1) => MVT::i1, 5622 // and for other integer types getRegisterType() => MVT::i32. 5623 // Extend i1 and ensure callee will get i32. 5624 if (Arg.getValueType() == MVT::i1) 5625 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5626 dl, MVT::i32, Arg); 5627 5628 if (VA.isRegLoc()) { 5629 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5630 // Put argument in a physical register. 5631 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5632 bool IsLE = Subtarget.isLittleEndian(); 5633 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5634 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5635 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5636 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5637 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5638 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5639 SVal.getValue(0))); 5640 } else 5641 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5642 } else { 5643 // Put argument in the parameter list area of the current stack frame. 5644 assert(VA.isMemLoc()); 5645 unsigned LocMemOffset = VA.getLocMemOffset(); 5646 5647 if (!IsTailCall) { 5648 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5649 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5650 StackPtr, PtrOff); 5651 5652 MemOpChains.push_back( 5653 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5654 } else { 5655 // Calculate and remember argument location. 5656 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5657 TailCallArguments); 5658 } 5659 } 5660 } 5661 5662 if (!MemOpChains.empty()) 5663 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5664 5665 // Build a sequence of copy-to-reg nodes chained together with token chain 5666 // and flag operands which copy the outgoing args into the appropriate regs. 5667 SDValue InFlag; 5668 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5669 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5670 RegsToPass[i].second, InFlag); 5671 InFlag = Chain.getValue(1); 5672 } 5673 5674 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5675 // registers. 5676 if (IsVarArg) { 5677 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5678 SDValue Ops[] = { Chain, InFlag }; 5679 5680 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5681 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5682 5683 InFlag = Chain.getValue(1); 5684 } 5685 5686 if (IsTailCall) 5687 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5688 TailCallArguments); 5689 5690 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5691 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5692 } 5693 5694 // Copy an argument into memory, being careful to do this outside the 5695 // call sequence for the call to which the argument belongs. 5696 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5697 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5698 SelectionDAG &DAG, const SDLoc &dl) const { 5699 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5700 CallSeqStart.getNode()->getOperand(0), 5701 Flags, DAG, dl); 5702 // The MEMCPY must go outside the CALLSEQ_START..END. 5703 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5704 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5705 SDLoc(MemcpyCall)); 5706 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5707 NewCallSeqStart.getNode()); 5708 return NewCallSeqStart; 5709 } 5710 5711 SDValue PPCTargetLowering::LowerCall_64SVR4( 5712 SDValue Chain, SDValue Callee, CallFlags CFlags, 5713 const SmallVectorImpl<ISD::OutputArg> &Outs, 5714 const SmallVectorImpl<SDValue> &OutVals, 5715 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5716 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5717 const CallBase *CB) const { 5718 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5719 bool isLittleEndian = Subtarget.isLittleEndian(); 5720 unsigned NumOps = Outs.size(); 5721 bool IsSibCall = false; 5722 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5723 5724 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5725 unsigned PtrByteSize = 8; 5726 5727 MachineFunction &MF = DAG.getMachineFunction(); 5728 5729 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5730 IsSibCall = true; 5731 5732 // Mark this function as potentially containing a function that contains a 5733 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5734 // and restoring the callers stack pointer in this functions epilog. This is 5735 // done because by tail calling the called function might overwrite the value 5736 // in this function's (MF) stack pointer stack slot 0(SP). 5737 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5738 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5739 5740 assert(!(IsFastCall && CFlags.IsVarArg) && 5741 "fastcc not supported on varargs functions"); 5742 5743 // Count how many bytes are to be pushed on the stack, including the linkage 5744 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5745 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5746 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5747 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5748 unsigned NumBytes = LinkageSize; 5749 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5750 5751 static const MCPhysReg GPR[] = { 5752 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5753 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5754 }; 5755 static const MCPhysReg VR[] = { 5756 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5757 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5758 }; 5759 5760 const unsigned NumGPRs = array_lengthof(GPR); 5761 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5762 const unsigned NumVRs = array_lengthof(VR); 5763 5764 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5765 // can be passed to the callee in registers. 5766 // For the fast calling convention, there is another check below. 5767 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5768 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5769 if (!HasParameterArea) { 5770 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5771 unsigned AvailableFPRs = NumFPRs; 5772 unsigned AvailableVRs = NumVRs; 5773 unsigned NumBytesTmp = NumBytes; 5774 for (unsigned i = 0; i != NumOps; ++i) { 5775 if (Outs[i].Flags.isNest()) continue; 5776 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5777 PtrByteSize, LinkageSize, ParamAreaSize, 5778 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5779 HasParameterArea = true; 5780 } 5781 } 5782 5783 // When using the fast calling convention, we don't provide backing for 5784 // arguments that will be in registers. 5785 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5786 5787 // Avoid allocating parameter area for fastcc functions if all the arguments 5788 // can be passed in the registers. 5789 if (IsFastCall) 5790 HasParameterArea = false; 5791 5792 // Add up all the space actually used. 5793 for (unsigned i = 0; i != NumOps; ++i) { 5794 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5795 EVT ArgVT = Outs[i].VT; 5796 EVT OrigVT = Outs[i].ArgVT; 5797 5798 if (Flags.isNest()) 5799 continue; 5800 5801 if (IsFastCall) { 5802 if (Flags.isByVal()) { 5803 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5804 if (NumGPRsUsed > NumGPRs) 5805 HasParameterArea = true; 5806 } else { 5807 switch (ArgVT.getSimpleVT().SimpleTy) { 5808 default: llvm_unreachable("Unexpected ValueType for argument!"); 5809 case MVT::i1: 5810 case MVT::i32: 5811 case MVT::i64: 5812 if (++NumGPRsUsed <= NumGPRs) 5813 continue; 5814 break; 5815 case MVT::v4i32: 5816 case MVT::v8i16: 5817 case MVT::v16i8: 5818 case MVT::v2f64: 5819 case MVT::v2i64: 5820 case MVT::v1i128: 5821 case MVT::f128: 5822 if (++NumVRsUsed <= NumVRs) 5823 continue; 5824 break; 5825 case MVT::v4f32: 5826 if (++NumVRsUsed <= NumVRs) 5827 continue; 5828 break; 5829 case MVT::f32: 5830 case MVT::f64: 5831 if (++NumFPRsUsed <= NumFPRs) 5832 continue; 5833 break; 5834 } 5835 HasParameterArea = true; 5836 } 5837 } 5838 5839 /* Respect alignment of argument on the stack. */ 5840 auto Alignement = 5841 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5842 NumBytes = alignTo(NumBytes, Alignement); 5843 5844 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5845 if (Flags.isInConsecutiveRegsLast()) 5846 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5847 } 5848 5849 unsigned NumBytesActuallyUsed = NumBytes; 5850 5851 // In the old ELFv1 ABI, 5852 // the prolog code of the callee may store up to 8 GPR argument registers to 5853 // the stack, allowing va_start to index over them in memory if its varargs. 5854 // Because we cannot tell if this is needed on the caller side, we have to 5855 // conservatively assume that it is needed. As such, make sure we have at 5856 // least enough stack space for the caller to store the 8 GPRs. 5857 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5858 // really requires memory operands, e.g. a vararg function. 5859 if (HasParameterArea) 5860 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5861 else 5862 NumBytes = LinkageSize; 5863 5864 // Tail call needs the stack to be aligned. 5865 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5866 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5867 5868 int SPDiff = 0; 5869 5870 // Calculate by how many bytes the stack has to be adjusted in case of tail 5871 // call optimization. 5872 if (!IsSibCall) 5873 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 5874 5875 // To protect arguments on the stack from being clobbered in a tail call, 5876 // force all the loads to happen before doing any other lowering. 5877 if (CFlags.IsTailCall) 5878 Chain = DAG.getStackArgumentTokenFactor(Chain); 5879 5880 // Adjust the stack pointer for the new arguments... 5881 // These operations are automatically eliminated by the prolog/epilog pass 5882 if (!IsSibCall) 5883 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5884 SDValue CallSeqStart = Chain; 5885 5886 // Load the return address and frame pointer so it can be move somewhere else 5887 // later. 5888 SDValue LROp, FPOp; 5889 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5890 5891 // Set up a copy of the stack pointer for use loading and storing any 5892 // arguments that may not fit in the registers available for argument 5893 // passing. 5894 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5895 5896 // Figure out which arguments are going to go in registers, and which in 5897 // memory. Also, if this is a vararg function, floating point operations 5898 // must be stored to our stack, and loaded into integer regs as well, if 5899 // any integer regs are available for argument passing. 5900 unsigned ArgOffset = LinkageSize; 5901 5902 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5903 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5904 5905 SmallVector<SDValue, 8> MemOpChains; 5906 for (unsigned i = 0; i != NumOps; ++i) { 5907 SDValue Arg = OutVals[i]; 5908 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5909 EVT ArgVT = Outs[i].VT; 5910 EVT OrigVT = Outs[i].ArgVT; 5911 5912 // PtrOff will be used to store the current argument to the stack if a 5913 // register cannot be found for it. 5914 SDValue PtrOff; 5915 5916 // We re-align the argument offset for each argument, except when using the 5917 // fast calling convention, when we need to make sure we do that only when 5918 // we'll actually use a stack slot. 5919 auto ComputePtrOff = [&]() { 5920 /* Respect alignment of argument on the stack. */ 5921 auto Alignment = 5922 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5923 ArgOffset = alignTo(ArgOffset, Alignment); 5924 5925 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5926 5927 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5928 }; 5929 5930 if (!IsFastCall) { 5931 ComputePtrOff(); 5932 5933 /* Compute GPR index associated with argument offset. */ 5934 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5935 GPR_idx = std::min(GPR_idx, NumGPRs); 5936 } 5937 5938 // Promote integers to 64-bit values. 5939 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5940 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5941 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5942 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5943 } 5944 5945 // FIXME memcpy is used way more than necessary. Correctness first. 5946 // Note: "by value" is code for passing a structure by value, not 5947 // basic types. 5948 if (Flags.isByVal()) { 5949 // Note: Size includes alignment padding, so 5950 // struct x { short a; char b; } 5951 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5952 // These are the proper values we need for right-justifying the 5953 // aggregate in a parameter register. 5954 unsigned Size = Flags.getByValSize(); 5955 5956 // An empty aggregate parameter takes up no storage and no 5957 // registers. 5958 if (Size == 0) 5959 continue; 5960 5961 if (IsFastCall) 5962 ComputePtrOff(); 5963 5964 // All aggregates smaller than 8 bytes must be passed right-justified. 5965 if (Size==1 || Size==2 || Size==4) { 5966 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5967 if (GPR_idx != NumGPRs) { 5968 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5969 MachinePointerInfo(), VT); 5970 MemOpChains.push_back(Load.getValue(1)); 5971 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5972 5973 ArgOffset += PtrByteSize; 5974 continue; 5975 } 5976 } 5977 5978 if (GPR_idx == NumGPRs && Size < 8) { 5979 SDValue AddPtr = PtrOff; 5980 if (!isLittleEndian) { 5981 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5982 PtrOff.getValueType()); 5983 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5984 } 5985 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5986 CallSeqStart, 5987 Flags, DAG, dl); 5988 ArgOffset += PtrByteSize; 5989 continue; 5990 } 5991 // Copy entire object into memory. There are cases where gcc-generated 5992 // code assumes it is there, even if it could be put entirely into 5993 // registers. (This is not what the doc says.) 5994 5995 // FIXME: The above statement is likely due to a misunderstanding of the 5996 // documents. All arguments must be copied into the parameter area BY 5997 // THE CALLEE in the event that the callee takes the address of any 5998 // formal argument. That has not yet been implemented. However, it is 5999 // reasonable to use the stack area as a staging area for the register 6000 // load. 6001 6002 // Skip this for small aggregates, as we will use the same slot for a 6003 // right-justified copy, below. 6004 if (Size >= 8) 6005 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6006 CallSeqStart, 6007 Flags, DAG, dl); 6008 6009 // When a register is available, pass a small aggregate right-justified. 6010 if (Size < 8 && GPR_idx != NumGPRs) { 6011 // The easiest way to get this right-justified in a register 6012 // is to copy the structure into the rightmost portion of a 6013 // local variable slot, then load the whole slot into the 6014 // register. 6015 // FIXME: The memcpy seems to produce pretty awful code for 6016 // small aggregates, particularly for packed ones. 6017 // FIXME: It would be preferable to use the slot in the 6018 // parameter save area instead of a new local variable. 6019 SDValue AddPtr = PtrOff; 6020 if (!isLittleEndian) { 6021 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6022 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6023 } 6024 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6025 CallSeqStart, 6026 Flags, DAG, dl); 6027 6028 // Load the slot into the register. 6029 SDValue Load = 6030 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6031 MemOpChains.push_back(Load.getValue(1)); 6032 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6033 6034 // Done with this argument. 6035 ArgOffset += PtrByteSize; 6036 continue; 6037 } 6038 6039 // For aggregates larger than PtrByteSize, copy the pieces of the 6040 // object that fit into registers from the parameter save area. 6041 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6042 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6043 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6044 if (GPR_idx != NumGPRs) { 6045 SDValue Load = 6046 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6047 MemOpChains.push_back(Load.getValue(1)); 6048 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6049 ArgOffset += PtrByteSize; 6050 } else { 6051 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6052 break; 6053 } 6054 } 6055 continue; 6056 } 6057 6058 switch (Arg.getSimpleValueType().SimpleTy) { 6059 default: llvm_unreachable("Unexpected ValueType for argument!"); 6060 case MVT::i1: 6061 case MVT::i32: 6062 case MVT::i64: 6063 if (Flags.isNest()) { 6064 // The 'nest' parameter, if any, is passed in R11. 6065 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6066 break; 6067 } 6068 6069 // These can be scalar arguments or elements of an integer array type 6070 // passed directly. Clang may use those instead of "byval" aggregate 6071 // types to avoid forcing arguments to memory unnecessarily. 6072 if (GPR_idx != NumGPRs) { 6073 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6074 } else { 6075 if (IsFastCall) 6076 ComputePtrOff(); 6077 6078 assert(HasParameterArea && 6079 "Parameter area must exist to pass an argument in memory."); 6080 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6081 true, CFlags.IsTailCall, false, MemOpChains, 6082 TailCallArguments, dl); 6083 if (IsFastCall) 6084 ArgOffset += PtrByteSize; 6085 } 6086 if (!IsFastCall) 6087 ArgOffset += PtrByteSize; 6088 break; 6089 case MVT::f32: 6090 case MVT::f64: { 6091 // These can be scalar arguments or elements of a float array type 6092 // passed directly. The latter are used to implement ELFv2 homogenous 6093 // float aggregates. 6094 6095 // Named arguments go into FPRs first, and once they overflow, the 6096 // remaining arguments go into GPRs and then the parameter save area. 6097 // Unnamed arguments for vararg functions always go to GPRs and 6098 // then the parameter save area. For now, put all arguments to vararg 6099 // routines always in both locations (FPR *and* GPR or stack slot). 6100 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6101 bool NeededLoad = false; 6102 6103 // First load the argument into the next available FPR. 6104 if (FPR_idx != NumFPRs) 6105 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6106 6107 // Next, load the argument into GPR or stack slot if needed. 6108 if (!NeedGPROrStack) 6109 ; 6110 else if (GPR_idx != NumGPRs && !IsFastCall) { 6111 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6112 // once we support fp <-> gpr moves. 6113 6114 // In the non-vararg case, this can only ever happen in the 6115 // presence of f32 array types, since otherwise we never run 6116 // out of FPRs before running out of GPRs. 6117 SDValue ArgVal; 6118 6119 // Double values are always passed in a single GPR. 6120 if (Arg.getValueType() != MVT::f32) { 6121 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6122 6123 // Non-array float values are extended and passed in a GPR. 6124 } else if (!Flags.isInConsecutiveRegs()) { 6125 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6126 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6127 6128 // If we have an array of floats, we collect every odd element 6129 // together with its predecessor into one GPR. 6130 } else if (ArgOffset % PtrByteSize != 0) { 6131 SDValue Lo, Hi; 6132 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6133 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6134 if (!isLittleEndian) 6135 std::swap(Lo, Hi); 6136 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6137 6138 // The final element, if even, goes into the first half of a GPR. 6139 } else if (Flags.isInConsecutiveRegsLast()) { 6140 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6141 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6142 if (!isLittleEndian) 6143 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6144 DAG.getConstant(32, dl, MVT::i32)); 6145 6146 // Non-final even elements are skipped; they will be handled 6147 // together the with subsequent argument on the next go-around. 6148 } else 6149 ArgVal = SDValue(); 6150 6151 if (ArgVal.getNode()) 6152 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6153 } else { 6154 if (IsFastCall) 6155 ComputePtrOff(); 6156 6157 // Single-precision floating-point values are mapped to the 6158 // second (rightmost) word of the stack doubleword. 6159 if (Arg.getValueType() == MVT::f32 && 6160 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6161 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6162 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6163 } 6164 6165 assert(HasParameterArea && 6166 "Parameter area must exist to pass an argument in memory."); 6167 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6168 true, CFlags.IsTailCall, false, MemOpChains, 6169 TailCallArguments, dl); 6170 6171 NeededLoad = true; 6172 } 6173 // When passing an array of floats, the array occupies consecutive 6174 // space in the argument area; only round up to the next doubleword 6175 // at the end of the array. Otherwise, each float takes 8 bytes. 6176 if (!IsFastCall || NeededLoad) { 6177 ArgOffset += (Arg.getValueType() == MVT::f32 && 6178 Flags.isInConsecutiveRegs()) ? 4 : 8; 6179 if (Flags.isInConsecutiveRegsLast()) 6180 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6181 } 6182 break; 6183 } 6184 case MVT::v4f32: 6185 case MVT::v4i32: 6186 case MVT::v8i16: 6187 case MVT::v16i8: 6188 case MVT::v2f64: 6189 case MVT::v2i64: 6190 case MVT::v1i128: 6191 case MVT::f128: 6192 // These can be scalar arguments or elements of a vector array type 6193 // passed directly. The latter are used to implement ELFv2 homogenous 6194 // vector aggregates. 6195 6196 // For a varargs call, named arguments go into VRs or on the stack as 6197 // usual; unnamed arguments always go to the stack or the corresponding 6198 // GPRs when within range. For now, we always put the value in both 6199 // locations (or even all three). 6200 if (CFlags.IsVarArg) { 6201 assert(HasParameterArea && 6202 "Parameter area must exist if we have a varargs call."); 6203 // We could elide this store in the case where the object fits 6204 // entirely in R registers. Maybe later. 6205 SDValue Store = 6206 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6207 MemOpChains.push_back(Store); 6208 if (VR_idx != NumVRs) { 6209 SDValue Load = 6210 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6211 MemOpChains.push_back(Load.getValue(1)); 6212 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6213 } 6214 ArgOffset += 16; 6215 for (unsigned i=0; i<16; i+=PtrByteSize) { 6216 if (GPR_idx == NumGPRs) 6217 break; 6218 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6219 DAG.getConstant(i, dl, PtrVT)); 6220 SDValue Load = 6221 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6222 MemOpChains.push_back(Load.getValue(1)); 6223 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6224 } 6225 break; 6226 } 6227 6228 // Non-varargs Altivec params go into VRs or on the stack. 6229 if (VR_idx != NumVRs) { 6230 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6231 } else { 6232 if (IsFastCall) 6233 ComputePtrOff(); 6234 6235 assert(HasParameterArea && 6236 "Parameter area must exist to pass an argument in memory."); 6237 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6238 true, CFlags.IsTailCall, true, MemOpChains, 6239 TailCallArguments, dl); 6240 if (IsFastCall) 6241 ArgOffset += 16; 6242 } 6243 6244 if (!IsFastCall) 6245 ArgOffset += 16; 6246 break; 6247 } 6248 } 6249 6250 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6251 "mismatch in size of parameter area"); 6252 (void)NumBytesActuallyUsed; 6253 6254 if (!MemOpChains.empty()) 6255 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6256 6257 // Check if this is an indirect call (MTCTR/BCTRL). 6258 // See prepareDescriptorIndirectCall and buildCallOperands for more 6259 // information about calls through function pointers in the 64-bit SVR4 ABI. 6260 if (CFlags.IsIndirect) { 6261 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6262 // caller in the TOC save area. 6263 if (isTOCSaveRestoreRequired(Subtarget)) { 6264 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6265 // Load r2 into a virtual register and store it to the TOC save area. 6266 setUsesTOCBasePtr(DAG); 6267 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6268 // TOC save area offset. 6269 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6270 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6271 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6272 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6273 MachinePointerInfo::getStack( 6274 DAG.getMachineFunction(), TOCSaveOffset)); 6275 } 6276 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6277 // This does not mean the MTCTR instruction must use R12; it's easier 6278 // to model this as an extra parameter, so do that. 6279 if (isELFv2ABI && !CFlags.IsPatchPoint) 6280 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6281 } 6282 6283 // Build a sequence of copy-to-reg nodes chained together with token chain 6284 // and flag operands which copy the outgoing args into the appropriate regs. 6285 SDValue InFlag; 6286 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6287 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6288 RegsToPass[i].second, InFlag); 6289 InFlag = Chain.getValue(1); 6290 } 6291 6292 if (CFlags.IsTailCall && !IsSibCall) 6293 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6294 TailCallArguments); 6295 6296 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6297 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6298 } 6299 6300 // Returns true when the shadow of a general purpose argument register 6301 // in the parameter save area is aligned to at least 'RequiredAlign'. 6302 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6303 assert(RequiredAlign.value() <= 16 && 6304 "Required alignment greater than stack alignment."); 6305 switch (Reg) { 6306 default: 6307 report_fatal_error("called on invalid register."); 6308 case PPC::R5: 6309 case PPC::R9: 6310 case PPC::X3: 6311 case PPC::X5: 6312 case PPC::X7: 6313 case PPC::X9: 6314 // These registers are 16 byte aligned which is the most strict aligment 6315 // we can support. 6316 return true; 6317 case PPC::R3: 6318 case PPC::R7: 6319 case PPC::X4: 6320 case PPC::X6: 6321 case PPC::X8: 6322 case PPC::X10: 6323 // The shadow of these registers in the PSA is 8 byte aligned. 6324 return RequiredAlign <= 8; 6325 case PPC::R4: 6326 case PPC::R6: 6327 case PPC::R8: 6328 case PPC::R10: 6329 return RequiredAlign <= 4; 6330 } 6331 } 6332 6333 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6334 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6335 CCState &S) { 6336 AIXCCState &State = static_cast<AIXCCState &>(S); 6337 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6338 State.getMachineFunction().getSubtarget()); 6339 const bool IsPPC64 = Subtarget.isPPC64(); 6340 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6341 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6342 6343 if (ValVT == MVT::f128) 6344 report_fatal_error("f128 is unimplemented on AIX."); 6345 6346 if (ArgFlags.isNest()) 6347 report_fatal_error("Nest arguments are unimplemented."); 6348 6349 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6350 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6351 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6352 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6353 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6354 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6355 6356 static const MCPhysReg VR[] = {// Vector registers. 6357 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6358 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6359 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6360 6361 if (ArgFlags.isByVal()) { 6362 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6363 report_fatal_error("Pass-by-value arguments with alignment greater than " 6364 "register width are not supported."); 6365 6366 const unsigned ByValSize = ArgFlags.getByValSize(); 6367 6368 // An empty aggregate parameter takes up no storage and no registers, 6369 // but needs a MemLoc for a stack slot for the formal arguments side. 6370 if (ByValSize == 0) { 6371 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6372 State.getNextStackOffset(), RegVT, 6373 LocInfo)); 6374 return false; 6375 } 6376 6377 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6378 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6379 for (const unsigned E = Offset + StackSize; Offset < E; 6380 Offset += PtrAlign.value()) { 6381 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6382 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6383 else { 6384 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6385 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6386 LocInfo)); 6387 break; 6388 } 6389 } 6390 return false; 6391 } 6392 6393 // Arguments always reserve parameter save area. 6394 switch (ValVT.SimpleTy) { 6395 default: 6396 report_fatal_error("Unhandled value type for argument."); 6397 case MVT::i64: 6398 // i64 arguments should have been split to i32 for PPC32. 6399 assert(IsPPC64 && "PPC32 should have split i64 values."); 6400 LLVM_FALLTHROUGH; 6401 case MVT::i1: 6402 case MVT::i32: { 6403 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6404 // AIX integer arguments are always passed in register width. 6405 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6406 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6407 : CCValAssign::LocInfo::ZExt; 6408 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6409 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6410 else 6411 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6412 6413 return false; 6414 } 6415 case MVT::f32: 6416 case MVT::f64: { 6417 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6418 const unsigned StoreSize = LocVT.getStoreSize(); 6419 // Floats are always 4-byte aligned in the PSA on AIX. 6420 // This includes f64 in 64-bit mode for ABI compatibility. 6421 const unsigned Offset = 6422 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6423 unsigned FReg = State.AllocateReg(FPR); 6424 if (FReg) 6425 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6426 6427 // Reserve and initialize GPRs or initialize the PSA as required. 6428 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6429 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6430 assert(FReg && "An FPR should be available when a GPR is reserved."); 6431 if (State.isVarArg()) { 6432 // Successfully reserved GPRs are only initialized for vararg calls. 6433 // Custom handling is required for: 6434 // f64 in PPC32 needs to be split into 2 GPRs. 6435 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6436 State.addLoc( 6437 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6438 } 6439 } else { 6440 // If there are insufficient GPRs, the PSA needs to be initialized. 6441 // Initialization occurs even if an FPR was initialized for 6442 // compatibility with the AIX XL compiler. The full memory for the 6443 // argument will be initialized even if a prior word is saved in GPR. 6444 // A custom memLoc is used when the argument also passes in FPR so 6445 // that the callee handling can skip over it easily. 6446 State.addLoc( 6447 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6448 LocInfo) 6449 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6450 break; 6451 } 6452 } 6453 6454 return false; 6455 } 6456 case MVT::v4f32: 6457 case MVT::v4i32: 6458 case MVT::v8i16: 6459 case MVT::v16i8: 6460 case MVT::v2i64: 6461 case MVT::v2f64: 6462 case MVT::v1i128: { 6463 const unsigned VecSize = 16; 6464 const Align VecAlign(VecSize); 6465 6466 if (!State.isVarArg()) { 6467 // If there are vector registers remaining we don't consume any stack 6468 // space. 6469 if (unsigned VReg = State.AllocateReg(VR)) { 6470 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6471 return false; 6472 } 6473 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6474 // might be allocated in the portion of the PSA that is shadowed by the 6475 // GPRs. 6476 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6477 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6478 return false; 6479 } 6480 6481 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6482 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6483 6484 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6485 // Burn any underaligned registers and their shadowed stack space until 6486 // we reach the required alignment. 6487 while (NextRegIndex != GPRs.size() && 6488 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6489 // Shadow allocate register and its stack shadow. 6490 unsigned Reg = State.AllocateReg(GPRs); 6491 State.AllocateStack(PtrSize, PtrAlign); 6492 assert(Reg && "Allocating register unexpectedly failed."); 6493 (void)Reg; 6494 NextRegIndex = State.getFirstUnallocated(GPRs); 6495 } 6496 6497 // Vectors that are passed as fixed arguments are handled differently. 6498 // They are passed in VRs if any are available (unlike arguments passed 6499 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6500 // functions) 6501 if (State.isFixed(ValNo)) { 6502 if (unsigned VReg = State.AllocateReg(VR)) { 6503 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6504 // Shadow allocate GPRs and stack space even though we pass in a VR. 6505 for (unsigned I = 0; I != VecSize; I += PtrSize) 6506 State.AllocateReg(GPRs); 6507 State.AllocateStack(VecSize, VecAlign); 6508 return false; 6509 } 6510 // No vector registers remain so pass on the stack. 6511 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6512 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6513 return false; 6514 } 6515 6516 // If all GPRS are consumed then we pass the argument fully on the stack. 6517 if (NextRegIndex == GPRs.size()) { 6518 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6519 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6520 return false; 6521 } 6522 6523 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6524 // half of the argument, and then need to pass the remaining half on the 6525 // stack. 6526 if (GPRs[NextRegIndex] == PPC::R9) { 6527 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6528 State.addLoc( 6529 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6530 6531 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6532 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6533 assert(FirstReg && SecondReg && 6534 "Allocating R9 or R10 unexpectedly failed."); 6535 State.addLoc( 6536 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6537 State.addLoc( 6538 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6539 return false; 6540 } 6541 6542 // We have enough GPRs to fully pass the vector argument, and we have 6543 // already consumed any underaligned registers. Start with the custom 6544 // MemLoc and then the custom RegLocs. 6545 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6546 State.addLoc( 6547 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6548 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6549 const unsigned Reg = State.AllocateReg(GPRs); 6550 assert(Reg && "Failed to allocated register for vararg vector argument"); 6551 State.addLoc( 6552 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6553 } 6554 return false; 6555 } 6556 } 6557 return true; 6558 } 6559 6560 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6561 bool IsPPC64) { 6562 assert((IsPPC64 || SVT != MVT::i64) && 6563 "i64 should have been split for 32-bit codegen."); 6564 6565 switch (SVT) { 6566 default: 6567 report_fatal_error("Unexpected value type for formal argument"); 6568 case MVT::i1: 6569 case MVT::i32: 6570 case MVT::i64: 6571 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6572 case MVT::f32: 6573 return &PPC::F4RCRegClass; 6574 case MVT::f64: 6575 return &PPC::F8RCRegClass; 6576 case MVT::v4f32: 6577 case MVT::v4i32: 6578 case MVT::v8i16: 6579 case MVT::v16i8: 6580 case MVT::v2i64: 6581 case MVT::v2f64: 6582 case MVT::v1i128: 6583 return &PPC::VRRCRegClass; 6584 } 6585 } 6586 6587 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6588 SelectionDAG &DAG, SDValue ArgValue, 6589 MVT LocVT, const SDLoc &dl) { 6590 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6591 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6592 6593 if (Flags.isSExt()) 6594 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6595 DAG.getValueType(ValVT)); 6596 else if (Flags.isZExt()) 6597 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6598 DAG.getValueType(ValVT)); 6599 6600 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6601 } 6602 6603 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6604 const unsigned LASize = FL->getLinkageSize(); 6605 6606 if (PPC::GPRCRegClass.contains(Reg)) { 6607 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6608 "Reg must be a valid argument register!"); 6609 return LASize + 4 * (Reg - PPC::R3); 6610 } 6611 6612 if (PPC::G8RCRegClass.contains(Reg)) { 6613 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6614 "Reg must be a valid argument register!"); 6615 return LASize + 8 * (Reg - PPC::X3); 6616 } 6617 6618 llvm_unreachable("Only general purpose registers expected."); 6619 } 6620 6621 // AIX ABI Stack Frame Layout: 6622 // 6623 // Low Memory +--------------------------------------------+ 6624 // SP +---> | Back chain | ---+ 6625 // | +--------------------------------------------+ | 6626 // | | Saved Condition Register | | 6627 // | +--------------------------------------------+ | 6628 // | | Saved Linkage Register | | 6629 // | +--------------------------------------------+ | Linkage Area 6630 // | | Reserved for compilers | | 6631 // | +--------------------------------------------+ | 6632 // | | Reserved for binders | | 6633 // | +--------------------------------------------+ | 6634 // | | Saved TOC pointer | ---+ 6635 // | +--------------------------------------------+ 6636 // | | Parameter save area | 6637 // | +--------------------------------------------+ 6638 // | | Alloca space | 6639 // | +--------------------------------------------+ 6640 // | | Local variable space | 6641 // | +--------------------------------------------+ 6642 // | | Float/int conversion temporary | 6643 // | +--------------------------------------------+ 6644 // | | Save area for AltiVec registers | 6645 // | +--------------------------------------------+ 6646 // | | AltiVec alignment padding | 6647 // | +--------------------------------------------+ 6648 // | | Save area for VRSAVE register | 6649 // | +--------------------------------------------+ 6650 // | | Save area for General Purpose registers | 6651 // | +--------------------------------------------+ 6652 // | | Save area for Floating Point registers | 6653 // | +--------------------------------------------+ 6654 // +---- | Back chain | 6655 // High Memory +--------------------------------------------+ 6656 // 6657 // Specifications: 6658 // AIX 7.2 Assembler Language Reference 6659 // Subroutine linkage convention 6660 6661 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6662 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6663 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6664 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6665 6666 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6667 CallConv == CallingConv::Fast) && 6668 "Unexpected calling convention!"); 6669 6670 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6671 report_fatal_error("Tail call support is unimplemented on AIX."); 6672 6673 if (useSoftFloat()) 6674 report_fatal_error("Soft float support is unimplemented on AIX."); 6675 6676 const PPCSubtarget &Subtarget = 6677 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6678 6679 const bool IsPPC64 = Subtarget.isPPC64(); 6680 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6681 6682 // Assign locations to all of the incoming arguments. 6683 SmallVector<CCValAssign, 16> ArgLocs; 6684 MachineFunction &MF = DAG.getMachineFunction(); 6685 MachineFrameInfo &MFI = MF.getFrameInfo(); 6686 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6687 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6688 6689 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6690 // Reserve space for the linkage area on the stack. 6691 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6692 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6693 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6694 6695 SmallVector<SDValue, 8> MemOps; 6696 6697 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6698 CCValAssign &VA = ArgLocs[I++]; 6699 MVT LocVT = VA.getLocVT(); 6700 MVT ValVT = VA.getValVT(); 6701 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6702 // For compatibility with the AIX XL compiler, the float args in the 6703 // parameter save area are initialized even if the argument is available 6704 // in register. The caller is required to initialize both the register 6705 // and memory, however, the callee can choose to expect it in either. 6706 // The memloc is dismissed here because the argument is retrieved from 6707 // the register. 6708 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6709 continue; 6710 6711 auto HandleMemLoc = [&]() { 6712 const unsigned LocSize = LocVT.getStoreSize(); 6713 const unsigned ValSize = ValVT.getStoreSize(); 6714 assert((ValSize <= LocSize) && 6715 "Object size is larger than size of MemLoc"); 6716 int CurArgOffset = VA.getLocMemOffset(); 6717 // Objects are right-justified because AIX is big-endian. 6718 if (LocSize > ValSize) 6719 CurArgOffset += LocSize - ValSize; 6720 // Potential tail calls could cause overwriting of argument stack slots. 6721 const bool IsImmutable = 6722 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6723 (CallConv == CallingConv::Fast)); 6724 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6725 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6726 SDValue ArgValue = 6727 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6728 InVals.push_back(ArgValue); 6729 }; 6730 6731 // Vector arguments to VaArg functions are passed both on the stack, and 6732 // in any available GPRs. Load the value from the stack and add the GPRs 6733 // as live ins. 6734 if (VA.isMemLoc() && VA.needsCustom()) { 6735 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 6736 assert(isVarArg && "Only use custom memloc for vararg."); 6737 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 6738 // matching custom RegLocs. 6739 const unsigned OriginalValNo = VA.getValNo(); 6740 (void)OriginalValNo; 6741 6742 auto HandleCustomVecRegLoc = [&]() { 6743 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 6744 "Missing custom RegLoc."); 6745 VA = ArgLocs[I++]; 6746 assert(VA.getValVT().isVector() && 6747 "Unexpected Val type for custom RegLoc."); 6748 assert(VA.getValNo() == OriginalValNo && 6749 "ValNo mismatch between custom MemLoc and RegLoc."); 6750 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 6751 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6752 }; 6753 6754 HandleMemLoc(); 6755 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 6756 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 6757 // R10. 6758 HandleCustomVecRegLoc(); 6759 HandleCustomVecRegLoc(); 6760 6761 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 6762 // we passed the vector in R5, R6, R7 and R8. 6763 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 6764 assert(!IsPPC64 && 6765 "Only 2 custom RegLocs expected for 64-bit codegen."); 6766 HandleCustomVecRegLoc(); 6767 HandleCustomVecRegLoc(); 6768 } 6769 6770 continue; 6771 } 6772 6773 if (VA.isRegLoc()) { 6774 if (VA.getValVT().isScalarInteger()) 6775 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 6776 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) 6777 FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32 6778 ? PPCFunctionInfo::ShortFloatPoint 6779 : PPCFunctionInfo::LongFloatPoint); 6780 } 6781 6782 if (Flags.isByVal() && VA.isMemLoc()) { 6783 const unsigned Size = 6784 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 6785 PtrByteSize); 6786 const int FI = MF.getFrameInfo().CreateFixedObject( 6787 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 6788 /* IsAliased */ true); 6789 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6790 InVals.push_back(FIN); 6791 6792 continue; 6793 } 6794 6795 if (Flags.isByVal()) { 6796 assert(VA.isRegLoc() && "MemLocs should already be handled."); 6797 6798 const MCPhysReg ArgReg = VA.getLocReg(); 6799 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 6800 6801 if (Flags.getNonZeroByValAlign() > PtrByteSize) 6802 report_fatal_error("Over aligned byvals not supported yet."); 6803 6804 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 6805 const int FI = MF.getFrameInfo().CreateFixedObject( 6806 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 6807 /* IsAliased */ true); 6808 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6809 InVals.push_back(FIN); 6810 6811 // Add live ins for all the RegLocs for the same ByVal. 6812 const TargetRegisterClass *RegClass = 6813 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6814 6815 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 6816 unsigned Offset) { 6817 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 6818 // Since the callers side has left justified the aggregate in the 6819 // register, we can simply store the entire register into the stack 6820 // slot. 6821 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6822 // The store to the fixedstack object is needed becuase accessing a 6823 // field of the ByVal will use a gep and load. Ideally we will optimize 6824 // to extracting the value from the register directly, and elide the 6825 // stores when the arguments address is not taken, but that will need to 6826 // be future work. 6827 SDValue Store = DAG.getStore( 6828 CopyFrom.getValue(1), dl, CopyFrom, 6829 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 6830 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 6831 6832 MemOps.push_back(Store); 6833 }; 6834 6835 unsigned Offset = 0; 6836 HandleRegLoc(VA.getLocReg(), Offset); 6837 Offset += PtrByteSize; 6838 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 6839 Offset += PtrByteSize) { 6840 assert(ArgLocs[I].getValNo() == VA.getValNo() && 6841 "RegLocs should be for ByVal argument."); 6842 6843 const CCValAssign RL = ArgLocs[I++]; 6844 HandleRegLoc(RL.getLocReg(), Offset); 6845 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 6846 } 6847 6848 if (Offset != StackSize) { 6849 assert(ArgLocs[I].getValNo() == VA.getValNo() && 6850 "Expected MemLoc for remaining bytes."); 6851 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 6852 // Consume the MemLoc.The InVal has already been emitted, so nothing 6853 // more needs to be done. 6854 ++I; 6855 } 6856 6857 continue; 6858 } 6859 6860 if (VA.isRegLoc() && !VA.needsCustom()) { 6861 MVT::SimpleValueType SVT = ValVT.SimpleTy; 6862 unsigned VReg = 6863 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6864 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6865 if (ValVT.isScalarInteger() && 6866 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 6867 ArgValue = 6868 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 6869 } 6870 InVals.push_back(ArgValue); 6871 continue; 6872 } 6873 if (VA.isMemLoc()) { 6874 HandleMemLoc(); 6875 continue; 6876 } 6877 } 6878 6879 // On AIX a minimum of 8 words is saved to the parameter save area. 6880 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6881 // Area that is at least reserved in the caller of this function. 6882 unsigned CallerReservedArea = 6883 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 6884 6885 // Set the size that is at least reserved in caller of this function. Tail 6886 // call optimized function's reserved stack space needs to be aligned so 6887 // that taking the difference between two stack areas will result in an 6888 // aligned stack. 6889 CallerReservedArea = 6890 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 6891 FuncInfo->setMinReservedArea(CallerReservedArea); 6892 6893 if (isVarArg) { 6894 FuncInfo->setVarArgsFrameIndex( 6895 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 6896 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 6897 6898 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6899 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6900 6901 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6902 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6903 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 6904 6905 // The fixed integer arguments of a variadic function are stored to the 6906 // VarArgsFrameIndex on the stack so that they may be loaded by 6907 // dereferencing the result of va_next. 6908 for (unsigned GPRIndex = 6909 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 6910 GPRIndex < NumGPArgRegs; ++GPRIndex) { 6911 6912 const unsigned VReg = 6913 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 6914 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 6915 6916 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 6917 SDValue Store = 6918 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 6919 MemOps.push_back(Store); 6920 // Increment the address for the next argument to store. 6921 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 6922 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 6923 } 6924 } 6925 6926 if (!MemOps.empty()) 6927 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 6928 6929 return Chain; 6930 } 6931 6932 SDValue PPCTargetLowering::LowerCall_AIX( 6933 SDValue Chain, SDValue Callee, CallFlags CFlags, 6934 const SmallVectorImpl<ISD::OutputArg> &Outs, 6935 const SmallVectorImpl<SDValue> &OutVals, 6936 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6937 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6938 const CallBase *CB) const { 6939 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 6940 // AIX ABI stack frame layout. 6941 6942 assert((CFlags.CallConv == CallingConv::C || 6943 CFlags.CallConv == CallingConv::Cold || 6944 CFlags.CallConv == CallingConv::Fast) && 6945 "Unexpected calling convention!"); 6946 6947 if (CFlags.IsPatchPoint) 6948 report_fatal_error("This call type is unimplemented on AIX."); 6949 6950 const PPCSubtarget& Subtarget = 6951 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 6952 6953 MachineFunction &MF = DAG.getMachineFunction(); 6954 SmallVector<CCValAssign, 16> ArgLocs; 6955 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 6956 *DAG.getContext()); 6957 6958 // Reserve space for the linkage save area (LSA) on the stack. 6959 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 6960 // [SP][CR][LR][2 x reserved][TOC]. 6961 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 6962 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6963 const bool IsPPC64 = Subtarget.isPPC64(); 6964 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6965 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6966 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6967 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 6968 6969 // The prolog code of the callee may store up to 8 GPR argument registers to 6970 // the stack, allowing va_start to index over them in memory if the callee 6971 // is variadic. 6972 // Because we cannot tell if this is needed on the caller side, we have to 6973 // conservatively assume that it is needed. As such, make sure we have at 6974 // least enough stack space for the caller to store the 8 GPRs. 6975 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 6976 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 6977 CCInfo.getNextStackOffset()); 6978 6979 // Adjust the stack pointer for the new arguments... 6980 // These operations are automatically eliminated by the prolog/epilog pass. 6981 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6982 SDValue CallSeqStart = Chain; 6983 6984 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6985 SmallVector<SDValue, 8> MemOpChains; 6986 6987 // Set up a copy of the stack pointer for loading and storing any 6988 // arguments that may not fit in the registers available for argument 6989 // passing. 6990 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 6991 : DAG.getRegister(PPC::R1, MVT::i32); 6992 6993 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 6994 const unsigned ValNo = ArgLocs[I].getValNo(); 6995 SDValue Arg = OutVals[ValNo]; 6996 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 6997 6998 if (Flags.isByVal()) { 6999 const unsigned ByValSize = Flags.getByValSize(); 7000 7001 // Nothing to do for zero-sized ByVals on the caller side. 7002 if (!ByValSize) { 7003 ++I; 7004 continue; 7005 } 7006 7007 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7008 return DAG.getExtLoad( 7009 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7010 (LoadOffset != 0) 7011 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7012 : Arg, 7013 MachinePointerInfo(), VT); 7014 }; 7015 7016 unsigned LoadOffset = 0; 7017 7018 // Initialize registers, which are fully occupied by the by-val argument. 7019 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7020 SDValue Load = GetLoad(PtrVT, LoadOffset); 7021 MemOpChains.push_back(Load.getValue(1)); 7022 LoadOffset += PtrByteSize; 7023 const CCValAssign &ByValVA = ArgLocs[I++]; 7024 assert(ByValVA.getValNo() == ValNo && 7025 "Unexpected location for pass-by-value argument."); 7026 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7027 } 7028 7029 if (LoadOffset == ByValSize) 7030 continue; 7031 7032 // There must be one more loc to handle the remainder. 7033 assert(ArgLocs[I].getValNo() == ValNo && 7034 "Expected additional location for by-value argument."); 7035 7036 if (ArgLocs[I].isMemLoc()) { 7037 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7038 const CCValAssign &ByValVA = ArgLocs[I++]; 7039 ISD::ArgFlagsTy MemcpyFlags = Flags; 7040 // Only memcpy the bytes that don't pass in register. 7041 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7042 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7043 (LoadOffset != 0) 7044 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7045 : Arg, 7046 DAG.getObjectPtrOffset(dl, StackPtr, 7047 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7048 CallSeqStart, MemcpyFlags, DAG, dl); 7049 continue; 7050 } 7051 7052 // Initialize the final register residue. 7053 // Any residue that occupies the final by-val arg register must be 7054 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7055 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7056 // 2 and 1 byte loads. 7057 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7058 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7059 "Unexpected register residue for by-value argument."); 7060 SDValue ResidueVal; 7061 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7062 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7063 const MVT VT = 7064 N == 1 ? MVT::i8 7065 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7066 SDValue Load = GetLoad(VT, LoadOffset); 7067 MemOpChains.push_back(Load.getValue(1)); 7068 LoadOffset += N; 7069 Bytes += N; 7070 7071 // By-val arguments are passed left-justfied in register. 7072 // Every load here needs to be shifted, otherwise a full register load 7073 // should have been used. 7074 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7075 "Unexpected load emitted during handling of pass-by-value " 7076 "argument."); 7077 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7078 EVT ShiftAmountTy = 7079 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7080 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7081 SDValue ShiftedLoad = 7082 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7083 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7084 ShiftedLoad) 7085 : ShiftedLoad; 7086 } 7087 7088 const CCValAssign &ByValVA = ArgLocs[I++]; 7089 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7090 continue; 7091 } 7092 7093 CCValAssign &VA = ArgLocs[I++]; 7094 const MVT LocVT = VA.getLocVT(); 7095 const MVT ValVT = VA.getValVT(); 7096 7097 switch (VA.getLocInfo()) { 7098 default: 7099 report_fatal_error("Unexpected argument extension type."); 7100 case CCValAssign::Full: 7101 break; 7102 case CCValAssign::ZExt: 7103 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7104 break; 7105 case CCValAssign::SExt: 7106 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7107 break; 7108 } 7109 7110 if (VA.isRegLoc() && !VA.needsCustom()) { 7111 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7112 continue; 7113 } 7114 7115 // Vector arguments passed to VarArg functions need custom handling when 7116 // they are passed (at least partially) in GPRs. 7117 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7118 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7119 // Store value to its stack slot. 7120 SDValue PtrOff = 7121 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7122 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7123 SDValue Store = 7124 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7125 MemOpChains.push_back(Store); 7126 const unsigned OriginalValNo = VA.getValNo(); 7127 // Then load the GPRs from the stack 7128 unsigned LoadOffset = 0; 7129 auto HandleCustomVecRegLoc = [&]() { 7130 assert(I != E && "Unexpected end of CCvalAssigns."); 7131 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7132 "Expected custom RegLoc."); 7133 CCValAssign RegVA = ArgLocs[I++]; 7134 assert(RegVA.getValNo() == OriginalValNo && 7135 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7136 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7137 DAG.getConstant(LoadOffset, dl, PtrVT)); 7138 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7139 MemOpChains.push_back(Load.getValue(1)); 7140 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7141 LoadOffset += PtrByteSize; 7142 }; 7143 7144 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7145 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7146 // R10. 7147 HandleCustomVecRegLoc(); 7148 HandleCustomVecRegLoc(); 7149 7150 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7151 ArgLocs[I].getValNo() == OriginalValNo) { 7152 assert(!IsPPC64 && 7153 "Only 2 custom RegLocs expected for 64-bit codegen."); 7154 HandleCustomVecRegLoc(); 7155 HandleCustomVecRegLoc(); 7156 } 7157 7158 continue; 7159 } 7160 7161 if (VA.isMemLoc()) { 7162 SDValue PtrOff = 7163 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7164 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7165 MemOpChains.push_back( 7166 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7167 7168 continue; 7169 } 7170 7171 if (!ValVT.isFloatingPoint()) 7172 report_fatal_error( 7173 "Unexpected register handling for calling convention."); 7174 7175 // Custom handling is used for GPR initializations for vararg float 7176 // arguments. 7177 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7178 LocVT.isInteger() && 7179 "Custom register handling only expected for VarArg."); 7180 7181 SDValue ArgAsInt = 7182 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7183 7184 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7185 // f32 in 32-bit GPR 7186 // f64 in 64-bit GPR 7187 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7188 else if (Arg.getValueType().getFixedSizeInBits() < 7189 LocVT.getFixedSizeInBits()) 7190 // f32 in 64-bit GPR. 7191 RegsToPass.push_back(std::make_pair( 7192 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7193 else { 7194 // f64 in two 32-bit GPRs 7195 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7196 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7197 "Unexpected custom register for argument!"); 7198 CCValAssign &GPR1 = VA; 7199 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7200 DAG.getConstant(32, dl, MVT::i8)); 7201 RegsToPass.push_back(std::make_pair( 7202 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7203 7204 if (I != E) { 7205 // If only 1 GPR was available, there will only be one custom GPR and 7206 // the argument will also pass in memory. 7207 CCValAssign &PeekArg = ArgLocs[I]; 7208 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7209 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7210 CCValAssign &GPR2 = ArgLocs[I++]; 7211 RegsToPass.push_back(std::make_pair( 7212 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7213 } 7214 } 7215 } 7216 } 7217 7218 if (!MemOpChains.empty()) 7219 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7220 7221 // For indirect calls, we need to save the TOC base to the stack for 7222 // restoration after the call. 7223 if (CFlags.IsIndirect) { 7224 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7225 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7226 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7227 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7228 const unsigned TOCSaveOffset = 7229 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7230 7231 setUsesTOCBasePtr(DAG); 7232 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7233 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7234 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7235 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7236 Chain = DAG.getStore( 7237 Val.getValue(1), dl, Val, AddPtr, 7238 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7239 } 7240 7241 // Build a sequence of copy-to-reg nodes chained together with token chain 7242 // and flag operands which copy the outgoing args into the appropriate regs. 7243 SDValue InFlag; 7244 for (auto Reg : RegsToPass) { 7245 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7246 InFlag = Chain.getValue(1); 7247 } 7248 7249 const int SPDiff = 0; 7250 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7251 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7252 } 7253 7254 bool 7255 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7256 MachineFunction &MF, bool isVarArg, 7257 const SmallVectorImpl<ISD::OutputArg> &Outs, 7258 LLVMContext &Context) const { 7259 SmallVector<CCValAssign, 16> RVLocs; 7260 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7261 return CCInfo.CheckReturn( 7262 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7263 ? RetCC_PPC_Cold 7264 : RetCC_PPC); 7265 } 7266 7267 SDValue 7268 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7269 bool isVarArg, 7270 const SmallVectorImpl<ISD::OutputArg> &Outs, 7271 const SmallVectorImpl<SDValue> &OutVals, 7272 const SDLoc &dl, SelectionDAG &DAG) const { 7273 SmallVector<CCValAssign, 16> RVLocs; 7274 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7275 *DAG.getContext()); 7276 CCInfo.AnalyzeReturn(Outs, 7277 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7278 ? RetCC_PPC_Cold 7279 : RetCC_PPC); 7280 7281 SDValue Flag; 7282 SmallVector<SDValue, 4> RetOps(1, Chain); 7283 7284 // Copy the result values into the output registers. 7285 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7286 CCValAssign &VA = RVLocs[i]; 7287 assert(VA.isRegLoc() && "Can only return in registers!"); 7288 7289 SDValue Arg = OutVals[RealResIdx]; 7290 7291 switch (VA.getLocInfo()) { 7292 default: llvm_unreachable("Unknown loc info!"); 7293 case CCValAssign::Full: break; 7294 case CCValAssign::AExt: 7295 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7296 break; 7297 case CCValAssign::ZExt: 7298 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7299 break; 7300 case CCValAssign::SExt: 7301 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7302 break; 7303 } 7304 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7305 bool isLittleEndian = Subtarget.isLittleEndian(); 7306 // Legalize ret f64 -> ret 2 x i32. 7307 SDValue SVal = 7308 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7309 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7310 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7311 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7312 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7313 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7314 Flag = Chain.getValue(1); 7315 VA = RVLocs[++i]; // skip ahead to next loc 7316 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7317 } else 7318 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7319 Flag = Chain.getValue(1); 7320 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7321 } 7322 7323 RetOps[0] = Chain; // Update chain. 7324 7325 // Add the flag if we have it. 7326 if (Flag.getNode()) 7327 RetOps.push_back(Flag); 7328 7329 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7330 } 7331 7332 SDValue 7333 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7334 SelectionDAG &DAG) const { 7335 SDLoc dl(Op); 7336 7337 // Get the correct type for integers. 7338 EVT IntVT = Op.getValueType(); 7339 7340 // Get the inputs. 7341 SDValue Chain = Op.getOperand(0); 7342 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7343 // Build a DYNAREAOFFSET node. 7344 SDValue Ops[2] = {Chain, FPSIdx}; 7345 SDVTList VTs = DAG.getVTList(IntVT); 7346 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7347 } 7348 7349 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7350 SelectionDAG &DAG) const { 7351 // When we pop the dynamic allocation we need to restore the SP link. 7352 SDLoc dl(Op); 7353 7354 // Get the correct type for pointers. 7355 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7356 7357 // Construct the stack pointer operand. 7358 bool isPPC64 = Subtarget.isPPC64(); 7359 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7360 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7361 7362 // Get the operands for the STACKRESTORE. 7363 SDValue Chain = Op.getOperand(0); 7364 SDValue SaveSP = Op.getOperand(1); 7365 7366 // Load the old link SP. 7367 SDValue LoadLinkSP = 7368 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7369 7370 // Restore the stack pointer. 7371 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7372 7373 // Store the old link SP. 7374 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7375 } 7376 7377 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7378 MachineFunction &MF = DAG.getMachineFunction(); 7379 bool isPPC64 = Subtarget.isPPC64(); 7380 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7381 7382 // Get current frame pointer save index. The users of this index will be 7383 // primarily DYNALLOC instructions. 7384 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7385 int RASI = FI->getReturnAddrSaveIndex(); 7386 7387 // If the frame pointer save index hasn't been defined yet. 7388 if (!RASI) { 7389 // Find out what the fix offset of the frame pointer save area. 7390 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7391 // Allocate the frame index for frame pointer save area. 7392 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7393 // Save the result. 7394 FI->setReturnAddrSaveIndex(RASI); 7395 } 7396 return DAG.getFrameIndex(RASI, PtrVT); 7397 } 7398 7399 SDValue 7400 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7401 MachineFunction &MF = DAG.getMachineFunction(); 7402 bool isPPC64 = Subtarget.isPPC64(); 7403 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7404 7405 // Get current frame pointer save index. The users of this index will be 7406 // primarily DYNALLOC instructions. 7407 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7408 int FPSI = FI->getFramePointerSaveIndex(); 7409 7410 // If the frame pointer save index hasn't been defined yet. 7411 if (!FPSI) { 7412 // Find out what the fix offset of the frame pointer save area. 7413 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7414 // Allocate the frame index for frame pointer save area. 7415 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7416 // Save the result. 7417 FI->setFramePointerSaveIndex(FPSI); 7418 } 7419 return DAG.getFrameIndex(FPSI, PtrVT); 7420 } 7421 7422 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7423 SelectionDAG &DAG) const { 7424 MachineFunction &MF = DAG.getMachineFunction(); 7425 // Get the inputs. 7426 SDValue Chain = Op.getOperand(0); 7427 SDValue Size = Op.getOperand(1); 7428 SDLoc dl(Op); 7429 7430 // Get the correct type for pointers. 7431 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7432 // Negate the size. 7433 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7434 DAG.getConstant(0, dl, PtrVT), Size); 7435 // Construct a node for the frame pointer save index. 7436 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7437 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7438 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7439 if (hasInlineStackProbe(MF)) 7440 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7441 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7442 } 7443 7444 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7445 SelectionDAG &DAG) const { 7446 MachineFunction &MF = DAG.getMachineFunction(); 7447 7448 bool isPPC64 = Subtarget.isPPC64(); 7449 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7450 7451 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7452 return DAG.getFrameIndex(FI, PtrVT); 7453 } 7454 7455 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7456 SelectionDAG &DAG) const { 7457 SDLoc DL(Op); 7458 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7459 DAG.getVTList(MVT::i32, MVT::Other), 7460 Op.getOperand(0), Op.getOperand(1)); 7461 } 7462 7463 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7464 SelectionDAG &DAG) const { 7465 SDLoc DL(Op); 7466 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7467 Op.getOperand(0), Op.getOperand(1)); 7468 } 7469 7470 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7471 if (Op.getValueType().isVector()) 7472 return LowerVectorLoad(Op, DAG); 7473 7474 assert(Op.getValueType() == MVT::i1 && 7475 "Custom lowering only for i1 loads"); 7476 7477 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7478 7479 SDLoc dl(Op); 7480 LoadSDNode *LD = cast<LoadSDNode>(Op); 7481 7482 SDValue Chain = LD->getChain(); 7483 SDValue BasePtr = LD->getBasePtr(); 7484 MachineMemOperand *MMO = LD->getMemOperand(); 7485 7486 SDValue NewLD = 7487 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7488 BasePtr, MVT::i8, MMO); 7489 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7490 7491 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7492 return DAG.getMergeValues(Ops, dl); 7493 } 7494 7495 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7496 if (Op.getOperand(1).getValueType().isVector()) 7497 return LowerVectorStore(Op, DAG); 7498 7499 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7500 "Custom lowering only for i1 stores"); 7501 7502 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7503 7504 SDLoc dl(Op); 7505 StoreSDNode *ST = cast<StoreSDNode>(Op); 7506 7507 SDValue Chain = ST->getChain(); 7508 SDValue BasePtr = ST->getBasePtr(); 7509 SDValue Value = ST->getValue(); 7510 MachineMemOperand *MMO = ST->getMemOperand(); 7511 7512 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7513 Value); 7514 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7515 } 7516 7517 // FIXME: Remove this once the ANDI glue bug is fixed: 7518 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7519 assert(Op.getValueType() == MVT::i1 && 7520 "Custom lowering only for i1 results"); 7521 7522 SDLoc DL(Op); 7523 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7524 } 7525 7526 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7527 SelectionDAG &DAG) const { 7528 7529 // Implements a vector truncate that fits in a vector register as a shuffle. 7530 // We want to legalize vector truncates down to where the source fits in 7531 // a vector register (and target is therefore smaller than vector register 7532 // size). At that point legalization will try to custom lower the sub-legal 7533 // result and get here - where we can contain the truncate as a single target 7534 // operation. 7535 7536 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7537 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7538 // 7539 // We will implement it for big-endian ordering as this (where x denotes 7540 // undefined): 7541 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7542 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7543 // 7544 // The same operation in little-endian ordering will be: 7545 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7546 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7547 7548 EVT TrgVT = Op.getValueType(); 7549 assert(TrgVT.isVector() && "Vector type expected."); 7550 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7551 EVT EltVT = TrgVT.getVectorElementType(); 7552 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7553 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7554 !isPowerOf2_32(EltVT.getSizeInBits())) 7555 return SDValue(); 7556 7557 SDValue N1 = Op.getOperand(0); 7558 EVT SrcVT = N1.getValueType(); 7559 unsigned SrcSize = SrcVT.getSizeInBits(); 7560 if (SrcSize > 256 || 7561 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7562 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7563 return SDValue(); 7564 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7565 return SDValue(); 7566 7567 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7568 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7569 7570 SDLoc DL(Op); 7571 SDValue Op1, Op2; 7572 if (SrcSize == 256) { 7573 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7574 EVT SplitVT = 7575 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7576 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7577 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7578 DAG.getConstant(0, DL, VecIdxTy)); 7579 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7580 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7581 } 7582 else { 7583 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7584 Op2 = DAG.getUNDEF(WideVT); 7585 } 7586 7587 // First list the elements we want to keep. 7588 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7589 SmallVector<int, 16> ShuffV; 7590 if (Subtarget.isLittleEndian()) 7591 for (unsigned i = 0; i < TrgNumElts; ++i) 7592 ShuffV.push_back(i * SizeMult); 7593 else 7594 for (unsigned i = 1; i <= TrgNumElts; ++i) 7595 ShuffV.push_back(i * SizeMult - 1); 7596 7597 // Populate the remaining elements with undefs. 7598 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7599 // ShuffV.push_back(i + WideNumElts); 7600 ShuffV.push_back(WideNumElts + 1); 7601 7602 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7603 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7604 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7605 } 7606 7607 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7608 /// possible. 7609 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7610 // Not FP, or using SPE? Not a fsel. 7611 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7612 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7613 return Op; 7614 7615 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7616 7617 EVT ResVT = Op.getValueType(); 7618 EVT CmpVT = Op.getOperand(0).getValueType(); 7619 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7620 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7621 SDLoc dl(Op); 7622 SDNodeFlags Flags = Op.getNode()->getFlags(); 7623 7624 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7625 // presence of infinities. 7626 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7627 switch (CC) { 7628 default: 7629 break; 7630 case ISD::SETOGT: 7631 case ISD::SETGT: 7632 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7633 case ISD::SETOLT: 7634 case ISD::SETLT: 7635 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7636 } 7637 } 7638 7639 // We might be able to do better than this under some circumstances, but in 7640 // general, fsel-based lowering of select is a finite-math-only optimization. 7641 // For more information, see section F.3 of the 2.06 ISA specification. 7642 // With ISA 3.0 7643 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7644 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7645 return Op; 7646 7647 // If the RHS of the comparison is a 0.0, we don't need to do the 7648 // subtraction at all. 7649 SDValue Sel1; 7650 if (isFloatingPointZero(RHS)) 7651 switch (CC) { 7652 default: break; // SETUO etc aren't handled by fsel. 7653 case ISD::SETNE: 7654 std::swap(TV, FV); 7655 LLVM_FALLTHROUGH; 7656 case ISD::SETEQ: 7657 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7658 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7659 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7660 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7661 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7662 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7663 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7664 case ISD::SETULT: 7665 case ISD::SETLT: 7666 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7667 LLVM_FALLTHROUGH; 7668 case ISD::SETOGE: 7669 case ISD::SETGE: 7670 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7671 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7672 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7673 case ISD::SETUGT: 7674 case ISD::SETGT: 7675 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7676 LLVM_FALLTHROUGH; 7677 case ISD::SETOLE: 7678 case ISD::SETLE: 7679 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7680 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7681 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7682 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7683 } 7684 7685 SDValue Cmp; 7686 switch (CC) { 7687 default: break; // SETUO etc aren't handled by fsel. 7688 case ISD::SETNE: 7689 std::swap(TV, FV); 7690 LLVM_FALLTHROUGH; 7691 case ISD::SETEQ: 7692 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7693 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7694 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7695 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7696 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7697 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7698 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7699 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7700 case ISD::SETULT: 7701 case ISD::SETLT: 7702 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7703 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7704 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7705 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7706 case ISD::SETOGE: 7707 case ISD::SETGE: 7708 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7709 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7710 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7711 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7712 case ISD::SETUGT: 7713 case ISD::SETGT: 7714 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7715 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7716 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7717 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7718 case ISD::SETOLE: 7719 case ISD::SETLE: 7720 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7721 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7722 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7723 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7724 } 7725 return Op; 7726 } 7727 7728 static unsigned getPPCStrictOpcode(unsigned Opc) { 7729 switch (Opc) { 7730 default: 7731 llvm_unreachable("No strict version of this opcode!"); 7732 case PPCISD::FCTIDZ: 7733 return PPCISD::STRICT_FCTIDZ; 7734 case PPCISD::FCTIWZ: 7735 return PPCISD::STRICT_FCTIWZ; 7736 case PPCISD::FCTIDUZ: 7737 return PPCISD::STRICT_FCTIDUZ; 7738 case PPCISD::FCTIWUZ: 7739 return PPCISD::STRICT_FCTIWUZ; 7740 case PPCISD::FCFID: 7741 return PPCISD::STRICT_FCFID; 7742 case PPCISD::FCFIDU: 7743 return PPCISD::STRICT_FCFIDU; 7744 case PPCISD::FCFIDS: 7745 return PPCISD::STRICT_FCFIDS; 7746 case PPCISD::FCFIDUS: 7747 return PPCISD::STRICT_FCFIDUS; 7748 } 7749 } 7750 7751 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 7752 const PPCSubtarget &Subtarget) { 7753 SDLoc dl(Op); 7754 bool IsStrict = Op->isStrictFPOpcode(); 7755 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7756 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7757 7758 // TODO: Any other flags to propagate? 7759 SDNodeFlags Flags; 7760 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 7761 7762 // For strict nodes, source is the second operand. 7763 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7764 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 7765 assert(Src.getValueType().isFloatingPoint()); 7766 if (Src.getValueType() == MVT::f32) { 7767 if (IsStrict) { 7768 Src = 7769 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 7770 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 7771 Chain = Src.getValue(1); 7772 } else 7773 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7774 } 7775 SDValue Conv; 7776 unsigned Opc = ISD::DELETED_NODE; 7777 switch (Op.getSimpleValueType().SimpleTy) { 7778 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7779 case MVT::i32: 7780 Opc = IsSigned ? PPCISD::FCTIWZ 7781 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 7782 break; 7783 case MVT::i64: 7784 assert((IsSigned || Subtarget.hasFPCVT()) && 7785 "i64 FP_TO_UINT is supported only with FPCVT"); 7786 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 7787 } 7788 if (IsStrict) { 7789 Opc = getPPCStrictOpcode(Opc); 7790 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 7791 {Chain, Src}, Flags); 7792 } else { 7793 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 7794 } 7795 return Conv; 7796 } 7797 7798 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7799 SelectionDAG &DAG, 7800 const SDLoc &dl) const { 7801 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 7802 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7803 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7804 bool IsStrict = Op->isStrictFPOpcode(); 7805 7806 // Convert the FP value to an int value through memory. 7807 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7808 (IsSigned || Subtarget.hasFPCVT()); 7809 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7810 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7811 MachinePointerInfo MPI = 7812 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7813 7814 // Emit a store to the stack slot. 7815 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 7816 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 7817 if (i32Stack) { 7818 MachineFunction &MF = DAG.getMachineFunction(); 7819 Alignment = Align(4); 7820 MachineMemOperand *MMO = 7821 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 7822 SDValue Ops[] = { Chain, Tmp, FIPtr }; 7823 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7824 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7825 } else 7826 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 7827 7828 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7829 // add in a bias on big endian. 7830 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7831 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7832 DAG.getConstant(4, dl, FIPtr.getValueType())); 7833 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7834 } 7835 7836 RLI.Chain = Chain; 7837 RLI.Ptr = FIPtr; 7838 RLI.MPI = MPI; 7839 RLI.Alignment = Alignment; 7840 } 7841 7842 /// Custom lowers floating point to integer conversions to use 7843 /// the direct move instructions available in ISA 2.07 to avoid the 7844 /// need for load/store combinations. 7845 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7846 SelectionDAG &DAG, 7847 const SDLoc &dl) const { 7848 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 7849 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 7850 if (Op->isStrictFPOpcode()) 7851 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 7852 else 7853 return Mov; 7854 } 7855 7856 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7857 const SDLoc &dl) const { 7858 bool IsStrict = Op->isStrictFPOpcode(); 7859 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7860 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7861 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7862 EVT SrcVT = Src.getValueType(); 7863 EVT DstVT = Op.getValueType(); 7864 7865 // FP to INT conversions are legal for f128. 7866 if (SrcVT == MVT::f128) 7867 return Subtarget.hasP9Vector() ? Op : SDValue(); 7868 7869 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7870 // PPC (the libcall is not available). 7871 if (SrcVT == MVT::ppcf128) { 7872 if (DstVT == MVT::i32) { 7873 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 7874 // set other fast-math flags to FP operations in both strict and 7875 // non-strict cases. (FP_TO_SINT, FSUB) 7876 SDNodeFlags Flags; 7877 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 7878 7879 if (IsSigned) { 7880 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 7881 DAG.getIntPtrConstant(0, dl)); 7882 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 7883 DAG.getIntPtrConstant(1, dl)); 7884 7885 // Add the two halves of the long double in round-to-zero mode, and use 7886 // a smaller FP_TO_SINT. 7887 if (IsStrict) { 7888 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 7889 DAG.getVTList(MVT::f64, MVT::Other), 7890 {Op.getOperand(0), Lo, Hi}, Flags); 7891 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 7892 DAG.getVTList(MVT::i32, MVT::Other), 7893 {Res.getValue(1), Res}, Flags); 7894 } else { 7895 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7896 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7897 } 7898 } else { 7899 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7900 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7901 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7902 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 7903 if (IsStrict) { 7904 // Sel = Src < 0x80000000 7905 // FltOfs = select Sel, 0.0, 0x80000000 7906 // IntOfs = select Sel, 0, 0x80000000 7907 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7908 SDValue Chain = Op.getOperand(0); 7909 EVT SetCCVT = 7910 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7911 EVT DstSetCCVT = 7912 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7913 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7914 Chain, true); 7915 Chain = Sel.getValue(1); 7916 7917 SDValue FltOfs = DAG.getSelect( 7918 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7919 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7920 7921 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 7922 DAG.getVTList(SrcVT, MVT::Other), 7923 {Chain, Src, FltOfs}, Flags); 7924 Chain = Val.getValue(1); 7925 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 7926 DAG.getVTList(DstVT, MVT::Other), 7927 {Chain, Val}, Flags); 7928 Chain = SInt.getValue(1); 7929 SDValue IntOfs = DAG.getSelect( 7930 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 7931 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7932 return DAG.getMergeValues({Result, Chain}, dl); 7933 } else { 7934 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7935 // FIXME: generated code sucks. 7936 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 7937 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7938 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 7939 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 7940 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 7941 } 7942 } 7943 } 7944 7945 return SDValue(); 7946 } 7947 7948 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7949 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7950 7951 ReuseLoadInfo RLI; 7952 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7953 7954 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7955 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7956 } 7957 7958 // We're trying to insert a regular store, S, and then a load, L. If the 7959 // incoming value, O, is a load, we might just be able to have our load use the 7960 // address used by O. However, we don't know if anything else will store to 7961 // that address before we can load from it. To prevent this situation, we need 7962 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7963 // the same chain operand as O, we create a token factor from the chain results 7964 // of O and L, and we replace all uses of O's chain result with that token 7965 // factor (see spliceIntoChain below for this last part). 7966 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7967 ReuseLoadInfo &RLI, 7968 SelectionDAG &DAG, 7969 ISD::LoadExtType ET) const { 7970 // Conservatively skip reusing for constrained FP nodes. 7971 if (Op->isStrictFPOpcode()) 7972 return false; 7973 7974 SDLoc dl(Op); 7975 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 7976 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 7977 if (ET == ISD::NON_EXTLOAD && 7978 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 7979 isOperationLegalOrCustom(Op.getOpcode(), 7980 Op.getOperand(0).getValueType())) { 7981 7982 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7983 return true; 7984 } 7985 7986 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7987 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7988 LD->isNonTemporal()) 7989 return false; 7990 if (LD->getMemoryVT() != MemVT) 7991 return false; 7992 7993 // If the result of the load is an illegal type, then we can't build a 7994 // valid chain for reuse since the legalised loads and token factor node that 7995 // ties the legalised loads together uses a different output chain then the 7996 // illegal load. 7997 if (!isTypeLegal(LD->getValueType(0))) 7998 return false; 7999 8000 RLI.Ptr = LD->getBasePtr(); 8001 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8002 assert(LD->getAddressingMode() == ISD::PRE_INC && 8003 "Non-pre-inc AM on PPC?"); 8004 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8005 LD->getOffset()); 8006 } 8007 8008 RLI.Chain = LD->getChain(); 8009 RLI.MPI = LD->getPointerInfo(); 8010 RLI.IsDereferenceable = LD->isDereferenceable(); 8011 RLI.IsInvariant = LD->isInvariant(); 8012 RLI.Alignment = LD->getAlign(); 8013 RLI.AAInfo = LD->getAAInfo(); 8014 RLI.Ranges = LD->getRanges(); 8015 8016 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8017 return true; 8018 } 8019 8020 // Given the head of the old chain, ResChain, insert a token factor containing 8021 // it and NewResChain, and make users of ResChain now be users of that token 8022 // factor. 8023 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8024 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8025 SDValue NewResChain, 8026 SelectionDAG &DAG) const { 8027 if (!ResChain) 8028 return; 8029 8030 SDLoc dl(NewResChain); 8031 8032 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8033 NewResChain, DAG.getUNDEF(MVT::Other)); 8034 assert(TF.getNode() != NewResChain.getNode() && 8035 "A new TF really is required here"); 8036 8037 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8038 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8039 } 8040 8041 /// Analyze profitability of direct move 8042 /// prefer float load to int load plus direct move 8043 /// when there is no integer use of int load 8044 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8045 SDNode *Origin = Op.getOperand(0).getNode(); 8046 if (Origin->getOpcode() != ISD::LOAD) 8047 return true; 8048 8049 // If there is no LXSIBZX/LXSIHZX, like Power8, 8050 // prefer direct move if the memory size is 1 or 2 bytes. 8051 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8052 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8053 return true; 8054 8055 for (SDNode::use_iterator UI = Origin->use_begin(), 8056 UE = Origin->use_end(); 8057 UI != UE; ++UI) { 8058 8059 // Only look at the users of the loaded value. 8060 if (UI.getUse().get().getResNo() != 0) 8061 continue; 8062 8063 if (UI->getOpcode() != ISD::SINT_TO_FP && 8064 UI->getOpcode() != ISD::UINT_TO_FP && 8065 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8066 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8067 return true; 8068 } 8069 8070 return false; 8071 } 8072 8073 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8074 const PPCSubtarget &Subtarget, 8075 SDValue Chain = SDValue()) { 8076 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8077 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8078 SDLoc dl(Op); 8079 8080 // TODO: Any other flags to propagate? 8081 SDNodeFlags Flags; 8082 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8083 8084 // If we have FCFIDS, then use it when converting to single-precision. 8085 // Otherwise, convert to double-precision and then round. 8086 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8087 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8088 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8089 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8090 if (Op->isStrictFPOpcode()) { 8091 if (!Chain) 8092 Chain = Op.getOperand(0); 8093 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8094 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8095 } else 8096 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8097 } 8098 8099 /// Custom lowers integer to floating point conversions to use 8100 /// the direct move instructions available in ISA 2.07 to avoid the 8101 /// need for load/store combinations. 8102 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8103 SelectionDAG &DAG, 8104 const SDLoc &dl) const { 8105 assert((Op.getValueType() == MVT::f32 || 8106 Op.getValueType() == MVT::f64) && 8107 "Invalid floating point type as target of conversion"); 8108 assert(Subtarget.hasFPCVT() && 8109 "Int to FP conversions with direct moves require FPCVT"); 8110 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8111 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8112 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8113 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8114 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8115 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8116 return convertIntToFP(Op, Mov, DAG, Subtarget); 8117 } 8118 8119 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8120 8121 EVT VecVT = Vec.getValueType(); 8122 assert(VecVT.isVector() && "Expected a vector type."); 8123 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8124 8125 EVT EltVT = VecVT.getVectorElementType(); 8126 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8127 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8128 8129 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8130 SmallVector<SDValue, 16> Ops(NumConcat); 8131 Ops[0] = Vec; 8132 SDValue UndefVec = DAG.getUNDEF(VecVT); 8133 for (unsigned i = 1; i < NumConcat; ++i) 8134 Ops[i] = UndefVec; 8135 8136 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8137 } 8138 8139 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8140 const SDLoc &dl) const { 8141 bool IsStrict = Op->isStrictFPOpcode(); 8142 unsigned Opc = Op.getOpcode(); 8143 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8144 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8145 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8146 "Unexpected conversion type"); 8147 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8148 "Supports conversions to v2f64/v4f32 only."); 8149 8150 // TODO: Any other flags to propagate? 8151 SDNodeFlags Flags; 8152 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8153 8154 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8155 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8156 8157 SDValue Wide = widenVec(DAG, Src, dl); 8158 EVT WideVT = Wide.getValueType(); 8159 unsigned WideNumElts = WideVT.getVectorNumElements(); 8160 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8161 8162 SmallVector<int, 16> ShuffV; 8163 for (unsigned i = 0; i < WideNumElts; ++i) 8164 ShuffV.push_back(i + WideNumElts); 8165 8166 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8167 int SaveElts = FourEltRes ? 4 : 2; 8168 if (Subtarget.isLittleEndian()) 8169 for (int i = 0; i < SaveElts; i++) 8170 ShuffV[i * Stride] = i; 8171 else 8172 for (int i = 1; i <= SaveElts; i++) 8173 ShuffV[i * Stride - 1] = i - 1; 8174 8175 SDValue ShuffleSrc2 = 8176 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8177 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8178 8179 SDValue Extend; 8180 if (SignedConv) { 8181 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8182 EVT ExtVT = Src.getValueType(); 8183 if (Subtarget.hasP9Altivec()) 8184 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8185 IntermediateVT.getVectorNumElements()); 8186 8187 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8188 DAG.getValueType(ExtVT)); 8189 } else 8190 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8191 8192 if (IsStrict) 8193 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8194 {Op.getOperand(0), Extend}, Flags); 8195 8196 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8197 } 8198 8199 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8200 SelectionDAG &DAG) const { 8201 SDLoc dl(Op); 8202 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8203 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8204 bool IsStrict = Op->isStrictFPOpcode(); 8205 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8206 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8207 8208 // TODO: Any other flags to propagate? 8209 SDNodeFlags Flags; 8210 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8211 8212 EVT InVT = Src.getValueType(); 8213 EVT OutVT = Op.getValueType(); 8214 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8215 isOperationCustom(Op.getOpcode(), InVT)) 8216 return LowerINT_TO_FPVector(Op, DAG, dl); 8217 8218 // Conversions to f128 are legal. 8219 if (Op.getValueType() == MVT::f128) 8220 return Subtarget.hasP9Vector() ? Op : SDValue(); 8221 8222 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8223 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8224 return SDValue(); 8225 8226 if (Src.getValueType() == MVT::i1) { 8227 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8228 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8229 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8230 if (IsStrict) 8231 return DAG.getMergeValues({Sel, Chain}, dl); 8232 else 8233 return Sel; 8234 } 8235 8236 // If we have direct moves, we can do all the conversion, skip the store/load 8237 // however, without FPCVT we can't do most conversions. 8238 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8239 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8240 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8241 8242 assert((IsSigned || Subtarget.hasFPCVT()) && 8243 "UINT_TO_FP is supported only with FPCVT"); 8244 8245 if (Src.getValueType() == MVT::i64) { 8246 SDValue SINT = Src; 8247 // When converting to single-precision, we actually need to convert 8248 // to double-precision first and then round to single-precision. 8249 // To avoid double-rounding effects during that operation, we have 8250 // to prepare the input operand. Bits that might be truncated when 8251 // converting to double-precision are replaced by a bit that won't 8252 // be lost at this stage, but is below the single-precision rounding 8253 // position. 8254 // 8255 // However, if -enable-unsafe-fp-math is in effect, accept double 8256 // rounding to avoid the extra overhead. 8257 if (Op.getValueType() == MVT::f32 && 8258 !Subtarget.hasFPCVT() && 8259 !DAG.getTarget().Options.UnsafeFPMath) { 8260 8261 // Twiddle input to make sure the low 11 bits are zero. (If this 8262 // is the case, we are guaranteed the value will fit into the 53 bit 8263 // mantissa of an IEEE double-precision value without rounding.) 8264 // If any of those low 11 bits were not zero originally, make sure 8265 // bit 12 (value 2048) is set instead, so that the final rounding 8266 // to single-precision gets the correct result. 8267 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8268 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8269 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8270 Round, DAG.getConstant(2047, dl, MVT::i64)); 8271 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8272 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8273 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8274 8275 // However, we cannot use that value unconditionally: if the magnitude 8276 // of the input value is small, the bit-twiddling we did above might 8277 // end up visibly changing the output. Fortunately, in that case, we 8278 // don't need to twiddle bits since the original input will convert 8279 // exactly to double-precision floating-point already. Therefore, 8280 // construct a conditional to use the original value if the top 11 8281 // bits are all sign-bit copies, and use the rounded value computed 8282 // above otherwise. 8283 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8284 SINT, DAG.getConstant(53, dl, MVT::i32)); 8285 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8286 Cond, DAG.getConstant(1, dl, MVT::i64)); 8287 Cond = DAG.getSetCC( 8288 dl, 8289 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8290 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8291 8292 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8293 } 8294 8295 ReuseLoadInfo RLI; 8296 SDValue Bits; 8297 8298 MachineFunction &MF = DAG.getMachineFunction(); 8299 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8300 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8301 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8302 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8303 } else if (Subtarget.hasLFIWAX() && 8304 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8305 MachineMemOperand *MMO = 8306 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8307 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8308 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8309 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8310 DAG.getVTList(MVT::f64, MVT::Other), 8311 Ops, MVT::i32, MMO); 8312 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8313 } else if (Subtarget.hasFPCVT() && 8314 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8315 MachineMemOperand *MMO = 8316 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8317 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8318 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8319 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8320 DAG.getVTList(MVT::f64, MVT::Other), 8321 Ops, MVT::i32, MMO); 8322 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8323 } else if (((Subtarget.hasLFIWAX() && 8324 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8325 (Subtarget.hasFPCVT() && 8326 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8327 SINT.getOperand(0).getValueType() == MVT::i32) { 8328 MachineFrameInfo &MFI = MF.getFrameInfo(); 8329 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8330 8331 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8332 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8333 8334 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8335 MachinePointerInfo::getFixedStack( 8336 DAG.getMachineFunction(), FrameIdx)); 8337 Chain = Store; 8338 8339 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8340 "Expected an i32 store"); 8341 8342 RLI.Ptr = FIdx; 8343 RLI.Chain = Chain; 8344 RLI.MPI = 8345 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8346 RLI.Alignment = Align(4); 8347 8348 MachineMemOperand *MMO = 8349 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8350 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8351 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8352 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8353 PPCISD::LFIWZX : PPCISD::LFIWAX, 8354 dl, DAG.getVTList(MVT::f64, MVT::Other), 8355 Ops, MVT::i32, MMO); 8356 Chain = Bits.getValue(1); 8357 } else 8358 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8359 8360 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8361 if (IsStrict) 8362 Chain = FP.getValue(1); 8363 8364 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8365 if (IsStrict) 8366 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8367 DAG.getVTList(MVT::f32, MVT::Other), 8368 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8369 else 8370 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8371 DAG.getIntPtrConstant(0, dl)); 8372 } 8373 return FP; 8374 } 8375 8376 assert(Src.getValueType() == MVT::i32 && 8377 "Unhandled INT_TO_FP type in custom expander!"); 8378 // Since we only generate this in 64-bit mode, we can take advantage of 8379 // 64-bit registers. In particular, sign extend the input value into the 8380 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8381 // then lfd it and fcfid it. 8382 MachineFunction &MF = DAG.getMachineFunction(); 8383 MachineFrameInfo &MFI = MF.getFrameInfo(); 8384 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8385 8386 SDValue Ld; 8387 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8388 ReuseLoadInfo RLI; 8389 bool ReusingLoad; 8390 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8391 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8392 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8393 8394 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8395 MachinePointerInfo::getFixedStack( 8396 DAG.getMachineFunction(), FrameIdx)); 8397 Chain = Store; 8398 8399 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8400 "Expected an i32 store"); 8401 8402 RLI.Ptr = FIdx; 8403 RLI.Chain = Chain; 8404 RLI.MPI = 8405 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8406 RLI.Alignment = Align(4); 8407 } 8408 8409 MachineMemOperand *MMO = 8410 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8411 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8412 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8413 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8414 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8415 MVT::i32, MMO); 8416 Chain = Ld.getValue(1); 8417 if (ReusingLoad) 8418 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8419 } else { 8420 assert(Subtarget.isPPC64() && 8421 "i32->FP without LFIWAX supported only on PPC64"); 8422 8423 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8424 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8425 8426 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8427 8428 // STD the extended value into the stack slot. 8429 SDValue Store = DAG.getStore( 8430 Chain, dl, Ext64, FIdx, 8431 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8432 Chain = Store; 8433 8434 // Load the value as a double. 8435 Ld = DAG.getLoad( 8436 MVT::f64, dl, Chain, FIdx, 8437 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8438 Chain = Ld.getValue(1); 8439 } 8440 8441 // FCFID it and return it. 8442 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8443 if (IsStrict) 8444 Chain = FP.getValue(1); 8445 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8446 if (IsStrict) 8447 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8448 DAG.getVTList(MVT::f32, MVT::Other), 8449 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8450 else 8451 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8452 DAG.getIntPtrConstant(0, dl)); 8453 } 8454 return FP; 8455 } 8456 8457 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8458 SelectionDAG &DAG) const { 8459 SDLoc dl(Op); 8460 /* 8461 The rounding mode is in bits 30:31 of FPSR, and has the following 8462 settings: 8463 00 Round to nearest 8464 01 Round to 0 8465 10 Round to +inf 8466 11 Round to -inf 8467 8468 FLT_ROUNDS, on the other hand, expects the following: 8469 -1 Undefined 8470 0 Round to 0 8471 1 Round to nearest 8472 2 Round to +inf 8473 3 Round to -inf 8474 8475 To perform the conversion, we do: 8476 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8477 */ 8478 8479 MachineFunction &MF = DAG.getMachineFunction(); 8480 EVT VT = Op.getValueType(); 8481 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8482 8483 // Save FP Control Word to register 8484 SDValue Chain = Op.getOperand(0); 8485 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8486 Chain = MFFS.getValue(1); 8487 8488 SDValue CWD; 8489 if (isTypeLegal(MVT::i64)) { 8490 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8491 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8492 } else { 8493 // Save FP register to stack slot 8494 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8495 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8496 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8497 8498 // Load FP Control Word from low 32 bits of stack slot. 8499 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8500 "Stack slot adjustment is valid only on big endian subtargets!"); 8501 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8502 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8503 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8504 Chain = CWD.getValue(1); 8505 } 8506 8507 // Transform as necessary 8508 SDValue CWD1 = 8509 DAG.getNode(ISD::AND, dl, MVT::i32, 8510 CWD, DAG.getConstant(3, dl, MVT::i32)); 8511 SDValue CWD2 = 8512 DAG.getNode(ISD::SRL, dl, MVT::i32, 8513 DAG.getNode(ISD::AND, dl, MVT::i32, 8514 DAG.getNode(ISD::XOR, dl, MVT::i32, 8515 CWD, DAG.getConstant(3, dl, MVT::i32)), 8516 DAG.getConstant(3, dl, MVT::i32)), 8517 DAG.getConstant(1, dl, MVT::i32)); 8518 8519 SDValue RetVal = 8520 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8521 8522 RetVal = 8523 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8524 dl, VT, RetVal); 8525 8526 return DAG.getMergeValues({RetVal, Chain}, dl); 8527 } 8528 8529 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8530 EVT VT = Op.getValueType(); 8531 unsigned BitWidth = VT.getSizeInBits(); 8532 SDLoc dl(Op); 8533 assert(Op.getNumOperands() == 3 && 8534 VT == Op.getOperand(1).getValueType() && 8535 "Unexpected SHL!"); 8536 8537 // Expand into a bunch of logical ops. Note that these ops 8538 // depend on the PPC behavior for oversized shift amounts. 8539 SDValue Lo = Op.getOperand(0); 8540 SDValue Hi = Op.getOperand(1); 8541 SDValue Amt = Op.getOperand(2); 8542 EVT AmtVT = Amt.getValueType(); 8543 8544 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8545 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8546 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8547 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8548 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8549 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8550 DAG.getConstant(-BitWidth, dl, AmtVT)); 8551 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8552 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8553 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8554 SDValue OutOps[] = { OutLo, OutHi }; 8555 return DAG.getMergeValues(OutOps, dl); 8556 } 8557 8558 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8559 EVT VT = Op.getValueType(); 8560 SDLoc dl(Op); 8561 unsigned BitWidth = VT.getSizeInBits(); 8562 assert(Op.getNumOperands() == 3 && 8563 VT == Op.getOperand(1).getValueType() && 8564 "Unexpected SRL!"); 8565 8566 // Expand into a bunch of logical ops. Note that these ops 8567 // depend on the PPC behavior for oversized shift amounts. 8568 SDValue Lo = Op.getOperand(0); 8569 SDValue Hi = Op.getOperand(1); 8570 SDValue Amt = Op.getOperand(2); 8571 EVT AmtVT = Amt.getValueType(); 8572 8573 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8574 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8575 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8576 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8577 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8578 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8579 DAG.getConstant(-BitWidth, dl, AmtVT)); 8580 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8581 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8582 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8583 SDValue OutOps[] = { OutLo, OutHi }; 8584 return DAG.getMergeValues(OutOps, dl); 8585 } 8586 8587 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8588 SDLoc dl(Op); 8589 EVT VT = Op.getValueType(); 8590 unsigned BitWidth = VT.getSizeInBits(); 8591 assert(Op.getNumOperands() == 3 && 8592 VT == Op.getOperand(1).getValueType() && 8593 "Unexpected SRA!"); 8594 8595 // Expand into a bunch of logical ops, followed by a select_cc. 8596 SDValue Lo = Op.getOperand(0); 8597 SDValue Hi = Op.getOperand(1); 8598 SDValue Amt = Op.getOperand(2); 8599 EVT AmtVT = Amt.getValueType(); 8600 8601 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8602 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8603 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8604 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8605 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8606 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8607 DAG.getConstant(-BitWidth, dl, AmtVT)); 8608 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8609 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8610 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8611 Tmp4, Tmp6, ISD::SETLE); 8612 SDValue OutOps[] = { OutLo, OutHi }; 8613 return DAG.getMergeValues(OutOps, dl); 8614 } 8615 8616 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8617 SelectionDAG &DAG) const { 8618 SDLoc dl(Op); 8619 EVT VT = Op.getValueType(); 8620 unsigned BitWidth = VT.getSizeInBits(); 8621 8622 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8623 SDValue X = Op.getOperand(0); 8624 SDValue Y = Op.getOperand(1); 8625 SDValue Z = Op.getOperand(2); 8626 EVT AmtVT = Z.getValueType(); 8627 8628 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8629 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8630 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8631 // on PowerPC shift by BW being well defined. 8632 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8633 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8634 SDValue SubZ = 8635 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8636 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8637 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8638 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8639 } 8640 8641 //===----------------------------------------------------------------------===// 8642 // Vector related lowering. 8643 // 8644 8645 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8646 /// element size of SplatSize. Cast the result to VT. 8647 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8648 SelectionDAG &DAG, const SDLoc &dl) { 8649 static const MVT VTys[] = { // canonical VT to use for each size. 8650 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8651 }; 8652 8653 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8654 8655 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8656 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8657 SplatSize = 1; 8658 Val = 0xFF; 8659 } 8660 8661 EVT CanonicalVT = VTys[SplatSize-1]; 8662 8663 // Build a canonical splat for this value. 8664 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8665 } 8666 8667 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8668 /// specified intrinsic ID. 8669 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8670 const SDLoc &dl, EVT DestVT = MVT::Other) { 8671 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8672 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8673 DAG.getConstant(IID, dl, MVT::i32), Op); 8674 } 8675 8676 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8677 /// specified intrinsic ID. 8678 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8679 SelectionDAG &DAG, const SDLoc &dl, 8680 EVT DestVT = MVT::Other) { 8681 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8682 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8683 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8684 } 8685 8686 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8687 /// specified intrinsic ID. 8688 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8689 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8690 EVT DestVT = MVT::Other) { 8691 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8692 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8693 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8694 } 8695 8696 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8697 /// amount. The result has the specified value type. 8698 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8699 SelectionDAG &DAG, const SDLoc &dl) { 8700 // Force LHS/RHS to be the right type. 8701 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8702 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8703 8704 int Ops[16]; 8705 for (unsigned i = 0; i != 16; ++i) 8706 Ops[i] = i + Amt; 8707 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8708 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8709 } 8710 8711 /// Do we have an efficient pattern in a .td file for this node? 8712 /// 8713 /// \param V - pointer to the BuildVectorSDNode being matched 8714 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8715 /// 8716 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8717 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8718 /// the opposite is true (expansion is beneficial) are: 8719 /// - The node builds a vector out of integers that are not 32 or 64-bits 8720 /// - The node builds a vector out of constants 8721 /// - The node is a "load-and-splat" 8722 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8723 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8724 bool HasDirectMove, 8725 bool HasP8Vector) { 8726 EVT VecVT = V->getValueType(0); 8727 bool RightType = VecVT == MVT::v2f64 || 8728 (HasP8Vector && VecVT == MVT::v4f32) || 8729 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8730 if (!RightType) 8731 return false; 8732 8733 bool IsSplat = true; 8734 bool IsLoad = false; 8735 SDValue Op0 = V->getOperand(0); 8736 8737 // This function is called in a block that confirms the node is not a constant 8738 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8739 // different constants. 8740 if (V->isConstant()) 8741 return false; 8742 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8743 if (V->getOperand(i).isUndef()) 8744 return false; 8745 // We want to expand nodes that represent load-and-splat even if the 8746 // loaded value is a floating point truncation or conversion to int. 8747 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8748 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8749 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8750 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8751 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8752 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8753 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8754 IsLoad = true; 8755 // If the operands are different or the input is not a load and has more 8756 // uses than just this BV node, then it isn't a splat. 8757 if (V->getOperand(i) != Op0 || 8758 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8759 IsSplat = false; 8760 } 8761 return !(IsSplat && IsLoad); 8762 } 8763 8764 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8765 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8766 8767 SDLoc dl(Op); 8768 SDValue Op0 = Op->getOperand(0); 8769 8770 if ((Op.getValueType() != MVT::f128) || 8771 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8772 (Op0.getOperand(0).getValueType() != MVT::i64) || 8773 (Op0.getOperand(1).getValueType() != MVT::i64)) 8774 return SDValue(); 8775 8776 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8777 Op0.getOperand(1)); 8778 } 8779 8780 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 8781 const SDValue *InputLoad = &Op; 8782 if (InputLoad->getOpcode() == ISD::BITCAST) 8783 InputLoad = &InputLoad->getOperand(0); 8784 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 8785 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 8786 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 8787 InputLoad = &InputLoad->getOperand(0); 8788 } 8789 if (InputLoad->getOpcode() != ISD::LOAD) 8790 return nullptr; 8791 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8792 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8793 } 8794 8795 // Convert the argument APFloat to a single precision APFloat if there is no 8796 // loss in information during the conversion to single precision APFloat and the 8797 // resulting number is not a denormal number. Return true if successful. 8798 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 8799 APFloat APFloatToConvert = ArgAPFloat; 8800 bool LosesInfo = true; 8801 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8802 &LosesInfo); 8803 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 8804 if (Success) 8805 ArgAPFloat = APFloatToConvert; 8806 return Success; 8807 } 8808 8809 // Bitcast the argument APInt to a double and convert it to a single precision 8810 // APFloat, bitcast the APFloat to an APInt and assign it to the original 8811 // argument if there is no loss in information during the conversion from 8812 // double to single precision APFloat and the resulting number is not a denormal 8813 // number. Return true if successful. 8814 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 8815 double DpValue = ArgAPInt.bitsToDouble(); 8816 APFloat APFloatDp(DpValue); 8817 bool Success = convertToNonDenormSingle(APFloatDp); 8818 if (Success) 8819 ArgAPInt = APFloatDp.bitcastToAPInt(); 8820 return Success; 8821 } 8822 8823 // Nondestructive check for convertTonNonDenormSingle. 8824 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 8825 // Only convert if it loses info, since XXSPLTIDP should 8826 // handle the other case. 8827 APFloat APFloatToConvert = ArgAPFloat; 8828 bool LosesInfo = true; 8829 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8830 &LosesInfo); 8831 8832 return (!LosesInfo && !APFloatToConvert.isDenormal()); 8833 } 8834 8835 // If this is a case we can't handle, return null and let the default 8836 // expansion code take care of it. If we CAN select this case, and if it 8837 // selects to a single instruction, return Op. Otherwise, if we can codegen 8838 // this case more efficiently than a constant pool load, lower it to the 8839 // sequence of ops that should be used. 8840 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8841 SelectionDAG &DAG) const { 8842 SDLoc dl(Op); 8843 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8844 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8845 8846 // Check if this is a splat of a constant value. 8847 APInt APSplatBits, APSplatUndef; 8848 unsigned SplatBitSize; 8849 bool HasAnyUndefs; 8850 bool BVNIsConstantSplat = 8851 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8852 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 8853 8854 // If it is a splat of a double, check if we can shrink it to a 32 bit 8855 // non-denormal float which when converted back to double gives us the same 8856 // double. This is to exploit the XXSPLTIDP instruction. 8857 // If we lose precision, we use XXSPLTI32DX. 8858 if (BVNIsConstantSplat && (SplatBitSize == 64) && 8859 Subtarget.hasPrefixInstrs()) { 8860 // Check the type first to short-circuit so we don't modify APSplatBits if 8861 // this block isn't executed. 8862 if ((Op->getValueType(0) == MVT::v2f64) && 8863 convertToNonDenormSingle(APSplatBits)) { 8864 SDValue SplatNode = DAG.getNode( 8865 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 8866 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 8867 return DAG.getBitcast(Op.getValueType(), SplatNode); 8868 } else { 8869 // We may lose precision, so we have to use XXSPLTI32DX. 8870 8871 uint32_t Hi = 8872 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 8873 uint32_t Lo = 8874 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 8875 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 8876 8877 if (!Hi || !Lo) 8878 // If either load is 0, then we should generate XXLXOR to set to 0. 8879 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 8880 8881 if (Hi) 8882 SplatNode = DAG.getNode( 8883 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 8884 DAG.getTargetConstant(0, dl, MVT::i32), 8885 DAG.getTargetConstant(Hi, dl, MVT::i32)); 8886 8887 if (Lo) 8888 SplatNode = 8889 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 8890 DAG.getTargetConstant(1, dl, MVT::i32), 8891 DAG.getTargetConstant(Lo, dl, MVT::i32)); 8892 8893 return DAG.getBitcast(Op.getValueType(), SplatNode); 8894 } 8895 } 8896 8897 if (!BVNIsConstantSplat || SplatBitSize > 32) { 8898 8899 bool IsPermutedLoad = false; 8900 const SDValue *InputLoad = 8901 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 8902 // Handle load-and-splat patterns as we have instructions that will do this 8903 // in one go. 8904 if (InputLoad && DAG.isSplatValue(Op, true)) { 8905 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8906 8907 // We have handling for 4 and 8 byte elements. 8908 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8909 8910 // Checking for a single use of this load, we have to check for vector 8911 // width (128 bits) / ElementSize uses (since each operand of the 8912 // BUILD_VECTOR is a separate use of the value. 8913 unsigned NumUsesOfInputLD = 128 / ElementSize; 8914 for (SDValue BVInOp : Op->ops()) 8915 if (BVInOp.isUndef()) 8916 NumUsesOfInputLD--; 8917 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 8918 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 8919 ((Subtarget.hasVSX() && ElementSize == 64) || 8920 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8921 SDValue Ops[] = { 8922 LD->getChain(), // Chain 8923 LD->getBasePtr(), // Ptr 8924 DAG.getValueType(Op.getValueType()) // VT 8925 }; 8926 SDValue LdSplt = DAG.getMemIntrinsicNode( 8927 PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8928 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8929 // Replace all uses of the output chain of the original load with the 8930 // output chain of the new load. 8931 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 8932 LdSplt.getValue(1)); 8933 return LdSplt; 8934 } 8935 } 8936 8937 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 8938 // 32-bits can be lowered to VSX instructions under certain conditions. 8939 // Without VSX, there is no pattern more efficient than expanding the node. 8940 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 8941 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8942 Subtarget.hasP8Vector())) 8943 return Op; 8944 return SDValue(); 8945 } 8946 8947 uint64_t SplatBits = APSplatBits.getZExtValue(); 8948 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 8949 unsigned SplatSize = SplatBitSize / 8; 8950 8951 // First, handle single instruction cases. 8952 8953 // All zeros? 8954 if (SplatBits == 0) { 8955 // Canonicalize all zero vectors to be v4i32. 8956 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8957 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8958 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8959 } 8960 return Op; 8961 } 8962 8963 // We have XXSPLTIW for constant splats four bytes wide. 8964 // Given vector length is a multiple of 4, 2-byte splats can be replaced 8965 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 8966 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 8967 // turned into a 4-byte splat of 0xABABABAB. 8968 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 8969 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 8970 Op.getValueType(), DAG, dl); 8971 8972 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 8973 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 8974 dl); 8975 8976 // We have XXSPLTIB for constant splats one byte wide. 8977 if (Subtarget.hasP9Vector() && SplatSize == 1) 8978 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 8979 dl); 8980 8981 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8982 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8983 (32-SplatBitSize)); 8984 if (SextVal >= -16 && SextVal <= 15) 8985 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 8986 dl); 8987 8988 // Two instruction sequences. 8989 8990 // If this value is in the range [-32,30] and is even, use: 8991 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8992 // If this value is in the range [17,31] and is odd, use: 8993 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8994 // If this value is in the range [-31,-17] and is odd, use: 8995 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8996 // Note the last two are three-instruction sequences. 8997 if (SextVal >= -32 && SextVal <= 31) { 8998 // To avoid having these optimizations undone by constant folding, 8999 // we convert to a pseudo that will be expanded later into one of 9000 // the above forms. 9001 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9002 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9003 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9004 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9005 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9006 if (VT == Op.getValueType()) 9007 return RetVal; 9008 else 9009 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9010 } 9011 9012 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9013 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9014 // for fneg/fabs. 9015 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9016 // Make -1 and vspltisw -1: 9017 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9018 9019 // Make the VSLW intrinsic, computing 0x8000_0000. 9020 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9021 OnesV, DAG, dl); 9022 9023 // xor by OnesV to invert it. 9024 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9025 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9026 } 9027 9028 // Check to see if this is a wide variety of vsplti*, binop self cases. 9029 static const signed char SplatCsts[] = { 9030 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9031 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9032 }; 9033 9034 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9035 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9036 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9037 int i = SplatCsts[idx]; 9038 9039 // Figure out what shift amount will be used by altivec if shifted by i in 9040 // this splat size. 9041 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9042 9043 // vsplti + shl self. 9044 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9045 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9046 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9047 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9048 Intrinsic::ppc_altivec_vslw 9049 }; 9050 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9051 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9052 } 9053 9054 // vsplti + srl self. 9055 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9056 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9057 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9058 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9059 Intrinsic::ppc_altivec_vsrw 9060 }; 9061 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9062 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9063 } 9064 9065 // vsplti + rol self. 9066 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9067 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9068 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9069 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9070 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9071 Intrinsic::ppc_altivec_vrlw 9072 }; 9073 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9074 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9075 } 9076 9077 // t = vsplti c, result = vsldoi t, t, 1 9078 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9079 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9080 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9081 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9082 } 9083 // t = vsplti c, result = vsldoi t, t, 2 9084 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9085 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9086 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9087 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9088 } 9089 // t = vsplti c, result = vsldoi t, t, 3 9090 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9091 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9092 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9093 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9094 } 9095 } 9096 9097 return SDValue(); 9098 } 9099 9100 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9101 /// the specified operations to build the shuffle. 9102 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9103 SDValue RHS, SelectionDAG &DAG, 9104 const SDLoc &dl) { 9105 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9106 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9107 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9108 9109 enum { 9110 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9111 OP_VMRGHW, 9112 OP_VMRGLW, 9113 OP_VSPLTISW0, 9114 OP_VSPLTISW1, 9115 OP_VSPLTISW2, 9116 OP_VSPLTISW3, 9117 OP_VSLDOI4, 9118 OP_VSLDOI8, 9119 OP_VSLDOI12 9120 }; 9121 9122 if (OpNum == OP_COPY) { 9123 if (LHSID == (1*9+2)*9+3) return LHS; 9124 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9125 return RHS; 9126 } 9127 9128 SDValue OpLHS, OpRHS; 9129 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9130 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9131 9132 int ShufIdxs[16]; 9133 switch (OpNum) { 9134 default: llvm_unreachable("Unknown i32 permute!"); 9135 case OP_VMRGHW: 9136 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9137 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9138 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9139 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9140 break; 9141 case OP_VMRGLW: 9142 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9143 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9144 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9145 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9146 break; 9147 case OP_VSPLTISW0: 9148 for (unsigned i = 0; i != 16; ++i) 9149 ShufIdxs[i] = (i&3)+0; 9150 break; 9151 case OP_VSPLTISW1: 9152 for (unsigned i = 0; i != 16; ++i) 9153 ShufIdxs[i] = (i&3)+4; 9154 break; 9155 case OP_VSPLTISW2: 9156 for (unsigned i = 0; i != 16; ++i) 9157 ShufIdxs[i] = (i&3)+8; 9158 break; 9159 case OP_VSPLTISW3: 9160 for (unsigned i = 0; i != 16; ++i) 9161 ShufIdxs[i] = (i&3)+12; 9162 break; 9163 case OP_VSLDOI4: 9164 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9165 case OP_VSLDOI8: 9166 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9167 case OP_VSLDOI12: 9168 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9169 } 9170 EVT VT = OpLHS.getValueType(); 9171 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9172 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9173 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9174 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9175 } 9176 9177 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9178 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9179 /// SDValue. 9180 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9181 SelectionDAG &DAG) const { 9182 const unsigned BytesInVector = 16; 9183 bool IsLE = Subtarget.isLittleEndian(); 9184 SDLoc dl(N); 9185 SDValue V1 = N->getOperand(0); 9186 SDValue V2 = N->getOperand(1); 9187 unsigned ShiftElts = 0, InsertAtByte = 0; 9188 bool Swap = false; 9189 9190 // Shifts required to get the byte we want at element 7. 9191 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9192 0, 15, 14, 13, 12, 11, 10, 9}; 9193 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9194 1, 2, 3, 4, 5, 6, 7, 8}; 9195 9196 ArrayRef<int> Mask = N->getMask(); 9197 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9198 9199 // For each mask element, find out if we're just inserting something 9200 // from V2 into V1 or vice versa. 9201 // Possible permutations inserting an element from V2 into V1: 9202 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9203 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9204 // ... 9205 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9206 // Inserting from V1 into V2 will be similar, except mask range will be 9207 // [16,31]. 9208 9209 bool FoundCandidate = false; 9210 // If both vector operands for the shuffle are the same vector, the mask 9211 // will contain only elements from the first one and the second one will be 9212 // undef. 9213 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9214 // Go through the mask of half-words to find an element that's being moved 9215 // from one vector to the other. 9216 for (unsigned i = 0; i < BytesInVector; ++i) { 9217 unsigned CurrentElement = Mask[i]; 9218 // If 2nd operand is undefined, we should only look for element 7 in the 9219 // Mask. 9220 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9221 continue; 9222 9223 bool OtherElementsInOrder = true; 9224 // Examine the other elements in the Mask to see if they're in original 9225 // order. 9226 for (unsigned j = 0; j < BytesInVector; ++j) { 9227 if (j == i) 9228 continue; 9229 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9230 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9231 // in which we always assume we're always picking from the 1st operand. 9232 int MaskOffset = 9233 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9234 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9235 OtherElementsInOrder = false; 9236 break; 9237 } 9238 } 9239 // If other elements are in original order, we record the number of shifts 9240 // we need to get the element we want into element 7. Also record which byte 9241 // in the vector we should insert into. 9242 if (OtherElementsInOrder) { 9243 // If 2nd operand is undefined, we assume no shifts and no swapping. 9244 if (V2.isUndef()) { 9245 ShiftElts = 0; 9246 Swap = false; 9247 } else { 9248 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9249 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9250 : BigEndianShifts[CurrentElement & 0xF]; 9251 Swap = CurrentElement < BytesInVector; 9252 } 9253 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9254 FoundCandidate = true; 9255 break; 9256 } 9257 } 9258 9259 if (!FoundCandidate) 9260 return SDValue(); 9261 9262 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9263 // optionally with VECSHL if shift is required. 9264 if (Swap) 9265 std::swap(V1, V2); 9266 if (V2.isUndef()) 9267 V2 = V1; 9268 if (ShiftElts) { 9269 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9270 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9271 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9272 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9273 } 9274 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9275 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9276 } 9277 9278 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9279 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9280 /// SDValue. 9281 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9282 SelectionDAG &DAG) const { 9283 const unsigned NumHalfWords = 8; 9284 const unsigned BytesInVector = NumHalfWords * 2; 9285 // Check that the shuffle is on half-words. 9286 if (!isNByteElemShuffleMask(N, 2, 1)) 9287 return SDValue(); 9288 9289 bool IsLE = Subtarget.isLittleEndian(); 9290 SDLoc dl(N); 9291 SDValue V1 = N->getOperand(0); 9292 SDValue V2 = N->getOperand(1); 9293 unsigned ShiftElts = 0, InsertAtByte = 0; 9294 bool Swap = false; 9295 9296 // Shifts required to get the half-word we want at element 3. 9297 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9298 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9299 9300 uint32_t Mask = 0; 9301 uint32_t OriginalOrderLow = 0x1234567; 9302 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9303 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9304 // 32-bit space, only need 4-bit nibbles per element. 9305 for (unsigned i = 0; i < NumHalfWords; ++i) { 9306 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9307 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9308 } 9309 9310 // For each mask element, find out if we're just inserting something 9311 // from V2 into V1 or vice versa. Possible permutations inserting an element 9312 // from V2 into V1: 9313 // X, 1, 2, 3, 4, 5, 6, 7 9314 // 0, X, 2, 3, 4, 5, 6, 7 9315 // 0, 1, X, 3, 4, 5, 6, 7 9316 // 0, 1, 2, X, 4, 5, 6, 7 9317 // 0, 1, 2, 3, X, 5, 6, 7 9318 // 0, 1, 2, 3, 4, X, 6, 7 9319 // 0, 1, 2, 3, 4, 5, X, 7 9320 // 0, 1, 2, 3, 4, 5, 6, X 9321 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9322 9323 bool FoundCandidate = false; 9324 // Go through the mask of half-words to find an element that's being moved 9325 // from one vector to the other. 9326 for (unsigned i = 0; i < NumHalfWords; ++i) { 9327 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9328 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9329 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9330 uint32_t TargetOrder = 0x0; 9331 9332 // If both vector operands for the shuffle are the same vector, the mask 9333 // will contain only elements from the first one and the second one will be 9334 // undef. 9335 if (V2.isUndef()) { 9336 ShiftElts = 0; 9337 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9338 TargetOrder = OriginalOrderLow; 9339 Swap = false; 9340 // Skip if not the correct element or mask of other elements don't equal 9341 // to our expected order. 9342 if (MaskOneElt == VINSERTHSrcElem && 9343 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9344 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9345 FoundCandidate = true; 9346 break; 9347 } 9348 } else { // If both operands are defined. 9349 // Target order is [8,15] if the current mask is between [0,7]. 9350 TargetOrder = 9351 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9352 // Skip if mask of other elements don't equal our expected order. 9353 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9354 // We only need the last 3 bits for the number of shifts. 9355 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9356 : BigEndianShifts[MaskOneElt & 0x7]; 9357 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9358 Swap = MaskOneElt < NumHalfWords; 9359 FoundCandidate = true; 9360 break; 9361 } 9362 } 9363 } 9364 9365 if (!FoundCandidate) 9366 return SDValue(); 9367 9368 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9369 // optionally with VECSHL if shift is required. 9370 if (Swap) 9371 std::swap(V1, V2); 9372 if (V2.isUndef()) 9373 V2 = V1; 9374 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9375 if (ShiftElts) { 9376 // Double ShiftElts because we're left shifting on v16i8 type. 9377 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9378 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9379 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9380 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9381 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9382 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9383 } 9384 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9385 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9386 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9387 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9388 } 9389 9390 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9391 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9392 /// return the default SDValue. 9393 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9394 SelectionDAG &DAG) const { 9395 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9396 // to v16i8. Peek through the bitcasts to get the actual operands. 9397 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9398 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9399 9400 auto ShuffleMask = SVN->getMask(); 9401 SDValue VecShuffle(SVN, 0); 9402 SDLoc DL(SVN); 9403 9404 // Check that we have a four byte shuffle. 9405 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9406 return SDValue(); 9407 9408 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9409 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9410 std::swap(LHS, RHS); 9411 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9412 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9413 } 9414 9415 // Ensure that the RHS is a vector of constants. 9416 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9417 if (!BVN) 9418 return SDValue(); 9419 9420 // Check if RHS is a splat of 4-bytes (or smaller). 9421 APInt APSplatValue, APSplatUndef; 9422 unsigned SplatBitSize; 9423 bool HasAnyUndefs; 9424 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9425 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9426 SplatBitSize > 32) 9427 return SDValue(); 9428 9429 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9430 // The instruction splats a constant C into two words of the source vector 9431 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9432 // Thus we check that the shuffle mask is the equivalent of 9433 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9434 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9435 // within each word are consecutive, so we only need to check the first byte. 9436 SDValue Index; 9437 bool IsLE = Subtarget.isLittleEndian(); 9438 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9439 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9440 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9441 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9442 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9443 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9444 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9445 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9446 else 9447 return SDValue(); 9448 9449 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9450 // for XXSPLTI32DX. 9451 unsigned SplatVal = APSplatValue.getZExtValue(); 9452 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9453 SplatVal |= (SplatVal << SplatBitSize); 9454 9455 SDValue SplatNode = DAG.getNode( 9456 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9457 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9458 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9459 } 9460 9461 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9462 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9463 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9464 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9465 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9466 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9467 assert(Op.getValueType() == MVT::v1i128 && 9468 "Only set v1i128 as custom, other type shouldn't reach here!"); 9469 SDLoc dl(Op); 9470 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9471 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9472 unsigned SHLAmt = N1.getConstantOperandVal(0); 9473 if (SHLAmt % 8 == 0) { 9474 SmallVector<int, 16> Mask(16, 0); 9475 std::iota(Mask.begin(), Mask.end(), 0); 9476 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9477 if (SDValue Shuffle = 9478 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9479 DAG.getUNDEF(MVT::v16i8), Mask)) 9480 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9481 } 9482 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9483 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9484 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9485 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9486 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9487 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9488 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9489 } 9490 9491 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9492 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9493 /// return the code it can be lowered into. Worst case, it can always be 9494 /// lowered into a vperm. 9495 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9496 SelectionDAG &DAG) const { 9497 SDLoc dl(Op); 9498 SDValue V1 = Op.getOperand(0); 9499 SDValue V2 = Op.getOperand(1); 9500 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9501 9502 // Any nodes that were combined in the target-independent combiner prior 9503 // to vector legalization will not be sent to the target combine. Try to 9504 // combine it here. 9505 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9506 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9507 return NewShuffle; 9508 Op = NewShuffle; 9509 SVOp = cast<ShuffleVectorSDNode>(Op); 9510 V1 = Op.getOperand(0); 9511 V2 = Op.getOperand(1); 9512 } 9513 EVT VT = Op.getValueType(); 9514 bool isLittleEndian = Subtarget.isLittleEndian(); 9515 9516 unsigned ShiftElts, InsertAtByte; 9517 bool Swap = false; 9518 9519 // If this is a load-and-splat, we can do that with a single instruction 9520 // in some cases. However if the load has multiple uses, we don't want to 9521 // combine it because that will just produce multiple loads. 9522 bool IsPermutedLoad = false; 9523 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9524 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9525 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9526 InputLoad->hasOneUse()) { 9527 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9528 int SplatIdx = 9529 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9530 9531 // The splat index for permuted loads will be in the left half of the vector 9532 // which is strictly wider than the loaded value by 8 bytes. So we need to 9533 // adjust the splat index to point to the correct address in memory. 9534 if (IsPermutedLoad) { 9535 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9536 SplatIdx += IsFourByte ? 2 : 1; 9537 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9538 "Splat of a value outside of the loaded memory"); 9539 } 9540 9541 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9542 // For 4-byte load-and-splat, we need Power9. 9543 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9544 uint64_t Offset = 0; 9545 if (IsFourByte) 9546 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9547 else 9548 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9549 9550 SDValue BasePtr = LD->getBasePtr(); 9551 if (Offset != 0) 9552 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9553 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9554 SDValue Ops[] = { 9555 LD->getChain(), // Chain 9556 BasePtr, // BasePtr 9557 DAG.getValueType(Op.getValueType()) // VT 9558 }; 9559 SDVTList VTL = 9560 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9561 SDValue LdSplt = 9562 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9563 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9564 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9565 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9566 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9567 return LdSplt; 9568 } 9569 } 9570 if (Subtarget.hasP9Vector() && 9571 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9572 isLittleEndian)) { 9573 if (Swap) 9574 std::swap(V1, V2); 9575 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9576 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9577 if (ShiftElts) { 9578 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9579 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9580 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9581 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9582 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9583 } 9584 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9585 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9586 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9587 } 9588 9589 if (Subtarget.hasPrefixInstrs()) { 9590 SDValue SplatInsertNode; 9591 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9592 return SplatInsertNode; 9593 } 9594 9595 if (Subtarget.hasP9Altivec()) { 9596 SDValue NewISDNode; 9597 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9598 return NewISDNode; 9599 9600 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9601 return NewISDNode; 9602 } 9603 9604 if (Subtarget.hasVSX() && 9605 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9606 if (Swap) 9607 std::swap(V1, V2); 9608 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9609 SDValue Conv2 = 9610 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9611 9612 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9613 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9614 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9615 } 9616 9617 if (Subtarget.hasVSX() && 9618 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9619 if (Swap) 9620 std::swap(V1, V2); 9621 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9622 SDValue Conv2 = 9623 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9624 9625 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9626 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9627 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9628 } 9629 9630 if (Subtarget.hasP9Vector()) { 9631 if (PPC::isXXBRHShuffleMask(SVOp)) { 9632 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9633 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9634 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9635 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9636 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9637 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9638 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9639 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9640 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9641 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9642 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9643 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9644 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9645 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9646 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9647 } 9648 } 9649 9650 if (Subtarget.hasVSX()) { 9651 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9652 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9653 9654 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9655 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9656 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9657 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9658 } 9659 9660 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9661 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9662 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9663 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9664 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9665 } 9666 } 9667 9668 // Cases that are handled by instructions that take permute immediates 9669 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9670 // selected by the instruction selector. 9671 if (V2.isUndef()) { 9672 if (PPC::isSplatShuffleMask(SVOp, 1) || 9673 PPC::isSplatShuffleMask(SVOp, 2) || 9674 PPC::isSplatShuffleMask(SVOp, 4) || 9675 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9676 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9677 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9678 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9679 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9680 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9681 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9682 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9683 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9684 (Subtarget.hasP8Altivec() && ( 9685 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9686 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9687 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9688 return Op; 9689 } 9690 } 9691 9692 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9693 // and produce a fixed permutation. If any of these match, do not lower to 9694 // VPERM. 9695 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9696 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9697 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9698 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9699 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9700 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9701 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9702 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9703 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9704 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9705 (Subtarget.hasP8Altivec() && ( 9706 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9707 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9708 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9709 return Op; 9710 9711 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9712 // perfect shuffle table to emit an optimal matching sequence. 9713 ArrayRef<int> PermMask = SVOp->getMask(); 9714 9715 unsigned PFIndexes[4]; 9716 bool isFourElementShuffle = true; 9717 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9718 unsigned EltNo = 8; // Start out undef. 9719 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9720 if (PermMask[i*4+j] < 0) 9721 continue; // Undef, ignore it. 9722 9723 unsigned ByteSource = PermMask[i*4+j]; 9724 if ((ByteSource & 3) != j) { 9725 isFourElementShuffle = false; 9726 break; 9727 } 9728 9729 if (EltNo == 8) { 9730 EltNo = ByteSource/4; 9731 } else if (EltNo != ByteSource/4) { 9732 isFourElementShuffle = false; 9733 break; 9734 } 9735 } 9736 PFIndexes[i] = EltNo; 9737 } 9738 9739 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9740 // perfect shuffle vector to determine if it is cost effective to do this as 9741 // discrete instructions, or whether we should use a vperm. 9742 // For now, we skip this for little endian until such time as we have a 9743 // little-endian perfect shuffle table. 9744 if (isFourElementShuffle && !isLittleEndian) { 9745 // Compute the index in the perfect shuffle table. 9746 unsigned PFTableIndex = 9747 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9748 9749 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9750 unsigned Cost = (PFEntry >> 30); 9751 9752 // Determining when to avoid vperm is tricky. Many things affect the cost 9753 // of vperm, particularly how many times the perm mask needs to be computed. 9754 // For example, if the perm mask can be hoisted out of a loop or is already 9755 // used (perhaps because there are multiple permutes with the same shuffle 9756 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9757 // the loop requires an extra register. 9758 // 9759 // As a compromise, we only emit discrete instructions if the shuffle can be 9760 // generated in 3 or fewer operations. When we have loop information 9761 // available, if this block is within a loop, we should avoid using vperm 9762 // for 3-operation perms and use a constant pool load instead. 9763 if (Cost < 3) 9764 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9765 } 9766 9767 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9768 // vector that will get spilled to the constant pool. 9769 if (V2.isUndef()) V2 = V1; 9770 9771 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9772 // that it is in input element units, not in bytes. Convert now. 9773 9774 // For little endian, the order of the input vectors is reversed, and 9775 // the permutation mask is complemented with respect to 31. This is 9776 // necessary to produce proper semantics with the big-endian-biased vperm 9777 // instruction. 9778 EVT EltVT = V1.getValueType().getVectorElementType(); 9779 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9780 9781 SmallVector<SDValue, 16> ResultMask; 9782 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9783 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9784 9785 for (unsigned j = 0; j != BytesPerElement; ++j) 9786 if (isLittleEndian) 9787 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9788 dl, MVT::i32)); 9789 else 9790 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9791 MVT::i32)); 9792 } 9793 9794 ShufflesHandledWithVPERM++; 9795 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9796 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9797 LLVM_DEBUG(SVOp->dump()); 9798 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9799 LLVM_DEBUG(VPermMask.dump()); 9800 9801 if (isLittleEndian) 9802 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9803 V2, V1, VPermMask); 9804 else 9805 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9806 V1, V2, VPermMask); 9807 } 9808 9809 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9810 /// vector comparison. If it is, return true and fill in Opc/isDot with 9811 /// information about the intrinsic. 9812 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9813 bool &isDot, const PPCSubtarget &Subtarget) { 9814 unsigned IntrinsicID = 9815 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9816 CompareOpc = -1; 9817 isDot = false; 9818 switch (IntrinsicID) { 9819 default: 9820 return false; 9821 // Comparison predicates. 9822 case Intrinsic::ppc_altivec_vcmpbfp_p: 9823 CompareOpc = 966; 9824 isDot = true; 9825 break; 9826 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9827 CompareOpc = 198; 9828 isDot = true; 9829 break; 9830 case Intrinsic::ppc_altivec_vcmpequb_p: 9831 CompareOpc = 6; 9832 isDot = true; 9833 break; 9834 case Intrinsic::ppc_altivec_vcmpequh_p: 9835 CompareOpc = 70; 9836 isDot = true; 9837 break; 9838 case Intrinsic::ppc_altivec_vcmpequw_p: 9839 CompareOpc = 134; 9840 isDot = true; 9841 break; 9842 case Intrinsic::ppc_altivec_vcmpequd_p: 9843 if (Subtarget.hasP8Altivec()) { 9844 CompareOpc = 199; 9845 isDot = true; 9846 } else 9847 return false; 9848 break; 9849 case Intrinsic::ppc_altivec_vcmpneb_p: 9850 case Intrinsic::ppc_altivec_vcmpneh_p: 9851 case Intrinsic::ppc_altivec_vcmpnew_p: 9852 case Intrinsic::ppc_altivec_vcmpnezb_p: 9853 case Intrinsic::ppc_altivec_vcmpnezh_p: 9854 case Intrinsic::ppc_altivec_vcmpnezw_p: 9855 if (Subtarget.hasP9Altivec()) { 9856 switch (IntrinsicID) { 9857 default: 9858 llvm_unreachable("Unknown comparison intrinsic."); 9859 case Intrinsic::ppc_altivec_vcmpneb_p: 9860 CompareOpc = 7; 9861 break; 9862 case Intrinsic::ppc_altivec_vcmpneh_p: 9863 CompareOpc = 71; 9864 break; 9865 case Intrinsic::ppc_altivec_vcmpnew_p: 9866 CompareOpc = 135; 9867 break; 9868 case Intrinsic::ppc_altivec_vcmpnezb_p: 9869 CompareOpc = 263; 9870 break; 9871 case Intrinsic::ppc_altivec_vcmpnezh_p: 9872 CompareOpc = 327; 9873 break; 9874 case Intrinsic::ppc_altivec_vcmpnezw_p: 9875 CompareOpc = 391; 9876 break; 9877 } 9878 isDot = true; 9879 } else 9880 return false; 9881 break; 9882 case Intrinsic::ppc_altivec_vcmpgefp_p: 9883 CompareOpc = 454; 9884 isDot = true; 9885 break; 9886 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9887 CompareOpc = 710; 9888 isDot = true; 9889 break; 9890 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9891 CompareOpc = 774; 9892 isDot = true; 9893 break; 9894 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9895 CompareOpc = 838; 9896 isDot = true; 9897 break; 9898 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9899 CompareOpc = 902; 9900 isDot = true; 9901 break; 9902 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9903 if (Subtarget.hasP8Altivec()) { 9904 CompareOpc = 967; 9905 isDot = true; 9906 } else 9907 return false; 9908 break; 9909 case Intrinsic::ppc_altivec_vcmpgtub_p: 9910 CompareOpc = 518; 9911 isDot = true; 9912 break; 9913 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9914 CompareOpc = 582; 9915 isDot = true; 9916 break; 9917 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9918 CompareOpc = 646; 9919 isDot = true; 9920 break; 9921 case Intrinsic::ppc_altivec_vcmpgtud_p: 9922 if (Subtarget.hasP8Altivec()) { 9923 CompareOpc = 711; 9924 isDot = true; 9925 } else 9926 return false; 9927 break; 9928 9929 case Intrinsic::ppc_altivec_vcmpequq: 9930 case Intrinsic::ppc_altivec_vcmpgtsq: 9931 case Intrinsic::ppc_altivec_vcmpgtuq: 9932 if (!Subtarget.isISA3_1()) 9933 return false; 9934 switch (IntrinsicID) { 9935 default: 9936 llvm_unreachable("Unknown comparison intrinsic."); 9937 case Intrinsic::ppc_altivec_vcmpequq: 9938 CompareOpc = 455; 9939 break; 9940 case Intrinsic::ppc_altivec_vcmpgtsq: 9941 CompareOpc = 903; 9942 break; 9943 case Intrinsic::ppc_altivec_vcmpgtuq: 9944 CompareOpc = 647; 9945 break; 9946 } 9947 break; 9948 9949 // VSX predicate comparisons use the same infrastructure 9950 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9951 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9952 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9953 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9954 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9955 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9956 if (Subtarget.hasVSX()) { 9957 switch (IntrinsicID) { 9958 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9959 CompareOpc = 99; 9960 break; 9961 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9962 CompareOpc = 115; 9963 break; 9964 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9965 CompareOpc = 107; 9966 break; 9967 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9968 CompareOpc = 67; 9969 break; 9970 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9971 CompareOpc = 83; 9972 break; 9973 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9974 CompareOpc = 75; 9975 break; 9976 } 9977 isDot = true; 9978 } else 9979 return false; 9980 break; 9981 9982 // Normal Comparisons. 9983 case Intrinsic::ppc_altivec_vcmpbfp: 9984 CompareOpc = 966; 9985 break; 9986 case Intrinsic::ppc_altivec_vcmpeqfp: 9987 CompareOpc = 198; 9988 break; 9989 case Intrinsic::ppc_altivec_vcmpequb: 9990 CompareOpc = 6; 9991 break; 9992 case Intrinsic::ppc_altivec_vcmpequh: 9993 CompareOpc = 70; 9994 break; 9995 case Intrinsic::ppc_altivec_vcmpequw: 9996 CompareOpc = 134; 9997 break; 9998 case Intrinsic::ppc_altivec_vcmpequd: 9999 if (Subtarget.hasP8Altivec()) 10000 CompareOpc = 199; 10001 else 10002 return false; 10003 break; 10004 case Intrinsic::ppc_altivec_vcmpneb: 10005 case Intrinsic::ppc_altivec_vcmpneh: 10006 case Intrinsic::ppc_altivec_vcmpnew: 10007 case Intrinsic::ppc_altivec_vcmpnezb: 10008 case Intrinsic::ppc_altivec_vcmpnezh: 10009 case Intrinsic::ppc_altivec_vcmpnezw: 10010 if (Subtarget.hasP9Altivec()) 10011 switch (IntrinsicID) { 10012 default: 10013 llvm_unreachable("Unknown comparison intrinsic."); 10014 case Intrinsic::ppc_altivec_vcmpneb: 10015 CompareOpc = 7; 10016 break; 10017 case Intrinsic::ppc_altivec_vcmpneh: 10018 CompareOpc = 71; 10019 break; 10020 case Intrinsic::ppc_altivec_vcmpnew: 10021 CompareOpc = 135; 10022 break; 10023 case Intrinsic::ppc_altivec_vcmpnezb: 10024 CompareOpc = 263; 10025 break; 10026 case Intrinsic::ppc_altivec_vcmpnezh: 10027 CompareOpc = 327; 10028 break; 10029 case Intrinsic::ppc_altivec_vcmpnezw: 10030 CompareOpc = 391; 10031 break; 10032 } 10033 else 10034 return false; 10035 break; 10036 case Intrinsic::ppc_altivec_vcmpgefp: 10037 CompareOpc = 454; 10038 break; 10039 case Intrinsic::ppc_altivec_vcmpgtfp: 10040 CompareOpc = 710; 10041 break; 10042 case Intrinsic::ppc_altivec_vcmpgtsb: 10043 CompareOpc = 774; 10044 break; 10045 case Intrinsic::ppc_altivec_vcmpgtsh: 10046 CompareOpc = 838; 10047 break; 10048 case Intrinsic::ppc_altivec_vcmpgtsw: 10049 CompareOpc = 902; 10050 break; 10051 case Intrinsic::ppc_altivec_vcmpgtsd: 10052 if (Subtarget.hasP8Altivec()) 10053 CompareOpc = 967; 10054 else 10055 return false; 10056 break; 10057 case Intrinsic::ppc_altivec_vcmpgtub: 10058 CompareOpc = 518; 10059 break; 10060 case Intrinsic::ppc_altivec_vcmpgtuh: 10061 CompareOpc = 582; 10062 break; 10063 case Intrinsic::ppc_altivec_vcmpgtuw: 10064 CompareOpc = 646; 10065 break; 10066 case Intrinsic::ppc_altivec_vcmpgtud: 10067 if (Subtarget.hasP8Altivec()) 10068 CompareOpc = 711; 10069 else 10070 return false; 10071 break; 10072 case Intrinsic::ppc_altivec_vcmpequq_p: 10073 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10074 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10075 if (!Subtarget.isISA3_1()) 10076 return false; 10077 switch (IntrinsicID) { 10078 default: 10079 llvm_unreachable("Unknown comparison intrinsic."); 10080 case Intrinsic::ppc_altivec_vcmpequq_p: 10081 CompareOpc = 455; 10082 break; 10083 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10084 CompareOpc = 903; 10085 break; 10086 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10087 CompareOpc = 647; 10088 break; 10089 } 10090 isDot = true; 10091 break; 10092 } 10093 return true; 10094 } 10095 10096 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10097 /// lower, do it, otherwise return null. 10098 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10099 SelectionDAG &DAG) const { 10100 unsigned IntrinsicID = 10101 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10102 10103 SDLoc dl(Op); 10104 10105 switch (IntrinsicID) { 10106 case Intrinsic::thread_pointer: 10107 // Reads the thread pointer register, used for __builtin_thread_pointer. 10108 if (Subtarget.isPPC64()) 10109 return DAG.getRegister(PPC::X13, MVT::i64); 10110 return DAG.getRegister(PPC::R2, MVT::i32); 10111 10112 case Intrinsic::ppc_mma_disassemble_acc: 10113 case Intrinsic::ppc_vsx_disassemble_pair: { 10114 int NumVecs = 2; 10115 SDValue WideVec = Op.getOperand(1); 10116 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10117 NumVecs = 4; 10118 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10119 } 10120 SmallVector<SDValue, 4> RetOps; 10121 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10122 SDValue Extract = DAG.getNode( 10123 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10124 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10125 : VecNo, 10126 dl, getPointerTy(DAG.getDataLayout()))); 10127 RetOps.push_back(Extract); 10128 } 10129 return DAG.getMergeValues(RetOps, dl); 10130 } 10131 } 10132 10133 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10134 // opcode number of the comparison. 10135 int CompareOpc; 10136 bool isDot; 10137 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10138 return SDValue(); // Don't custom lower most intrinsics. 10139 10140 // If this is a non-dot comparison, make the VCMP node and we are done. 10141 if (!isDot) { 10142 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10143 Op.getOperand(1), Op.getOperand(2), 10144 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10145 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10146 } 10147 10148 // Create the PPCISD altivec 'dot' comparison node. 10149 SDValue Ops[] = { 10150 Op.getOperand(2), // LHS 10151 Op.getOperand(3), // RHS 10152 DAG.getConstant(CompareOpc, dl, MVT::i32) 10153 }; 10154 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10155 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10156 10157 // Now that we have the comparison, emit a copy from the CR to a GPR. 10158 // This is flagged to the above dot comparison. 10159 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10160 DAG.getRegister(PPC::CR6, MVT::i32), 10161 CompNode.getValue(1)); 10162 10163 // Unpack the result based on how the target uses it. 10164 unsigned BitNo; // Bit # of CR6. 10165 bool InvertBit; // Invert result? 10166 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10167 default: // Can't happen, don't crash on invalid number though. 10168 case 0: // Return the value of the EQ bit of CR6. 10169 BitNo = 0; InvertBit = false; 10170 break; 10171 case 1: // Return the inverted value of the EQ bit of CR6. 10172 BitNo = 0; InvertBit = true; 10173 break; 10174 case 2: // Return the value of the LT bit of CR6. 10175 BitNo = 2; InvertBit = false; 10176 break; 10177 case 3: // Return the inverted value of the LT bit of CR6. 10178 BitNo = 2; InvertBit = true; 10179 break; 10180 } 10181 10182 // Shift the bit into the low position. 10183 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10184 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10185 // Isolate the bit. 10186 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10187 DAG.getConstant(1, dl, MVT::i32)); 10188 10189 // If we are supposed to, toggle the bit. 10190 if (InvertBit) 10191 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10192 DAG.getConstant(1, dl, MVT::i32)); 10193 return Flags; 10194 } 10195 10196 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10197 SelectionDAG &DAG) const { 10198 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10199 // the beginning of the argument list. 10200 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10201 SDLoc DL(Op); 10202 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10203 case Intrinsic::ppc_cfence: { 10204 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10205 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10206 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10207 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10208 Op.getOperand(ArgStart + 1)), 10209 Op.getOperand(0)), 10210 0); 10211 } 10212 default: 10213 break; 10214 } 10215 return SDValue(); 10216 } 10217 10218 // Lower scalar BSWAP64 to xxbrd. 10219 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10220 SDLoc dl(Op); 10221 // MTVSRDD 10222 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10223 Op.getOperand(0)); 10224 // XXBRD 10225 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10226 // MFVSRD 10227 int VectorIndex = 0; 10228 if (Subtarget.isLittleEndian()) 10229 VectorIndex = 1; 10230 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10231 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10232 return Op; 10233 } 10234 10235 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10236 // compared to a value that is atomically loaded (atomic loads zero-extend). 10237 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10238 SelectionDAG &DAG) const { 10239 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10240 "Expecting an atomic compare-and-swap here."); 10241 SDLoc dl(Op); 10242 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10243 EVT MemVT = AtomicNode->getMemoryVT(); 10244 if (MemVT.getSizeInBits() >= 32) 10245 return Op; 10246 10247 SDValue CmpOp = Op.getOperand(2); 10248 // If this is already correctly zero-extended, leave it alone. 10249 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10250 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10251 return Op; 10252 10253 // Clear the high bits of the compare operand. 10254 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10255 SDValue NewCmpOp = 10256 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10257 DAG.getConstant(MaskVal, dl, MVT::i32)); 10258 10259 // Replace the existing compare operand with the properly zero-extended one. 10260 SmallVector<SDValue, 4> Ops; 10261 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10262 Ops.push_back(AtomicNode->getOperand(i)); 10263 Ops[2] = NewCmpOp; 10264 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10265 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10266 auto NodeTy = 10267 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10268 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10269 } 10270 10271 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10272 SelectionDAG &DAG) const { 10273 SDLoc dl(Op); 10274 // Create a stack slot that is 16-byte aligned. 10275 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10276 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10277 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10278 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10279 10280 // Store the input value into Value#0 of the stack slot. 10281 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10282 MachinePointerInfo()); 10283 // Load it out. 10284 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10285 } 10286 10287 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10288 SelectionDAG &DAG) const { 10289 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10290 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10291 10292 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10293 10294 EVT VT = Op.getValueType(); 10295 SDLoc dl(Op); 10296 SDValue V1 = Op.getOperand(0); 10297 SDValue V2 = Op.getOperand(1); 10298 SDValue V3 = Op.getOperand(2); 10299 10300 if (Subtarget.isISA3_1()) { 10301 // On P10, we have legal lowering for constant and variable indices for 10302 // integer vectors. 10303 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 10304 VT == MVT::v2i64) 10305 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10306 // For f32 and f64 vectors, we have legal lowering for variable indices. 10307 // For f32 we also have legal lowering when the element is loaded from 10308 // memory. 10309 if (VT == MVT::v4f32 || VT == MVT::v2f64) { 10310 if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2))) 10311 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3); 10312 return SDValue(); 10313 } 10314 } 10315 10316 // Before P10, we have legal lowering for constant indices but not for 10317 // variable ones. 10318 if (!C) 10319 return SDValue(); 10320 10321 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10322 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10323 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10324 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10325 unsigned InsertAtElement = C->getZExtValue(); 10326 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10327 if (Subtarget.isLittleEndian()) { 10328 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10329 } 10330 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10331 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10332 } 10333 return Op; 10334 } 10335 10336 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10337 SelectionDAG &DAG) const { 10338 SDLoc dl(Op); 10339 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10340 SDValue LoadChain = LN->getChain(); 10341 SDValue BasePtr = LN->getBasePtr(); 10342 EVT VT = Op.getValueType(); 10343 10344 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10345 return Op; 10346 10347 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10348 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10349 // 2 or 4 vsx registers. 10350 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10351 "Type unsupported without MMA"); 10352 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10353 "Type unsupported without paired vector support"); 10354 Align Alignment = LN->getAlign(); 10355 SmallVector<SDValue, 4> Loads; 10356 SmallVector<SDValue, 4> LoadChains; 10357 unsigned NumVecs = VT.getSizeInBits() / 128; 10358 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10359 SDValue Load = 10360 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10361 LN->getPointerInfo().getWithOffset(Idx * 16), 10362 commonAlignment(Alignment, Idx * 16), 10363 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10364 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10365 DAG.getConstant(16, dl, BasePtr.getValueType())); 10366 Loads.push_back(Load); 10367 LoadChains.push_back(Load.getValue(1)); 10368 } 10369 if (Subtarget.isLittleEndian()) { 10370 std::reverse(Loads.begin(), Loads.end()); 10371 std::reverse(LoadChains.begin(), LoadChains.end()); 10372 } 10373 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10374 SDValue Value = 10375 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10376 dl, VT, Loads); 10377 SDValue RetOps[] = {Value, TF}; 10378 return DAG.getMergeValues(RetOps, dl); 10379 } 10380 10381 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10382 SelectionDAG &DAG) const { 10383 SDLoc dl(Op); 10384 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10385 SDValue StoreChain = SN->getChain(); 10386 SDValue BasePtr = SN->getBasePtr(); 10387 SDValue Value = SN->getValue(); 10388 EVT StoreVT = Value.getValueType(); 10389 10390 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10391 return Op; 10392 10393 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10394 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10395 // underlying registers individually. 10396 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10397 "Type unsupported without MMA"); 10398 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10399 "Type unsupported without paired vector support"); 10400 Align Alignment = SN->getAlign(); 10401 SmallVector<SDValue, 4> Stores; 10402 unsigned NumVecs = 2; 10403 if (StoreVT == MVT::v512i1) { 10404 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10405 NumVecs = 4; 10406 } 10407 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10408 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10409 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10410 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 10411 SDValue Store = 10412 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10413 SN->getPointerInfo().getWithOffset(Idx * 16), 10414 commonAlignment(Alignment, Idx * 16), 10415 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10416 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10417 DAG.getConstant(16, dl, BasePtr.getValueType())); 10418 Stores.push_back(Store); 10419 } 10420 SDValue TF = DAG.getTokenFactor(dl, Stores); 10421 return TF; 10422 } 10423 10424 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10425 SDLoc dl(Op); 10426 if (Op.getValueType() == MVT::v4i32) { 10427 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10428 10429 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10430 // +16 as shift amt. 10431 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10432 SDValue RHSSwap = // = vrlw RHS, 16 10433 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10434 10435 // Shrinkify inputs to v8i16. 10436 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10437 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10438 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10439 10440 // Low parts multiplied together, generating 32-bit results (we ignore the 10441 // top parts). 10442 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10443 LHS, RHS, DAG, dl, MVT::v4i32); 10444 10445 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10446 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10447 // Shift the high parts up 16 bits. 10448 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10449 Neg16, DAG, dl); 10450 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10451 } else if (Op.getValueType() == MVT::v16i8) { 10452 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10453 bool isLittleEndian = Subtarget.isLittleEndian(); 10454 10455 // Multiply the even 8-bit parts, producing 16-bit sums. 10456 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10457 LHS, RHS, DAG, dl, MVT::v8i16); 10458 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10459 10460 // Multiply the odd 8-bit parts, producing 16-bit sums. 10461 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10462 LHS, RHS, DAG, dl, MVT::v8i16); 10463 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10464 10465 // Merge the results together. Because vmuleub and vmuloub are 10466 // instructions with a big-endian bias, we must reverse the 10467 // element numbering and reverse the meaning of "odd" and "even" 10468 // when generating little endian code. 10469 int Ops[16]; 10470 for (unsigned i = 0; i != 8; ++i) { 10471 if (isLittleEndian) { 10472 Ops[i*2 ] = 2*i; 10473 Ops[i*2+1] = 2*i+16; 10474 } else { 10475 Ops[i*2 ] = 2*i+1; 10476 Ops[i*2+1] = 2*i+1+16; 10477 } 10478 } 10479 if (isLittleEndian) 10480 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10481 else 10482 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10483 } else { 10484 llvm_unreachable("Unknown mul to lower!"); 10485 } 10486 } 10487 10488 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 10489 bool IsStrict = Op->isStrictFPOpcode(); 10490 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 10491 !Subtarget.hasP9Vector()) 10492 return SDValue(); 10493 10494 return Op; 10495 } 10496 10497 // Custom lowering for fpext vf32 to v2f64 10498 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10499 10500 assert(Op.getOpcode() == ISD::FP_EXTEND && 10501 "Should only be called for ISD::FP_EXTEND"); 10502 10503 // FIXME: handle extends from half precision float vectors on P9. 10504 // We only want to custom lower an extend from v2f32 to v2f64. 10505 if (Op.getValueType() != MVT::v2f64 || 10506 Op.getOperand(0).getValueType() != MVT::v2f32) 10507 return SDValue(); 10508 10509 SDLoc dl(Op); 10510 SDValue Op0 = Op.getOperand(0); 10511 10512 switch (Op0.getOpcode()) { 10513 default: 10514 return SDValue(); 10515 case ISD::EXTRACT_SUBVECTOR: { 10516 assert(Op0.getNumOperands() == 2 && 10517 isa<ConstantSDNode>(Op0->getOperand(1)) && 10518 "Node should have 2 operands with second one being a constant!"); 10519 10520 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10521 return SDValue(); 10522 10523 // Custom lower is only done for high or low doubleword. 10524 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10525 if (Idx % 2 != 0) 10526 return SDValue(); 10527 10528 // Since input is v4f32, at this point Idx is either 0 or 2. 10529 // Shift to get the doubleword position we want. 10530 int DWord = Idx >> 1; 10531 10532 // High and low word positions are different on little endian. 10533 if (Subtarget.isLittleEndian()) 10534 DWord ^= 0x1; 10535 10536 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10537 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10538 } 10539 case ISD::FADD: 10540 case ISD::FMUL: 10541 case ISD::FSUB: { 10542 SDValue NewLoad[2]; 10543 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10544 // Ensure both input are loads. 10545 SDValue LdOp = Op0.getOperand(i); 10546 if (LdOp.getOpcode() != ISD::LOAD) 10547 return SDValue(); 10548 // Generate new load node. 10549 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10550 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10551 NewLoad[i] = DAG.getMemIntrinsicNode( 10552 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10553 LD->getMemoryVT(), LD->getMemOperand()); 10554 } 10555 SDValue NewOp = 10556 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10557 NewLoad[1], Op0.getNode()->getFlags()); 10558 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10559 DAG.getConstant(0, dl, MVT::i32)); 10560 } 10561 case ISD::LOAD: { 10562 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10563 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10564 SDValue NewLd = DAG.getMemIntrinsicNode( 10565 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10566 LD->getMemoryVT(), LD->getMemOperand()); 10567 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10568 DAG.getConstant(0, dl, MVT::i32)); 10569 } 10570 } 10571 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10572 } 10573 10574 /// LowerOperation - Provide custom lowering hooks for some operations. 10575 /// 10576 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10577 switch (Op.getOpcode()) { 10578 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10579 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10580 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10581 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10582 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10583 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10584 case ISD::SETCC: return LowerSETCC(Op, DAG); 10585 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10586 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10587 10588 // Variable argument lowering. 10589 case ISD::VASTART: return LowerVASTART(Op, DAG); 10590 case ISD::VAARG: return LowerVAARG(Op, DAG); 10591 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10592 10593 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10594 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10595 case ISD::GET_DYNAMIC_AREA_OFFSET: 10596 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10597 10598 // Exception handling lowering. 10599 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10600 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10601 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10602 10603 case ISD::LOAD: return LowerLOAD(Op, DAG); 10604 case ISD::STORE: return LowerSTORE(Op, DAG); 10605 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10606 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10607 case ISD::STRICT_FP_TO_UINT: 10608 case ISD::STRICT_FP_TO_SINT: 10609 case ISD::FP_TO_UINT: 10610 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10611 case ISD::STRICT_UINT_TO_FP: 10612 case ISD::STRICT_SINT_TO_FP: 10613 case ISD::UINT_TO_FP: 10614 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10615 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10616 10617 // Lower 64-bit shifts. 10618 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10619 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10620 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10621 10622 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10623 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10624 10625 // Vector-related lowering. 10626 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10627 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10628 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10629 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10630 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10631 case ISD::MUL: return LowerMUL(Op, DAG); 10632 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10633 case ISD::STRICT_FP_ROUND: 10634 case ISD::FP_ROUND: 10635 return LowerFP_ROUND(Op, DAG); 10636 case ISD::ROTL: return LowerROTL(Op, DAG); 10637 10638 // For counter-based loop handling. 10639 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10640 10641 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10642 10643 // Frame & Return address. 10644 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10645 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10646 10647 case ISD::INTRINSIC_VOID: 10648 return LowerINTRINSIC_VOID(Op, DAG); 10649 case ISD::BSWAP: 10650 return LowerBSWAP(Op, DAG); 10651 case ISD::ATOMIC_CMP_SWAP: 10652 return LowerATOMIC_CMP_SWAP(Op, DAG); 10653 } 10654 } 10655 10656 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10657 SmallVectorImpl<SDValue>&Results, 10658 SelectionDAG &DAG) const { 10659 SDLoc dl(N); 10660 switch (N->getOpcode()) { 10661 default: 10662 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10663 case ISD::READCYCLECOUNTER: { 10664 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10665 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10666 10667 Results.push_back( 10668 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10669 Results.push_back(RTB.getValue(2)); 10670 break; 10671 } 10672 case ISD::INTRINSIC_W_CHAIN: { 10673 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10674 Intrinsic::loop_decrement) 10675 break; 10676 10677 assert(N->getValueType(0) == MVT::i1 && 10678 "Unexpected result type for CTR decrement intrinsic"); 10679 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10680 N->getValueType(0)); 10681 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10682 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10683 N->getOperand(1)); 10684 10685 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10686 Results.push_back(NewInt.getValue(1)); 10687 break; 10688 } 10689 case ISD::VAARG: { 10690 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10691 return; 10692 10693 EVT VT = N->getValueType(0); 10694 10695 if (VT == MVT::i64) { 10696 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10697 10698 Results.push_back(NewNode); 10699 Results.push_back(NewNode.getValue(1)); 10700 } 10701 return; 10702 } 10703 case ISD::STRICT_FP_TO_SINT: 10704 case ISD::STRICT_FP_TO_UINT: 10705 case ISD::FP_TO_SINT: 10706 case ISD::FP_TO_UINT: 10707 // LowerFP_TO_INT() can only handle f32 and f64. 10708 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10709 MVT::ppcf128) 10710 return; 10711 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10712 return; 10713 case ISD::TRUNCATE: { 10714 if (!N->getValueType(0).isVector()) 10715 return; 10716 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10717 if (Lowered) 10718 Results.push_back(Lowered); 10719 return; 10720 } 10721 case ISD::FSHL: 10722 case ISD::FSHR: 10723 // Don't handle funnel shifts here. 10724 return; 10725 case ISD::BITCAST: 10726 // Don't handle bitcast here. 10727 return; 10728 case ISD::FP_EXTEND: 10729 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10730 if (Lowered) 10731 Results.push_back(Lowered); 10732 return; 10733 } 10734 } 10735 10736 //===----------------------------------------------------------------------===// 10737 // Other Lowering Code 10738 //===----------------------------------------------------------------------===// 10739 10740 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10741 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10742 Function *Func = Intrinsic::getDeclaration(M, Id); 10743 return Builder.CreateCall(Func, {}); 10744 } 10745 10746 // The mappings for emitLeading/TrailingFence is taken from 10747 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10748 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10749 Instruction *Inst, 10750 AtomicOrdering Ord) const { 10751 if (Ord == AtomicOrdering::SequentiallyConsistent) 10752 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10753 if (isReleaseOrStronger(Ord)) 10754 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10755 return nullptr; 10756 } 10757 10758 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10759 Instruction *Inst, 10760 AtomicOrdering Ord) const { 10761 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10762 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10763 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10764 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10765 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10766 return Builder.CreateCall( 10767 Intrinsic::getDeclaration( 10768 Builder.GetInsertBlock()->getParent()->getParent(), 10769 Intrinsic::ppc_cfence, {Inst->getType()}), 10770 {Inst}); 10771 // FIXME: Can use isync for rmw operation. 10772 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10773 } 10774 return nullptr; 10775 } 10776 10777 MachineBasicBlock * 10778 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10779 unsigned AtomicSize, 10780 unsigned BinOpcode, 10781 unsigned CmpOpcode, 10782 unsigned CmpPred) const { 10783 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10784 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10785 10786 auto LoadMnemonic = PPC::LDARX; 10787 auto StoreMnemonic = PPC::STDCX; 10788 switch (AtomicSize) { 10789 default: 10790 llvm_unreachable("Unexpected size of atomic entity"); 10791 case 1: 10792 LoadMnemonic = PPC::LBARX; 10793 StoreMnemonic = PPC::STBCX; 10794 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10795 break; 10796 case 2: 10797 LoadMnemonic = PPC::LHARX; 10798 StoreMnemonic = PPC::STHCX; 10799 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10800 break; 10801 case 4: 10802 LoadMnemonic = PPC::LWARX; 10803 StoreMnemonic = PPC::STWCX; 10804 break; 10805 case 8: 10806 LoadMnemonic = PPC::LDARX; 10807 StoreMnemonic = PPC::STDCX; 10808 break; 10809 } 10810 10811 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10812 MachineFunction *F = BB->getParent(); 10813 MachineFunction::iterator It = ++BB->getIterator(); 10814 10815 Register dest = MI.getOperand(0).getReg(); 10816 Register ptrA = MI.getOperand(1).getReg(); 10817 Register ptrB = MI.getOperand(2).getReg(); 10818 Register incr = MI.getOperand(3).getReg(); 10819 DebugLoc dl = MI.getDebugLoc(); 10820 10821 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10822 MachineBasicBlock *loop2MBB = 10823 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10824 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10825 F->insert(It, loopMBB); 10826 if (CmpOpcode) 10827 F->insert(It, loop2MBB); 10828 F->insert(It, exitMBB); 10829 exitMBB->splice(exitMBB->begin(), BB, 10830 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10831 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10832 10833 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10834 Register TmpReg = (!BinOpcode) ? incr : 10835 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10836 : &PPC::GPRCRegClass); 10837 10838 // thisMBB: 10839 // ... 10840 // fallthrough --> loopMBB 10841 BB->addSuccessor(loopMBB); 10842 10843 // loopMBB: 10844 // l[wd]arx dest, ptr 10845 // add r0, dest, incr 10846 // st[wd]cx. r0, ptr 10847 // bne- loopMBB 10848 // fallthrough --> exitMBB 10849 10850 // For max/min... 10851 // loopMBB: 10852 // l[wd]arx dest, ptr 10853 // cmpl?[wd] incr, dest 10854 // bgt exitMBB 10855 // loop2MBB: 10856 // st[wd]cx. dest, ptr 10857 // bne- loopMBB 10858 // fallthrough --> exitMBB 10859 10860 BB = loopMBB; 10861 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10862 .addReg(ptrA).addReg(ptrB); 10863 if (BinOpcode) 10864 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10865 if (CmpOpcode) { 10866 // Signed comparisons of byte or halfword values must be sign-extended. 10867 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10868 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10869 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10870 ExtReg).addReg(dest); 10871 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10872 .addReg(incr).addReg(ExtReg); 10873 } else 10874 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10875 .addReg(incr).addReg(dest); 10876 10877 BuildMI(BB, dl, TII->get(PPC::BCC)) 10878 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10879 BB->addSuccessor(loop2MBB); 10880 BB->addSuccessor(exitMBB); 10881 BB = loop2MBB; 10882 } 10883 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10884 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10885 BuildMI(BB, dl, TII->get(PPC::BCC)) 10886 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10887 BB->addSuccessor(loopMBB); 10888 BB->addSuccessor(exitMBB); 10889 10890 // exitMBB: 10891 // ... 10892 BB = exitMBB; 10893 return BB; 10894 } 10895 10896 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 10897 switch(MI.getOpcode()) { 10898 default: 10899 return false; 10900 case PPC::COPY: 10901 return TII->isSignExtended(MI); 10902 case PPC::LHA: 10903 case PPC::LHA8: 10904 case PPC::LHAU: 10905 case PPC::LHAU8: 10906 case PPC::LHAUX: 10907 case PPC::LHAUX8: 10908 case PPC::LHAX: 10909 case PPC::LHAX8: 10910 case PPC::LWA: 10911 case PPC::LWAUX: 10912 case PPC::LWAX: 10913 case PPC::LWAX_32: 10914 case PPC::LWA_32: 10915 case PPC::PLHA: 10916 case PPC::PLHA8: 10917 case PPC::PLHA8pc: 10918 case PPC::PLHApc: 10919 case PPC::PLWA: 10920 case PPC::PLWA8: 10921 case PPC::PLWA8pc: 10922 case PPC::PLWApc: 10923 case PPC::EXTSB: 10924 case PPC::EXTSB8: 10925 case PPC::EXTSB8_32_64: 10926 case PPC::EXTSB8_rec: 10927 case PPC::EXTSB_rec: 10928 case PPC::EXTSH: 10929 case PPC::EXTSH8: 10930 case PPC::EXTSH8_32_64: 10931 case PPC::EXTSH8_rec: 10932 case PPC::EXTSH_rec: 10933 case PPC::EXTSW: 10934 case PPC::EXTSWSLI: 10935 case PPC::EXTSWSLI_32_64: 10936 case PPC::EXTSWSLI_32_64_rec: 10937 case PPC::EXTSWSLI_rec: 10938 case PPC::EXTSW_32: 10939 case PPC::EXTSW_32_64: 10940 case PPC::EXTSW_32_64_rec: 10941 case PPC::EXTSW_rec: 10942 case PPC::SRAW: 10943 case PPC::SRAWI: 10944 case PPC::SRAWI_rec: 10945 case PPC::SRAW_rec: 10946 return true; 10947 } 10948 return false; 10949 } 10950 10951 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10952 MachineInstr &MI, MachineBasicBlock *BB, 10953 bool is8bit, // operation 10954 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10955 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10956 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 10957 10958 // If this is a signed comparison and the value being compared is not known 10959 // to be sign extended, sign extend it here. 10960 DebugLoc dl = MI.getDebugLoc(); 10961 MachineFunction *F = BB->getParent(); 10962 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10963 Register incr = MI.getOperand(3).getReg(); 10964 bool IsSignExtended = Register::isVirtualRegister(incr) && 10965 isSignExtended(*RegInfo.getVRegDef(incr), TII); 10966 10967 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 10968 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10969 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 10970 .addReg(MI.getOperand(3).getReg()); 10971 MI.getOperand(3).setReg(ValueReg); 10972 } 10973 // If we support part-word atomic mnemonics, just use them 10974 if (Subtarget.hasPartwordAtomics()) 10975 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10976 CmpPred); 10977 10978 // In 64 bit mode we have to use 64 bits for addresses, even though the 10979 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10980 // registers without caring whether they're 32 or 64, but here we're 10981 // doing actual arithmetic on the addresses. 10982 bool is64bit = Subtarget.isPPC64(); 10983 bool isLittleEndian = Subtarget.isLittleEndian(); 10984 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10985 10986 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10987 MachineFunction::iterator It = ++BB->getIterator(); 10988 10989 Register dest = MI.getOperand(0).getReg(); 10990 Register ptrA = MI.getOperand(1).getReg(); 10991 Register ptrB = MI.getOperand(2).getReg(); 10992 10993 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10994 MachineBasicBlock *loop2MBB = 10995 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10996 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10997 F->insert(It, loopMBB); 10998 if (CmpOpcode) 10999 F->insert(It, loop2MBB); 11000 F->insert(It, exitMBB); 11001 exitMBB->splice(exitMBB->begin(), BB, 11002 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11003 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11004 11005 const TargetRegisterClass *RC = 11006 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11007 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11008 11009 Register PtrReg = RegInfo.createVirtualRegister(RC); 11010 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11011 Register ShiftReg = 11012 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11013 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11014 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11015 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11016 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11017 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11018 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11019 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11020 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11021 Register Ptr1Reg; 11022 Register TmpReg = 11023 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11024 11025 // thisMBB: 11026 // ... 11027 // fallthrough --> loopMBB 11028 BB->addSuccessor(loopMBB); 11029 11030 // The 4-byte load must be aligned, while a char or short may be 11031 // anywhere in the word. Hence all this nasty bookkeeping code. 11032 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11033 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11034 // xori shift, shift1, 24 [16] 11035 // rlwinm ptr, ptr1, 0, 0, 29 11036 // slw incr2, incr, shift 11037 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11038 // slw mask, mask2, shift 11039 // loopMBB: 11040 // lwarx tmpDest, ptr 11041 // add tmp, tmpDest, incr2 11042 // andc tmp2, tmpDest, mask 11043 // and tmp3, tmp, mask 11044 // or tmp4, tmp3, tmp2 11045 // stwcx. tmp4, ptr 11046 // bne- loopMBB 11047 // fallthrough --> exitMBB 11048 // srw dest, tmpDest, shift 11049 if (ptrA != ZeroReg) { 11050 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11051 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11052 .addReg(ptrA) 11053 .addReg(ptrB); 11054 } else { 11055 Ptr1Reg = ptrB; 11056 } 11057 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11058 // mode. 11059 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11060 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11061 .addImm(3) 11062 .addImm(27) 11063 .addImm(is8bit ? 28 : 27); 11064 if (!isLittleEndian) 11065 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11066 .addReg(Shift1Reg) 11067 .addImm(is8bit ? 24 : 16); 11068 if (is64bit) 11069 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11070 .addReg(Ptr1Reg) 11071 .addImm(0) 11072 .addImm(61); 11073 else 11074 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11075 .addReg(Ptr1Reg) 11076 .addImm(0) 11077 .addImm(0) 11078 .addImm(29); 11079 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11080 if (is8bit) 11081 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11082 else { 11083 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11084 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11085 .addReg(Mask3Reg) 11086 .addImm(65535); 11087 } 11088 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11089 .addReg(Mask2Reg) 11090 .addReg(ShiftReg); 11091 11092 BB = loopMBB; 11093 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11094 .addReg(ZeroReg) 11095 .addReg(PtrReg); 11096 if (BinOpcode) 11097 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11098 .addReg(Incr2Reg) 11099 .addReg(TmpDestReg); 11100 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11101 .addReg(TmpDestReg) 11102 .addReg(MaskReg); 11103 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11104 if (CmpOpcode) { 11105 // For unsigned comparisons, we can directly compare the shifted values. 11106 // For signed comparisons we shift and sign extend. 11107 Register SReg = RegInfo.createVirtualRegister(GPRC); 11108 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11109 .addReg(TmpDestReg) 11110 .addReg(MaskReg); 11111 unsigned ValueReg = SReg; 11112 unsigned CmpReg = Incr2Reg; 11113 if (CmpOpcode == PPC::CMPW) { 11114 ValueReg = RegInfo.createVirtualRegister(GPRC); 11115 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11116 .addReg(SReg) 11117 .addReg(ShiftReg); 11118 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11119 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11120 .addReg(ValueReg); 11121 ValueReg = ValueSReg; 11122 CmpReg = incr; 11123 } 11124 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11125 .addReg(CmpReg) 11126 .addReg(ValueReg); 11127 BuildMI(BB, dl, TII->get(PPC::BCC)) 11128 .addImm(CmpPred) 11129 .addReg(PPC::CR0) 11130 .addMBB(exitMBB); 11131 BB->addSuccessor(loop2MBB); 11132 BB->addSuccessor(exitMBB); 11133 BB = loop2MBB; 11134 } 11135 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11136 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11137 .addReg(Tmp4Reg) 11138 .addReg(ZeroReg) 11139 .addReg(PtrReg); 11140 BuildMI(BB, dl, TII->get(PPC::BCC)) 11141 .addImm(PPC::PRED_NE) 11142 .addReg(PPC::CR0) 11143 .addMBB(loopMBB); 11144 BB->addSuccessor(loopMBB); 11145 BB->addSuccessor(exitMBB); 11146 11147 // exitMBB: 11148 // ... 11149 BB = exitMBB; 11150 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11151 .addReg(TmpDestReg) 11152 .addReg(ShiftReg); 11153 return BB; 11154 } 11155 11156 llvm::MachineBasicBlock * 11157 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11158 MachineBasicBlock *MBB) const { 11159 DebugLoc DL = MI.getDebugLoc(); 11160 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11161 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11162 11163 MachineFunction *MF = MBB->getParent(); 11164 MachineRegisterInfo &MRI = MF->getRegInfo(); 11165 11166 const BasicBlock *BB = MBB->getBasicBlock(); 11167 MachineFunction::iterator I = ++MBB->getIterator(); 11168 11169 Register DstReg = MI.getOperand(0).getReg(); 11170 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11171 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11172 Register mainDstReg = MRI.createVirtualRegister(RC); 11173 Register restoreDstReg = MRI.createVirtualRegister(RC); 11174 11175 MVT PVT = getPointerTy(MF->getDataLayout()); 11176 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11177 "Invalid Pointer Size!"); 11178 // For v = setjmp(buf), we generate 11179 // 11180 // thisMBB: 11181 // SjLjSetup mainMBB 11182 // bl mainMBB 11183 // v_restore = 1 11184 // b sinkMBB 11185 // 11186 // mainMBB: 11187 // buf[LabelOffset] = LR 11188 // v_main = 0 11189 // 11190 // sinkMBB: 11191 // v = phi(main, restore) 11192 // 11193 11194 MachineBasicBlock *thisMBB = MBB; 11195 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11196 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11197 MF->insert(I, mainMBB); 11198 MF->insert(I, sinkMBB); 11199 11200 MachineInstrBuilder MIB; 11201 11202 // Transfer the remainder of BB and its successor edges to sinkMBB. 11203 sinkMBB->splice(sinkMBB->begin(), MBB, 11204 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11205 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11206 11207 // Note that the structure of the jmp_buf used here is not compatible 11208 // with that used by libc, and is not designed to be. Specifically, it 11209 // stores only those 'reserved' registers that LLVM does not otherwise 11210 // understand how to spill. Also, by convention, by the time this 11211 // intrinsic is called, Clang has already stored the frame address in the 11212 // first slot of the buffer and stack address in the third. Following the 11213 // X86 target code, we'll store the jump address in the second slot. We also 11214 // need to save the TOC pointer (R2) to handle jumps between shared 11215 // libraries, and that will be stored in the fourth slot. The thread 11216 // identifier (R13) is not affected. 11217 11218 // thisMBB: 11219 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11220 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11221 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11222 11223 // Prepare IP either in reg. 11224 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11225 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11226 Register BufReg = MI.getOperand(1).getReg(); 11227 11228 if (Subtarget.is64BitELFABI()) { 11229 setUsesTOCBasePtr(*MBB->getParent()); 11230 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11231 .addReg(PPC::X2) 11232 .addImm(TOCOffset) 11233 .addReg(BufReg) 11234 .cloneMemRefs(MI); 11235 } 11236 11237 // Naked functions never have a base pointer, and so we use r1. For all 11238 // other functions, this decision must be delayed until during PEI. 11239 unsigned BaseReg; 11240 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11241 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11242 else 11243 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11244 11245 MIB = BuildMI(*thisMBB, MI, DL, 11246 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11247 .addReg(BaseReg) 11248 .addImm(BPOffset) 11249 .addReg(BufReg) 11250 .cloneMemRefs(MI); 11251 11252 // Setup 11253 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11254 MIB.addRegMask(TRI->getNoPreservedMask()); 11255 11256 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11257 11258 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11259 .addMBB(mainMBB); 11260 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11261 11262 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11263 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11264 11265 // mainMBB: 11266 // mainDstReg = 0 11267 MIB = 11268 BuildMI(mainMBB, DL, 11269 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11270 11271 // Store IP 11272 if (Subtarget.isPPC64()) { 11273 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11274 .addReg(LabelReg) 11275 .addImm(LabelOffset) 11276 .addReg(BufReg); 11277 } else { 11278 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11279 .addReg(LabelReg) 11280 .addImm(LabelOffset) 11281 .addReg(BufReg); 11282 } 11283 MIB.cloneMemRefs(MI); 11284 11285 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11286 mainMBB->addSuccessor(sinkMBB); 11287 11288 // sinkMBB: 11289 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11290 TII->get(PPC::PHI), DstReg) 11291 .addReg(mainDstReg).addMBB(mainMBB) 11292 .addReg(restoreDstReg).addMBB(thisMBB); 11293 11294 MI.eraseFromParent(); 11295 return sinkMBB; 11296 } 11297 11298 MachineBasicBlock * 11299 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11300 MachineBasicBlock *MBB) const { 11301 DebugLoc DL = MI.getDebugLoc(); 11302 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11303 11304 MachineFunction *MF = MBB->getParent(); 11305 MachineRegisterInfo &MRI = MF->getRegInfo(); 11306 11307 MVT PVT = getPointerTy(MF->getDataLayout()); 11308 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11309 "Invalid Pointer Size!"); 11310 11311 const TargetRegisterClass *RC = 11312 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11313 Register Tmp = MRI.createVirtualRegister(RC); 11314 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11315 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11316 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11317 unsigned BP = 11318 (PVT == MVT::i64) 11319 ? PPC::X30 11320 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11321 : PPC::R30); 11322 11323 MachineInstrBuilder MIB; 11324 11325 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11326 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11327 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11328 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11329 11330 Register BufReg = MI.getOperand(0).getReg(); 11331 11332 // Reload FP (the jumped-to function may not have had a 11333 // frame pointer, and if so, then its r31 will be restored 11334 // as necessary). 11335 if (PVT == MVT::i64) { 11336 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11337 .addImm(0) 11338 .addReg(BufReg); 11339 } else { 11340 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11341 .addImm(0) 11342 .addReg(BufReg); 11343 } 11344 MIB.cloneMemRefs(MI); 11345 11346 // Reload IP 11347 if (PVT == MVT::i64) { 11348 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11349 .addImm(LabelOffset) 11350 .addReg(BufReg); 11351 } else { 11352 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11353 .addImm(LabelOffset) 11354 .addReg(BufReg); 11355 } 11356 MIB.cloneMemRefs(MI); 11357 11358 // Reload SP 11359 if (PVT == MVT::i64) { 11360 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11361 .addImm(SPOffset) 11362 .addReg(BufReg); 11363 } else { 11364 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11365 .addImm(SPOffset) 11366 .addReg(BufReg); 11367 } 11368 MIB.cloneMemRefs(MI); 11369 11370 // Reload BP 11371 if (PVT == MVT::i64) { 11372 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11373 .addImm(BPOffset) 11374 .addReg(BufReg); 11375 } else { 11376 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11377 .addImm(BPOffset) 11378 .addReg(BufReg); 11379 } 11380 MIB.cloneMemRefs(MI); 11381 11382 // Reload TOC 11383 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11384 setUsesTOCBasePtr(*MBB->getParent()); 11385 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11386 .addImm(TOCOffset) 11387 .addReg(BufReg) 11388 .cloneMemRefs(MI); 11389 } 11390 11391 // Jump 11392 BuildMI(*MBB, MI, DL, 11393 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11394 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11395 11396 MI.eraseFromParent(); 11397 return MBB; 11398 } 11399 11400 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11401 // If the function specifically requests inline stack probes, emit them. 11402 if (MF.getFunction().hasFnAttribute("probe-stack")) 11403 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11404 "inline-asm"; 11405 return false; 11406 } 11407 11408 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11409 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11410 unsigned StackAlign = TFI->getStackAlignment(); 11411 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11412 "Unexpected stack alignment"); 11413 // The default stack probe size is 4096 if the function has no 11414 // stack-probe-size attribute. 11415 unsigned StackProbeSize = 4096; 11416 const Function &Fn = MF.getFunction(); 11417 if (Fn.hasFnAttribute("stack-probe-size")) 11418 Fn.getFnAttribute("stack-probe-size") 11419 .getValueAsString() 11420 .getAsInteger(0, StackProbeSize); 11421 // Round down to the stack alignment. 11422 StackProbeSize &= ~(StackAlign - 1); 11423 return StackProbeSize ? StackProbeSize : StackAlign; 11424 } 11425 11426 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11427 // into three phases. In the first phase, it uses pseudo instruction 11428 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11429 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11430 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11431 // MaxCallFrameSize so that it can calculate correct data area pointer. 11432 MachineBasicBlock * 11433 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11434 MachineBasicBlock *MBB) const { 11435 const bool isPPC64 = Subtarget.isPPC64(); 11436 MachineFunction *MF = MBB->getParent(); 11437 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11438 DebugLoc DL = MI.getDebugLoc(); 11439 const unsigned ProbeSize = getStackProbeSize(*MF); 11440 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11441 MachineRegisterInfo &MRI = MF->getRegInfo(); 11442 // The CFG of probing stack looks as 11443 // +-----+ 11444 // | MBB | 11445 // +--+--+ 11446 // | 11447 // +----v----+ 11448 // +--->+ TestMBB +---+ 11449 // | +----+----+ | 11450 // | | | 11451 // | +-----v----+ | 11452 // +---+ BlockMBB | | 11453 // +----------+ | 11454 // | 11455 // +---------+ | 11456 // | TailMBB +<--+ 11457 // +---------+ 11458 // In MBB, calculate previous frame pointer and final stack pointer. 11459 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11460 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11461 // TailMBB is spliced via \p MI. 11462 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11463 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11464 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11465 11466 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11467 MF->insert(MBBIter, TestMBB); 11468 MF->insert(MBBIter, BlockMBB); 11469 MF->insert(MBBIter, TailMBB); 11470 11471 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11472 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11473 11474 Register DstReg = MI.getOperand(0).getReg(); 11475 Register NegSizeReg = MI.getOperand(1).getReg(); 11476 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11477 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11478 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11479 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11480 11481 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11482 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11483 // NegSize. 11484 unsigned ProbeOpc; 11485 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11486 ProbeOpc = 11487 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11488 else 11489 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11490 // and NegSizeReg will be allocated in the same phyreg to avoid 11491 // redundant copy when NegSizeReg has only one use which is current MI and 11492 // will be replaced by PREPARE_PROBED_ALLOCA then. 11493 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11494 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11495 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11496 .addDef(ActualNegSizeReg) 11497 .addReg(NegSizeReg) 11498 .add(MI.getOperand(2)) 11499 .add(MI.getOperand(3)); 11500 11501 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11502 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11503 FinalStackPtr) 11504 .addReg(SPReg) 11505 .addReg(ActualNegSizeReg); 11506 11507 // Materialize a scratch register for update. 11508 int64_t NegProbeSize = -(int64_t)ProbeSize; 11509 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11510 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11511 if (!isInt<16>(NegProbeSize)) { 11512 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11513 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11514 .addImm(NegProbeSize >> 16); 11515 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11516 ScratchReg) 11517 .addReg(TempReg) 11518 .addImm(NegProbeSize & 0xFFFF); 11519 } else 11520 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11521 .addImm(NegProbeSize); 11522 11523 { 11524 // Probing leading residual part. 11525 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11526 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11527 .addReg(ActualNegSizeReg) 11528 .addReg(ScratchReg); 11529 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11530 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11531 .addReg(Div) 11532 .addReg(ScratchReg); 11533 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11534 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11535 .addReg(Mul) 11536 .addReg(ActualNegSizeReg); 11537 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11538 .addReg(FramePointer) 11539 .addReg(SPReg) 11540 .addReg(NegMod); 11541 } 11542 11543 { 11544 // Remaining part should be multiple of ProbeSize. 11545 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11546 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11547 .addReg(SPReg) 11548 .addReg(FinalStackPtr); 11549 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11550 .addImm(PPC::PRED_EQ) 11551 .addReg(CmpResult) 11552 .addMBB(TailMBB); 11553 TestMBB->addSuccessor(BlockMBB); 11554 TestMBB->addSuccessor(TailMBB); 11555 } 11556 11557 { 11558 // Touch the block. 11559 // |P...|P...|P... 11560 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11561 .addReg(FramePointer) 11562 .addReg(SPReg) 11563 .addReg(ScratchReg); 11564 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11565 BlockMBB->addSuccessor(TestMBB); 11566 } 11567 11568 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11569 // DYNAREAOFFSET pseudo instruction to get the future result. 11570 Register MaxCallFrameSizeReg = 11571 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11572 BuildMI(TailMBB, DL, 11573 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11574 MaxCallFrameSizeReg) 11575 .add(MI.getOperand(2)) 11576 .add(MI.getOperand(3)); 11577 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11578 .addReg(SPReg) 11579 .addReg(MaxCallFrameSizeReg); 11580 11581 // Splice instructions after MI to TailMBB. 11582 TailMBB->splice(TailMBB->end(), MBB, 11583 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11584 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11585 MBB->addSuccessor(TestMBB); 11586 11587 // Delete the pseudo instruction. 11588 MI.eraseFromParent(); 11589 11590 ++NumDynamicAllocaProbed; 11591 return TailMBB; 11592 } 11593 11594 MachineBasicBlock * 11595 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11596 MachineBasicBlock *BB) const { 11597 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11598 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11599 if (Subtarget.is64BitELFABI() && 11600 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11601 !Subtarget.isUsingPCRelativeCalls()) { 11602 // Call lowering should have added an r2 operand to indicate a dependence 11603 // on the TOC base pointer value. It can't however, because there is no 11604 // way to mark the dependence as implicit there, and so the stackmap code 11605 // will confuse it with a regular operand. Instead, add the dependence 11606 // here. 11607 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11608 } 11609 11610 return emitPatchPoint(MI, BB); 11611 } 11612 11613 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11614 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11615 return emitEHSjLjSetJmp(MI, BB); 11616 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11617 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11618 return emitEHSjLjLongJmp(MI, BB); 11619 } 11620 11621 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11622 11623 // To "insert" these instructions we actually have to insert their 11624 // control-flow patterns. 11625 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11626 MachineFunction::iterator It = ++BB->getIterator(); 11627 11628 MachineFunction *F = BB->getParent(); 11629 11630 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11631 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11632 MI.getOpcode() == PPC::SELECT_I8) { 11633 SmallVector<MachineOperand, 2> Cond; 11634 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11635 MI.getOpcode() == PPC::SELECT_CC_I8) 11636 Cond.push_back(MI.getOperand(4)); 11637 else 11638 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11639 Cond.push_back(MI.getOperand(1)); 11640 11641 DebugLoc dl = MI.getDebugLoc(); 11642 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11643 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11644 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11645 MI.getOpcode() == PPC::SELECT_CC_F8 || 11646 MI.getOpcode() == PPC::SELECT_CC_F16 || 11647 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11648 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11649 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11650 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11651 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11652 MI.getOpcode() == PPC::SELECT_CC_SPE || 11653 MI.getOpcode() == PPC::SELECT_F4 || 11654 MI.getOpcode() == PPC::SELECT_F8 || 11655 MI.getOpcode() == PPC::SELECT_F16 || 11656 MI.getOpcode() == PPC::SELECT_SPE || 11657 MI.getOpcode() == PPC::SELECT_SPE4 || 11658 MI.getOpcode() == PPC::SELECT_VRRC || 11659 MI.getOpcode() == PPC::SELECT_VSFRC || 11660 MI.getOpcode() == PPC::SELECT_VSSRC || 11661 MI.getOpcode() == PPC::SELECT_VSRC) { 11662 // The incoming instruction knows the destination vreg to set, the 11663 // condition code register to branch on, the true/false values to 11664 // select between, and a branch opcode to use. 11665 11666 // thisMBB: 11667 // ... 11668 // TrueVal = ... 11669 // cmpTY ccX, r1, r2 11670 // bCC copy1MBB 11671 // fallthrough --> copy0MBB 11672 MachineBasicBlock *thisMBB = BB; 11673 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11674 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11675 DebugLoc dl = MI.getDebugLoc(); 11676 F->insert(It, copy0MBB); 11677 F->insert(It, sinkMBB); 11678 11679 // Transfer the remainder of BB and its successor edges to sinkMBB. 11680 sinkMBB->splice(sinkMBB->begin(), BB, 11681 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11682 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11683 11684 // Next, add the true and fallthrough blocks as its successors. 11685 BB->addSuccessor(copy0MBB); 11686 BB->addSuccessor(sinkMBB); 11687 11688 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11689 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11690 MI.getOpcode() == PPC::SELECT_F16 || 11691 MI.getOpcode() == PPC::SELECT_SPE4 || 11692 MI.getOpcode() == PPC::SELECT_SPE || 11693 MI.getOpcode() == PPC::SELECT_VRRC || 11694 MI.getOpcode() == PPC::SELECT_VSFRC || 11695 MI.getOpcode() == PPC::SELECT_VSSRC || 11696 MI.getOpcode() == PPC::SELECT_VSRC) { 11697 BuildMI(BB, dl, TII->get(PPC::BC)) 11698 .addReg(MI.getOperand(1).getReg()) 11699 .addMBB(sinkMBB); 11700 } else { 11701 unsigned SelectPred = MI.getOperand(4).getImm(); 11702 BuildMI(BB, dl, TII->get(PPC::BCC)) 11703 .addImm(SelectPred) 11704 .addReg(MI.getOperand(1).getReg()) 11705 .addMBB(sinkMBB); 11706 } 11707 11708 // copy0MBB: 11709 // %FalseValue = ... 11710 // # fallthrough to sinkMBB 11711 BB = copy0MBB; 11712 11713 // Update machine-CFG edges 11714 BB->addSuccessor(sinkMBB); 11715 11716 // sinkMBB: 11717 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11718 // ... 11719 BB = sinkMBB; 11720 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11721 .addReg(MI.getOperand(3).getReg()) 11722 .addMBB(copy0MBB) 11723 .addReg(MI.getOperand(2).getReg()) 11724 .addMBB(thisMBB); 11725 } else if (MI.getOpcode() == PPC::ReadTB) { 11726 // To read the 64-bit time-base register on a 32-bit target, we read the 11727 // two halves. Should the counter have wrapped while it was being read, we 11728 // need to try again. 11729 // ... 11730 // readLoop: 11731 // mfspr Rx,TBU # load from TBU 11732 // mfspr Ry,TB # load from TB 11733 // mfspr Rz,TBU # load from TBU 11734 // cmpw crX,Rx,Rz # check if 'old'='new' 11735 // bne readLoop # branch if they're not equal 11736 // ... 11737 11738 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11739 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11740 DebugLoc dl = MI.getDebugLoc(); 11741 F->insert(It, readMBB); 11742 F->insert(It, sinkMBB); 11743 11744 // Transfer the remainder of BB and its successor edges to sinkMBB. 11745 sinkMBB->splice(sinkMBB->begin(), BB, 11746 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11747 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11748 11749 BB->addSuccessor(readMBB); 11750 BB = readMBB; 11751 11752 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11753 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11754 Register LoReg = MI.getOperand(0).getReg(); 11755 Register HiReg = MI.getOperand(1).getReg(); 11756 11757 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11758 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11759 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11760 11761 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11762 11763 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11764 .addReg(HiReg) 11765 .addReg(ReadAgainReg); 11766 BuildMI(BB, dl, TII->get(PPC::BCC)) 11767 .addImm(PPC::PRED_NE) 11768 .addReg(CmpReg) 11769 .addMBB(readMBB); 11770 11771 BB->addSuccessor(readMBB); 11772 BB->addSuccessor(sinkMBB); 11773 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11774 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11775 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11776 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11777 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11778 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11779 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11780 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11781 11782 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11783 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11784 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11785 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11787 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11788 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11789 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11790 11791 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11792 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11793 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11794 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11795 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11796 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11797 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11798 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11799 11800 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11801 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11802 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11803 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11804 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11805 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11806 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11807 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11808 11809 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11810 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11811 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11812 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11813 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11814 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11815 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11816 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11817 11818 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11819 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11820 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11821 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11822 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11823 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11824 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11825 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11826 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11828 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11829 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11830 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11831 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11832 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11833 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11834 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11835 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11837 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11838 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11839 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11840 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11841 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11842 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11843 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11844 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11846 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11847 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11848 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11849 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11850 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11851 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11852 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11853 11854 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11855 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11856 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11857 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11858 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11859 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11860 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11861 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11862 11863 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11864 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11865 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11866 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11867 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11868 BB = EmitAtomicBinary(MI, BB, 4, 0); 11869 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11870 BB = EmitAtomicBinary(MI, BB, 8, 0); 11871 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11872 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11873 (Subtarget.hasPartwordAtomics() && 11874 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11875 (Subtarget.hasPartwordAtomics() && 11876 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11877 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11878 11879 auto LoadMnemonic = PPC::LDARX; 11880 auto StoreMnemonic = PPC::STDCX; 11881 switch (MI.getOpcode()) { 11882 default: 11883 llvm_unreachable("Compare and swap of unknown size"); 11884 case PPC::ATOMIC_CMP_SWAP_I8: 11885 LoadMnemonic = PPC::LBARX; 11886 StoreMnemonic = PPC::STBCX; 11887 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11888 break; 11889 case PPC::ATOMIC_CMP_SWAP_I16: 11890 LoadMnemonic = PPC::LHARX; 11891 StoreMnemonic = PPC::STHCX; 11892 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11893 break; 11894 case PPC::ATOMIC_CMP_SWAP_I32: 11895 LoadMnemonic = PPC::LWARX; 11896 StoreMnemonic = PPC::STWCX; 11897 break; 11898 case PPC::ATOMIC_CMP_SWAP_I64: 11899 LoadMnemonic = PPC::LDARX; 11900 StoreMnemonic = PPC::STDCX; 11901 break; 11902 } 11903 Register dest = MI.getOperand(0).getReg(); 11904 Register ptrA = MI.getOperand(1).getReg(); 11905 Register ptrB = MI.getOperand(2).getReg(); 11906 Register oldval = MI.getOperand(3).getReg(); 11907 Register newval = MI.getOperand(4).getReg(); 11908 DebugLoc dl = MI.getDebugLoc(); 11909 11910 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11911 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11912 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11913 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11914 F->insert(It, loop1MBB); 11915 F->insert(It, loop2MBB); 11916 F->insert(It, midMBB); 11917 F->insert(It, exitMBB); 11918 exitMBB->splice(exitMBB->begin(), BB, 11919 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11920 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11921 11922 // thisMBB: 11923 // ... 11924 // fallthrough --> loopMBB 11925 BB->addSuccessor(loop1MBB); 11926 11927 // loop1MBB: 11928 // l[bhwd]arx dest, ptr 11929 // cmp[wd] dest, oldval 11930 // bne- midMBB 11931 // loop2MBB: 11932 // st[bhwd]cx. newval, ptr 11933 // bne- loopMBB 11934 // b exitBB 11935 // midMBB: 11936 // st[bhwd]cx. dest, ptr 11937 // exitBB: 11938 BB = loop1MBB; 11939 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11940 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11941 .addReg(oldval) 11942 .addReg(dest); 11943 BuildMI(BB, dl, TII->get(PPC::BCC)) 11944 .addImm(PPC::PRED_NE) 11945 .addReg(PPC::CR0) 11946 .addMBB(midMBB); 11947 BB->addSuccessor(loop2MBB); 11948 BB->addSuccessor(midMBB); 11949 11950 BB = loop2MBB; 11951 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11952 .addReg(newval) 11953 .addReg(ptrA) 11954 .addReg(ptrB); 11955 BuildMI(BB, dl, TII->get(PPC::BCC)) 11956 .addImm(PPC::PRED_NE) 11957 .addReg(PPC::CR0) 11958 .addMBB(loop1MBB); 11959 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11960 BB->addSuccessor(loop1MBB); 11961 BB->addSuccessor(exitMBB); 11962 11963 BB = midMBB; 11964 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11965 .addReg(dest) 11966 .addReg(ptrA) 11967 .addReg(ptrB); 11968 BB->addSuccessor(exitMBB); 11969 11970 // exitMBB: 11971 // ... 11972 BB = exitMBB; 11973 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11974 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11975 // We must use 64-bit registers for addresses when targeting 64-bit, 11976 // since we're actually doing arithmetic on them. Other registers 11977 // can be 32-bit. 11978 bool is64bit = Subtarget.isPPC64(); 11979 bool isLittleEndian = Subtarget.isLittleEndian(); 11980 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11981 11982 Register dest = MI.getOperand(0).getReg(); 11983 Register ptrA = MI.getOperand(1).getReg(); 11984 Register ptrB = MI.getOperand(2).getReg(); 11985 Register oldval = MI.getOperand(3).getReg(); 11986 Register newval = MI.getOperand(4).getReg(); 11987 DebugLoc dl = MI.getDebugLoc(); 11988 11989 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11990 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11991 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11992 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11993 F->insert(It, loop1MBB); 11994 F->insert(It, loop2MBB); 11995 F->insert(It, midMBB); 11996 F->insert(It, exitMBB); 11997 exitMBB->splice(exitMBB->begin(), BB, 11998 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11999 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12000 12001 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12002 const TargetRegisterClass *RC = 12003 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12004 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12005 12006 Register PtrReg = RegInfo.createVirtualRegister(RC); 12007 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12008 Register ShiftReg = 12009 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12010 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12011 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12012 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12013 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12014 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12015 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12016 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12017 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12018 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12019 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12020 Register Ptr1Reg; 12021 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12022 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12023 // thisMBB: 12024 // ... 12025 // fallthrough --> loopMBB 12026 BB->addSuccessor(loop1MBB); 12027 12028 // The 4-byte load must be aligned, while a char or short may be 12029 // anywhere in the word. Hence all this nasty bookkeeping code. 12030 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12031 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12032 // xori shift, shift1, 24 [16] 12033 // rlwinm ptr, ptr1, 0, 0, 29 12034 // slw newval2, newval, shift 12035 // slw oldval2, oldval,shift 12036 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12037 // slw mask, mask2, shift 12038 // and newval3, newval2, mask 12039 // and oldval3, oldval2, mask 12040 // loop1MBB: 12041 // lwarx tmpDest, ptr 12042 // and tmp, tmpDest, mask 12043 // cmpw tmp, oldval3 12044 // bne- midMBB 12045 // loop2MBB: 12046 // andc tmp2, tmpDest, mask 12047 // or tmp4, tmp2, newval3 12048 // stwcx. tmp4, ptr 12049 // bne- loop1MBB 12050 // b exitBB 12051 // midMBB: 12052 // stwcx. tmpDest, ptr 12053 // exitBB: 12054 // srw dest, tmpDest, shift 12055 if (ptrA != ZeroReg) { 12056 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12057 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12058 .addReg(ptrA) 12059 .addReg(ptrB); 12060 } else { 12061 Ptr1Reg = ptrB; 12062 } 12063 12064 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12065 // mode. 12066 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12067 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12068 .addImm(3) 12069 .addImm(27) 12070 .addImm(is8bit ? 28 : 27); 12071 if (!isLittleEndian) 12072 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12073 .addReg(Shift1Reg) 12074 .addImm(is8bit ? 24 : 16); 12075 if (is64bit) 12076 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12077 .addReg(Ptr1Reg) 12078 .addImm(0) 12079 .addImm(61); 12080 else 12081 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12082 .addReg(Ptr1Reg) 12083 .addImm(0) 12084 .addImm(0) 12085 .addImm(29); 12086 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12087 .addReg(newval) 12088 .addReg(ShiftReg); 12089 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12090 .addReg(oldval) 12091 .addReg(ShiftReg); 12092 if (is8bit) 12093 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12094 else { 12095 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12096 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12097 .addReg(Mask3Reg) 12098 .addImm(65535); 12099 } 12100 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12101 .addReg(Mask2Reg) 12102 .addReg(ShiftReg); 12103 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12104 .addReg(NewVal2Reg) 12105 .addReg(MaskReg); 12106 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12107 .addReg(OldVal2Reg) 12108 .addReg(MaskReg); 12109 12110 BB = loop1MBB; 12111 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12112 .addReg(ZeroReg) 12113 .addReg(PtrReg); 12114 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12115 .addReg(TmpDestReg) 12116 .addReg(MaskReg); 12117 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12118 .addReg(TmpReg) 12119 .addReg(OldVal3Reg); 12120 BuildMI(BB, dl, TII->get(PPC::BCC)) 12121 .addImm(PPC::PRED_NE) 12122 .addReg(PPC::CR0) 12123 .addMBB(midMBB); 12124 BB->addSuccessor(loop2MBB); 12125 BB->addSuccessor(midMBB); 12126 12127 BB = loop2MBB; 12128 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12129 .addReg(TmpDestReg) 12130 .addReg(MaskReg); 12131 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12132 .addReg(Tmp2Reg) 12133 .addReg(NewVal3Reg); 12134 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12135 .addReg(Tmp4Reg) 12136 .addReg(ZeroReg) 12137 .addReg(PtrReg); 12138 BuildMI(BB, dl, TII->get(PPC::BCC)) 12139 .addImm(PPC::PRED_NE) 12140 .addReg(PPC::CR0) 12141 .addMBB(loop1MBB); 12142 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12143 BB->addSuccessor(loop1MBB); 12144 BB->addSuccessor(exitMBB); 12145 12146 BB = midMBB; 12147 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12148 .addReg(TmpDestReg) 12149 .addReg(ZeroReg) 12150 .addReg(PtrReg); 12151 BB->addSuccessor(exitMBB); 12152 12153 // exitMBB: 12154 // ... 12155 BB = exitMBB; 12156 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12157 .addReg(TmpReg) 12158 .addReg(ShiftReg); 12159 } else if (MI.getOpcode() == PPC::FADDrtz) { 12160 // This pseudo performs an FADD with rounding mode temporarily forced 12161 // to round-to-zero. We emit this via custom inserter since the FPSCR 12162 // is not modeled at the SelectionDAG level. 12163 Register Dest = MI.getOperand(0).getReg(); 12164 Register Src1 = MI.getOperand(1).getReg(); 12165 Register Src2 = MI.getOperand(2).getReg(); 12166 DebugLoc dl = MI.getDebugLoc(); 12167 12168 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12169 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12170 12171 // Save FPSCR value. 12172 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12173 12174 // Set rounding mode to round-to-zero. 12175 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12176 .addImm(31) 12177 .addReg(PPC::RM, RegState::ImplicitDefine); 12178 12179 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12180 .addImm(30) 12181 .addReg(PPC::RM, RegState::ImplicitDefine); 12182 12183 // Perform addition. 12184 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12185 .addReg(Src1) 12186 .addReg(Src2); 12187 if (MI.getFlag(MachineInstr::NoFPExcept)) 12188 MIB.setMIFlag(MachineInstr::NoFPExcept); 12189 12190 // Restore FPSCR value. 12191 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12192 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12193 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12194 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12195 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12196 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12197 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12198 ? PPC::ANDI8_rec 12199 : PPC::ANDI_rec; 12200 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12201 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12202 12203 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12204 Register Dest = RegInfo.createVirtualRegister( 12205 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12206 12207 DebugLoc Dl = MI.getDebugLoc(); 12208 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12209 .addReg(MI.getOperand(1).getReg()) 12210 .addImm(1); 12211 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12212 MI.getOperand(0).getReg()) 12213 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12214 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12215 DebugLoc Dl = MI.getDebugLoc(); 12216 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12217 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12218 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12219 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12220 MI.getOperand(0).getReg()) 12221 .addReg(CRReg); 12222 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12223 DebugLoc Dl = MI.getDebugLoc(); 12224 unsigned Imm = MI.getOperand(1).getImm(); 12225 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12226 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12227 MI.getOperand(0).getReg()) 12228 .addReg(PPC::CR0EQ); 12229 } else if (MI.getOpcode() == PPC::SETRNDi) { 12230 DebugLoc dl = MI.getDebugLoc(); 12231 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12232 12233 // Save FPSCR value. 12234 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12235 12236 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12237 // the following settings: 12238 // 00 Round to nearest 12239 // 01 Round to 0 12240 // 10 Round to +inf 12241 // 11 Round to -inf 12242 12243 // When the operand is immediate, using the two least significant bits of 12244 // the immediate to set the bits 62:63 of FPSCR. 12245 unsigned Mode = MI.getOperand(1).getImm(); 12246 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12247 .addImm(31) 12248 .addReg(PPC::RM, RegState::ImplicitDefine); 12249 12250 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12251 .addImm(30) 12252 .addReg(PPC::RM, RegState::ImplicitDefine); 12253 } else if (MI.getOpcode() == PPC::SETRND) { 12254 DebugLoc dl = MI.getDebugLoc(); 12255 12256 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12257 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12258 // If the target doesn't have DirectMove, we should use stack to do the 12259 // conversion, because the target doesn't have the instructions like mtvsrd 12260 // or mfvsrd to do this conversion directly. 12261 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12262 if (Subtarget.hasDirectMove()) { 12263 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12264 .addReg(SrcReg); 12265 } else { 12266 // Use stack to do the register copy. 12267 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12268 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12269 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12270 if (RC == &PPC::F8RCRegClass) { 12271 // Copy register from F8RCRegClass to G8RCRegclass. 12272 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12273 "Unsupported RegClass."); 12274 12275 StoreOp = PPC::STFD; 12276 LoadOp = PPC::LD; 12277 } else { 12278 // Copy register from G8RCRegClass to F8RCRegclass. 12279 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12280 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12281 "Unsupported RegClass."); 12282 } 12283 12284 MachineFrameInfo &MFI = F->getFrameInfo(); 12285 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12286 12287 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12288 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12289 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12290 MFI.getObjectAlign(FrameIdx)); 12291 12292 // Store the SrcReg into the stack. 12293 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12294 .addReg(SrcReg) 12295 .addImm(0) 12296 .addFrameIndex(FrameIdx) 12297 .addMemOperand(MMOStore); 12298 12299 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12300 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12301 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12302 MFI.getObjectAlign(FrameIdx)); 12303 12304 // Load from the stack where SrcReg is stored, and save to DestReg, 12305 // so we have done the RegClass conversion from RegClass::SrcReg to 12306 // RegClass::DestReg. 12307 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12308 .addImm(0) 12309 .addFrameIndex(FrameIdx) 12310 .addMemOperand(MMOLoad); 12311 } 12312 }; 12313 12314 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12315 12316 // Save FPSCR value. 12317 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12318 12319 // When the operand is gprc register, use two least significant bits of the 12320 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12321 // 12322 // copy OldFPSCRTmpReg, OldFPSCRReg 12323 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12324 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12325 // copy NewFPSCRReg, NewFPSCRTmpReg 12326 // mtfsf 255, NewFPSCRReg 12327 MachineOperand SrcOp = MI.getOperand(1); 12328 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12329 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12330 12331 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12332 12333 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12334 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12335 12336 // The first operand of INSERT_SUBREG should be a register which has 12337 // subregisters, we only care about its RegClass, so we should use an 12338 // IMPLICIT_DEF register. 12339 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12340 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12341 .addReg(ImDefReg) 12342 .add(SrcOp) 12343 .addImm(1); 12344 12345 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12346 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12347 .addReg(OldFPSCRTmpReg) 12348 .addReg(ExtSrcReg) 12349 .addImm(0) 12350 .addImm(62); 12351 12352 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12353 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12354 12355 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12356 // bits of FPSCR. 12357 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12358 .addImm(255) 12359 .addReg(NewFPSCRReg) 12360 .addImm(0) 12361 .addImm(0); 12362 } else if (MI.getOpcode() == PPC::SETFLM) { 12363 DebugLoc Dl = MI.getDebugLoc(); 12364 12365 // Result of setflm is previous FPSCR content, so we need to save it first. 12366 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12367 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12368 12369 // Put bits in 32:63 to FPSCR. 12370 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12371 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12372 .addImm(255) 12373 .addReg(NewFPSCRReg) 12374 .addImm(0) 12375 .addImm(0); 12376 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12377 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12378 return emitProbedAlloca(MI, BB); 12379 } else { 12380 llvm_unreachable("Unexpected instr type to insert"); 12381 } 12382 12383 MI.eraseFromParent(); // The pseudo instruction is gone now. 12384 return BB; 12385 } 12386 12387 //===----------------------------------------------------------------------===// 12388 // Target Optimization Hooks 12389 //===----------------------------------------------------------------------===// 12390 12391 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12392 // For the estimates, convergence is quadratic, so we essentially double the 12393 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12394 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12395 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12396 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12397 if (VT.getScalarType() == MVT::f64) 12398 RefinementSteps++; 12399 return RefinementSteps; 12400 } 12401 12402 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 12403 const DenormalMode &Mode) const { 12404 // We only have VSX Vector Test for software Square Root. 12405 EVT VT = Op.getValueType(); 12406 if (!isTypeLegal(MVT::i1) || 12407 (VT != MVT::f64 && 12408 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 12409 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 12410 12411 SDLoc DL(Op); 12412 // The output register of FTSQRT is CR field. 12413 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 12414 // ftsqrt BF,FRB 12415 // Let e_b be the unbiased exponent of the double-precision 12416 // floating-point operand in register FRB. 12417 // fe_flag is set to 1 if either of the following conditions occurs. 12418 // - The double-precision floating-point operand in register FRB is a zero, 12419 // a NaN, or an infinity, or a negative value. 12420 // - e_b is less than or equal to -970. 12421 // Otherwise fe_flag is set to 0. 12422 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 12423 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 12424 // exponent is less than -970) 12425 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 12426 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 12427 FTSQRT, SRIdxVal), 12428 0); 12429 } 12430 12431 SDValue 12432 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 12433 SelectionDAG &DAG) const { 12434 // We only have VSX Vector Square Root. 12435 EVT VT = Op.getValueType(); 12436 if (VT != MVT::f64 && 12437 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 12438 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 12439 12440 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 12441 } 12442 12443 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12444 int Enabled, int &RefinementSteps, 12445 bool &UseOneConstNR, 12446 bool Reciprocal) const { 12447 EVT VT = Operand.getValueType(); 12448 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12449 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12450 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12451 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12452 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12453 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12454 12455 // The Newton-Raphson computation with a single constant does not provide 12456 // enough accuracy on some CPUs. 12457 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12458 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12459 } 12460 return SDValue(); 12461 } 12462 12463 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12464 int Enabled, 12465 int &RefinementSteps) const { 12466 EVT VT = Operand.getValueType(); 12467 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12468 (VT == MVT::f64 && Subtarget.hasFRE()) || 12469 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12470 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12471 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12472 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12473 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12474 } 12475 return SDValue(); 12476 } 12477 12478 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12479 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12480 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12481 // enabled for division), this functionality is redundant with the default 12482 // combiner logic (once the division -> reciprocal/multiply transformation 12483 // has taken place). As a result, this matters more for older cores than for 12484 // newer ones. 12485 12486 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12487 // reciprocal if there are two or more FDIVs (for embedded cores with only 12488 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12489 switch (Subtarget.getCPUDirective()) { 12490 default: 12491 return 3; 12492 case PPC::DIR_440: 12493 case PPC::DIR_A2: 12494 case PPC::DIR_E500: 12495 case PPC::DIR_E500mc: 12496 case PPC::DIR_E5500: 12497 return 2; 12498 } 12499 } 12500 12501 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12502 // collapsed, and so we need to look through chains of them. 12503 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12504 int64_t& Offset, SelectionDAG &DAG) { 12505 if (DAG.isBaseWithConstantOffset(Loc)) { 12506 Base = Loc.getOperand(0); 12507 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12508 12509 // The base might itself be a base plus an offset, and if so, accumulate 12510 // that as well. 12511 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12512 } 12513 } 12514 12515 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12516 unsigned Bytes, int Dist, 12517 SelectionDAG &DAG) { 12518 if (VT.getSizeInBits() / 8 != Bytes) 12519 return false; 12520 12521 SDValue BaseLoc = Base->getBasePtr(); 12522 if (Loc.getOpcode() == ISD::FrameIndex) { 12523 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12524 return false; 12525 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12526 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12527 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12528 int FS = MFI.getObjectSize(FI); 12529 int BFS = MFI.getObjectSize(BFI); 12530 if (FS != BFS || FS != (int)Bytes) return false; 12531 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12532 } 12533 12534 SDValue Base1 = Loc, Base2 = BaseLoc; 12535 int64_t Offset1 = 0, Offset2 = 0; 12536 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12537 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12538 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12539 return true; 12540 12541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12542 const GlobalValue *GV1 = nullptr; 12543 const GlobalValue *GV2 = nullptr; 12544 Offset1 = 0; 12545 Offset2 = 0; 12546 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12547 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12548 if (isGA1 && isGA2 && GV1 == GV2) 12549 return Offset1 == (Offset2 + Dist*Bytes); 12550 return false; 12551 } 12552 12553 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12554 // not enforce equality of the chain operands. 12555 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12556 unsigned Bytes, int Dist, 12557 SelectionDAG &DAG) { 12558 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12559 EVT VT = LS->getMemoryVT(); 12560 SDValue Loc = LS->getBasePtr(); 12561 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12562 } 12563 12564 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12565 EVT VT; 12566 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12567 default: return false; 12568 case Intrinsic::ppc_altivec_lvx: 12569 case Intrinsic::ppc_altivec_lvxl: 12570 case Intrinsic::ppc_vsx_lxvw4x: 12571 case Intrinsic::ppc_vsx_lxvw4x_be: 12572 VT = MVT::v4i32; 12573 break; 12574 case Intrinsic::ppc_vsx_lxvd2x: 12575 case Intrinsic::ppc_vsx_lxvd2x_be: 12576 VT = MVT::v2f64; 12577 break; 12578 case Intrinsic::ppc_altivec_lvebx: 12579 VT = MVT::i8; 12580 break; 12581 case Intrinsic::ppc_altivec_lvehx: 12582 VT = MVT::i16; 12583 break; 12584 case Intrinsic::ppc_altivec_lvewx: 12585 VT = MVT::i32; 12586 break; 12587 } 12588 12589 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12590 } 12591 12592 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12593 EVT VT; 12594 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12595 default: return false; 12596 case Intrinsic::ppc_altivec_stvx: 12597 case Intrinsic::ppc_altivec_stvxl: 12598 case Intrinsic::ppc_vsx_stxvw4x: 12599 VT = MVT::v4i32; 12600 break; 12601 case Intrinsic::ppc_vsx_stxvd2x: 12602 VT = MVT::v2f64; 12603 break; 12604 case Intrinsic::ppc_vsx_stxvw4x_be: 12605 VT = MVT::v4i32; 12606 break; 12607 case Intrinsic::ppc_vsx_stxvd2x_be: 12608 VT = MVT::v2f64; 12609 break; 12610 case Intrinsic::ppc_altivec_stvebx: 12611 VT = MVT::i8; 12612 break; 12613 case Intrinsic::ppc_altivec_stvehx: 12614 VT = MVT::i16; 12615 break; 12616 case Intrinsic::ppc_altivec_stvewx: 12617 VT = MVT::i32; 12618 break; 12619 } 12620 12621 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12622 } 12623 12624 return false; 12625 } 12626 12627 // Return true is there is a nearyby consecutive load to the one provided 12628 // (regardless of alignment). We search up and down the chain, looking though 12629 // token factors and other loads (but nothing else). As a result, a true result 12630 // indicates that it is safe to create a new consecutive load adjacent to the 12631 // load provided. 12632 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12633 SDValue Chain = LD->getChain(); 12634 EVT VT = LD->getMemoryVT(); 12635 12636 SmallSet<SDNode *, 16> LoadRoots; 12637 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12638 SmallSet<SDNode *, 16> Visited; 12639 12640 // First, search up the chain, branching to follow all token-factor operands. 12641 // If we find a consecutive load, then we're done, otherwise, record all 12642 // nodes just above the top-level loads and token factors. 12643 while (!Queue.empty()) { 12644 SDNode *ChainNext = Queue.pop_back_val(); 12645 if (!Visited.insert(ChainNext).second) 12646 continue; 12647 12648 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12649 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12650 return true; 12651 12652 if (!Visited.count(ChainLD->getChain().getNode())) 12653 Queue.push_back(ChainLD->getChain().getNode()); 12654 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12655 for (const SDUse &O : ChainNext->ops()) 12656 if (!Visited.count(O.getNode())) 12657 Queue.push_back(O.getNode()); 12658 } else 12659 LoadRoots.insert(ChainNext); 12660 } 12661 12662 // Second, search down the chain, starting from the top-level nodes recorded 12663 // in the first phase. These top-level nodes are the nodes just above all 12664 // loads and token factors. Starting with their uses, recursively look though 12665 // all loads (just the chain uses) and token factors to find a consecutive 12666 // load. 12667 Visited.clear(); 12668 Queue.clear(); 12669 12670 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12671 IE = LoadRoots.end(); I != IE; ++I) { 12672 Queue.push_back(*I); 12673 12674 while (!Queue.empty()) { 12675 SDNode *LoadRoot = Queue.pop_back_val(); 12676 if (!Visited.insert(LoadRoot).second) 12677 continue; 12678 12679 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12680 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12681 return true; 12682 12683 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12684 UE = LoadRoot->use_end(); UI != UE; ++UI) 12685 if (((isa<MemSDNode>(*UI) && 12686 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12687 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12688 Queue.push_back(*UI); 12689 } 12690 } 12691 12692 return false; 12693 } 12694 12695 /// This function is called when we have proved that a SETCC node can be replaced 12696 /// by subtraction (and other supporting instructions) so that the result of 12697 /// comparison is kept in a GPR instead of CR. This function is purely for 12698 /// codegen purposes and has some flags to guide the codegen process. 12699 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12700 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12701 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12702 12703 // Zero extend the operands to the largest legal integer. Originally, they 12704 // must be of a strictly smaller size. 12705 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12706 DAG.getConstant(Size, DL, MVT::i32)); 12707 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12708 DAG.getConstant(Size, DL, MVT::i32)); 12709 12710 // Swap if needed. Depends on the condition code. 12711 if (Swap) 12712 std::swap(Op0, Op1); 12713 12714 // Subtract extended integers. 12715 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12716 12717 // Move the sign bit to the least significant position and zero out the rest. 12718 // Now the least significant bit carries the result of original comparison. 12719 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12720 DAG.getConstant(Size - 1, DL, MVT::i32)); 12721 auto Final = Shifted; 12722 12723 // Complement the result if needed. Based on the condition code. 12724 if (Complement) 12725 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12726 DAG.getConstant(1, DL, MVT::i64)); 12727 12728 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12729 } 12730 12731 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12732 DAGCombinerInfo &DCI) const { 12733 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12734 12735 SelectionDAG &DAG = DCI.DAG; 12736 SDLoc DL(N); 12737 12738 // Size of integers being compared has a critical role in the following 12739 // analysis, so we prefer to do this when all types are legal. 12740 if (!DCI.isAfterLegalizeDAG()) 12741 return SDValue(); 12742 12743 // If all users of SETCC extend its value to a legal integer type 12744 // then we replace SETCC with a subtraction 12745 for (SDNode::use_iterator UI = N->use_begin(), 12746 UE = N->use_end(); UI != UE; ++UI) { 12747 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12748 return SDValue(); 12749 } 12750 12751 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12752 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12753 12754 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12755 12756 if (OpSize < Size) { 12757 switch (CC) { 12758 default: break; 12759 case ISD::SETULT: 12760 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12761 case ISD::SETULE: 12762 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12763 case ISD::SETUGT: 12764 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12765 case ISD::SETUGE: 12766 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12767 } 12768 } 12769 12770 return SDValue(); 12771 } 12772 12773 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12774 DAGCombinerInfo &DCI) const { 12775 SelectionDAG &DAG = DCI.DAG; 12776 SDLoc dl(N); 12777 12778 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12779 // If we're tracking CR bits, we need to be careful that we don't have: 12780 // trunc(binary-ops(zext(x), zext(y))) 12781 // or 12782 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12783 // such that we're unnecessarily moving things into GPRs when it would be 12784 // better to keep them in CR bits. 12785 12786 // Note that trunc here can be an actual i1 trunc, or can be the effective 12787 // truncation that comes from a setcc or select_cc. 12788 if (N->getOpcode() == ISD::TRUNCATE && 12789 N->getValueType(0) != MVT::i1) 12790 return SDValue(); 12791 12792 if (N->getOperand(0).getValueType() != MVT::i32 && 12793 N->getOperand(0).getValueType() != MVT::i64) 12794 return SDValue(); 12795 12796 if (N->getOpcode() == ISD::SETCC || 12797 N->getOpcode() == ISD::SELECT_CC) { 12798 // If we're looking at a comparison, then we need to make sure that the 12799 // high bits (all except for the first) don't matter the result. 12800 ISD::CondCode CC = 12801 cast<CondCodeSDNode>(N->getOperand( 12802 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12803 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12804 12805 if (ISD::isSignedIntSetCC(CC)) { 12806 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12807 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12808 return SDValue(); 12809 } else if (ISD::isUnsignedIntSetCC(CC)) { 12810 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12811 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12812 !DAG.MaskedValueIsZero(N->getOperand(1), 12813 APInt::getHighBitsSet(OpBits, OpBits-1))) 12814 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12815 : SDValue()); 12816 } else { 12817 // This is neither a signed nor an unsigned comparison, just make sure 12818 // that the high bits are equal. 12819 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12820 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12821 12822 // We don't really care about what is known about the first bit (if 12823 // anything), so pretend that it is known zero for both to ensure they can 12824 // be compared as constants. 12825 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 12826 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 12827 12828 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 12829 Op1Known.getConstant() != Op2Known.getConstant()) 12830 return SDValue(); 12831 } 12832 } 12833 12834 // We now know that the higher-order bits are irrelevant, we just need to 12835 // make sure that all of the intermediate operations are bit operations, and 12836 // all inputs are extensions. 12837 if (N->getOperand(0).getOpcode() != ISD::AND && 12838 N->getOperand(0).getOpcode() != ISD::OR && 12839 N->getOperand(0).getOpcode() != ISD::XOR && 12840 N->getOperand(0).getOpcode() != ISD::SELECT && 12841 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12842 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12843 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12844 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12845 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12846 return SDValue(); 12847 12848 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12849 N->getOperand(1).getOpcode() != ISD::AND && 12850 N->getOperand(1).getOpcode() != ISD::OR && 12851 N->getOperand(1).getOpcode() != ISD::XOR && 12852 N->getOperand(1).getOpcode() != ISD::SELECT && 12853 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12854 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12855 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12856 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12857 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12858 return SDValue(); 12859 12860 SmallVector<SDValue, 4> Inputs; 12861 SmallVector<SDValue, 8> BinOps, PromOps; 12862 SmallPtrSet<SDNode *, 16> Visited; 12863 12864 for (unsigned i = 0; i < 2; ++i) { 12865 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12866 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12867 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12868 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12869 isa<ConstantSDNode>(N->getOperand(i))) 12870 Inputs.push_back(N->getOperand(i)); 12871 else 12872 BinOps.push_back(N->getOperand(i)); 12873 12874 if (N->getOpcode() == ISD::TRUNCATE) 12875 break; 12876 } 12877 12878 // Visit all inputs, collect all binary operations (and, or, xor and 12879 // select) that are all fed by extensions. 12880 while (!BinOps.empty()) { 12881 SDValue BinOp = BinOps.pop_back_val(); 12882 12883 if (!Visited.insert(BinOp.getNode()).second) 12884 continue; 12885 12886 PromOps.push_back(BinOp); 12887 12888 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12889 // The condition of the select is not promoted. 12890 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12891 continue; 12892 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12893 continue; 12894 12895 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12896 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12897 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12898 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12899 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12900 Inputs.push_back(BinOp.getOperand(i)); 12901 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12902 BinOp.getOperand(i).getOpcode() == ISD::OR || 12903 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12904 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12905 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12906 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12907 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12908 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12909 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12910 BinOps.push_back(BinOp.getOperand(i)); 12911 } else { 12912 // We have an input that is not an extension or another binary 12913 // operation; we'll abort this transformation. 12914 return SDValue(); 12915 } 12916 } 12917 } 12918 12919 // Make sure that this is a self-contained cluster of operations (which 12920 // is not quite the same thing as saying that everything has only one 12921 // use). 12922 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12923 if (isa<ConstantSDNode>(Inputs[i])) 12924 continue; 12925 12926 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12927 UE = Inputs[i].getNode()->use_end(); 12928 UI != UE; ++UI) { 12929 SDNode *User = *UI; 12930 if (User != N && !Visited.count(User)) 12931 return SDValue(); 12932 12933 // Make sure that we're not going to promote the non-output-value 12934 // operand(s) or SELECT or SELECT_CC. 12935 // FIXME: Although we could sometimes handle this, and it does occur in 12936 // practice that one of the condition inputs to the select is also one of 12937 // the outputs, we currently can't deal with this. 12938 if (User->getOpcode() == ISD::SELECT) { 12939 if (User->getOperand(0) == Inputs[i]) 12940 return SDValue(); 12941 } else if (User->getOpcode() == ISD::SELECT_CC) { 12942 if (User->getOperand(0) == Inputs[i] || 12943 User->getOperand(1) == Inputs[i]) 12944 return SDValue(); 12945 } 12946 } 12947 } 12948 12949 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12950 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12951 UE = PromOps[i].getNode()->use_end(); 12952 UI != UE; ++UI) { 12953 SDNode *User = *UI; 12954 if (User != N && !Visited.count(User)) 12955 return SDValue(); 12956 12957 // Make sure that we're not going to promote the non-output-value 12958 // operand(s) or SELECT or SELECT_CC. 12959 // FIXME: Although we could sometimes handle this, and it does occur in 12960 // practice that one of the condition inputs to the select is also one of 12961 // the outputs, we currently can't deal with this. 12962 if (User->getOpcode() == ISD::SELECT) { 12963 if (User->getOperand(0) == PromOps[i]) 12964 return SDValue(); 12965 } else if (User->getOpcode() == ISD::SELECT_CC) { 12966 if (User->getOperand(0) == PromOps[i] || 12967 User->getOperand(1) == PromOps[i]) 12968 return SDValue(); 12969 } 12970 } 12971 } 12972 12973 // Replace all inputs with the extension operand. 12974 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12975 // Constants may have users outside the cluster of to-be-promoted nodes, 12976 // and so we need to replace those as we do the promotions. 12977 if (isa<ConstantSDNode>(Inputs[i])) 12978 continue; 12979 else 12980 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12981 } 12982 12983 std::list<HandleSDNode> PromOpHandles; 12984 for (auto &PromOp : PromOps) 12985 PromOpHandles.emplace_back(PromOp); 12986 12987 // Replace all operations (these are all the same, but have a different 12988 // (i1) return type). DAG.getNode will validate that the types of 12989 // a binary operator match, so go through the list in reverse so that 12990 // we've likely promoted both operands first. Any intermediate truncations or 12991 // extensions disappear. 12992 while (!PromOpHandles.empty()) { 12993 SDValue PromOp = PromOpHandles.back().getValue(); 12994 PromOpHandles.pop_back(); 12995 12996 if (PromOp.getOpcode() == ISD::TRUNCATE || 12997 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12998 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12999 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13000 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13001 PromOp.getOperand(0).getValueType() != MVT::i1) { 13002 // The operand is not yet ready (see comment below). 13003 PromOpHandles.emplace_front(PromOp); 13004 continue; 13005 } 13006 13007 SDValue RepValue = PromOp.getOperand(0); 13008 if (isa<ConstantSDNode>(RepValue)) 13009 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13010 13011 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13012 continue; 13013 } 13014 13015 unsigned C; 13016 switch (PromOp.getOpcode()) { 13017 default: C = 0; break; 13018 case ISD::SELECT: C = 1; break; 13019 case ISD::SELECT_CC: C = 2; break; 13020 } 13021 13022 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13023 PromOp.getOperand(C).getValueType() != MVT::i1) || 13024 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13025 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13026 // The to-be-promoted operands of this node have not yet been 13027 // promoted (this should be rare because we're going through the 13028 // list backward, but if one of the operands has several users in 13029 // this cluster of to-be-promoted nodes, it is possible). 13030 PromOpHandles.emplace_front(PromOp); 13031 continue; 13032 } 13033 13034 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13035 PromOp.getNode()->op_end()); 13036 13037 // If there are any constant inputs, make sure they're replaced now. 13038 for (unsigned i = 0; i < 2; ++i) 13039 if (isa<ConstantSDNode>(Ops[C+i])) 13040 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13041 13042 DAG.ReplaceAllUsesOfValueWith(PromOp, 13043 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13044 } 13045 13046 // Now we're left with the initial truncation itself. 13047 if (N->getOpcode() == ISD::TRUNCATE) 13048 return N->getOperand(0); 13049 13050 // Otherwise, this is a comparison. The operands to be compared have just 13051 // changed type (to i1), but everything else is the same. 13052 return SDValue(N, 0); 13053 } 13054 13055 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13056 DAGCombinerInfo &DCI) const { 13057 SelectionDAG &DAG = DCI.DAG; 13058 SDLoc dl(N); 13059 13060 // If we're tracking CR bits, we need to be careful that we don't have: 13061 // zext(binary-ops(trunc(x), trunc(y))) 13062 // or 13063 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13064 // such that we're unnecessarily moving things into CR bits that can more 13065 // efficiently stay in GPRs. Note that if we're not certain that the high 13066 // bits are set as required by the final extension, we still may need to do 13067 // some masking to get the proper behavior. 13068 13069 // This same functionality is important on PPC64 when dealing with 13070 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13071 // the return values of functions. Because it is so similar, it is handled 13072 // here as well. 13073 13074 if (N->getValueType(0) != MVT::i32 && 13075 N->getValueType(0) != MVT::i64) 13076 return SDValue(); 13077 13078 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13079 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13080 return SDValue(); 13081 13082 if (N->getOperand(0).getOpcode() != ISD::AND && 13083 N->getOperand(0).getOpcode() != ISD::OR && 13084 N->getOperand(0).getOpcode() != ISD::XOR && 13085 N->getOperand(0).getOpcode() != ISD::SELECT && 13086 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13087 return SDValue(); 13088 13089 SmallVector<SDValue, 4> Inputs; 13090 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13091 SmallPtrSet<SDNode *, 16> Visited; 13092 13093 // Visit all inputs, collect all binary operations (and, or, xor and 13094 // select) that are all fed by truncations. 13095 while (!BinOps.empty()) { 13096 SDValue BinOp = BinOps.pop_back_val(); 13097 13098 if (!Visited.insert(BinOp.getNode()).second) 13099 continue; 13100 13101 PromOps.push_back(BinOp); 13102 13103 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13104 // The condition of the select is not promoted. 13105 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13106 continue; 13107 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13108 continue; 13109 13110 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13111 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13112 Inputs.push_back(BinOp.getOperand(i)); 13113 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13114 BinOp.getOperand(i).getOpcode() == ISD::OR || 13115 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13116 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13117 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13118 BinOps.push_back(BinOp.getOperand(i)); 13119 } else { 13120 // We have an input that is not a truncation or another binary 13121 // operation; we'll abort this transformation. 13122 return SDValue(); 13123 } 13124 } 13125 } 13126 13127 // The operands of a select that must be truncated when the select is 13128 // promoted because the operand is actually part of the to-be-promoted set. 13129 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13130 13131 // Make sure that this is a self-contained cluster of operations (which 13132 // is not quite the same thing as saying that everything has only one 13133 // use). 13134 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13135 if (isa<ConstantSDNode>(Inputs[i])) 13136 continue; 13137 13138 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13139 UE = Inputs[i].getNode()->use_end(); 13140 UI != UE; ++UI) { 13141 SDNode *User = *UI; 13142 if (User != N && !Visited.count(User)) 13143 return SDValue(); 13144 13145 // If we're going to promote the non-output-value operand(s) or SELECT or 13146 // SELECT_CC, record them for truncation. 13147 if (User->getOpcode() == ISD::SELECT) { 13148 if (User->getOperand(0) == Inputs[i]) 13149 SelectTruncOp[0].insert(std::make_pair(User, 13150 User->getOperand(0).getValueType())); 13151 } else if (User->getOpcode() == ISD::SELECT_CC) { 13152 if (User->getOperand(0) == Inputs[i]) 13153 SelectTruncOp[0].insert(std::make_pair(User, 13154 User->getOperand(0).getValueType())); 13155 if (User->getOperand(1) == Inputs[i]) 13156 SelectTruncOp[1].insert(std::make_pair(User, 13157 User->getOperand(1).getValueType())); 13158 } 13159 } 13160 } 13161 13162 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13163 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13164 UE = PromOps[i].getNode()->use_end(); 13165 UI != UE; ++UI) { 13166 SDNode *User = *UI; 13167 if (User != N && !Visited.count(User)) 13168 return SDValue(); 13169 13170 // If we're going to promote the non-output-value operand(s) or SELECT or 13171 // SELECT_CC, record them for truncation. 13172 if (User->getOpcode() == ISD::SELECT) { 13173 if (User->getOperand(0) == PromOps[i]) 13174 SelectTruncOp[0].insert(std::make_pair(User, 13175 User->getOperand(0).getValueType())); 13176 } else if (User->getOpcode() == ISD::SELECT_CC) { 13177 if (User->getOperand(0) == PromOps[i]) 13178 SelectTruncOp[0].insert(std::make_pair(User, 13179 User->getOperand(0).getValueType())); 13180 if (User->getOperand(1) == PromOps[i]) 13181 SelectTruncOp[1].insert(std::make_pair(User, 13182 User->getOperand(1).getValueType())); 13183 } 13184 } 13185 } 13186 13187 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13188 bool ReallyNeedsExt = false; 13189 if (N->getOpcode() != ISD::ANY_EXTEND) { 13190 // If all of the inputs are not already sign/zero extended, then 13191 // we'll still need to do that at the end. 13192 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13193 if (isa<ConstantSDNode>(Inputs[i])) 13194 continue; 13195 13196 unsigned OpBits = 13197 Inputs[i].getOperand(0).getValueSizeInBits(); 13198 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13199 13200 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13201 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13202 APInt::getHighBitsSet(OpBits, 13203 OpBits-PromBits))) || 13204 (N->getOpcode() == ISD::SIGN_EXTEND && 13205 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13206 (OpBits-(PromBits-1)))) { 13207 ReallyNeedsExt = true; 13208 break; 13209 } 13210 } 13211 } 13212 13213 // Replace all inputs, either with the truncation operand, or a 13214 // truncation or extension to the final output type. 13215 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13216 // Constant inputs need to be replaced with the to-be-promoted nodes that 13217 // use them because they might have users outside of the cluster of 13218 // promoted nodes. 13219 if (isa<ConstantSDNode>(Inputs[i])) 13220 continue; 13221 13222 SDValue InSrc = Inputs[i].getOperand(0); 13223 if (Inputs[i].getValueType() == N->getValueType(0)) 13224 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13225 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13226 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13227 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13228 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13229 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13230 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13231 else 13232 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13233 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13234 } 13235 13236 std::list<HandleSDNode> PromOpHandles; 13237 for (auto &PromOp : PromOps) 13238 PromOpHandles.emplace_back(PromOp); 13239 13240 // Replace all operations (these are all the same, but have a different 13241 // (promoted) return type). DAG.getNode will validate that the types of 13242 // a binary operator match, so go through the list in reverse so that 13243 // we've likely promoted both operands first. 13244 while (!PromOpHandles.empty()) { 13245 SDValue PromOp = PromOpHandles.back().getValue(); 13246 PromOpHandles.pop_back(); 13247 13248 unsigned C; 13249 switch (PromOp.getOpcode()) { 13250 default: C = 0; break; 13251 case ISD::SELECT: C = 1; break; 13252 case ISD::SELECT_CC: C = 2; break; 13253 } 13254 13255 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13256 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13257 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13258 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13259 // The to-be-promoted operands of this node have not yet been 13260 // promoted (this should be rare because we're going through the 13261 // list backward, but if one of the operands has several users in 13262 // this cluster of to-be-promoted nodes, it is possible). 13263 PromOpHandles.emplace_front(PromOp); 13264 continue; 13265 } 13266 13267 // For SELECT and SELECT_CC nodes, we do a similar check for any 13268 // to-be-promoted comparison inputs. 13269 if (PromOp.getOpcode() == ISD::SELECT || 13270 PromOp.getOpcode() == ISD::SELECT_CC) { 13271 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13272 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13273 (SelectTruncOp[1].count(PromOp.getNode()) && 13274 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13275 PromOpHandles.emplace_front(PromOp); 13276 continue; 13277 } 13278 } 13279 13280 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13281 PromOp.getNode()->op_end()); 13282 13283 // If this node has constant inputs, then they'll need to be promoted here. 13284 for (unsigned i = 0; i < 2; ++i) { 13285 if (!isa<ConstantSDNode>(Ops[C+i])) 13286 continue; 13287 if (Ops[C+i].getValueType() == N->getValueType(0)) 13288 continue; 13289 13290 if (N->getOpcode() == ISD::SIGN_EXTEND) 13291 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13292 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13293 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13294 else 13295 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13296 } 13297 13298 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13299 // truncate them again to the original value type. 13300 if (PromOp.getOpcode() == ISD::SELECT || 13301 PromOp.getOpcode() == ISD::SELECT_CC) { 13302 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13303 if (SI0 != SelectTruncOp[0].end()) 13304 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13305 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13306 if (SI1 != SelectTruncOp[1].end()) 13307 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13308 } 13309 13310 DAG.ReplaceAllUsesOfValueWith(PromOp, 13311 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13312 } 13313 13314 // Now we're left with the initial extension itself. 13315 if (!ReallyNeedsExt) 13316 return N->getOperand(0); 13317 13318 // To zero extend, just mask off everything except for the first bit (in the 13319 // i1 case). 13320 if (N->getOpcode() == ISD::ZERO_EXTEND) 13321 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13322 DAG.getConstant(APInt::getLowBitsSet( 13323 N->getValueSizeInBits(0), PromBits), 13324 dl, N->getValueType(0))); 13325 13326 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13327 "Invalid extension type"); 13328 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13329 SDValue ShiftCst = 13330 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13331 return DAG.getNode( 13332 ISD::SRA, dl, N->getValueType(0), 13333 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13334 ShiftCst); 13335 } 13336 13337 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13338 DAGCombinerInfo &DCI) const { 13339 assert(N->getOpcode() == ISD::SETCC && 13340 "Should be called with a SETCC node"); 13341 13342 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13343 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13344 SDValue LHS = N->getOperand(0); 13345 SDValue RHS = N->getOperand(1); 13346 13347 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13348 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13349 LHS.hasOneUse()) 13350 std::swap(LHS, RHS); 13351 13352 // x == 0-y --> x+y == 0 13353 // x != 0-y --> x+y != 0 13354 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13355 RHS.hasOneUse()) { 13356 SDLoc DL(N); 13357 SelectionDAG &DAG = DCI.DAG; 13358 EVT VT = N->getValueType(0); 13359 EVT OpVT = LHS.getValueType(); 13360 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13361 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13362 } 13363 } 13364 13365 return DAGCombineTruncBoolExt(N, DCI); 13366 } 13367 13368 // Is this an extending load from an f32 to an f64? 13369 static bool isFPExtLoad(SDValue Op) { 13370 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13371 return LD->getExtensionType() == ISD::EXTLOAD && 13372 Op.getValueType() == MVT::f64; 13373 return false; 13374 } 13375 13376 /// Reduces the number of fp-to-int conversion when building a vector. 13377 /// 13378 /// If this vector is built out of floating to integer conversions, 13379 /// transform it to a vector built out of floating point values followed by a 13380 /// single floating to integer conversion of the vector. 13381 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13382 /// becomes (fptosi (build_vector ($A, $B, ...))) 13383 SDValue PPCTargetLowering:: 13384 combineElementTruncationToVectorTruncation(SDNode *N, 13385 DAGCombinerInfo &DCI) const { 13386 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13387 "Should be called with a BUILD_VECTOR node"); 13388 13389 SelectionDAG &DAG = DCI.DAG; 13390 SDLoc dl(N); 13391 13392 SDValue FirstInput = N->getOperand(0); 13393 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13394 "The input operand must be an fp-to-int conversion."); 13395 13396 // This combine happens after legalization so the fp_to_[su]i nodes are 13397 // already converted to PPCSISD nodes. 13398 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13399 if (FirstConversion == PPCISD::FCTIDZ || 13400 FirstConversion == PPCISD::FCTIDUZ || 13401 FirstConversion == PPCISD::FCTIWZ || 13402 FirstConversion == PPCISD::FCTIWUZ) { 13403 bool IsSplat = true; 13404 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13405 FirstConversion == PPCISD::FCTIWUZ; 13406 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13407 SmallVector<SDValue, 4> Ops; 13408 EVT TargetVT = N->getValueType(0); 13409 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13410 SDValue NextOp = N->getOperand(i); 13411 if (NextOp.getOpcode() != PPCISD::MFVSR) 13412 return SDValue(); 13413 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13414 if (NextConversion != FirstConversion) 13415 return SDValue(); 13416 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13417 // This is not valid if the input was originally double precision. It is 13418 // also not profitable to do unless this is an extending load in which 13419 // case doing this combine will allow us to combine consecutive loads. 13420 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13421 return SDValue(); 13422 if (N->getOperand(i) != FirstInput) 13423 IsSplat = false; 13424 } 13425 13426 // If this is a splat, we leave it as-is since there will be only a single 13427 // fp-to-int conversion followed by a splat of the integer. This is better 13428 // for 32-bit and smaller ints and neutral for 64-bit ints. 13429 if (IsSplat) 13430 return SDValue(); 13431 13432 // Now that we know we have the right type of node, get its operands 13433 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13434 SDValue In = N->getOperand(i).getOperand(0); 13435 if (Is32Bit) { 13436 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13437 // here, we know that all inputs are extending loads so this is safe). 13438 if (In.isUndef()) 13439 Ops.push_back(DAG.getUNDEF(SrcVT)); 13440 else { 13441 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13442 MVT::f32, In.getOperand(0), 13443 DAG.getIntPtrConstant(1, dl)); 13444 Ops.push_back(Trunc); 13445 } 13446 } else 13447 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13448 } 13449 13450 unsigned Opcode; 13451 if (FirstConversion == PPCISD::FCTIDZ || 13452 FirstConversion == PPCISD::FCTIWZ) 13453 Opcode = ISD::FP_TO_SINT; 13454 else 13455 Opcode = ISD::FP_TO_UINT; 13456 13457 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13458 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13459 return DAG.getNode(Opcode, dl, TargetVT, BV); 13460 } 13461 return SDValue(); 13462 } 13463 13464 /// Reduce the number of loads when building a vector. 13465 /// 13466 /// Building a vector out of multiple loads can be converted to a load 13467 /// of the vector type if the loads are consecutive. If the loads are 13468 /// consecutive but in descending order, a shuffle is added at the end 13469 /// to reorder the vector. 13470 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13471 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13472 "Should be called with a BUILD_VECTOR node"); 13473 13474 SDLoc dl(N); 13475 13476 // Return early for non byte-sized type, as they can't be consecutive. 13477 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13478 return SDValue(); 13479 13480 bool InputsAreConsecutiveLoads = true; 13481 bool InputsAreReverseConsecutive = true; 13482 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13483 SDValue FirstInput = N->getOperand(0); 13484 bool IsRoundOfExtLoad = false; 13485 13486 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13487 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13488 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13489 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13490 } 13491 // Not a build vector of (possibly fp_rounded) loads. 13492 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13493 N->getNumOperands() == 1) 13494 return SDValue(); 13495 13496 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13497 // If any inputs are fp_round(extload), they all must be. 13498 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13499 return SDValue(); 13500 13501 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13502 N->getOperand(i); 13503 if (NextInput.getOpcode() != ISD::LOAD) 13504 return SDValue(); 13505 13506 SDValue PreviousInput = 13507 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13508 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13509 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13510 13511 // If any inputs are fp_round(extload), they all must be. 13512 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13513 return SDValue(); 13514 13515 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13516 InputsAreConsecutiveLoads = false; 13517 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13518 InputsAreReverseConsecutive = false; 13519 13520 // Exit early if the loads are neither consecutive nor reverse consecutive. 13521 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13522 return SDValue(); 13523 } 13524 13525 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13526 "The loads cannot be both consecutive and reverse consecutive."); 13527 13528 SDValue FirstLoadOp = 13529 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13530 SDValue LastLoadOp = 13531 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13532 N->getOperand(N->getNumOperands()-1); 13533 13534 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13535 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13536 if (InputsAreConsecutiveLoads) { 13537 assert(LD1 && "Input needs to be a LoadSDNode."); 13538 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13539 LD1->getBasePtr(), LD1->getPointerInfo(), 13540 LD1->getAlignment()); 13541 } 13542 if (InputsAreReverseConsecutive) { 13543 assert(LDL && "Input needs to be a LoadSDNode."); 13544 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13545 LDL->getBasePtr(), LDL->getPointerInfo(), 13546 LDL->getAlignment()); 13547 SmallVector<int, 16> Ops; 13548 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13549 Ops.push_back(i); 13550 13551 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13552 DAG.getUNDEF(N->getValueType(0)), Ops); 13553 } 13554 return SDValue(); 13555 } 13556 13557 // This function adds the required vector_shuffle needed to get 13558 // the elements of the vector extract in the correct position 13559 // as specified by the CorrectElems encoding. 13560 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13561 SDValue Input, uint64_t Elems, 13562 uint64_t CorrectElems) { 13563 SDLoc dl(N); 13564 13565 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13566 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13567 13568 // Knowing the element indices being extracted from the original 13569 // vector and the order in which they're being inserted, just put 13570 // them at element indices required for the instruction. 13571 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13572 if (DAG.getDataLayout().isLittleEndian()) 13573 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13574 else 13575 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13576 CorrectElems = CorrectElems >> 8; 13577 Elems = Elems >> 8; 13578 } 13579 13580 SDValue Shuffle = 13581 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13582 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13583 13584 EVT VT = N->getValueType(0); 13585 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13586 13587 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13588 Input.getValueType().getVectorElementType(), 13589 VT.getVectorNumElements()); 13590 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13591 DAG.getValueType(ExtVT)); 13592 } 13593 13594 // Look for build vector patterns where input operands come from sign 13595 // extended vector_extract elements of specific indices. If the correct indices 13596 // aren't used, add a vector shuffle to fix up the indices and create 13597 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13598 // during instruction selection. 13599 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13600 // This array encodes the indices that the vector sign extend instructions 13601 // extract from when extending from one type to another for both BE and LE. 13602 // The right nibble of each byte corresponds to the LE incides. 13603 // and the left nibble of each byte corresponds to the BE incides. 13604 // For example: 0x3074B8FC byte->word 13605 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13606 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13607 // For example: 0x000070F8 byte->double word 13608 // For LE: the allowed indices are: 0x0,0x8 13609 // For BE: the allowed indices are: 0x7,0xF 13610 uint64_t TargetElems[] = { 13611 0x3074B8FC, // b->w 13612 0x000070F8, // b->d 13613 0x10325476, // h->w 13614 0x00003074, // h->d 13615 0x00001032, // w->d 13616 }; 13617 13618 uint64_t Elems = 0; 13619 int Index; 13620 SDValue Input; 13621 13622 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13623 if (!Op) 13624 return false; 13625 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13626 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13627 return false; 13628 13629 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13630 // of the right width. 13631 SDValue Extract = Op.getOperand(0); 13632 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13633 Extract = Extract.getOperand(0); 13634 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13635 return false; 13636 13637 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13638 if (!ExtOp) 13639 return false; 13640 13641 Index = ExtOp->getZExtValue(); 13642 if (Input && Input != Extract.getOperand(0)) 13643 return false; 13644 13645 if (!Input) 13646 Input = Extract.getOperand(0); 13647 13648 Elems = Elems << 8; 13649 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13650 Elems |= Index; 13651 13652 return true; 13653 }; 13654 13655 // If the build vector operands aren't sign extended vector extracts, 13656 // of the same input vector, then return. 13657 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13658 if (!isSExtOfVecExtract(N->getOperand(i))) { 13659 return SDValue(); 13660 } 13661 } 13662 13663 // If the vector extract indicies are not correct, add the appropriate 13664 // vector_shuffle. 13665 int TgtElemArrayIdx; 13666 int InputSize = Input.getValueType().getScalarSizeInBits(); 13667 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13668 if (InputSize + OutputSize == 40) 13669 TgtElemArrayIdx = 0; 13670 else if (InputSize + OutputSize == 72) 13671 TgtElemArrayIdx = 1; 13672 else if (InputSize + OutputSize == 48) 13673 TgtElemArrayIdx = 2; 13674 else if (InputSize + OutputSize == 80) 13675 TgtElemArrayIdx = 3; 13676 else if (InputSize + OutputSize == 96) 13677 TgtElemArrayIdx = 4; 13678 else 13679 return SDValue(); 13680 13681 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13682 CorrectElems = DAG.getDataLayout().isLittleEndian() 13683 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13684 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13685 if (Elems != CorrectElems) { 13686 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13687 } 13688 13689 // Regular lowering will catch cases where a shuffle is not needed. 13690 return SDValue(); 13691 } 13692 13693 // Look for the pattern of a load from a narrow width to i128, feeding 13694 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13695 // (LXVRZX). This node represents a zero extending load that will be matched 13696 // to the Load VSX Vector Rightmost instructions. 13697 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13698 SDLoc DL(N); 13699 13700 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13701 if (N->getValueType(0) != MVT::v1i128) 13702 return SDValue(); 13703 13704 SDValue Operand = N->getOperand(0); 13705 // Proceed with the transformation if the operand to the BUILD_VECTOR 13706 // is a load instruction. 13707 if (Operand.getOpcode() != ISD::LOAD) 13708 return SDValue(); 13709 13710 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13711 EVT MemoryType = LD->getMemoryVT(); 13712 13713 // This transformation is only valid if the we are loading either a byte, 13714 // halfword, word, or doubleword. 13715 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13716 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13717 13718 // Ensure that the load from the narrow width is being zero extended to i128. 13719 if (!ValidLDType || 13720 (LD->getExtensionType() != ISD::ZEXTLOAD && 13721 LD->getExtensionType() != ISD::EXTLOAD)) 13722 return SDValue(); 13723 13724 SDValue LoadOps[] = { 13725 LD->getChain(), LD->getBasePtr(), 13726 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13727 13728 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13729 DAG.getVTList(MVT::v1i128, MVT::Other), 13730 LoadOps, MemoryType, LD->getMemOperand()); 13731 } 13732 13733 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13734 DAGCombinerInfo &DCI) const { 13735 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13736 "Should be called with a BUILD_VECTOR node"); 13737 13738 SelectionDAG &DAG = DCI.DAG; 13739 SDLoc dl(N); 13740 13741 if (!Subtarget.hasVSX()) 13742 return SDValue(); 13743 13744 // The target independent DAG combiner will leave a build_vector of 13745 // float-to-int conversions intact. We can generate MUCH better code for 13746 // a float-to-int conversion of a vector of floats. 13747 SDValue FirstInput = N->getOperand(0); 13748 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13749 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13750 if (Reduced) 13751 return Reduced; 13752 } 13753 13754 // If we're building a vector out of consecutive loads, just load that 13755 // vector type. 13756 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13757 if (Reduced) 13758 return Reduced; 13759 13760 // If we're building a vector out of extended elements from another vector 13761 // we have P9 vector integer extend instructions. The code assumes legal 13762 // input types (i.e. it can't handle things like v4i16) so do not run before 13763 // legalization. 13764 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13765 Reduced = combineBVOfVecSExt(N, DAG); 13766 if (Reduced) 13767 return Reduced; 13768 } 13769 13770 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13771 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13772 // is a load from <valid narrow width> to i128. 13773 if (Subtarget.isISA3_1()) { 13774 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13775 if (BVOfZLoad) 13776 return BVOfZLoad; 13777 } 13778 13779 if (N->getValueType(0) != MVT::v2f64) 13780 return SDValue(); 13781 13782 // Looking for: 13783 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13784 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13785 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13786 return SDValue(); 13787 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13788 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13789 return SDValue(); 13790 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13791 return SDValue(); 13792 13793 SDValue Ext1 = FirstInput.getOperand(0); 13794 SDValue Ext2 = N->getOperand(1).getOperand(0); 13795 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13796 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13797 return SDValue(); 13798 13799 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13800 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13801 if (!Ext1Op || !Ext2Op) 13802 return SDValue(); 13803 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13804 Ext1.getOperand(0) != Ext2.getOperand(0)) 13805 return SDValue(); 13806 13807 int FirstElem = Ext1Op->getZExtValue(); 13808 int SecondElem = Ext2Op->getZExtValue(); 13809 int SubvecIdx; 13810 if (FirstElem == 0 && SecondElem == 1) 13811 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13812 else if (FirstElem == 2 && SecondElem == 3) 13813 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13814 else 13815 return SDValue(); 13816 13817 SDValue SrcVec = Ext1.getOperand(0); 13818 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13819 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13820 return DAG.getNode(NodeType, dl, MVT::v2f64, 13821 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13822 } 13823 13824 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13825 DAGCombinerInfo &DCI) const { 13826 assert((N->getOpcode() == ISD::SINT_TO_FP || 13827 N->getOpcode() == ISD::UINT_TO_FP) && 13828 "Need an int -> FP conversion node here"); 13829 13830 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13831 return SDValue(); 13832 13833 SelectionDAG &DAG = DCI.DAG; 13834 SDLoc dl(N); 13835 SDValue Op(N, 0); 13836 13837 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13838 // from the hardware. 13839 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13840 return SDValue(); 13841 if (!Op.getOperand(0).getValueType().isSimple()) 13842 return SDValue(); 13843 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13844 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13845 return SDValue(); 13846 13847 SDValue FirstOperand(Op.getOperand(0)); 13848 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13849 (FirstOperand.getValueType() == MVT::i8 || 13850 FirstOperand.getValueType() == MVT::i16); 13851 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13852 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13853 bool DstDouble = Op.getValueType() == MVT::f64; 13854 unsigned ConvOp = Signed ? 13855 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13856 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13857 SDValue WidthConst = 13858 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13859 dl, false); 13860 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13861 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13862 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13863 DAG.getVTList(MVT::f64, MVT::Other), 13864 Ops, MVT::i8, LDN->getMemOperand()); 13865 13866 // For signed conversion, we need to sign-extend the value in the VSR 13867 if (Signed) { 13868 SDValue ExtOps[] = { Ld, WidthConst }; 13869 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13870 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13871 } else 13872 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13873 } 13874 13875 13876 // For i32 intermediate values, unfortunately, the conversion functions 13877 // leave the upper 32 bits of the value are undefined. Within the set of 13878 // scalar instructions, we have no method for zero- or sign-extending the 13879 // value. Thus, we cannot handle i32 intermediate values here. 13880 if (Op.getOperand(0).getValueType() == MVT::i32) 13881 return SDValue(); 13882 13883 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13884 "UINT_TO_FP is supported only with FPCVT"); 13885 13886 // If we have FCFIDS, then use it when converting to single-precision. 13887 // Otherwise, convert to double-precision and then round. 13888 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13889 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13890 : PPCISD::FCFIDS) 13891 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13892 : PPCISD::FCFID); 13893 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13894 ? MVT::f32 13895 : MVT::f64; 13896 13897 // If we're converting from a float, to an int, and back to a float again, 13898 // then we don't need the store/load pair at all. 13899 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13900 Subtarget.hasFPCVT()) || 13901 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13902 SDValue Src = Op.getOperand(0).getOperand(0); 13903 if (Src.getValueType() == MVT::f32) { 13904 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13905 DCI.AddToWorklist(Src.getNode()); 13906 } else if (Src.getValueType() != MVT::f64) { 13907 // Make sure that we don't pick up a ppc_fp128 source value. 13908 return SDValue(); 13909 } 13910 13911 unsigned FCTOp = 13912 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13913 PPCISD::FCTIDUZ; 13914 13915 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13916 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13917 13918 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13919 FP = DAG.getNode(ISD::FP_ROUND, dl, 13920 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13921 DCI.AddToWorklist(FP.getNode()); 13922 } 13923 13924 return FP; 13925 } 13926 13927 return SDValue(); 13928 } 13929 13930 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13931 // builtins) into loads with swaps. 13932 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13933 DAGCombinerInfo &DCI) const { 13934 SelectionDAG &DAG = DCI.DAG; 13935 SDLoc dl(N); 13936 SDValue Chain; 13937 SDValue Base; 13938 MachineMemOperand *MMO; 13939 13940 switch (N->getOpcode()) { 13941 default: 13942 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13943 case ISD::LOAD: { 13944 LoadSDNode *LD = cast<LoadSDNode>(N); 13945 Chain = LD->getChain(); 13946 Base = LD->getBasePtr(); 13947 MMO = LD->getMemOperand(); 13948 // If the MMO suggests this isn't a load of a full vector, leave 13949 // things alone. For a built-in, we have to make the change for 13950 // correctness, so if there is a size problem that will be a bug. 13951 if (MMO->getSize() < 16) 13952 return SDValue(); 13953 break; 13954 } 13955 case ISD::INTRINSIC_W_CHAIN: { 13956 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13957 Chain = Intrin->getChain(); 13958 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13959 // us what we want. Get operand 2 instead. 13960 Base = Intrin->getOperand(2); 13961 MMO = Intrin->getMemOperand(); 13962 break; 13963 } 13964 } 13965 13966 MVT VecTy = N->getValueType(0).getSimpleVT(); 13967 13968 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13969 // aligned and the type is a vector with elements up to 4 bytes 13970 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13971 VecTy.getScalarSizeInBits() <= 32) { 13972 return SDValue(); 13973 } 13974 13975 SDValue LoadOps[] = { Chain, Base }; 13976 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13977 DAG.getVTList(MVT::v2f64, MVT::Other), 13978 LoadOps, MVT::v2f64, MMO); 13979 13980 DCI.AddToWorklist(Load.getNode()); 13981 Chain = Load.getValue(1); 13982 SDValue Swap = DAG.getNode( 13983 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13984 DCI.AddToWorklist(Swap.getNode()); 13985 13986 // Add a bitcast if the resulting load type doesn't match v2f64. 13987 if (VecTy != MVT::v2f64) { 13988 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13989 DCI.AddToWorklist(N.getNode()); 13990 // Package {bitcast value, swap's chain} to match Load's shape. 13991 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13992 N, Swap.getValue(1)); 13993 } 13994 13995 return Swap; 13996 } 13997 13998 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13999 // builtins) into stores with swaps. 14000 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14001 DAGCombinerInfo &DCI) const { 14002 SelectionDAG &DAG = DCI.DAG; 14003 SDLoc dl(N); 14004 SDValue Chain; 14005 SDValue Base; 14006 unsigned SrcOpnd; 14007 MachineMemOperand *MMO; 14008 14009 switch (N->getOpcode()) { 14010 default: 14011 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14012 case ISD::STORE: { 14013 StoreSDNode *ST = cast<StoreSDNode>(N); 14014 Chain = ST->getChain(); 14015 Base = ST->getBasePtr(); 14016 MMO = ST->getMemOperand(); 14017 SrcOpnd = 1; 14018 // If the MMO suggests this isn't a store of a full vector, leave 14019 // things alone. For a built-in, we have to make the change for 14020 // correctness, so if there is a size problem that will be a bug. 14021 if (MMO->getSize() < 16) 14022 return SDValue(); 14023 break; 14024 } 14025 case ISD::INTRINSIC_VOID: { 14026 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14027 Chain = Intrin->getChain(); 14028 // Intrin->getBasePtr() oddly does not get what we want. 14029 Base = Intrin->getOperand(3); 14030 MMO = Intrin->getMemOperand(); 14031 SrcOpnd = 2; 14032 break; 14033 } 14034 } 14035 14036 SDValue Src = N->getOperand(SrcOpnd); 14037 MVT VecTy = Src.getValueType().getSimpleVT(); 14038 14039 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14040 // aligned and the type is a vector with elements up to 4 bytes 14041 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14042 VecTy.getScalarSizeInBits() <= 32) { 14043 return SDValue(); 14044 } 14045 14046 // All stores are done as v2f64 and possible bit cast. 14047 if (VecTy != MVT::v2f64) { 14048 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14049 DCI.AddToWorklist(Src.getNode()); 14050 } 14051 14052 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14053 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14054 DCI.AddToWorklist(Swap.getNode()); 14055 Chain = Swap.getValue(1); 14056 SDValue StoreOps[] = { Chain, Swap, Base }; 14057 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14058 DAG.getVTList(MVT::Other), 14059 StoreOps, VecTy, MMO); 14060 DCI.AddToWorklist(Store.getNode()); 14061 return Store; 14062 } 14063 14064 // Handle DAG combine for STORE (FP_TO_INT F). 14065 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14066 DAGCombinerInfo &DCI) const { 14067 14068 SelectionDAG &DAG = DCI.DAG; 14069 SDLoc dl(N); 14070 unsigned Opcode = N->getOperand(1).getOpcode(); 14071 14072 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14073 && "Not a FP_TO_INT Instruction!"); 14074 14075 SDValue Val = N->getOperand(1).getOperand(0); 14076 EVT Op1VT = N->getOperand(1).getValueType(); 14077 EVT ResVT = Val.getValueType(); 14078 14079 if (!isTypeLegal(ResVT)) 14080 return SDValue(); 14081 14082 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14083 bool ValidTypeForStoreFltAsInt = 14084 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14085 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14086 14087 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14088 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14089 return SDValue(); 14090 14091 // Extend f32 values to f64 14092 if (ResVT.getScalarSizeInBits() == 32) { 14093 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14094 DCI.AddToWorklist(Val.getNode()); 14095 } 14096 14097 // Set signed or unsigned conversion opcode. 14098 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14099 PPCISD::FP_TO_SINT_IN_VSR : 14100 PPCISD::FP_TO_UINT_IN_VSR; 14101 14102 Val = DAG.getNode(ConvOpcode, 14103 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14104 DCI.AddToWorklist(Val.getNode()); 14105 14106 // Set number of bytes being converted. 14107 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14108 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14109 DAG.getIntPtrConstant(ByteSize, dl, false), 14110 DAG.getValueType(Op1VT) }; 14111 14112 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14113 DAG.getVTList(MVT::Other), Ops, 14114 cast<StoreSDNode>(N)->getMemoryVT(), 14115 cast<StoreSDNode>(N)->getMemOperand()); 14116 14117 DCI.AddToWorklist(Val.getNode()); 14118 return Val; 14119 } 14120 14121 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14122 // Check that the source of the element keeps flipping 14123 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14124 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14125 for (int i = 1, e = Mask.size(); i < e; i++) { 14126 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14127 return false; 14128 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14129 return false; 14130 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14131 } 14132 return true; 14133 } 14134 14135 static bool isSplatBV(SDValue Op) { 14136 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14137 return false; 14138 SDValue FirstOp; 14139 14140 // Find first non-undef input. 14141 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14142 FirstOp = Op.getOperand(i); 14143 if (!FirstOp.isUndef()) 14144 break; 14145 } 14146 14147 // All inputs are undef or the same as the first non-undef input. 14148 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14149 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14150 return false; 14151 return true; 14152 } 14153 14154 static SDValue isScalarToVec(SDValue Op) { 14155 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14156 return Op; 14157 if (Op.getOpcode() != ISD::BITCAST) 14158 return SDValue(); 14159 Op = Op.getOperand(0); 14160 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14161 return Op; 14162 return SDValue(); 14163 } 14164 14165 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14166 int LHSMaxIdx, int RHSMinIdx, 14167 int RHSMaxIdx, int HalfVec) { 14168 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14169 int Idx = ShuffV[i]; 14170 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14171 ShuffV[i] += HalfVec; 14172 } 14173 } 14174 14175 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14176 // the original is: 14177 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14178 // In such a case, just change the shuffle mask to extract the element 14179 // from the permuted index. 14180 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14181 SDLoc dl(OrigSToV); 14182 EVT VT = OrigSToV.getValueType(); 14183 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14184 "Expecting a SCALAR_TO_VECTOR here"); 14185 SDValue Input = OrigSToV.getOperand(0); 14186 14187 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14188 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14189 SDValue OrigVector = Input.getOperand(0); 14190 14191 // Can't handle non-const element indices or different vector types 14192 // for the input to the extract and the output of the scalar_to_vector. 14193 if (Idx && VT == OrigVector.getValueType()) { 14194 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14195 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14196 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14197 } 14198 } 14199 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14200 OrigSToV.getOperand(0)); 14201 } 14202 14203 // On little endian subtargets, combine shuffles such as: 14204 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14205 // into: 14206 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14207 // because the latter can be matched to a single instruction merge. 14208 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14209 // to put the value into element zero. Adjust the shuffle mask so that the 14210 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14211 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14212 SelectionDAG &DAG) const { 14213 SDValue LHS = SVN->getOperand(0); 14214 SDValue RHS = SVN->getOperand(1); 14215 auto Mask = SVN->getMask(); 14216 int NumElts = LHS.getValueType().getVectorNumElements(); 14217 SDValue Res(SVN, 0); 14218 SDLoc dl(SVN); 14219 14220 // None of these combines are useful on big endian systems since the ISA 14221 // already has a big endian bias. 14222 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14223 return Res; 14224 14225 // If this is not a shuffle of a shuffle and the first element comes from 14226 // the second vector, canonicalize to the commuted form. This will make it 14227 // more likely to match one of the single instruction patterns. 14228 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14229 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14230 std::swap(LHS, RHS); 14231 Res = DAG.getCommutedVectorShuffle(*SVN); 14232 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14233 } 14234 14235 // Adjust the shuffle mask if either input vector comes from a 14236 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14237 // form (to prevent the need for a swap). 14238 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14239 SDValue SToVLHS = isScalarToVec(LHS); 14240 SDValue SToVRHS = isScalarToVec(RHS); 14241 if (SToVLHS || SToVRHS) { 14242 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14243 : SToVRHS.getValueType().getVectorNumElements(); 14244 int NumEltsOut = ShuffV.size(); 14245 14246 // Initially assume that neither input is permuted. These will be adjusted 14247 // accordingly if either input is. 14248 int LHSMaxIdx = -1; 14249 int RHSMinIdx = -1; 14250 int RHSMaxIdx = -1; 14251 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14252 14253 // Get the permuted scalar to vector nodes for the source(s) that come from 14254 // ISD::SCALAR_TO_VECTOR. 14255 if (SToVLHS) { 14256 // Set up the values for the shuffle vector fixup. 14257 LHSMaxIdx = NumEltsOut / NumEltsIn; 14258 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14259 if (SToVLHS.getValueType() != LHS.getValueType()) 14260 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14261 LHS = SToVLHS; 14262 } 14263 if (SToVRHS) { 14264 RHSMinIdx = NumEltsOut; 14265 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14266 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14267 if (SToVRHS.getValueType() != RHS.getValueType()) 14268 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14269 RHS = SToVRHS; 14270 } 14271 14272 // Fix up the shuffle mask to reflect where the desired element actually is. 14273 // The minimum and maximum indices that correspond to element zero for both 14274 // the LHS and RHS are computed and will control which shuffle mask entries 14275 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14276 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14277 // HalfVec to refer to the corresponding element in the permuted vector. 14278 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14279 HalfVec); 14280 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14281 14282 // We may have simplified away the shuffle. We won't be able to do anything 14283 // further with it here. 14284 if (!isa<ShuffleVectorSDNode>(Res)) 14285 return Res; 14286 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14287 } 14288 14289 // The common case after we commuted the shuffle is that the RHS is a splat 14290 // and we have elements coming in from the splat at indices that are not 14291 // conducive to using a merge. 14292 // Example: 14293 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14294 if (!isSplatBV(RHS)) 14295 return Res; 14296 14297 // We are looking for a mask such that all even elements are from 14298 // one vector and all odd elements from the other. 14299 if (!isAlternatingShuffMask(Mask, NumElts)) 14300 return Res; 14301 14302 // Adjust the mask so we are pulling in the same index from the splat 14303 // as the index from the interesting vector in consecutive elements. 14304 // Example (even elements from first vector): 14305 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14306 if (Mask[0] < NumElts) 14307 for (int i = 1, e = Mask.size(); i < e; i += 2) 14308 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14309 // Example (odd elements from first vector): 14310 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14311 else 14312 for (int i = 0, e = Mask.size(); i < e; i += 2) 14313 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14314 14315 // If the RHS has undefs, we need to remove them since we may have created 14316 // a shuffle that adds those instead of the splat value. 14317 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14318 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14319 14320 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14321 return Res; 14322 } 14323 14324 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14325 LSBaseSDNode *LSBase, 14326 DAGCombinerInfo &DCI) const { 14327 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14328 "Not a reverse memop pattern!"); 14329 14330 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14331 auto Mask = SVN->getMask(); 14332 int i = 0; 14333 auto I = Mask.rbegin(); 14334 auto E = Mask.rend(); 14335 14336 for (; I != E; ++I) { 14337 if (*I != i) 14338 return false; 14339 i++; 14340 } 14341 return true; 14342 }; 14343 14344 SelectionDAG &DAG = DCI.DAG; 14345 EVT VT = SVN->getValueType(0); 14346 14347 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14348 return SDValue(); 14349 14350 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14351 // See comment in PPCVSXSwapRemoval.cpp. 14352 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14353 if (!Subtarget.hasP9Vector()) 14354 return SDValue(); 14355 14356 if(!IsElementReverse(SVN)) 14357 return SDValue(); 14358 14359 if (LSBase->getOpcode() == ISD::LOAD) { 14360 SDLoc dl(SVN); 14361 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14362 return DAG.getMemIntrinsicNode( 14363 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14364 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14365 } 14366 14367 if (LSBase->getOpcode() == ISD::STORE) { 14368 SDLoc dl(LSBase); 14369 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14370 LSBase->getBasePtr()}; 14371 return DAG.getMemIntrinsicNode( 14372 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14373 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14374 } 14375 14376 llvm_unreachable("Expected a load or store node here"); 14377 } 14378 14379 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14380 DAGCombinerInfo &DCI) const { 14381 SelectionDAG &DAG = DCI.DAG; 14382 SDLoc dl(N); 14383 switch (N->getOpcode()) { 14384 default: break; 14385 case ISD::ADD: 14386 return combineADD(N, DCI); 14387 case ISD::SHL: 14388 return combineSHL(N, DCI); 14389 case ISD::SRA: 14390 return combineSRA(N, DCI); 14391 case ISD::SRL: 14392 return combineSRL(N, DCI); 14393 case ISD::MUL: 14394 return combineMUL(N, DCI); 14395 case ISD::FMA: 14396 case PPCISD::FNMSUB: 14397 return combineFMALike(N, DCI); 14398 case PPCISD::SHL: 14399 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14400 return N->getOperand(0); 14401 break; 14402 case PPCISD::SRL: 14403 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14404 return N->getOperand(0); 14405 break; 14406 case PPCISD::SRA: 14407 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14408 if (C->isNullValue() || // 0 >>s V -> 0. 14409 C->isAllOnesValue()) // -1 >>s V -> -1. 14410 return N->getOperand(0); 14411 } 14412 break; 14413 case ISD::SIGN_EXTEND: 14414 case ISD::ZERO_EXTEND: 14415 case ISD::ANY_EXTEND: 14416 return DAGCombineExtBoolTrunc(N, DCI); 14417 case ISD::TRUNCATE: 14418 return combineTRUNCATE(N, DCI); 14419 case ISD::SETCC: 14420 if (SDValue CSCC = combineSetCC(N, DCI)) 14421 return CSCC; 14422 LLVM_FALLTHROUGH; 14423 case ISD::SELECT_CC: 14424 return DAGCombineTruncBoolExt(N, DCI); 14425 case ISD::SINT_TO_FP: 14426 case ISD::UINT_TO_FP: 14427 return combineFPToIntToFP(N, DCI); 14428 case ISD::VECTOR_SHUFFLE: 14429 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14430 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14431 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14432 } 14433 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14434 case ISD::STORE: { 14435 14436 EVT Op1VT = N->getOperand(1).getValueType(); 14437 unsigned Opcode = N->getOperand(1).getOpcode(); 14438 14439 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14440 SDValue Val= combineStoreFPToInt(N, DCI); 14441 if (Val) 14442 return Val; 14443 } 14444 14445 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14446 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14447 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14448 if (Val) 14449 return Val; 14450 } 14451 14452 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14453 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14454 N->getOperand(1).getNode()->hasOneUse() && 14455 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14456 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14457 14458 // STBRX can only handle simple types and it makes no sense to store less 14459 // two bytes in byte-reversed order. 14460 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14461 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14462 break; 14463 14464 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14465 // Do an any-extend to 32-bits if this is a half-word input. 14466 if (BSwapOp.getValueType() == MVT::i16) 14467 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14468 14469 // If the type of BSWAP operand is wider than stored memory width 14470 // it need to be shifted to the right side before STBRX. 14471 if (Op1VT.bitsGT(mVT)) { 14472 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14473 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14474 DAG.getConstant(Shift, dl, MVT::i32)); 14475 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14476 if (Op1VT == MVT::i64) 14477 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14478 } 14479 14480 SDValue Ops[] = { 14481 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14482 }; 14483 return 14484 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14485 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14486 cast<StoreSDNode>(N)->getMemOperand()); 14487 } 14488 14489 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14490 // So it can increase the chance of CSE constant construction. 14491 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14492 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14493 // Need to sign-extended to 64-bits to handle negative values. 14494 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14495 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14496 MemVT.getSizeInBits()); 14497 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14498 14499 // DAG.getTruncStore() can't be used here because it doesn't accept 14500 // the general (base + offset) addressing mode. 14501 // So we use UpdateNodeOperands and setTruncatingStore instead. 14502 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14503 N->getOperand(3)); 14504 cast<StoreSDNode>(N)->setTruncatingStore(true); 14505 return SDValue(N, 0); 14506 } 14507 14508 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14509 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14510 if (Op1VT.isSimple()) { 14511 MVT StoreVT = Op1VT.getSimpleVT(); 14512 if (Subtarget.needsSwapsForVSXMemOps() && 14513 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14514 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14515 return expandVSXStoreForLE(N, DCI); 14516 } 14517 break; 14518 } 14519 case ISD::LOAD: { 14520 LoadSDNode *LD = cast<LoadSDNode>(N); 14521 EVT VT = LD->getValueType(0); 14522 14523 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14524 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14525 if (VT.isSimple()) { 14526 MVT LoadVT = VT.getSimpleVT(); 14527 if (Subtarget.needsSwapsForVSXMemOps() && 14528 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14529 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14530 return expandVSXLoadForLE(N, DCI); 14531 } 14532 14533 // We sometimes end up with a 64-bit integer load, from which we extract 14534 // two single-precision floating-point numbers. This happens with 14535 // std::complex<float>, and other similar structures, because of the way we 14536 // canonicalize structure copies. However, if we lack direct moves, 14537 // then the final bitcasts from the extracted integer values to the 14538 // floating-point numbers turn into store/load pairs. Even with direct moves, 14539 // just loading the two floating-point numbers is likely better. 14540 auto ReplaceTwoFloatLoad = [&]() { 14541 if (VT != MVT::i64) 14542 return false; 14543 14544 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14545 LD->isVolatile()) 14546 return false; 14547 14548 // We're looking for a sequence like this: 14549 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14550 // t16: i64 = srl t13, Constant:i32<32> 14551 // t17: i32 = truncate t16 14552 // t18: f32 = bitcast t17 14553 // t19: i32 = truncate t13 14554 // t20: f32 = bitcast t19 14555 14556 if (!LD->hasNUsesOfValue(2, 0)) 14557 return false; 14558 14559 auto UI = LD->use_begin(); 14560 while (UI.getUse().getResNo() != 0) ++UI; 14561 SDNode *Trunc = *UI++; 14562 while (UI.getUse().getResNo() != 0) ++UI; 14563 SDNode *RightShift = *UI; 14564 if (Trunc->getOpcode() != ISD::TRUNCATE) 14565 std::swap(Trunc, RightShift); 14566 14567 if (Trunc->getOpcode() != ISD::TRUNCATE || 14568 Trunc->getValueType(0) != MVT::i32 || 14569 !Trunc->hasOneUse()) 14570 return false; 14571 if (RightShift->getOpcode() != ISD::SRL || 14572 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14573 RightShift->getConstantOperandVal(1) != 32 || 14574 !RightShift->hasOneUse()) 14575 return false; 14576 14577 SDNode *Trunc2 = *RightShift->use_begin(); 14578 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14579 Trunc2->getValueType(0) != MVT::i32 || 14580 !Trunc2->hasOneUse()) 14581 return false; 14582 14583 SDNode *Bitcast = *Trunc->use_begin(); 14584 SDNode *Bitcast2 = *Trunc2->use_begin(); 14585 14586 if (Bitcast->getOpcode() != ISD::BITCAST || 14587 Bitcast->getValueType(0) != MVT::f32) 14588 return false; 14589 if (Bitcast2->getOpcode() != ISD::BITCAST || 14590 Bitcast2->getValueType(0) != MVT::f32) 14591 return false; 14592 14593 if (Subtarget.isLittleEndian()) 14594 std::swap(Bitcast, Bitcast2); 14595 14596 // Bitcast has the second float (in memory-layout order) and Bitcast2 14597 // has the first one. 14598 14599 SDValue BasePtr = LD->getBasePtr(); 14600 if (LD->isIndexed()) { 14601 assert(LD->getAddressingMode() == ISD::PRE_INC && 14602 "Non-pre-inc AM on PPC?"); 14603 BasePtr = 14604 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14605 LD->getOffset()); 14606 } 14607 14608 auto MMOFlags = 14609 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14610 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14611 LD->getPointerInfo(), LD->getAlignment(), 14612 MMOFlags, LD->getAAInfo()); 14613 SDValue AddPtr = 14614 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14615 BasePtr, DAG.getIntPtrConstant(4, dl)); 14616 SDValue FloatLoad2 = DAG.getLoad( 14617 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14618 LD->getPointerInfo().getWithOffset(4), 14619 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14620 14621 if (LD->isIndexed()) { 14622 // Note that DAGCombine should re-form any pre-increment load(s) from 14623 // what is produced here if that makes sense. 14624 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14625 } 14626 14627 DCI.CombineTo(Bitcast2, FloatLoad); 14628 DCI.CombineTo(Bitcast, FloatLoad2); 14629 14630 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14631 SDValue(FloatLoad2.getNode(), 1)); 14632 return true; 14633 }; 14634 14635 if (ReplaceTwoFloatLoad()) 14636 return SDValue(N, 0); 14637 14638 EVT MemVT = LD->getMemoryVT(); 14639 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14640 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14641 if (LD->isUnindexed() && VT.isVector() && 14642 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14643 // P8 and later hardware should just use LOAD. 14644 !Subtarget.hasP8Vector() && 14645 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14646 VT == MVT::v4f32))) && 14647 LD->getAlign() < ABIAlignment) { 14648 // This is a type-legal unaligned Altivec load. 14649 SDValue Chain = LD->getChain(); 14650 SDValue Ptr = LD->getBasePtr(); 14651 bool isLittleEndian = Subtarget.isLittleEndian(); 14652 14653 // This implements the loading of unaligned vectors as described in 14654 // the venerable Apple Velocity Engine overview. Specifically: 14655 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14656 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14657 // 14658 // The general idea is to expand a sequence of one or more unaligned 14659 // loads into an alignment-based permutation-control instruction (lvsl 14660 // or lvsr), a series of regular vector loads (which always truncate 14661 // their input address to an aligned address), and a series of 14662 // permutations. The results of these permutations are the requested 14663 // loaded values. The trick is that the last "extra" load is not taken 14664 // from the address you might suspect (sizeof(vector) bytes after the 14665 // last requested load), but rather sizeof(vector) - 1 bytes after the 14666 // last requested vector. The point of this is to avoid a page fault if 14667 // the base address happened to be aligned. This works because if the 14668 // base address is aligned, then adding less than a full vector length 14669 // will cause the last vector in the sequence to be (re)loaded. 14670 // Otherwise, the next vector will be fetched as you might suspect was 14671 // necessary. 14672 14673 // We might be able to reuse the permutation generation from 14674 // a different base address offset from this one by an aligned amount. 14675 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14676 // optimization later. 14677 Intrinsic::ID Intr, IntrLD, IntrPerm; 14678 MVT PermCntlTy, PermTy, LDTy; 14679 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14680 : Intrinsic::ppc_altivec_lvsl; 14681 IntrLD = Intrinsic::ppc_altivec_lvx; 14682 IntrPerm = Intrinsic::ppc_altivec_vperm; 14683 PermCntlTy = MVT::v16i8; 14684 PermTy = MVT::v4i32; 14685 LDTy = MVT::v4i32; 14686 14687 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14688 14689 // Create the new MMO for the new base load. It is like the original MMO, 14690 // but represents an area in memory almost twice the vector size centered 14691 // on the original address. If the address is unaligned, we might start 14692 // reading up to (sizeof(vector)-1) bytes below the address of the 14693 // original unaligned load. 14694 MachineFunction &MF = DAG.getMachineFunction(); 14695 MachineMemOperand *BaseMMO = 14696 MF.getMachineMemOperand(LD->getMemOperand(), 14697 -(long)MemVT.getStoreSize()+1, 14698 2*MemVT.getStoreSize()-1); 14699 14700 // Create the new base load. 14701 SDValue LDXIntID = 14702 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14703 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14704 SDValue BaseLoad = 14705 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14706 DAG.getVTList(PermTy, MVT::Other), 14707 BaseLoadOps, LDTy, BaseMMO); 14708 14709 // Note that the value of IncOffset (which is provided to the next 14710 // load's pointer info offset value, and thus used to calculate the 14711 // alignment), and the value of IncValue (which is actually used to 14712 // increment the pointer value) are different! This is because we 14713 // require the next load to appear to be aligned, even though it 14714 // is actually offset from the base pointer by a lesser amount. 14715 int IncOffset = VT.getSizeInBits() / 8; 14716 int IncValue = IncOffset; 14717 14718 // Walk (both up and down) the chain looking for another load at the real 14719 // (aligned) offset (the alignment of the other load does not matter in 14720 // this case). If found, then do not use the offset reduction trick, as 14721 // that will prevent the loads from being later combined (as they would 14722 // otherwise be duplicates). 14723 if (!findConsecutiveLoad(LD, DAG)) 14724 --IncValue; 14725 14726 SDValue Increment = 14727 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14728 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14729 14730 MachineMemOperand *ExtraMMO = 14731 MF.getMachineMemOperand(LD->getMemOperand(), 14732 1, 2*MemVT.getStoreSize()-1); 14733 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14734 SDValue ExtraLoad = 14735 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14736 DAG.getVTList(PermTy, MVT::Other), 14737 ExtraLoadOps, LDTy, ExtraMMO); 14738 14739 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14740 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14741 14742 // Because vperm has a big-endian bias, we must reverse the order 14743 // of the input vectors and complement the permute control vector 14744 // when generating little endian code. We have already handled the 14745 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14746 // and ExtraLoad here. 14747 SDValue Perm; 14748 if (isLittleEndian) 14749 Perm = BuildIntrinsicOp(IntrPerm, 14750 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14751 else 14752 Perm = BuildIntrinsicOp(IntrPerm, 14753 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14754 14755 if (VT != PermTy) 14756 Perm = Subtarget.hasAltivec() 14757 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14758 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14759 DAG.getTargetConstant(1, dl, MVT::i64)); 14760 // second argument is 1 because this rounding 14761 // is always exact. 14762 14763 // The output of the permutation is our loaded result, the TokenFactor is 14764 // our new chain. 14765 DCI.CombineTo(N, Perm, TF); 14766 return SDValue(N, 0); 14767 } 14768 } 14769 break; 14770 case ISD::INTRINSIC_WO_CHAIN: { 14771 bool isLittleEndian = Subtarget.isLittleEndian(); 14772 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14773 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14774 : Intrinsic::ppc_altivec_lvsl); 14775 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14776 SDValue Add = N->getOperand(1); 14777 14778 int Bits = 4 /* 16 byte alignment */; 14779 14780 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14781 APInt::getAllOnesValue(Bits /* alignment */) 14782 .zext(Add.getScalarValueSizeInBits()))) { 14783 SDNode *BasePtr = Add->getOperand(0).getNode(); 14784 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14785 UE = BasePtr->use_end(); 14786 UI != UE; ++UI) { 14787 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14788 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14789 IID) { 14790 // We've found another LVSL/LVSR, and this address is an aligned 14791 // multiple of that one. The results will be the same, so use the 14792 // one we've just found instead. 14793 14794 return SDValue(*UI, 0); 14795 } 14796 } 14797 } 14798 14799 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14800 SDNode *BasePtr = Add->getOperand(0).getNode(); 14801 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14802 UE = BasePtr->use_end(); UI != UE; ++UI) { 14803 if (UI->getOpcode() == ISD::ADD && 14804 isa<ConstantSDNode>(UI->getOperand(1)) && 14805 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14806 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14807 (1ULL << Bits) == 0) { 14808 SDNode *OtherAdd = *UI; 14809 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14810 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14811 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14812 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14813 return SDValue(*VI, 0); 14814 } 14815 } 14816 } 14817 } 14818 } 14819 } 14820 14821 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14822 // Expose the vabsduw/h/b opportunity for down stream 14823 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14824 (IID == Intrinsic::ppc_altivec_vmaxsw || 14825 IID == Intrinsic::ppc_altivec_vmaxsh || 14826 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14827 SDValue V1 = N->getOperand(1); 14828 SDValue V2 = N->getOperand(2); 14829 if ((V1.getSimpleValueType() == MVT::v4i32 || 14830 V1.getSimpleValueType() == MVT::v8i16 || 14831 V1.getSimpleValueType() == MVT::v16i8) && 14832 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14833 // (0-a, a) 14834 if (V1.getOpcode() == ISD::SUB && 14835 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14836 V1.getOperand(1) == V2) { 14837 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14838 } 14839 // (a, 0-a) 14840 if (V2.getOpcode() == ISD::SUB && 14841 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14842 V2.getOperand(1) == V1) { 14843 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14844 } 14845 // (x-y, y-x) 14846 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14847 V1.getOperand(0) == V2.getOperand(1) && 14848 V1.getOperand(1) == V2.getOperand(0)) { 14849 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14850 } 14851 } 14852 } 14853 } 14854 14855 break; 14856 case ISD::INTRINSIC_W_CHAIN: 14857 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14858 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14859 if (Subtarget.needsSwapsForVSXMemOps()) { 14860 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14861 default: 14862 break; 14863 case Intrinsic::ppc_vsx_lxvw4x: 14864 case Intrinsic::ppc_vsx_lxvd2x: 14865 return expandVSXLoadForLE(N, DCI); 14866 } 14867 } 14868 break; 14869 case ISD::INTRINSIC_VOID: 14870 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14871 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14872 if (Subtarget.needsSwapsForVSXMemOps()) { 14873 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14874 default: 14875 break; 14876 case Intrinsic::ppc_vsx_stxvw4x: 14877 case Intrinsic::ppc_vsx_stxvd2x: 14878 return expandVSXStoreForLE(N, DCI); 14879 } 14880 } 14881 break; 14882 case ISD::BSWAP: 14883 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14884 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14885 N->getOperand(0).hasOneUse() && 14886 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14887 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14888 N->getValueType(0) == MVT::i64))) { 14889 SDValue Load = N->getOperand(0); 14890 LoadSDNode *LD = cast<LoadSDNode>(Load); 14891 // Create the byte-swapping load. 14892 SDValue Ops[] = { 14893 LD->getChain(), // Chain 14894 LD->getBasePtr(), // Ptr 14895 DAG.getValueType(N->getValueType(0)) // VT 14896 }; 14897 SDValue BSLoad = 14898 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14899 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14900 MVT::i64 : MVT::i32, MVT::Other), 14901 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14902 14903 // If this is an i16 load, insert the truncate. 14904 SDValue ResVal = BSLoad; 14905 if (N->getValueType(0) == MVT::i16) 14906 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14907 14908 // First, combine the bswap away. This makes the value produced by the 14909 // load dead. 14910 DCI.CombineTo(N, ResVal); 14911 14912 // Next, combine the load away, we give it a bogus result value but a real 14913 // chain result. The result value is dead because the bswap is dead. 14914 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14915 14916 // Return N so it doesn't get rechecked! 14917 return SDValue(N, 0); 14918 } 14919 break; 14920 case PPCISD::VCMP: 14921 // If a VCMP_rec node already exists with exactly the same operands as this 14922 // node, use its result instead of this node (VCMP_rec computes both a CR6 14923 // and a normal output). 14924 // 14925 if (!N->getOperand(0).hasOneUse() && 14926 !N->getOperand(1).hasOneUse() && 14927 !N->getOperand(2).hasOneUse()) { 14928 14929 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 14930 SDNode *VCMPrecNode = nullptr; 14931 14932 SDNode *LHSN = N->getOperand(0).getNode(); 14933 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14934 UI != E; ++UI) 14935 if (UI->getOpcode() == PPCISD::VCMP_rec && 14936 UI->getOperand(1) == N->getOperand(1) && 14937 UI->getOperand(2) == N->getOperand(2) && 14938 UI->getOperand(0) == N->getOperand(0)) { 14939 VCMPrecNode = *UI; 14940 break; 14941 } 14942 14943 // If there is no VCMP_rec node, or if the flag value has a single use, 14944 // don't transform this. 14945 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 14946 break; 14947 14948 // Look at the (necessarily single) use of the flag value. If it has a 14949 // chain, this transformation is more complex. Note that multiple things 14950 // could use the value result, which we should ignore. 14951 SDNode *FlagUser = nullptr; 14952 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 14953 FlagUser == nullptr; ++UI) { 14954 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 14955 SDNode *User = *UI; 14956 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14957 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 14958 FlagUser = User; 14959 break; 14960 } 14961 } 14962 } 14963 14964 // If the user is a MFOCRF instruction, we know this is safe. 14965 // Otherwise we give up for right now. 14966 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14967 return SDValue(VCMPrecNode, 0); 14968 } 14969 break; 14970 case ISD::BRCOND: { 14971 SDValue Cond = N->getOperand(1); 14972 SDValue Target = N->getOperand(2); 14973 14974 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14975 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14976 Intrinsic::loop_decrement) { 14977 14978 // We now need to make the intrinsic dead (it cannot be instruction 14979 // selected). 14980 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14981 assert(Cond.getNode()->hasOneUse() && 14982 "Counter decrement has more than one use"); 14983 14984 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14985 N->getOperand(0), Target); 14986 } 14987 } 14988 break; 14989 case ISD::BR_CC: { 14990 // If this is a branch on an altivec predicate comparison, lower this so 14991 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14992 // lowering is done pre-legalize, because the legalizer lowers the predicate 14993 // compare down to code that is difficult to reassemble. 14994 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14995 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14996 14997 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14998 // value. If so, pass-through the AND to get to the intrinsic. 14999 if (LHS.getOpcode() == ISD::AND && 15000 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15001 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15002 Intrinsic::loop_decrement && 15003 isa<ConstantSDNode>(LHS.getOperand(1)) && 15004 !isNullConstant(LHS.getOperand(1))) 15005 LHS = LHS.getOperand(0); 15006 15007 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15008 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15009 Intrinsic::loop_decrement && 15010 isa<ConstantSDNode>(RHS)) { 15011 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15012 "Counter decrement comparison is not EQ or NE"); 15013 15014 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15015 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15016 (CC == ISD::SETNE && !Val); 15017 15018 // We now need to make the intrinsic dead (it cannot be instruction 15019 // selected). 15020 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15021 assert(LHS.getNode()->hasOneUse() && 15022 "Counter decrement has more than one use"); 15023 15024 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15025 N->getOperand(0), N->getOperand(4)); 15026 } 15027 15028 int CompareOpc; 15029 bool isDot; 15030 15031 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15032 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15033 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15034 assert(isDot && "Can't compare against a vector result!"); 15035 15036 // If this is a comparison against something other than 0/1, then we know 15037 // that the condition is never/always true. 15038 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15039 if (Val != 0 && Val != 1) { 15040 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15041 return N->getOperand(0); 15042 // Always !=, turn it into an unconditional branch. 15043 return DAG.getNode(ISD::BR, dl, MVT::Other, 15044 N->getOperand(0), N->getOperand(4)); 15045 } 15046 15047 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15048 15049 // Create the PPCISD altivec 'dot' comparison node. 15050 SDValue Ops[] = { 15051 LHS.getOperand(2), // LHS of compare 15052 LHS.getOperand(3), // RHS of compare 15053 DAG.getConstant(CompareOpc, dl, MVT::i32) 15054 }; 15055 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15056 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15057 15058 // Unpack the result based on how the target uses it. 15059 PPC::Predicate CompOpc; 15060 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15061 default: // Can't happen, don't crash on invalid number though. 15062 case 0: // Branch on the value of the EQ bit of CR6. 15063 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15064 break; 15065 case 1: // Branch on the inverted value of the EQ bit of CR6. 15066 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15067 break; 15068 case 2: // Branch on the value of the LT bit of CR6. 15069 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15070 break; 15071 case 3: // Branch on the inverted value of the LT bit of CR6. 15072 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15073 break; 15074 } 15075 15076 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15077 DAG.getConstant(CompOpc, dl, MVT::i32), 15078 DAG.getRegister(PPC::CR6, MVT::i32), 15079 N->getOperand(4), CompNode.getValue(1)); 15080 } 15081 break; 15082 } 15083 case ISD::BUILD_VECTOR: 15084 return DAGCombineBuildVector(N, DCI); 15085 case ISD::ABS: 15086 return combineABS(N, DCI); 15087 case ISD::VSELECT: 15088 return combineVSelect(N, DCI); 15089 } 15090 15091 return SDValue(); 15092 } 15093 15094 SDValue 15095 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15096 SelectionDAG &DAG, 15097 SmallVectorImpl<SDNode *> &Created) const { 15098 // fold (sdiv X, pow2) 15099 EVT VT = N->getValueType(0); 15100 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15101 return SDValue(); 15102 if ((VT != MVT::i32 && VT != MVT::i64) || 15103 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15104 return SDValue(); 15105 15106 SDLoc DL(N); 15107 SDValue N0 = N->getOperand(0); 15108 15109 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15110 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15111 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15112 15113 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15114 Created.push_back(Op.getNode()); 15115 15116 if (IsNegPow2) { 15117 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15118 Created.push_back(Op.getNode()); 15119 } 15120 15121 return Op; 15122 } 15123 15124 //===----------------------------------------------------------------------===// 15125 // Inline Assembly Support 15126 //===----------------------------------------------------------------------===// 15127 15128 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15129 KnownBits &Known, 15130 const APInt &DemandedElts, 15131 const SelectionDAG &DAG, 15132 unsigned Depth) const { 15133 Known.resetAll(); 15134 switch (Op.getOpcode()) { 15135 default: break; 15136 case PPCISD::LBRX: { 15137 // lhbrx is known to have the top bits cleared out. 15138 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15139 Known.Zero = 0xFFFF0000; 15140 break; 15141 } 15142 case ISD::INTRINSIC_WO_CHAIN: { 15143 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15144 default: break; 15145 case Intrinsic::ppc_altivec_vcmpbfp_p: 15146 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15147 case Intrinsic::ppc_altivec_vcmpequb_p: 15148 case Intrinsic::ppc_altivec_vcmpequh_p: 15149 case Intrinsic::ppc_altivec_vcmpequw_p: 15150 case Intrinsic::ppc_altivec_vcmpequd_p: 15151 case Intrinsic::ppc_altivec_vcmpequq_p: 15152 case Intrinsic::ppc_altivec_vcmpgefp_p: 15153 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15154 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15155 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15156 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15157 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15158 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15159 case Intrinsic::ppc_altivec_vcmpgtub_p: 15160 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15161 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15162 case Intrinsic::ppc_altivec_vcmpgtud_p: 15163 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15164 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15165 break; 15166 } 15167 } 15168 } 15169 } 15170 15171 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15172 switch (Subtarget.getCPUDirective()) { 15173 default: break; 15174 case PPC::DIR_970: 15175 case PPC::DIR_PWR4: 15176 case PPC::DIR_PWR5: 15177 case PPC::DIR_PWR5X: 15178 case PPC::DIR_PWR6: 15179 case PPC::DIR_PWR6X: 15180 case PPC::DIR_PWR7: 15181 case PPC::DIR_PWR8: 15182 case PPC::DIR_PWR9: 15183 case PPC::DIR_PWR10: 15184 case PPC::DIR_PWR_FUTURE: { 15185 if (!ML) 15186 break; 15187 15188 if (!DisableInnermostLoopAlign32) { 15189 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15190 // so that we can decrease cache misses and branch-prediction misses. 15191 // Actual alignment of the loop will depend on the hotness check and other 15192 // logic in alignBlocks. 15193 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15194 return Align(32); 15195 } 15196 15197 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15198 15199 // For small loops (between 5 and 8 instructions), align to a 32-byte 15200 // boundary so that the entire loop fits in one instruction-cache line. 15201 uint64_t LoopSize = 0; 15202 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15203 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15204 LoopSize += TII->getInstSizeInBytes(*J); 15205 if (LoopSize > 32) 15206 break; 15207 } 15208 15209 if (LoopSize > 16 && LoopSize <= 32) 15210 return Align(32); 15211 15212 break; 15213 } 15214 } 15215 15216 return TargetLowering::getPrefLoopAlignment(ML); 15217 } 15218 15219 /// getConstraintType - Given a constraint, return the type of 15220 /// constraint it is for this target. 15221 PPCTargetLowering::ConstraintType 15222 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15223 if (Constraint.size() == 1) { 15224 switch (Constraint[0]) { 15225 default: break; 15226 case 'b': 15227 case 'r': 15228 case 'f': 15229 case 'd': 15230 case 'v': 15231 case 'y': 15232 return C_RegisterClass; 15233 case 'Z': 15234 // FIXME: While Z does indicate a memory constraint, it specifically 15235 // indicates an r+r address (used in conjunction with the 'y' modifier 15236 // in the replacement string). Currently, we're forcing the base 15237 // register to be r0 in the asm printer (which is interpreted as zero) 15238 // and forming the complete address in the second register. This is 15239 // suboptimal. 15240 return C_Memory; 15241 } 15242 } else if (Constraint == "wc") { // individual CR bits. 15243 return C_RegisterClass; 15244 } else if (Constraint == "wa" || Constraint == "wd" || 15245 Constraint == "wf" || Constraint == "ws" || 15246 Constraint == "wi" || Constraint == "ww") { 15247 return C_RegisterClass; // VSX registers. 15248 } 15249 return TargetLowering::getConstraintType(Constraint); 15250 } 15251 15252 /// Examine constraint type and operand type and determine a weight value. 15253 /// This object must already have been set up with the operand type 15254 /// and the current alternative constraint selected. 15255 TargetLowering::ConstraintWeight 15256 PPCTargetLowering::getSingleConstraintMatchWeight( 15257 AsmOperandInfo &info, const char *constraint) const { 15258 ConstraintWeight weight = CW_Invalid; 15259 Value *CallOperandVal = info.CallOperandVal; 15260 // If we don't have a value, we can't do a match, 15261 // but allow it at the lowest weight. 15262 if (!CallOperandVal) 15263 return CW_Default; 15264 Type *type = CallOperandVal->getType(); 15265 15266 // Look at the constraint type. 15267 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15268 return CW_Register; // an individual CR bit. 15269 else if ((StringRef(constraint) == "wa" || 15270 StringRef(constraint) == "wd" || 15271 StringRef(constraint) == "wf") && 15272 type->isVectorTy()) 15273 return CW_Register; 15274 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15275 return CW_Register; // just hold 64-bit integers data. 15276 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15277 return CW_Register; 15278 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15279 return CW_Register; 15280 15281 switch (*constraint) { 15282 default: 15283 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15284 break; 15285 case 'b': 15286 if (type->isIntegerTy()) 15287 weight = CW_Register; 15288 break; 15289 case 'f': 15290 if (type->isFloatTy()) 15291 weight = CW_Register; 15292 break; 15293 case 'd': 15294 if (type->isDoubleTy()) 15295 weight = CW_Register; 15296 break; 15297 case 'v': 15298 if (type->isVectorTy()) 15299 weight = CW_Register; 15300 break; 15301 case 'y': 15302 weight = CW_Register; 15303 break; 15304 case 'Z': 15305 weight = CW_Memory; 15306 break; 15307 } 15308 return weight; 15309 } 15310 15311 std::pair<unsigned, const TargetRegisterClass *> 15312 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15313 StringRef Constraint, 15314 MVT VT) const { 15315 if (Constraint.size() == 1) { 15316 // GCC RS6000 Constraint Letters 15317 switch (Constraint[0]) { 15318 case 'b': // R1-R31 15319 if (VT == MVT::i64 && Subtarget.isPPC64()) 15320 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15321 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15322 case 'r': // R0-R31 15323 if (VT == MVT::i64 && Subtarget.isPPC64()) 15324 return std::make_pair(0U, &PPC::G8RCRegClass); 15325 return std::make_pair(0U, &PPC::GPRCRegClass); 15326 // 'd' and 'f' constraints are both defined to be "the floating point 15327 // registers", where one is for 32-bit and the other for 64-bit. We don't 15328 // really care overly much here so just give them all the same reg classes. 15329 case 'd': 15330 case 'f': 15331 if (Subtarget.hasSPE()) { 15332 if (VT == MVT::f32 || VT == MVT::i32) 15333 return std::make_pair(0U, &PPC::GPRCRegClass); 15334 if (VT == MVT::f64 || VT == MVT::i64) 15335 return std::make_pair(0U, &PPC::SPERCRegClass); 15336 } else { 15337 if (VT == MVT::f32 || VT == MVT::i32) 15338 return std::make_pair(0U, &PPC::F4RCRegClass); 15339 if (VT == MVT::f64 || VT == MVT::i64) 15340 return std::make_pair(0U, &PPC::F8RCRegClass); 15341 } 15342 break; 15343 case 'v': 15344 if (Subtarget.hasAltivec()) 15345 return std::make_pair(0U, &PPC::VRRCRegClass); 15346 break; 15347 case 'y': // crrc 15348 return std::make_pair(0U, &PPC::CRRCRegClass); 15349 } 15350 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15351 // An individual CR bit. 15352 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15353 } else if ((Constraint == "wa" || Constraint == "wd" || 15354 Constraint == "wf" || Constraint == "wi") && 15355 Subtarget.hasVSX()) { 15356 return std::make_pair(0U, &PPC::VSRCRegClass); 15357 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15358 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15359 return std::make_pair(0U, &PPC::VSSRCRegClass); 15360 else 15361 return std::make_pair(0U, &PPC::VSFRCRegClass); 15362 } 15363 15364 // Handle special cases of physical registers that are not properly handled 15365 // by the base class. 15366 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 15367 // If we name a VSX register, we can't defer to the base class because it 15368 // will not recognize the correct register (their names will be VSL{0-31} 15369 // and V{0-31} so they won't match). So we match them here. 15370 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15371 int VSNum = atoi(Constraint.data() + 3); 15372 assert(VSNum >= 0 && VSNum <= 63 && 15373 "Attempted to access a vsr out of range"); 15374 if (VSNum < 32) 15375 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15376 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15377 } 15378 15379 // For float registers, we can't defer to the base class as it will match 15380 // the SPILLTOVSRRC class. 15381 if (Constraint.size() > 3 && Constraint[1] == 'f') { 15382 int RegNum = atoi(Constraint.data() + 2); 15383 if (RegNum > 31 || RegNum < 0) 15384 report_fatal_error("Invalid floating point register number"); 15385 if (VT == MVT::f32 || VT == MVT::i32) 15386 return Subtarget.hasSPE() 15387 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 15388 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 15389 if (VT == MVT::f64 || VT == MVT::i64) 15390 return Subtarget.hasSPE() 15391 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 15392 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 15393 } 15394 } 15395 15396 std::pair<unsigned, const TargetRegisterClass *> R = 15397 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15398 15399 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15400 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15401 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15402 // register. 15403 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15404 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15405 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15406 PPC::GPRCRegClass.contains(R.first)) 15407 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15408 PPC::sub_32, &PPC::G8RCRegClass), 15409 &PPC::G8RCRegClass); 15410 15411 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15412 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15413 R.first = PPC::CR0; 15414 R.second = &PPC::CRRCRegClass; 15415 } 15416 // FIXME: This warning should ideally be emitted in the front end. 15417 const auto &TM = getTargetMachine(); 15418 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 15419 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 15420 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 15421 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 15422 errs() << "warning: vector registers 20 to 32 are reserved in the " 15423 "default AIX AltiVec ABI and cannot be used\n"; 15424 } 15425 15426 return R; 15427 } 15428 15429 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15430 /// vector. If it is invalid, don't add anything to Ops. 15431 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15432 std::string &Constraint, 15433 std::vector<SDValue>&Ops, 15434 SelectionDAG &DAG) const { 15435 SDValue Result; 15436 15437 // Only support length 1 constraints. 15438 if (Constraint.length() > 1) return; 15439 15440 char Letter = Constraint[0]; 15441 switch (Letter) { 15442 default: break; 15443 case 'I': 15444 case 'J': 15445 case 'K': 15446 case 'L': 15447 case 'M': 15448 case 'N': 15449 case 'O': 15450 case 'P': { 15451 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15452 if (!CST) return; // Must be an immediate to match. 15453 SDLoc dl(Op); 15454 int64_t Value = CST->getSExtValue(); 15455 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15456 // numbers are printed as such. 15457 switch (Letter) { 15458 default: llvm_unreachable("Unknown constraint letter!"); 15459 case 'I': // "I" is a signed 16-bit constant. 15460 if (isInt<16>(Value)) 15461 Result = DAG.getTargetConstant(Value, dl, TCVT); 15462 break; 15463 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15464 if (isShiftedUInt<16, 16>(Value)) 15465 Result = DAG.getTargetConstant(Value, dl, TCVT); 15466 break; 15467 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15468 if (isShiftedInt<16, 16>(Value)) 15469 Result = DAG.getTargetConstant(Value, dl, TCVT); 15470 break; 15471 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15472 if (isUInt<16>(Value)) 15473 Result = DAG.getTargetConstant(Value, dl, TCVT); 15474 break; 15475 case 'M': // "M" is a constant that is greater than 31. 15476 if (Value > 31) 15477 Result = DAG.getTargetConstant(Value, dl, TCVT); 15478 break; 15479 case 'N': // "N" is a positive constant that is an exact power of two. 15480 if (Value > 0 && isPowerOf2_64(Value)) 15481 Result = DAG.getTargetConstant(Value, dl, TCVT); 15482 break; 15483 case 'O': // "O" is the constant zero. 15484 if (Value == 0) 15485 Result = DAG.getTargetConstant(Value, dl, TCVT); 15486 break; 15487 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15488 if (isInt<16>(-Value)) 15489 Result = DAG.getTargetConstant(Value, dl, TCVT); 15490 break; 15491 } 15492 break; 15493 } 15494 } 15495 15496 if (Result.getNode()) { 15497 Ops.push_back(Result); 15498 return; 15499 } 15500 15501 // Handle standard constraint letters. 15502 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15503 } 15504 15505 // isLegalAddressingMode - Return true if the addressing mode represented 15506 // by AM is legal for this target, for a load/store of the specified type. 15507 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15508 const AddrMode &AM, Type *Ty, 15509 unsigned AS, 15510 Instruction *I) const { 15511 // Vector type r+i form is supported since power9 as DQ form. We don't check 15512 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15513 // imm form is preferred and the offset can be adjusted to use imm form later 15514 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15515 // max offset to check legal addressing mode, we should be a little aggressive 15516 // to contain other offsets for that LSRUse. 15517 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15518 return false; 15519 15520 // PPC allows a sign-extended 16-bit immediate field. 15521 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15522 return false; 15523 15524 // No global is ever allowed as a base. 15525 if (AM.BaseGV) 15526 return false; 15527 15528 // PPC only support r+r, 15529 switch (AM.Scale) { 15530 case 0: // "r+i" or just "i", depending on HasBaseReg. 15531 break; 15532 case 1: 15533 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15534 return false; 15535 // Otherwise we have r+r or r+i. 15536 break; 15537 case 2: 15538 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15539 return false; 15540 // Allow 2*r as r+r. 15541 break; 15542 default: 15543 // No other scales are supported. 15544 return false; 15545 } 15546 15547 return true; 15548 } 15549 15550 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15551 SelectionDAG &DAG) const { 15552 MachineFunction &MF = DAG.getMachineFunction(); 15553 MachineFrameInfo &MFI = MF.getFrameInfo(); 15554 MFI.setReturnAddressIsTaken(true); 15555 15556 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15557 return SDValue(); 15558 15559 SDLoc dl(Op); 15560 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15561 15562 // Make sure the function does not optimize away the store of the RA to 15563 // the stack. 15564 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15565 FuncInfo->setLRStoreRequired(); 15566 bool isPPC64 = Subtarget.isPPC64(); 15567 auto PtrVT = getPointerTy(MF.getDataLayout()); 15568 15569 if (Depth > 0) { 15570 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15571 SDValue Offset = 15572 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15573 isPPC64 ? MVT::i64 : MVT::i32); 15574 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15575 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15576 MachinePointerInfo()); 15577 } 15578 15579 // Just load the return address off the stack. 15580 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15581 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15582 MachinePointerInfo()); 15583 } 15584 15585 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15586 SelectionDAG &DAG) const { 15587 SDLoc dl(Op); 15588 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15589 15590 MachineFunction &MF = DAG.getMachineFunction(); 15591 MachineFrameInfo &MFI = MF.getFrameInfo(); 15592 MFI.setFrameAddressIsTaken(true); 15593 15594 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15595 bool isPPC64 = PtrVT == MVT::i64; 15596 15597 // Naked functions never have a frame pointer, and so we use r1. For all 15598 // other functions, this decision must be delayed until during PEI. 15599 unsigned FrameReg; 15600 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15601 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15602 else 15603 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15604 15605 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15606 PtrVT); 15607 while (Depth--) 15608 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15609 FrameAddr, MachinePointerInfo()); 15610 return FrameAddr; 15611 } 15612 15613 // FIXME? Maybe this could be a TableGen attribute on some registers and 15614 // this table could be generated automatically from RegInfo. 15615 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15616 const MachineFunction &MF) const { 15617 bool isPPC64 = Subtarget.isPPC64(); 15618 15619 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15620 if (!is64Bit && VT != LLT::scalar(32)) 15621 report_fatal_error("Invalid register global variable type"); 15622 15623 Register Reg = StringSwitch<Register>(RegName) 15624 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15625 .Case("r2", isPPC64 ? Register() : PPC::R2) 15626 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15627 .Default(Register()); 15628 15629 if (Reg) 15630 return Reg; 15631 report_fatal_error("Invalid register name global variable"); 15632 } 15633 15634 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15635 // 32-bit SVR4 ABI access everything as got-indirect. 15636 if (Subtarget.is32BitELFABI()) 15637 return true; 15638 15639 // AIX accesses everything indirectly through the TOC, which is similar to 15640 // the GOT. 15641 if (Subtarget.isAIXABI()) 15642 return true; 15643 15644 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15645 // If it is small or large code model, module locals are accessed 15646 // indirectly by loading their address from .toc/.got. 15647 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15648 return true; 15649 15650 // JumpTable and BlockAddress are accessed as got-indirect. 15651 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15652 return true; 15653 15654 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15655 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15656 15657 return false; 15658 } 15659 15660 bool 15661 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15662 // The PowerPC target isn't yet aware of offsets. 15663 return false; 15664 } 15665 15666 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15667 const CallInst &I, 15668 MachineFunction &MF, 15669 unsigned Intrinsic) const { 15670 switch (Intrinsic) { 15671 case Intrinsic::ppc_altivec_lvx: 15672 case Intrinsic::ppc_altivec_lvxl: 15673 case Intrinsic::ppc_altivec_lvebx: 15674 case Intrinsic::ppc_altivec_lvehx: 15675 case Intrinsic::ppc_altivec_lvewx: 15676 case Intrinsic::ppc_vsx_lxvd2x: 15677 case Intrinsic::ppc_vsx_lxvw4x: 15678 case Intrinsic::ppc_vsx_lxvd2x_be: 15679 case Intrinsic::ppc_vsx_lxvw4x_be: 15680 case Intrinsic::ppc_vsx_lxvl: 15681 case Intrinsic::ppc_vsx_lxvll: { 15682 EVT VT; 15683 switch (Intrinsic) { 15684 case Intrinsic::ppc_altivec_lvebx: 15685 VT = MVT::i8; 15686 break; 15687 case Intrinsic::ppc_altivec_lvehx: 15688 VT = MVT::i16; 15689 break; 15690 case Intrinsic::ppc_altivec_lvewx: 15691 VT = MVT::i32; 15692 break; 15693 case Intrinsic::ppc_vsx_lxvd2x: 15694 case Intrinsic::ppc_vsx_lxvd2x_be: 15695 VT = MVT::v2f64; 15696 break; 15697 default: 15698 VT = MVT::v4i32; 15699 break; 15700 } 15701 15702 Info.opc = ISD::INTRINSIC_W_CHAIN; 15703 Info.memVT = VT; 15704 Info.ptrVal = I.getArgOperand(0); 15705 Info.offset = -VT.getStoreSize()+1; 15706 Info.size = 2*VT.getStoreSize()-1; 15707 Info.align = Align(1); 15708 Info.flags = MachineMemOperand::MOLoad; 15709 return true; 15710 } 15711 case Intrinsic::ppc_altivec_stvx: 15712 case Intrinsic::ppc_altivec_stvxl: 15713 case Intrinsic::ppc_altivec_stvebx: 15714 case Intrinsic::ppc_altivec_stvehx: 15715 case Intrinsic::ppc_altivec_stvewx: 15716 case Intrinsic::ppc_vsx_stxvd2x: 15717 case Intrinsic::ppc_vsx_stxvw4x: 15718 case Intrinsic::ppc_vsx_stxvd2x_be: 15719 case Intrinsic::ppc_vsx_stxvw4x_be: 15720 case Intrinsic::ppc_vsx_stxvl: 15721 case Intrinsic::ppc_vsx_stxvll: { 15722 EVT VT; 15723 switch (Intrinsic) { 15724 case Intrinsic::ppc_altivec_stvebx: 15725 VT = MVT::i8; 15726 break; 15727 case Intrinsic::ppc_altivec_stvehx: 15728 VT = MVT::i16; 15729 break; 15730 case Intrinsic::ppc_altivec_stvewx: 15731 VT = MVT::i32; 15732 break; 15733 case Intrinsic::ppc_vsx_stxvd2x: 15734 case Intrinsic::ppc_vsx_stxvd2x_be: 15735 VT = MVT::v2f64; 15736 break; 15737 default: 15738 VT = MVT::v4i32; 15739 break; 15740 } 15741 15742 Info.opc = ISD::INTRINSIC_VOID; 15743 Info.memVT = VT; 15744 Info.ptrVal = I.getArgOperand(1); 15745 Info.offset = -VT.getStoreSize()+1; 15746 Info.size = 2*VT.getStoreSize()-1; 15747 Info.align = Align(1); 15748 Info.flags = MachineMemOperand::MOStore; 15749 return true; 15750 } 15751 default: 15752 break; 15753 } 15754 15755 return false; 15756 } 15757 15758 /// It returns EVT::Other if the type should be determined using generic 15759 /// target-independent logic. 15760 EVT PPCTargetLowering::getOptimalMemOpType( 15761 const MemOp &Op, const AttributeList &FuncAttributes) const { 15762 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15763 // We should use Altivec/VSX loads and stores when available. For unaligned 15764 // addresses, unaligned VSX loads are only fast starting with the P8. 15765 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15766 (Op.isAligned(Align(16)) || 15767 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15768 return MVT::v4i32; 15769 } 15770 15771 if (Subtarget.isPPC64()) { 15772 return MVT::i64; 15773 } 15774 15775 return MVT::i32; 15776 } 15777 15778 /// Returns true if it is beneficial to convert a load of a constant 15779 /// to just the constant itself. 15780 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15781 Type *Ty) const { 15782 assert(Ty->isIntegerTy()); 15783 15784 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15785 return !(BitSize == 0 || BitSize > 64); 15786 } 15787 15788 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15789 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15790 return false; 15791 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15792 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15793 return NumBits1 == 64 && NumBits2 == 32; 15794 } 15795 15796 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15797 if (!VT1.isInteger() || !VT2.isInteger()) 15798 return false; 15799 unsigned NumBits1 = VT1.getSizeInBits(); 15800 unsigned NumBits2 = VT2.getSizeInBits(); 15801 return NumBits1 == 64 && NumBits2 == 32; 15802 } 15803 15804 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15805 // Generally speaking, zexts are not free, but they are free when they can be 15806 // folded with other operations. 15807 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15808 EVT MemVT = LD->getMemoryVT(); 15809 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15810 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15811 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15812 LD->getExtensionType() == ISD::ZEXTLOAD)) 15813 return true; 15814 } 15815 15816 // FIXME: Add other cases... 15817 // - 32-bit shifts with a zext to i64 15818 // - zext after ctlz, bswap, etc. 15819 // - zext after and by a constant mask 15820 15821 return TargetLowering::isZExtFree(Val, VT2); 15822 } 15823 15824 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15825 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15826 "invalid fpext types"); 15827 // Extending to float128 is not free. 15828 if (DestVT == MVT::f128) 15829 return false; 15830 return true; 15831 } 15832 15833 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15834 return isInt<16>(Imm) || isUInt<16>(Imm); 15835 } 15836 15837 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15838 return isInt<16>(Imm) || isUInt<16>(Imm); 15839 } 15840 15841 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 15842 MachineMemOperand::Flags, 15843 bool *Fast) const { 15844 if (DisablePPCUnaligned) 15845 return false; 15846 15847 // PowerPC supports unaligned memory access for simple non-vector types. 15848 // Although accessing unaligned addresses is not as efficient as accessing 15849 // aligned addresses, it is generally more efficient than manual expansion, 15850 // and generally only traps for software emulation when crossing page 15851 // boundaries. 15852 15853 if (!VT.isSimple()) 15854 return false; 15855 15856 if (VT.isFloatingPoint() && !VT.isVector() && 15857 !Subtarget.allowsUnalignedFPAccess()) 15858 return false; 15859 15860 if (VT.getSimpleVT().isVector()) { 15861 if (Subtarget.hasVSX()) { 15862 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15863 VT != MVT::v4f32 && VT != MVT::v4i32) 15864 return false; 15865 } else { 15866 return false; 15867 } 15868 } 15869 15870 if (VT == MVT::ppcf128) 15871 return false; 15872 15873 if (Fast) 15874 *Fast = true; 15875 15876 return true; 15877 } 15878 15879 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 15880 SDValue C) const { 15881 // Check integral scalar types. 15882 if (!VT.isScalarInteger()) 15883 return false; 15884 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 15885 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 15886 return false; 15887 // This transformation will generate >= 2 operations. But the following 15888 // cases will generate <= 2 instructions during ISEL. So exclude them. 15889 // 1. If the constant multiplier fits 16 bits, it can be handled by one 15890 // HW instruction, ie. MULLI 15891 // 2. If the multiplier after shifted fits 16 bits, an extra shift 15892 // instruction is needed than case 1, ie. MULLI and RLDICR 15893 int64_t Imm = ConstNode->getSExtValue(); 15894 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 15895 Imm >>= Shift; 15896 if (isInt<16>(Imm)) 15897 return false; 15898 uint64_t UImm = static_cast<uint64_t>(Imm); 15899 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 15900 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 15901 return true; 15902 } 15903 return false; 15904 } 15905 15906 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15907 EVT VT) const { 15908 return isFMAFasterThanFMulAndFAdd( 15909 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15910 } 15911 15912 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15913 Type *Ty) const { 15914 switch (Ty->getScalarType()->getTypeID()) { 15915 case Type::FloatTyID: 15916 case Type::DoubleTyID: 15917 return true; 15918 case Type::FP128TyID: 15919 return Subtarget.hasP9Vector(); 15920 default: 15921 return false; 15922 } 15923 } 15924 15925 // FIXME: add more patterns which are not profitable to hoist. 15926 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15927 if (!I->hasOneUse()) 15928 return true; 15929 15930 Instruction *User = I->user_back(); 15931 assert(User && "A single use instruction with no uses."); 15932 15933 switch (I->getOpcode()) { 15934 case Instruction::FMul: { 15935 // Don't break FMA, PowerPC prefers FMA. 15936 if (User->getOpcode() != Instruction::FSub && 15937 User->getOpcode() != Instruction::FAdd) 15938 return true; 15939 15940 const TargetOptions &Options = getTargetMachine().Options; 15941 const Function *F = I->getFunction(); 15942 const DataLayout &DL = F->getParent()->getDataLayout(); 15943 Type *Ty = User->getOperand(0)->getType(); 15944 15945 return !( 15946 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15947 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15948 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15949 } 15950 case Instruction::Load: { 15951 // Don't break "store (load float*)" pattern, this pattern will be combined 15952 // to "store (load int32)" in later InstCombine pass. See function 15953 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15954 // cycles than loading a 32 bit integer. 15955 LoadInst *LI = cast<LoadInst>(I); 15956 // For the loads that combineLoadToOperationType does nothing, like 15957 // ordered load, it should be profitable to hoist them. 15958 // For swifterror load, it can only be used for pointer to pointer type, so 15959 // later type check should get rid of this case. 15960 if (!LI->isUnordered()) 15961 return true; 15962 15963 if (User->getOpcode() != Instruction::Store) 15964 return true; 15965 15966 if (I->getType()->getTypeID() != Type::FloatTyID) 15967 return true; 15968 15969 return false; 15970 } 15971 default: 15972 return true; 15973 } 15974 return true; 15975 } 15976 15977 const MCPhysReg * 15978 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15979 // LR is a callee-save register, but we must treat it as clobbered by any call 15980 // site. Hence we include LR in the scratch registers, which are in turn added 15981 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15982 // to CTR, which is used by any indirect call. 15983 static const MCPhysReg ScratchRegs[] = { 15984 PPC::X12, PPC::LR8, PPC::CTR8, 0 15985 }; 15986 15987 return ScratchRegs; 15988 } 15989 15990 Register PPCTargetLowering::getExceptionPointerRegister( 15991 const Constant *PersonalityFn) const { 15992 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15993 } 15994 15995 Register PPCTargetLowering::getExceptionSelectorRegister( 15996 const Constant *PersonalityFn) const { 15997 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15998 } 15999 16000 bool 16001 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16002 EVT VT , unsigned DefinedValues) const { 16003 if (VT == MVT::v2i64) 16004 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16005 16006 if (Subtarget.hasVSX()) 16007 return true; 16008 16009 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16010 } 16011 16012 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16013 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16014 return TargetLowering::getSchedulingPreference(N); 16015 16016 return Sched::ILP; 16017 } 16018 16019 // Create a fast isel object. 16020 FastISel * 16021 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16022 const TargetLibraryInfo *LibInfo) const { 16023 return PPC::createFastISel(FuncInfo, LibInfo); 16024 } 16025 16026 // 'Inverted' means the FMA opcode after negating one multiplicand. 16027 // For example, (fma -a b c) = (fnmsub a b c) 16028 static unsigned invertFMAOpcode(unsigned Opc) { 16029 switch (Opc) { 16030 default: 16031 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16032 case ISD::FMA: 16033 return PPCISD::FNMSUB; 16034 case PPCISD::FNMSUB: 16035 return ISD::FMA; 16036 } 16037 } 16038 16039 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16040 bool LegalOps, bool OptForSize, 16041 NegatibleCost &Cost, 16042 unsigned Depth) const { 16043 if (Depth > SelectionDAG::MaxRecursionDepth) 16044 return SDValue(); 16045 16046 unsigned Opc = Op.getOpcode(); 16047 EVT VT = Op.getValueType(); 16048 SDNodeFlags Flags = Op.getNode()->getFlags(); 16049 16050 switch (Opc) { 16051 case PPCISD::FNMSUB: 16052 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16053 break; 16054 16055 const TargetOptions &Options = getTargetMachine().Options; 16056 SDValue N0 = Op.getOperand(0); 16057 SDValue N1 = Op.getOperand(1); 16058 SDValue N2 = Op.getOperand(2); 16059 SDLoc Loc(Op); 16060 16061 NegatibleCost N2Cost = NegatibleCost::Expensive; 16062 SDValue NegN2 = 16063 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16064 16065 if (!NegN2) 16066 return SDValue(); 16067 16068 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16069 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16070 // These transformations may change sign of zeroes. For example, 16071 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16072 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16073 // Try and choose the cheaper one to negate. 16074 NegatibleCost N0Cost = NegatibleCost::Expensive; 16075 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16076 N0Cost, Depth + 1); 16077 16078 NegatibleCost N1Cost = NegatibleCost::Expensive; 16079 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16080 N1Cost, Depth + 1); 16081 16082 if (NegN0 && N0Cost <= N1Cost) { 16083 Cost = std::min(N0Cost, N2Cost); 16084 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16085 } else if (NegN1) { 16086 Cost = std::min(N1Cost, N2Cost); 16087 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16088 } 16089 } 16090 16091 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16092 if (isOperationLegal(ISD::FMA, VT)) { 16093 Cost = N2Cost; 16094 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16095 } 16096 16097 break; 16098 } 16099 16100 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16101 Cost, Depth); 16102 } 16103 16104 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16105 bool PPCTargetLowering::useLoadStackGuardNode() const { 16106 if (!Subtarget.isTargetLinux()) 16107 return TargetLowering::useLoadStackGuardNode(); 16108 return true; 16109 } 16110 16111 // Override to disable global variable loading on Linux. 16112 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16113 if (!Subtarget.isTargetLinux()) 16114 return TargetLowering::insertSSPDeclarations(M); 16115 } 16116 16117 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16118 bool ForCodeSize) const { 16119 if (!VT.isSimple() || !Subtarget.hasVSX()) 16120 return false; 16121 16122 switch(VT.getSimpleVT().SimpleTy) { 16123 default: 16124 // For FP types that are currently not supported by PPC backend, return 16125 // false. Examples: f16, f80. 16126 return false; 16127 case MVT::f32: 16128 case MVT::f64: 16129 if (Subtarget.hasPrefixInstrs()) { 16130 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 16131 return true; 16132 } 16133 LLVM_FALLTHROUGH; 16134 case MVT::ppcf128: 16135 return Imm.isPosZero(); 16136 } 16137 } 16138 16139 // For vector shift operation op, fold 16140 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16141 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16142 SelectionDAG &DAG) { 16143 SDValue N0 = N->getOperand(0); 16144 SDValue N1 = N->getOperand(1); 16145 EVT VT = N0.getValueType(); 16146 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16147 unsigned Opcode = N->getOpcode(); 16148 unsigned TargetOpcode; 16149 16150 switch (Opcode) { 16151 default: 16152 llvm_unreachable("Unexpected shift operation"); 16153 case ISD::SHL: 16154 TargetOpcode = PPCISD::SHL; 16155 break; 16156 case ISD::SRL: 16157 TargetOpcode = PPCISD::SRL; 16158 break; 16159 case ISD::SRA: 16160 TargetOpcode = PPCISD::SRA; 16161 break; 16162 } 16163 16164 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16165 N1->getOpcode() == ISD::AND) 16166 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16167 if (Mask->getZExtValue() == OpSizeInBits - 1) 16168 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16169 16170 return SDValue(); 16171 } 16172 16173 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16174 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16175 return Value; 16176 16177 SDValue N0 = N->getOperand(0); 16178 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16179 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16180 N0.getOpcode() != ISD::SIGN_EXTEND || 16181 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16182 N->getValueType(0) != MVT::i64) 16183 return SDValue(); 16184 16185 // We can't save an operation here if the value is already extended, and 16186 // the existing shift is easier to combine. 16187 SDValue ExtsSrc = N0.getOperand(0); 16188 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16189 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16190 return SDValue(); 16191 16192 SDLoc DL(N0); 16193 SDValue ShiftBy = SDValue(CN1, 0); 16194 // We want the shift amount to be i32 on the extswli, but the shift could 16195 // have an i64. 16196 if (ShiftBy.getValueType() == MVT::i64) 16197 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16198 16199 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16200 ShiftBy); 16201 } 16202 16203 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16204 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16205 return Value; 16206 16207 return SDValue(); 16208 } 16209 16210 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16211 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16212 return Value; 16213 16214 return SDValue(); 16215 } 16216 16217 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16218 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16219 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16220 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16221 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16222 const PPCSubtarget &Subtarget) { 16223 if (!Subtarget.isPPC64()) 16224 return SDValue(); 16225 16226 SDValue LHS = N->getOperand(0); 16227 SDValue RHS = N->getOperand(1); 16228 16229 auto isZextOfCompareWithConstant = [](SDValue Op) { 16230 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16231 Op.getValueType() != MVT::i64) 16232 return false; 16233 16234 SDValue Cmp = Op.getOperand(0); 16235 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16236 Cmp.getOperand(0).getValueType() != MVT::i64) 16237 return false; 16238 16239 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16240 int64_t NegConstant = 0 - Constant->getSExtValue(); 16241 // Due to the limitations of the addi instruction, 16242 // -C is required to be [-32768, 32767]. 16243 return isInt<16>(NegConstant); 16244 } 16245 16246 return false; 16247 }; 16248 16249 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16250 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16251 16252 // If there is a pattern, canonicalize a zext operand to the RHS. 16253 if (LHSHasPattern && !RHSHasPattern) 16254 std::swap(LHS, RHS); 16255 else if (!LHSHasPattern && !RHSHasPattern) 16256 return SDValue(); 16257 16258 SDLoc DL(N); 16259 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16260 SDValue Cmp = RHS.getOperand(0); 16261 SDValue Z = Cmp.getOperand(0); 16262 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16263 16264 assert(Constant && "Constant Should not be a null pointer."); 16265 int64_t NegConstant = 0 - Constant->getSExtValue(); 16266 16267 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16268 default: break; 16269 case ISD::SETNE: { 16270 // when C == 0 16271 // --> addze X, (addic Z, -1).carry 16272 // / 16273 // add X, (zext(setne Z, C))-- 16274 // \ when -32768 <= -C <= 32767 && C != 0 16275 // --> addze X, (addic (addi Z, -C), -1).carry 16276 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16277 DAG.getConstant(NegConstant, DL, MVT::i64)); 16278 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16279 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16280 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16281 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16282 SDValue(Addc.getNode(), 1)); 16283 } 16284 case ISD::SETEQ: { 16285 // when C == 0 16286 // --> addze X, (subfic Z, 0).carry 16287 // / 16288 // add X, (zext(sete Z, C))-- 16289 // \ when -32768 <= -C <= 32767 && C != 0 16290 // --> addze X, (subfic (addi Z, -C), 0).carry 16291 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16292 DAG.getConstant(NegConstant, DL, MVT::i64)); 16293 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16294 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16295 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16296 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16297 SDValue(Subc.getNode(), 1)); 16298 } 16299 } 16300 16301 return SDValue(); 16302 } 16303 16304 // Transform 16305 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16306 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16307 // In this case both C1 and C2 must be known constants. 16308 // C1+C2 must fit into a 34 bit signed integer. 16309 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16310 const PPCSubtarget &Subtarget) { 16311 if (!Subtarget.isUsingPCRelativeCalls()) 16312 return SDValue(); 16313 16314 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16315 // If we find that node try to cast the Global Address and the Constant. 16316 SDValue LHS = N->getOperand(0); 16317 SDValue RHS = N->getOperand(1); 16318 16319 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16320 std::swap(LHS, RHS); 16321 16322 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16323 return SDValue(); 16324 16325 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16326 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16327 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16328 16329 // Check that both casts succeeded. 16330 if (!GSDN || !ConstNode) 16331 return SDValue(); 16332 16333 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16334 SDLoc DL(GSDN); 16335 16336 // The signed int offset needs to fit in 34 bits. 16337 if (!isInt<34>(NewOffset)) 16338 return SDValue(); 16339 16340 // The new global address is a copy of the old global address except 16341 // that it has the updated Offset. 16342 SDValue GA = 16343 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16344 NewOffset, GSDN->getTargetFlags()); 16345 SDValue MatPCRel = 16346 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16347 return MatPCRel; 16348 } 16349 16350 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16351 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16352 return Value; 16353 16354 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16355 return Value; 16356 16357 return SDValue(); 16358 } 16359 16360 // Detect TRUNCATE operations on bitcasts of float128 values. 16361 // What we are looking for here is the situtation where we extract a subset 16362 // of bits from a 128 bit float. 16363 // This can be of two forms: 16364 // 1) BITCAST of f128 feeding TRUNCATE 16365 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16366 // The reason this is required is because we do not have a legal i128 type 16367 // and so we want to prevent having to store the f128 and then reload part 16368 // of it. 16369 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16370 DAGCombinerInfo &DCI) const { 16371 // If we are using CRBits then try that first. 16372 if (Subtarget.useCRBits()) { 16373 // Check if CRBits did anything and return that if it did. 16374 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16375 return CRTruncValue; 16376 } 16377 16378 SDLoc dl(N); 16379 SDValue Op0 = N->getOperand(0); 16380 16381 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16382 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16383 EVT VT = N->getValueType(0); 16384 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16385 return SDValue(); 16386 SDValue Sub = Op0.getOperand(0); 16387 if (Sub.getOpcode() == ISD::SUB) { 16388 SDValue SubOp0 = Sub.getOperand(0); 16389 SDValue SubOp1 = Sub.getOperand(1); 16390 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16391 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16392 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16393 SubOp1.getOperand(0), 16394 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16395 } 16396 } 16397 } 16398 16399 // Looking for a truncate of i128 to i64. 16400 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16401 return SDValue(); 16402 16403 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16404 16405 // SRL feeding TRUNCATE. 16406 if (Op0.getOpcode() == ISD::SRL) { 16407 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16408 // The right shift has to be by 64 bits. 16409 if (!ConstNode || ConstNode->getZExtValue() != 64) 16410 return SDValue(); 16411 16412 // Switch the element number to extract. 16413 EltToExtract = EltToExtract ? 0 : 1; 16414 // Update Op0 past the SRL. 16415 Op0 = Op0.getOperand(0); 16416 } 16417 16418 // BITCAST feeding a TRUNCATE possibly via SRL. 16419 if (Op0.getOpcode() == ISD::BITCAST && 16420 Op0.getValueType() == MVT::i128 && 16421 Op0.getOperand(0).getValueType() == MVT::f128) { 16422 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16423 return DCI.DAG.getNode( 16424 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16425 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16426 } 16427 return SDValue(); 16428 } 16429 16430 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16431 SelectionDAG &DAG = DCI.DAG; 16432 16433 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16434 if (!ConstOpOrElement) 16435 return SDValue(); 16436 16437 // An imul is usually smaller than the alternative sequence for legal type. 16438 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16439 isOperationLegal(ISD::MUL, N->getValueType(0))) 16440 return SDValue(); 16441 16442 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16443 switch (this->Subtarget.getCPUDirective()) { 16444 default: 16445 // TODO: enhance the condition for subtarget before pwr8 16446 return false; 16447 case PPC::DIR_PWR8: 16448 // type mul add shl 16449 // scalar 4 1 1 16450 // vector 7 2 2 16451 return true; 16452 case PPC::DIR_PWR9: 16453 case PPC::DIR_PWR10: 16454 case PPC::DIR_PWR_FUTURE: 16455 // type mul add shl 16456 // scalar 5 2 2 16457 // vector 7 2 2 16458 16459 // The cycle RATIO of related operations are showed as a table above. 16460 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16461 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16462 // are 4, it is always profitable; but for 3 instrs patterns 16463 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16464 // So we should only do it for vector type. 16465 return IsAddOne && IsNeg ? VT.isVector() : true; 16466 } 16467 }; 16468 16469 EVT VT = N->getValueType(0); 16470 SDLoc DL(N); 16471 16472 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16473 bool IsNeg = MulAmt.isNegative(); 16474 APInt MulAmtAbs = MulAmt.abs(); 16475 16476 if ((MulAmtAbs - 1).isPowerOf2()) { 16477 // (mul x, 2^N + 1) => (add (shl x, N), x) 16478 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16479 16480 if (!IsProfitable(IsNeg, true, VT)) 16481 return SDValue(); 16482 16483 SDValue Op0 = N->getOperand(0); 16484 SDValue Op1 = 16485 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16486 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16487 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16488 16489 if (!IsNeg) 16490 return Res; 16491 16492 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16493 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16494 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16495 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16496 16497 if (!IsProfitable(IsNeg, false, VT)) 16498 return SDValue(); 16499 16500 SDValue Op0 = N->getOperand(0); 16501 SDValue Op1 = 16502 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16503 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16504 16505 if (!IsNeg) 16506 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16507 else 16508 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16509 16510 } else { 16511 return SDValue(); 16512 } 16513 } 16514 16515 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16516 // in combiner since we need to check SD flags and other subtarget features. 16517 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16518 DAGCombinerInfo &DCI) const { 16519 SDValue N0 = N->getOperand(0); 16520 SDValue N1 = N->getOperand(1); 16521 SDValue N2 = N->getOperand(2); 16522 SDNodeFlags Flags = N->getFlags(); 16523 EVT VT = N->getValueType(0); 16524 SelectionDAG &DAG = DCI.DAG; 16525 const TargetOptions &Options = getTargetMachine().Options; 16526 unsigned Opc = N->getOpcode(); 16527 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16528 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16529 SDLoc Loc(N); 16530 16531 if (!isOperationLegal(ISD::FMA, VT)) 16532 return SDValue(); 16533 16534 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16535 // since (fnmsub a b c)=-0 while c-ab=+0. 16536 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16537 return SDValue(); 16538 16539 // (fma (fneg a) b c) => (fnmsub a b c) 16540 // (fnmsub (fneg a) b c) => (fma a b c) 16541 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16542 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16543 16544 // (fma a (fneg b) c) => (fnmsub a b c) 16545 // (fnmsub a (fneg b) c) => (fma a b c) 16546 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16547 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16548 16549 return SDValue(); 16550 } 16551 16552 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16553 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16554 if (!Subtarget.is64BitELFABI()) 16555 return false; 16556 16557 // If not a tail call then no need to proceed. 16558 if (!CI->isTailCall()) 16559 return false; 16560 16561 // If sibling calls have been disabled and tail-calls aren't guaranteed 16562 // there is no reason to duplicate. 16563 auto &TM = getTargetMachine(); 16564 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16565 return false; 16566 16567 // Can't tail call a function called indirectly, or if it has variadic args. 16568 const Function *Callee = CI->getCalledFunction(); 16569 if (!Callee || Callee->isVarArg()) 16570 return false; 16571 16572 // Make sure the callee and caller calling conventions are eligible for tco. 16573 const Function *Caller = CI->getParent()->getParent(); 16574 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16575 CI->getCallingConv())) 16576 return false; 16577 16578 // If the function is local then we have a good chance at tail-calling it 16579 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16580 } 16581 16582 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16583 if (!Subtarget.hasVSX()) 16584 return false; 16585 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16586 return true; 16587 return VT == MVT::f32 || VT == MVT::f64 || 16588 VT == MVT::v4f32 || VT == MVT::v2f64; 16589 } 16590 16591 bool PPCTargetLowering:: 16592 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16593 const Value *Mask = AndI.getOperand(1); 16594 // If the mask is suitable for andi. or andis. we should sink the and. 16595 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16596 // Can't handle constants wider than 64-bits. 16597 if (CI->getBitWidth() > 64) 16598 return false; 16599 int64_t ConstVal = CI->getZExtValue(); 16600 return isUInt<16>(ConstVal) || 16601 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16602 } 16603 16604 // For non-constant masks, we can always use the record-form and. 16605 return true; 16606 } 16607 16608 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16609 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16610 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16611 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16612 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16613 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16614 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16615 assert(Subtarget.hasP9Altivec() && 16616 "Only combine this when P9 altivec supported!"); 16617 EVT VT = N->getValueType(0); 16618 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16619 return SDValue(); 16620 16621 SelectionDAG &DAG = DCI.DAG; 16622 SDLoc dl(N); 16623 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16624 // Even for signed integers, if it's known to be positive (as signed 16625 // integer) due to zero-extended inputs. 16626 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16627 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16628 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16629 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16630 (SubOpcd1 == ISD::ZERO_EXTEND || 16631 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16632 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16633 N->getOperand(0)->getOperand(0), 16634 N->getOperand(0)->getOperand(1), 16635 DAG.getTargetConstant(0, dl, MVT::i32)); 16636 } 16637 16638 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16639 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16640 N->getOperand(0).hasOneUse()) { 16641 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16642 N->getOperand(0)->getOperand(0), 16643 N->getOperand(0)->getOperand(1), 16644 DAG.getTargetConstant(1, dl, MVT::i32)); 16645 } 16646 } 16647 16648 return SDValue(); 16649 } 16650 16651 // For type v4i32/v8ii16/v16i8, transform 16652 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16653 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16654 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16655 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16656 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16657 DAGCombinerInfo &DCI) const { 16658 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16659 assert(Subtarget.hasP9Altivec() && 16660 "Only combine this when P9 altivec supported!"); 16661 16662 SelectionDAG &DAG = DCI.DAG; 16663 SDLoc dl(N); 16664 SDValue Cond = N->getOperand(0); 16665 SDValue TrueOpnd = N->getOperand(1); 16666 SDValue FalseOpnd = N->getOperand(2); 16667 EVT VT = N->getOperand(1).getValueType(); 16668 16669 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16670 FalseOpnd.getOpcode() != ISD::SUB) 16671 return SDValue(); 16672 16673 // ABSD only available for type v4i32/v8i16/v16i8 16674 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16675 return SDValue(); 16676 16677 // At least to save one more dependent computation 16678 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16679 return SDValue(); 16680 16681 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16682 16683 // Can only handle unsigned comparison here 16684 switch (CC) { 16685 default: 16686 return SDValue(); 16687 case ISD::SETUGT: 16688 case ISD::SETUGE: 16689 break; 16690 case ISD::SETULT: 16691 case ISD::SETULE: 16692 std::swap(TrueOpnd, FalseOpnd); 16693 break; 16694 } 16695 16696 SDValue CmpOpnd1 = Cond.getOperand(0); 16697 SDValue CmpOpnd2 = Cond.getOperand(1); 16698 16699 // SETCC CmpOpnd1 CmpOpnd2 cond 16700 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16701 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16702 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16703 TrueOpnd.getOperand(1) == CmpOpnd2 && 16704 FalseOpnd.getOperand(0) == CmpOpnd2 && 16705 FalseOpnd.getOperand(1) == CmpOpnd1) { 16706 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16707 CmpOpnd1, CmpOpnd2, 16708 DAG.getTargetConstant(0, dl, MVT::i32)); 16709 } 16710 16711 return SDValue(); 16712 } 16713