1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSectionXCOFF.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 122 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 123 124 static cl::opt<bool> EnablePPCPCRelTLS( 125 "enable-ppc-pcrel-tls", 126 cl::desc("enable the use of PC relative memops in TLS instructions on PPC"), 127 cl::Hidden); 128 129 STATISTIC(NumTailCalls, "Number of tail calls"); 130 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 133 134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 135 136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 137 138 // FIXME: Remove this once the bug has been fixed! 139 extern cl::opt<bool> ANDIGlueBug; 140 141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 142 const PPCSubtarget &STI) 143 : TargetLowering(TM), Subtarget(STI) { 144 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 145 // arguments are at least 4/8 bytes aligned. 146 bool isPPC64 = Subtarget.isPPC64(); 147 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 148 149 // Set up the register classes. 150 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 151 if (!useSoftFloat()) { 152 if (hasSPE()) { 153 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 154 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 155 } else { 156 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 157 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 158 } 159 } 160 161 // Match BITREVERSE to customized fast code sequence in the td file. 162 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 163 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 164 165 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 166 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 167 168 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 169 for (MVT VT : MVT::integer_valuetypes()) { 170 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 172 } 173 174 if (Subtarget.isISA3_0()) { 175 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 176 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 177 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 178 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 179 } else { 180 // No extending loads from f16 or HW conversions back and forth. 181 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 182 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 183 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 184 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 185 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 186 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 187 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 188 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 189 } 190 191 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 192 193 // PowerPC has pre-inc load and store's. 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 200 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 201 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 204 if (!Subtarget.hasSPE()) { 205 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 206 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 207 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 208 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 209 } 210 211 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 212 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 213 for (MVT VT : ScalarIntVTs) { 214 setOperationAction(ISD::ADDC, VT, Legal); 215 setOperationAction(ISD::ADDE, VT, Legal); 216 setOperationAction(ISD::SUBC, VT, Legal); 217 setOperationAction(ISD::SUBE, VT, Legal); 218 } 219 220 if (Subtarget.useCRBits()) { 221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 222 223 if (isPPC64 || Subtarget.hasFPCVT()) { 224 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 225 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 226 isPPC64 ? MVT::i64 : MVT::i32); 227 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 228 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 229 isPPC64 ? MVT::i64 : MVT::i32); 230 231 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 232 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 233 isPPC64 ? MVT::i64 : MVT::i32); 234 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 235 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 236 isPPC64 ? MVT::i64 : MVT::i32); 237 } else { 238 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 239 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 240 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 241 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 242 } 243 244 // PowerPC does not support direct load/store of condition registers. 245 setOperationAction(ISD::LOAD, MVT::i1, Custom); 246 setOperationAction(ISD::STORE, MVT::i1, Custom); 247 248 // FIXME: Remove this once the ANDI glue bug is fixed: 249 if (ANDIGlueBug) 250 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 251 252 for (MVT VT : MVT::integer_valuetypes()) { 253 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 254 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 255 setTruncStoreAction(VT, MVT::i1, Expand); 256 } 257 258 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 259 } 260 261 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 262 // PPC (the libcall is not available). 263 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 264 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 265 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 266 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 267 268 // We do not currently implement these libm ops for PowerPC. 269 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 270 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 271 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 272 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 273 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 274 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 275 276 // PowerPC has no SREM/UREM instructions unless we are on P9 277 // On P9 we may use a hardware instruction to compute the remainder. 278 // When the result of both the remainder and the division is required it is 279 // more efficient to compute the remainder from the result of the division 280 // rather than use the remainder instruction. The instructions are legalized 281 // directly because the DivRemPairsPass performs the transformation at the IR 282 // level. 283 if (Subtarget.isISA3_0()) { 284 setOperationAction(ISD::SREM, MVT::i32, Legal); 285 setOperationAction(ISD::UREM, MVT::i32, Legal); 286 setOperationAction(ISD::SREM, MVT::i64, Legal); 287 setOperationAction(ISD::UREM, MVT::i64, Legal); 288 } else { 289 setOperationAction(ISD::SREM, MVT::i32, Expand); 290 setOperationAction(ISD::UREM, MVT::i32, Expand); 291 setOperationAction(ISD::SREM, MVT::i64, Expand); 292 setOperationAction(ISD::UREM, MVT::i64, Expand); 293 } 294 295 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 296 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 297 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 298 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 299 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 300 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 301 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 302 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 303 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 304 305 // Handle constrained floating-point operations of scalar. 306 // TODO: Handle SPE specific operation. 307 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 308 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 309 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 310 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 311 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 312 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 313 314 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 315 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 316 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 317 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 318 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 319 if (Subtarget.hasVSX()) { 320 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 321 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 322 } 323 324 if (Subtarget.hasFSQRT()) { 325 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 326 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 327 } 328 329 if (Subtarget.hasFPRND()) { 330 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 331 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 332 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 333 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 334 335 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 336 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 337 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 338 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 339 } 340 341 // We don't support sin/cos/sqrt/fmod/pow 342 setOperationAction(ISD::FSIN , MVT::f64, Expand); 343 setOperationAction(ISD::FCOS , MVT::f64, Expand); 344 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 345 setOperationAction(ISD::FREM , MVT::f64, Expand); 346 setOperationAction(ISD::FPOW , MVT::f64, Expand); 347 setOperationAction(ISD::FSIN , MVT::f32, Expand); 348 setOperationAction(ISD::FCOS , MVT::f32, Expand); 349 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 350 setOperationAction(ISD::FREM , MVT::f32, Expand); 351 setOperationAction(ISD::FPOW , MVT::f32, Expand); 352 if (Subtarget.hasSPE()) { 353 setOperationAction(ISD::FMA , MVT::f64, Expand); 354 setOperationAction(ISD::FMA , MVT::f32, Expand); 355 } else { 356 setOperationAction(ISD::FMA , MVT::f64, Legal); 357 setOperationAction(ISD::FMA , MVT::f32, Legal); 358 } 359 360 if (Subtarget.hasSPE()) 361 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 362 363 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 364 365 // If we're enabling GP optimizations, use hardware square root 366 if (!Subtarget.hasFSQRT() && 367 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 368 Subtarget.hasFRE())) 369 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 370 371 if (!Subtarget.hasFSQRT() && 372 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 373 Subtarget.hasFRES())) 374 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 375 376 if (Subtarget.hasFCPSGN()) { 377 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 378 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 379 } else { 380 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 381 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 382 } 383 384 if (Subtarget.hasFPRND()) { 385 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 386 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 387 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 388 setOperationAction(ISD::FROUND, MVT::f64, Legal); 389 390 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 391 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 392 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 393 setOperationAction(ISD::FROUND, MVT::f32, Legal); 394 } 395 396 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 397 // to speed up scalar BSWAP64. 398 // CTPOP or CTTZ were introduced in P8/P9 respectively 399 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 400 if (Subtarget.hasP9Vector()) 401 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 402 else 403 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 404 if (Subtarget.isISA3_0()) { 405 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 406 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 407 } else { 408 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 409 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 410 } 411 412 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 413 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 414 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 415 } else { 416 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 417 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 418 } 419 420 // PowerPC does not have ROTR 421 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 422 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 423 424 if (!Subtarget.useCRBits()) { 425 // PowerPC does not have Select 426 setOperationAction(ISD::SELECT, MVT::i32, Expand); 427 setOperationAction(ISD::SELECT, MVT::i64, Expand); 428 setOperationAction(ISD::SELECT, MVT::f32, Expand); 429 setOperationAction(ISD::SELECT, MVT::f64, Expand); 430 } 431 432 // PowerPC wants to turn select_cc of FP into fsel when possible. 433 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 434 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 435 436 // PowerPC wants to optimize integer setcc a bit 437 if (!Subtarget.useCRBits()) 438 setOperationAction(ISD::SETCC, MVT::i32, Custom); 439 440 if (Subtarget.hasFPU()) { 441 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 442 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 443 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 444 445 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 446 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 447 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 448 } 449 450 // PowerPC does not have BRCOND which requires SetCC 451 if (!Subtarget.useCRBits()) 452 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 453 454 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 455 456 if (Subtarget.hasSPE()) { 457 // SPE has built-in conversions 458 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 459 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 460 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 461 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 462 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 463 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 464 } else { 465 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 466 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 467 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 468 469 // PowerPC does not have [U|S]INT_TO_FP 470 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 471 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 472 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 473 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 474 } 475 476 if (Subtarget.hasDirectMove() && isPPC64) { 477 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 478 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 479 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 480 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 481 if (TM.Options.UnsafeFPMath) { 482 setOperationAction(ISD::LRINT, MVT::f64, Legal); 483 setOperationAction(ISD::LRINT, MVT::f32, Legal); 484 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 485 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 486 setOperationAction(ISD::LROUND, MVT::f64, Legal); 487 setOperationAction(ISD::LROUND, MVT::f32, Legal); 488 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 489 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 490 } 491 } else { 492 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 493 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 494 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 495 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 496 } 497 498 // We cannot sextinreg(i1). Expand to shifts. 499 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 500 501 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 502 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 503 // support continuation, user-level threading, and etc.. As a result, no 504 // other SjLj exception interfaces are implemented and please don't build 505 // your own exception handling based on them. 506 // LLVM/Clang supports zero-cost DWARF exception handling. 507 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 508 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 509 510 // We want to legalize GlobalAddress and ConstantPool nodes into the 511 // appropriate instructions to materialize the address. 512 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 513 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 514 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 515 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 516 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 517 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 518 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 519 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 520 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 521 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 522 523 // TRAP is legal. 524 setOperationAction(ISD::TRAP, MVT::Other, Legal); 525 526 // TRAMPOLINE is custom lowered. 527 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 528 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 529 530 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 531 setOperationAction(ISD::VASTART , MVT::Other, Custom); 532 533 if (Subtarget.is64BitELFABI()) { 534 // VAARG always uses double-word chunks, so promote anything smaller. 535 setOperationAction(ISD::VAARG, MVT::i1, Promote); 536 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 537 setOperationAction(ISD::VAARG, MVT::i8, Promote); 538 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 539 setOperationAction(ISD::VAARG, MVT::i16, Promote); 540 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 541 setOperationAction(ISD::VAARG, MVT::i32, Promote); 542 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 543 setOperationAction(ISD::VAARG, MVT::Other, Expand); 544 } else if (Subtarget.is32BitELFABI()) { 545 // VAARG is custom lowered with the 32-bit SVR4 ABI. 546 setOperationAction(ISD::VAARG, MVT::Other, Custom); 547 setOperationAction(ISD::VAARG, MVT::i64, Custom); 548 } else 549 setOperationAction(ISD::VAARG, MVT::Other, Expand); 550 551 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 552 if (Subtarget.is32BitELFABI()) 553 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 554 else 555 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 556 557 // Use the default implementation. 558 setOperationAction(ISD::VAEND , MVT::Other, Expand); 559 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 560 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 561 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 562 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 563 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 564 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 565 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 566 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 567 568 // We want to custom lower some of our intrinsics. 569 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 570 571 // To handle counter-based loop conditions. 572 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 573 574 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 575 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 576 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 577 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 578 579 // Comparisons that require checking two conditions. 580 if (Subtarget.hasSPE()) { 581 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 582 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 583 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 584 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 585 } 586 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 587 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 588 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 589 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 590 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 591 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 592 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 593 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 594 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 595 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 596 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 597 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 598 599 if (Subtarget.has64BitSupport()) { 600 // They also have instructions for converting between i64 and fp. 601 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 602 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 603 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 604 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 605 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 606 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 607 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 608 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 609 // This is just the low 32 bits of a (signed) fp->i64 conversion. 610 // We cannot do this with Promote because i64 is not a legal type. 611 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 612 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 613 614 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 615 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 616 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 617 } 618 } else { 619 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 620 if (Subtarget.hasSPE()) { 621 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 622 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 623 } else { 624 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 625 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 626 } 627 } 628 629 // With the instructions enabled under FPCVT, we can do everything. 630 if (Subtarget.hasFPCVT()) { 631 if (Subtarget.has64BitSupport()) { 632 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 633 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 634 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 635 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 636 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 637 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 638 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 639 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 640 } 641 642 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 643 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 644 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 645 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 646 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 647 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 648 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 649 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 650 } 651 652 if (Subtarget.use64BitRegs()) { 653 // 64-bit PowerPC implementations can support i64 types directly 654 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 655 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 656 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 657 // 64-bit PowerPC wants to expand i128 shifts itself. 658 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 659 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 660 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 661 } else { 662 // 32-bit PowerPC wants to expand i64 shifts itself. 663 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 664 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 665 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 666 } 667 668 // PowerPC has better expansions for funnel shifts than the generic 669 // TargetLowering::expandFunnelShift. 670 if (Subtarget.has64BitSupport()) { 671 setOperationAction(ISD::FSHL, MVT::i64, Custom); 672 setOperationAction(ISD::FSHR, MVT::i64, Custom); 673 } 674 setOperationAction(ISD::FSHL, MVT::i32, Custom); 675 setOperationAction(ISD::FSHR, MVT::i32, Custom); 676 677 if (Subtarget.hasVSX()) { 678 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 679 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 680 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 681 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 682 } 683 684 if (Subtarget.hasAltivec()) { 685 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 686 setOperationAction(ISD::SADDSAT, VT, Legal); 687 setOperationAction(ISD::SSUBSAT, VT, Legal); 688 setOperationAction(ISD::UADDSAT, VT, Legal); 689 setOperationAction(ISD::USUBSAT, VT, Legal); 690 } 691 // First set operation action for all vector types to expand. Then we 692 // will selectively turn on ones that can be effectively codegen'd. 693 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 694 // add/sub are legal for all supported vector VT's. 695 setOperationAction(ISD::ADD, VT, Legal); 696 setOperationAction(ISD::SUB, VT, Legal); 697 698 // For v2i64, these are only valid with P8Vector. This is corrected after 699 // the loop. 700 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 701 setOperationAction(ISD::SMAX, VT, Legal); 702 setOperationAction(ISD::SMIN, VT, Legal); 703 setOperationAction(ISD::UMAX, VT, Legal); 704 setOperationAction(ISD::UMIN, VT, Legal); 705 } 706 else { 707 setOperationAction(ISD::SMAX, VT, Expand); 708 setOperationAction(ISD::SMIN, VT, Expand); 709 setOperationAction(ISD::UMAX, VT, Expand); 710 setOperationAction(ISD::UMIN, VT, Expand); 711 } 712 713 if (Subtarget.hasVSX()) { 714 setOperationAction(ISD::FMAXNUM, VT, Legal); 715 setOperationAction(ISD::FMINNUM, VT, Legal); 716 } 717 718 // Vector instructions introduced in P8 719 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 720 setOperationAction(ISD::CTPOP, VT, Legal); 721 setOperationAction(ISD::CTLZ, VT, Legal); 722 } 723 else { 724 setOperationAction(ISD::CTPOP, VT, Expand); 725 setOperationAction(ISD::CTLZ, VT, Expand); 726 } 727 728 // Vector instructions introduced in P9 729 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 730 setOperationAction(ISD::CTTZ, VT, Legal); 731 else 732 setOperationAction(ISD::CTTZ, VT, Expand); 733 734 // We promote all shuffles to v16i8. 735 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 736 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 737 738 // We promote all non-typed operations to v4i32. 739 setOperationAction(ISD::AND , VT, Promote); 740 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 741 setOperationAction(ISD::OR , VT, Promote); 742 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 743 setOperationAction(ISD::XOR , VT, Promote); 744 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 745 setOperationAction(ISD::LOAD , VT, Promote); 746 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 747 setOperationAction(ISD::SELECT, VT, Promote); 748 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 749 setOperationAction(ISD::VSELECT, VT, Legal); 750 setOperationAction(ISD::SELECT_CC, VT, Promote); 751 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 752 setOperationAction(ISD::STORE, VT, Promote); 753 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 754 755 // No other operations are legal. 756 setOperationAction(ISD::MUL , VT, Expand); 757 setOperationAction(ISD::SDIV, VT, Expand); 758 setOperationAction(ISD::SREM, VT, Expand); 759 setOperationAction(ISD::UDIV, VT, Expand); 760 setOperationAction(ISD::UREM, VT, Expand); 761 setOperationAction(ISD::FDIV, VT, Expand); 762 setOperationAction(ISD::FREM, VT, Expand); 763 setOperationAction(ISD::FNEG, VT, Expand); 764 setOperationAction(ISD::FSQRT, VT, Expand); 765 setOperationAction(ISD::FLOG, VT, Expand); 766 setOperationAction(ISD::FLOG10, VT, Expand); 767 setOperationAction(ISD::FLOG2, VT, Expand); 768 setOperationAction(ISD::FEXP, VT, Expand); 769 setOperationAction(ISD::FEXP2, VT, Expand); 770 setOperationAction(ISD::FSIN, VT, Expand); 771 setOperationAction(ISD::FCOS, VT, Expand); 772 setOperationAction(ISD::FABS, VT, Expand); 773 setOperationAction(ISD::FFLOOR, VT, Expand); 774 setOperationAction(ISD::FCEIL, VT, Expand); 775 setOperationAction(ISD::FTRUNC, VT, Expand); 776 setOperationAction(ISD::FRINT, VT, Expand); 777 setOperationAction(ISD::FNEARBYINT, VT, Expand); 778 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 779 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 780 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 781 setOperationAction(ISD::MULHU, VT, Expand); 782 setOperationAction(ISD::MULHS, VT, Expand); 783 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 784 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 785 setOperationAction(ISD::UDIVREM, VT, Expand); 786 setOperationAction(ISD::SDIVREM, VT, Expand); 787 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 788 setOperationAction(ISD::FPOW, VT, Expand); 789 setOperationAction(ISD::BSWAP, VT, Expand); 790 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 791 setOperationAction(ISD::ROTL, VT, Expand); 792 setOperationAction(ISD::ROTR, VT, Expand); 793 794 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 795 setTruncStoreAction(VT, InnerVT, Expand); 796 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 797 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 798 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 799 } 800 } 801 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 802 if (!Subtarget.hasP8Vector()) { 803 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 804 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 805 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 806 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 807 } 808 809 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 810 setOperationAction(ISD::ABS, VT, Custom); 811 812 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 813 // with merges, splats, etc. 814 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 815 816 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 817 // are cheap, so handle them before they get expanded to scalar. 818 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 819 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 820 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 821 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 822 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 823 824 setOperationAction(ISD::AND , MVT::v4i32, Legal); 825 setOperationAction(ISD::OR , MVT::v4i32, Legal); 826 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 827 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 828 setOperationAction(ISD::SELECT, MVT::v4i32, 829 Subtarget.useCRBits() ? Legal : Expand); 830 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 831 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 832 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 833 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 834 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 835 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 836 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 837 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 838 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 839 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 840 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 841 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 842 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 843 844 // Without hasP8Altivec set, v2i64 SMAX isn't available. 845 // But ABS custom lowering requires SMAX support. 846 if (!Subtarget.hasP8Altivec()) 847 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 848 849 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 850 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 851 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 852 if (Subtarget.hasAltivec()) 853 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 854 setOperationAction(ISD::ROTL, VT, Legal); 855 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 856 if (Subtarget.hasP8Altivec()) 857 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 858 859 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 860 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 861 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 862 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 863 864 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 865 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 866 867 if (Subtarget.hasVSX()) { 868 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 869 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 870 } 871 872 if (Subtarget.hasP8Altivec()) 873 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 874 else 875 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 876 877 if (Subtarget.isISA3_1()) { 878 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 879 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 880 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 881 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 882 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 883 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 884 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 885 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 886 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 887 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 888 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 889 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 890 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 891 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 892 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 893 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 894 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 895 } 896 897 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 898 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 899 900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 902 903 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 904 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 905 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 906 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 907 908 // Altivec does not contain unordered floating-point compare instructions 909 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 910 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 911 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 912 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 913 914 if (Subtarget.hasVSX()) { 915 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 917 if (Subtarget.hasP8Vector()) { 918 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 919 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 920 } 921 if (Subtarget.hasDirectMove() && isPPC64) { 922 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 923 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 924 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 925 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 926 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 928 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 929 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 930 } 931 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 932 933 // The nearbyint variants are not allowed to raise the inexact exception 934 // so we can only code-gen them with unsafe math. 935 if (TM.Options.UnsafeFPMath) { 936 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 937 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 938 } 939 940 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 941 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 942 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 943 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 944 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 945 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 946 setOperationAction(ISD::FROUND, MVT::f64, Legal); 947 setOperationAction(ISD::FRINT, MVT::f64, Legal); 948 949 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 950 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 951 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 952 setOperationAction(ISD::FROUND, MVT::f32, Legal); 953 setOperationAction(ISD::FRINT, MVT::f32, Legal); 954 955 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 956 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 957 958 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 959 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 960 961 // Share the Altivec comparison restrictions. 962 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 963 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 964 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 965 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 966 967 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 968 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 969 970 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 971 972 if (Subtarget.hasP8Vector()) 973 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 974 975 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 976 977 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 978 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 979 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 980 981 if (Subtarget.hasP8Altivec()) { 982 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 983 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 984 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 985 986 // 128 bit shifts can be accomplished via 3 instructions for SHL and 987 // SRL, but not for SRA because of the instructions available: 988 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 989 // doing 990 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 991 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 992 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 993 994 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 995 } 996 else { 997 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 998 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 999 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1000 1001 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1002 1003 // VSX v2i64 only supports non-arithmetic operations. 1004 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1005 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1006 } 1007 1008 if (Subtarget.isISA3_1()) 1009 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1010 else 1011 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1012 1013 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1014 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1015 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1016 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1017 1018 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1019 1020 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1021 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1022 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1023 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1024 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1025 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1026 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1027 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1028 1029 // Custom handling for partial vectors of integers converted to 1030 // floating point. We already have optimal handling for v2i32 through 1031 // the DAG combine, so those aren't necessary. 1032 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1033 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1034 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1035 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1036 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1037 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1038 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1039 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1040 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1041 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1042 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1043 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1044 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1045 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1046 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1047 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1048 1049 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1050 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1051 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1052 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1053 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1054 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1055 1056 if (Subtarget.hasDirectMove()) 1057 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1058 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1059 1060 // Handle constrained floating-point operations of vector. 1061 // The predictor is `hasVSX` because altivec instruction has 1062 // no exception but VSX vector instruction has. 1063 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1064 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1065 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1066 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1067 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1068 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1069 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1070 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1071 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1072 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1073 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1074 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1075 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1076 1077 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1078 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1079 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1080 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1081 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1082 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1083 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1084 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1085 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1086 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1087 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1088 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1089 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1090 1091 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1092 } 1093 1094 if (Subtarget.hasP8Altivec()) { 1095 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1096 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1097 } 1098 1099 if (Subtarget.hasP9Vector()) { 1100 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1101 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1102 1103 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1104 // SRL, but not for SRA because of the instructions available: 1105 // VS{RL} and VS{RL}O. 1106 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1107 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1108 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1109 1110 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1111 setOperationAction(ISD::FADD, MVT::f128, Legal); 1112 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1113 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1114 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1115 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1116 // No extending loads to f128 on PPC. 1117 for (MVT FPT : MVT::fp_valuetypes()) 1118 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1119 setOperationAction(ISD::FMA, MVT::f128, Legal); 1120 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1121 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1122 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1123 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1124 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1125 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1126 1127 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1128 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1129 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1130 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1131 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1132 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1133 1134 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1135 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1136 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1137 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1138 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1139 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1140 // No implementation for these ops for PowerPC. 1141 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1142 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1143 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1144 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1145 setOperationAction(ISD::FREM, MVT::f128, Expand); 1146 1147 // Handle constrained floating-point operations of fp128 1148 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1149 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1150 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1151 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1152 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1153 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1154 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1155 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1156 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1157 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1158 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1159 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1160 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1161 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1162 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1163 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1164 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1165 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1166 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1167 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1168 } 1169 1170 if (Subtarget.hasP9Altivec()) { 1171 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1172 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1173 1174 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1175 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1176 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1177 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1178 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1179 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1180 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1181 } 1182 } 1183 1184 if (Subtarget.pairedVectorMemops()) { 1185 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1186 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1187 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1188 } 1189 if (Subtarget.hasMMA()) { 1190 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1191 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1192 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1193 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1194 } 1195 1196 if (Subtarget.has64BitSupport()) 1197 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1198 1199 if (Subtarget.isISA3_1()) 1200 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1201 1202 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1203 1204 if (!isPPC64) { 1205 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1206 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1207 } 1208 1209 setBooleanContents(ZeroOrOneBooleanContent); 1210 1211 if (Subtarget.hasAltivec()) { 1212 // Altivec instructions set fields to all zeros or all ones. 1213 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1214 } 1215 1216 if (!isPPC64) { 1217 // These libcalls are not available in 32-bit. 1218 setLibcallName(RTLIB::SHL_I128, nullptr); 1219 setLibcallName(RTLIB::SRL_I128, nullptr); 1220 setLibcallName(RTLIB::SRA_I128, nullptr); 1221 } 1222 1223 if (!isPPC64) 1224 setMaxAtomicSizeInBitsSupported(32); 1225 1226 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1227 1228 // We have target-specific dag combine patterns for the following nodes: 1229 setTargetDAGCombine(ISD::ADD); 1230 setTargetDAGCombine(ISD::SHL); 1231 setTargetDAGCombine(ISD::SRA); 1232 setTargetDAGCombine(ISD::SRL); 1233 setTargetDAGCombine(ISD::MUL); 1234 setTargetDAGCombine(ISD::FMA); 1235 setTargetDAGCombine(ISD::SINT_TO_FP); 1236 setTargetDAGCombine(ISD::BUILD_VECTOR); 1237 if (Subtarget.hasFPCVT()) 1238 setTargetDAGCombine(ISD::UINT_TO_FP); 1239 setTargetDAGCombine(ISD::LOAD); 1240 setTargetDAGCombine(ISD::STORE); 1241 setTargetDAGCombine(ISD::BR_CC); 1242 if (Subtarget.useCRBits()) 1243 setTargetDAGCombine(ISD::BRCOND); 1244 setTargetDAGCombine(ISD::BSWAP); 1245 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1246 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1247 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1248 1249 setTargetDAGCombine(ISD::SIGN_EXTEND); 1250 setTargetDAGCombine(ISD::ZERO_EXTEND); 1251 setTargetDAGCombine(ISD::ANY_EXTEND); 1252 1253 setTargetDAGCombine(ISD::TRUNCATE); 1254 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1255 1256 1257 if (Subtarget.useCRBits()) { 1258 setTargetDAGCombine(ISD::TRUNCATE); 1259 setTargetDAGCombine(ISD::SETCC); 1260 setTargetDAGCombine(ISD::SELECT_CC); 1261 } 1262 1263 if (Subtarget.hasP9Altivec()) { 1264 setTargetDAGCombine(ISD::ABS); 1265 setTargetDAGCombine(ISD::VSELECT); 1266 } 1267 1268 setLibcallName(RTLIB::LOG_F128, "logf128"); 1269 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1270 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1271 setLibcallName(RTLIB::EXP_F128, "expf128"); 1272 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1273 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1274 setLibcallName(RTLIB::COS_F128, "cosf128"); 1275 setLibcallName(RTLIB::POW_F128, "powf128"); 1276 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1277 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1278 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1279 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1280 1281 // With 32 condition bits, we don't need to sink (and duplicate) compares 1282 // aggressively in CodeGenPrep. 1283 if (Subtarget.useCRBits()) { 1284 setHasMultipleConditionRegisters(); 1285 setJumpIsExpensive(); 1286 } 1287 1288 setMinFunctionAlignment(Align(4)); 1289 1290 switch (Subtarget.getCPUDirective()) { 1291 default: break; 1292 case PPC::DIR_970: 1293 case PPC::DIR_A2: 1294 case PPC::DIR_E500: 1295 case PPC::DIR_E500mc: 1296 case PPC::DIR_E5500: 1297 case PPC::DIR_PWR4: 1298 case PPC::DIR_PWR5: 1299 case PPC::DIR_PWR5X: 1300 case PPC::DIR_PWR6: 1301 case PPC::DIR_PWR6X: 1302 case PPC::DIR_PWR7: 1303 case PPC::DIR_PWR8: 1304 case PPC::DIR_PWR9: 1305 case PPC::DIR_PWR10: 1306 case PPC::DIR_PWR_FUTURE: 1307 setPrefLoopAlignment(Align(16)); 1308 setPrefFunctionAlignment(Align(16)); 1309 break; 1310 } 1311 1312 if (Subtarget.enableMachineScheduler()) 1313 setSchedulingPreference(Sched::Source); 1314 else 1315 setSchedulingPreference(Sched::Hybrid); 1316 1317 computeRegisterProperties(STI.getRegisterInfo()); 1318 1319 // The Freescale cores do better with aggressive inlining of memcpy and 1320 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1321 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1322 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1323 MaxStoresPerMemset = 32; 1324 MaxStoresPerMemsetOptSize = 16; 1325 MaxStoresPerMemcpy = 32; 1326 MaxStoresPerMemcpyOptSize = 8; 1327 MaxStoresPerMemmove = 32; 1328 MaxStoresPerMemmoveOptSize = 8; 1329 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1330 // The A2 also benefits from (very) aggressive inlining of memcpy and 1331 // friends. The overhead of a the function call, even when warm, can be 1332 // over one hundred cycles. 1333 MaxStoresPerMemset = 128; 1334 MaxStoresPerMemcpy = 128; 1335 MaxStoresPerMemmove = 128; 1336 MaxLoadsPerMemcmp = 128; 1337 } else { 1338 MaxLoadsPerMemcmp = 8; 1339 MaxLoadsPerMemcmpOptSize = 4; 1340 } 1341 1342 IsStrictFPEnabled = true; 1343 1344 // Let the subtarget (CPU) decide if a predictable select is more expensive 1345 // than the corresponding branch. This information is used in CGP to decide 1346 // when to convert selects into branches. 1347 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1348 } 1349 1350 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1351 /// the desired ByVal argument alignment. 1352 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1353 if (MaxAlign == MaxMaxAlign) 1354 return; 1355 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1356 if (MaxMaxAlign >= 32 && 1357 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1358 MaxAlign = Align(32); 1359 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1360 MaxAlign < 16) 1361 MaxAlign = Align(16); 1362 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1363 Align EltAlign; 1364 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1365 if (EltAlign > MaxAlign) 1366 MaxAlign = EltAlign; 1367 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1368 for (auto *EltTy : STy->elements()) { 1369 Align EltAlign; 1370 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1371 if (EltAlign > MaxAlign) 1372 MaxAlign = EltAlign; 1373 if (MaxAlign == MaxMaxAlign) 1374 break; 1375 } 1376 } 1377 } 1378 1379 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1380 /// function arguments in the caller parameter area. 1381 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1382 const DataLayout &DL) const { 1383 // 16byte and wider vectors are passed on 16byte boundary. 1384 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1385 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1386 if (Subtarget.hasAltivec()) 1387 getMaxByValAlign(Ty, Alignment, Align(16)); 1388 return Alignment.value(); 1389 } 1390 1391 bool PPCTargetLowering::useSoftFloat() const { 1392 return Subtarget.useSoftFloat(); 1393 } 1394 1395 bool PPCTargetLowering::hasSPE() const { 1396 return Subtarget.hasSPE(); 1397 } 1398 1399 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1400 return VT.isScalarInteger(); 1401 } 1402 1403 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1404 /// type is cheaper than a multiply followed by a shift. 1405 /// This is true for words and doublewords on 64-bit PowerPC. 1406 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1407 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1408 isOperationLegal(ISD::MULHU, Type))) 1409 return true; 1410 return TargetLowering::isMulhCheaperThanMulShift(Type); 1411 } 1412 1413 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1414 switch ((PPCISD::NodeType)Opcode) { 1415 case PPCISD::FIRST_NUMBER: break; 1416 case PPCISD::FSEL: return "PPCISD::FSEL"; 1417 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1418 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1419 case PPCISD::FCFID: return "PPCISD::FCFID"; 1420 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1421 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1422 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1423 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1424 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1425 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1426 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1427 case PPCISD::FP_TO_UINT_IN_VSR: 1428 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1429 case PPCISD::FP_TO_SINT_IN_VSR: 1430 return "PPCISD::FP_TO_SINT_IN_VSR"; 1431 case PPCISD::FRE: return "PPCISD::FRE"; 1432 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1433 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1434 case PPCISD::VPERM: return "PPCISD::VPERM"; 1435 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1436 case PPCISD::XXSPLTI_SP_TO_DP: 1437 return "PPCISD::XXSPLTI_SP_TO_DP"; 1438 case PPCISD::XXSPLTI32DX: 1439 return "PPCISD::XXSPLTI32DX"; 1440 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1441 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1442 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1443 case PPCISD::CMPB: return "PPCISD::CMPB"; 1444 case PPCISD::Hi: return "PPCISD::Hi"; 1445 case PPCISD::Lo: return "PPCISD::Lo"; 1446 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1447 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1448 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1449 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1450 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1451 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1452 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1453 case PPCISD::SRL: return "PPCISD::SRL"; 1454 case PPCISD::SRA: return "PPCISD::SRA"; 1455 case PPCISD::SHL: return "PPCISD::SHL"; 1456 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1457 case PPCISD::CALL: return "PPCISD::CALL"; 1458 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1459 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1460 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1461 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1462 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1463 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1464 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1465 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1466 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1467 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1468 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1469 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1470 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1471 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1472 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1473 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1474 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1475 case PPCISD::ANDI_rec_1_EQ_BIT: 1476 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1477 case PPCISD::ANDI_rec_1_GT_BIT: 1478 return "PPCISD::ANDI_rec_1_GT_BIT"; 1479 case PPCISD::VCMP: return "PPCISD::VCMP"; 1480 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1481 case PPCISD::LBRX: return "PPCISD::LBRX"; 1482 case PPCISD::STBRX: return "PPCISD::STBRX"; 1483 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1484 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1485 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1486 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1487 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1488 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1489 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1490 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1491 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1492 case PPCISD::ST_VSR_SCAL_INT: 1493 return "PPCISD::ST_VSR_SCAL_INT"; 1494 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1495 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1496 case PPCISD::BDZ: return "PPCISD::BDZ"; 1497 case PPCISD::MFFS: return "PPCISD::MFFS"; 1498 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1499 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1500 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1501 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1502 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1503 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1504 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1505 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1506 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1507 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1508 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1509 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1510 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1511 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1512 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1513 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1514 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1515 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1516 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1517 case PPCISD::PADDI_DTPREL: 1518 return "PPCISD::PADDI_DTPREL"; 1519 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1520 case PPCISD::SC: return "PPCISD::SC"; 1521 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1522 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1523 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1524 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1525 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1526 case PPCISD::VABSD: return "PPCISD::VABSD"; 1527 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1528 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1529 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1530 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1531 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1532 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1533 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1534 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1535 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1536 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1537 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1538 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1539 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1540 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1541 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1542 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1543 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1544 case PPCISD::STRICT_FADDRTZ: 1545 return "PPCISD::STRICT_FADDRTZ"; 1546 case PPCISD::STRICT_FCTIDZ: 1547 return "PPCISD::STRICT_FCTIDZ"; 1548 case PPCISD::STRICT_FCTIWZ: 1549 return "PPCISD::STRICT_FCTIWZ"; 1550 case PPCISD::STRICT_FCTIDUZ: 1551 return "PPCISD::STRICT_FCTIDUZ"; 1552 case PPCISD::STRICT_FCTIWUZ: 1553 return "PPCISD::STRICT_FCTIWUZ"; 1554 case PPCISD::STRICT_FCFID: 1555 return "PPCISD::STRICT_FCFID"; 1556 case PPCISD::STRICT_FCFIDU: 1557 return "PPCISD::STRICT_FCFIDU"; 1558 case PPCISD::STRICT_FCFIDS: 1559 return "PPCISD::STRICT_FCFIDS"; 1560 case PPCISD::STRICT_FCFIDUS: 1561 return "PPCISD::STRICT_FCFIDUS"; 1562 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1563 } 1564 return nullptr; 1565 } 1566 1567 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1568 EVT VT) const { 1569 if (!VT.isVector()) 1570 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1571 1572 return VT.changeVectorElementTypeToInteger(); 1573 } 1574 1575 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1576 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1577 return true; 1578 } 1579 1580 //===----------------------------------------------------------------------===// 1581 // Node matching predicates, for use by the tblgen matching code. 1582 //===----------------------------------------------------------------------===// 1583 1584 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1585 static bool isFloatingPointZero(SDValue Op) { 1586 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1587 return CFP->getValueAPF().isZero(); 1588 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1589 // Maybe this has already been legalized into the constant pool? 1590 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1591 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1592 return CFP->getValueAPF().isZero(); 1593 } 1594 return false; 1595 } 1596 1597 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1598 /// true if Op is undef or if it matches the specified value. 1599 static bool isConstantOrUndef(int Op, int Val) { 1600 return Op < 0 || Op == Val; 1601 } 1602 1603 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1604 /// VPKUHUM instruction. 1605 /// The ShuffleKind distinguishes between big-endian operations with 1606 /// two different inputs (0), either-endian operations with two identical 1607 /// inputs (1), and little-endian operations with two different inputs (2). 1608 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1609 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1610 SelectionDAG &DAG) { 1611 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1612 if (ShuffleKind == 0) { 1613 if (IsLE) 1614 return false; 1615 for (unsigned i = 0; i != 16; ++i) 1616 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1617 return false; 1618 } else if (ShuffleKind == 2) { 1619 if (!IsLE) 1620 return false; 1621 for (unsigned i = 0; i != 16; ++i) 1622 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1623 return false; 1624 } else if (ShuffleKind == 1) { 1625 unsigned j = IsLE ? 0 : 1; 1626 for (unsigned i = 0; i != 8; ++i) 1627 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1628 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1629 return false; 1630 } 1631 return true; 1632 } 1633 1634 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1635 /// VPKUWUM instruction. 1636 /// The ShuffleKind distinguishes between big-endian operations with 1637 /// two different inputs (0), either-endian operations with two identical 1638 /// inputs (1), and little-endian operations with two different inputs (2). 1639 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1640 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1641 SelectionDAG &DAG) { 1642 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1643 if (ShuffleKind == 0) { 1644 if (IsLE) 1645 return false; 1646 for (unsigned i = 0; i != 16; i += 2) 1647 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1648 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1649 return false; 1650 } else if (ShuffleKind == 2) { 1651 if (!IsLE) 1652 return false; 1653 for (unsigned i = 0; i != 16; i += 2) 1654 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1655 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1656 return false; 1657 } else if (ShuffleKind == 1) { 1658 unsigned j = IsLE ? 0 : 2; 1659 for (unsigned i = 0; i != 8; i += 2) 1660 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1661 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1662 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1663 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1664 return false; 1665 } 1666 return true; 1667 } 1668 1669 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1670 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1671 /// current subtarget. 1672 /// 1673 /// The ShuffleKind distinguishes between big-endian operations with 1674 /// two different inputs (0), either-endian operations with two identical 1675 /// inputs (1), and little-endian operations with two different inputs (2). 1676 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1677 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1678 SelectionDAG &DAG) { 1679 const PPCSubtarget& Subtarget = 1680 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1681 if (!Subtarget.hasP8Vector()) 1682 return false; 1683 1684 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1685 if (ShuffleKind == 0) { 1686 if (IsLE) 1687 return false; 1688 for (unsigned i = 0; i != 16; i += 4) 1689 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1690 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1691 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1692 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1693 return false; 1694 } else if (ShuffleKind == 2) { 1695 if (!IsLE) 1696 return false; 1697 for (unsigned i = 0; i != 16; i += 4) 1698 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1699 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1700 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1701 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1702 return false; 1703 } else if (ShuffleKind == 1) { 1704 unsigned j = IsLE ? 0 : 4; 1705 for (unsigned i = 0; i != 8; i += 4) 1706 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1707 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1708 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1709 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1710 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1711 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1712 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1713 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1714 return false; 1715 } 1716 return true; 1717 } 1718 1719 /// isVMerge - Common function, used to match vmrg* shuffles. 1720 /// 1721 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1722 unsigned LHSStart, unsigned RHSStart) { 1723 if (N->getValueType(0) != MVT::v16i8) 1724 return false; 1725 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1726 "Unsupported merge size!"); 1727 1728 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1729 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1730 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1731 LHSStart+j+i*UnitSize) || 1732 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1733 RHSStart+j+i*UnitSize)) 1734 return false; 1735 } 1736 return true; 1737 } 1738 1739 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1740 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1741 /// The ShuffleKind distinguishes between big-endian merges with two 1742 /// different inputs (0), either-endian merges with two identical inputs (1), 1743 /// and little-endian merges with two different inputs (2). For the latter, 1744 /// the input operands are swapped (see PPCInstrAltivec.td). 1745 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1746 unsigned ShuffleKind, SelectionDAG &DAG) { 1747 if (DAG.getDataLayout().isLittleEndian()) { 1748 if (ShuffleKind == 1) // unary 1749 return isVMerge(N, UnitSize, 0, 0); 1750 else if (ShuffleKind == 2) // swapped 1751 return isVMerge(N, UnitSize, 0, 16); 1752 else 1753 return false; 1754 } else { 1755 if (ShuffleKind == 1) // unary 1756 return isVMerge(N, UnitSize, 8, 8); 1757 else if (ShuffleKind == 0) // normal 1758 return isVMerge(N, UnitSize, 8, 24); 1759 else 1760 return false; 1761 } 1762 } 1763 1764 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1765 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1766 /// The ShuffleKind distinguishes between big-endian merges with two 1767 /// different inputs (0), either-endian merges with two identical inputs (1), 1768 /// and little-endian merges with two different inputs (2). For the latter, 1769 /// the input operands are swapped (see PPCInstrAltivec.td). 1770 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1771 unsigned ShuffleKind, SelectionDAG &DAG) { 1772 if (DAG.getDataLayout().isLittleEndian()) { 1773 if (ShuffleKind == 1) // unary 1774 return isVMerge(N, UnitSize, 8, 8); 1775 else if (ShuffleKind == 2) // swapped 1776 return isVMerge(N, UnitSize, 8, 24); 1777 else 1778 return false; 1779 } else { 1780 if (ShuffleKind == 1) // unary 1781 return isVMerge(N, UnitSize, 0, 0); 1782 else if (ShuffleKind == 0) // normal 1783 return isVMerge(N, UnitSize, 0, 16); 1784 else 1785 return false; 1786 } 1787 } 1788 1789 /** 1790 * Common function used to match vmrgew and vmrgow shuffles 1791 * 1792 * The indexOffset determines whether to look for even or odd words in 1793 * the shuffle mask. This is based on the of the endianness of the target 1794 * machine. 1795 * - Little Endian: 1796 * - Use offset of 0 to check for odd elements 1797 * - Use offset of 4 to check for even elements 1798 * - Big Endian: 1799 * - Use offset of 0 to check for even elements 1800 * - Use offset of 4 to check for odd elements 1801 * A detailed description of the vector element ordering for little endian and 1802 * big endian can be found at 1803 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1804 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1805 * compiler differences mean to you 1806 * 1807 * The mask to the shuffle vector instruction specifies the indices of the 1808 * elements from the two input vectors to place in the result. The elements are 1809 * numbered in array-access order, starting with the first vector. These vectors 1810 * are always of type v16i8, thus each vector will contain 16 elements of size 1811 * 8. More info on the shuffle vector can be found in the 1812 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1813 * Language Reference. 1814 * 1815 * The RHSStartValue indicates whether the same input vectors are used (unary) 1816 * or two different input vectors are used, based on the following: 1817 * - If the instruction uses the same vector for both inputs, the range of the 1818 * indices will be 0 to 15. In this case, the RHSStart value passed should 1819 * be 0. 1820 * - If the instruction has two different vectors then the range of the 1821 * indices will be 0 to 31. In this case, the RHSStart value passed should 1822 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1823 * to 31 specify elements in the second vector). 1824 * 1825 * \param[in] N The shuffle vector SD Node to analyze 1826 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1827 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1828 * vector to the shuffle_vector instruction 1829 * \return true iff this shuffle vector represents an even or odd word merge 1830 */ 1831 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1832 unsigned RHSStartValue) { 1833 if (N->getValueType(0) != MVT::v16i8) 1834 return false; 1835 1836 for (unsigned i = 0; i < 2; ++i) 1837 for (unsigned j = 0; j < 4; ++j) 1838 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1839 i*RHSStartValue+j+IndexOffset) || 1840 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1841 i*RHSStartValue+j+IndexOffset+8)) 1842 return false; 1843 return true; 1844 } 1845 1846 /** 1847 * Determine if the specified shuffle mask is suitable for the vmrgew or 1848 * vmrgow instructions. 1849 * 1850 * \param[in] N The shuffle vector SD Node to analyze 1851 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1852 * \param[in] ShuffleKind Identify the type of merge: 1853 * - 0 = big-endian merge with two different inputs; 1854 * - 1 = either-endian merge with two identical inputs; 1855 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1856 * little-endian merges). 1857 * \param[in] DAG The current SelectionDAG 1858 * \return true iff this shuffle mask 1859 */ 1860 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1861 unsigned ShuffleKind, SelectionDAG &DAG) { 1862 if (DAG.getDataLayout().isLittleEndian()) { 1863 unsigned indexOffset = CheckEven ? 4 : 0; 1864 if (ShuffleKind == 1) // Unary 1865 return isVMerge(N, indexOffset, 0); 1866 else if (ShuffleKind == 2) // swapped 1867 return isVMerge(N, indexOffset, 16); 1868 else 1869 return false; 1870 } 1871 else { 1872 unsigned indexOffset = CheckEven ? 0 : 4; 1873 if (ShuffleKind == 1) // Unary 1874 return isVMerge(N, indexOffset, 0); 1875 else if (ShuffleKind == 0) // Normal 1876 return isVMerge(N, indexOffset, 16); 1877 else 1878 return false; 1879 } 1880 return false; 1881 } 1882 1883 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1884 /// amount, otherwise return -1. 1885 /// The ShuffleKind distinguishes between big-endian operations with two 1886 /// different inputs (0), either-endian operations with two identical inputs 1887 /// (1), and little-endian operations with two different inputs (2). For the 1888 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1889 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1890 SelectionDAG &DAG) { 1891 if (N->getValueType(0) != MVT::v16i8) 1892 return -1; 1893 1894 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1895 1896 // Find the first non-undef value in the shuffle mask. 1897 unsigned i; 1898 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1899 /*search*/; 1900 1901 if (i == 16) return -1; // all undef. 1902 1903 // Otherwise, check to see if the rest of the elements are consecutively 1904 // numbered from this value. 1905 unsigned ShiftAmt = SVOp->getMaskElt(i); 1906 if (ShiftAmt < i) return -1; 1907 1908 ShiftAmt -= i; 1909 bool isLE = DAG.getDataLayout().isLittleEndian(); 1910 1911 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1912 // Check the rest of the elements to see if they are consecutive. 1913 for (++i; i != 16; ++i) 1914 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1915 return -1; 1916 } else if (ShuffleKind == 1) { 1917 // Check the rest of the elements to see if they are consecutive. 1918 for (++i; i != 16; ++i) 1919 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1920 return -1; 1921 } else 1922 return -1; 1923 1924 if (isLE) 1925 ShiftAmt = 16 - ShiftAmt; 1926 1927 return ShiftAmt; 1928 } 1929 1930 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1931 /// specifies a splat of a single element that is suitable for input to 1932 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1933 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1934 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1935 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1936 1937 // The consecutive indices need to specify an element, not part of two 1938 // different elements. So abandon ship early if this isn't the case. 1939 if (N->getMaskElt(0) % EltSize != 0) 1940 return false; 1941 1942 // This is a splat operation if each element of the permute is the same, and 1943 // if the value doesn't reference the second vector. 1944 unsigned ElementBase = N->getMaskElt(0); 1945 1946 // FIXME: Handle UNDEF elements too! 1947 if (ElementBase >= 16) 1948 return false; 1949 1950 // Check that the indices are consecutive, in the case of a multi-byte element 1951 // splatted with a v16i8 mask. 1952 for (unsigned i = 1; i != EltSize; ++i) 1953 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1954 return false; 1955 1956 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1957 if (N->getMaskElt(i) < 0) continue; 1958 for (unsigned j = 0; j != EltSize; ++j) 1959 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1960 return false; 1961 } 1962 return true; 1963 } 1964 1965 /// Check that the mask is shuffling N byte elements. Within each N byte 1966 /// element of the mask, the indices could be either in increasing or 1967 /// decreasing order as long as they are consecutive. 1968 /// \param[in] N the shuffle vector SD Node to analyze 1969 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1970 /// Word/DoubleWord/QuadWord). 1971 /// \param[in] StepLen the delta indices number among the N byte element, if 1972 /// the mask is in increasing/decreasing order then it is 1/-1. 1973 /// \return true iff the mask is shuffling N byte elements. 1974 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1975 int StepLen) { 1976 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1977 "Unexpected element width."); 1978 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1979 1980 unsigned NumOfElem = 16 / Width; 1981 unsigned MaskVal[16]; // Width is never greater than 16 1982 for (unsigned i = 0; i < NumOfElem; ++i) { 1983 MaskVal[0] = N->getMaskElt(i * Width); 1984 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1985 return false; 1986 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1987 return false; 1988 } 1989 1990 for (unsigned int j = 1; j < Width; ++j) { 1991 MaskVal[j] = N->getMaskElt(i * Width + j); 1992 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1993 return false; 1994 } 1995 } 1996 } 1997 1998 return true; 1999 } 2000 2001 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2002 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2003 if (!isNByteElemShuffleMask(N, 4, 1)) 2004 return false; 2005 2006 // Now we look at mask elements 0,4,8,12 2007 unsigned M0 = N->getMaskElt(0) / 4; 2008 unsigned M1 = N->getMaskElt(4) / 4; 2009 unsigned M2 = N->getMaskElt(8) / 4; 2010 unsigned M3 = N->getMaskElt(12) / 4; 2011 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2012 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2013 2014 // Below, let H and L be arbitrary elements of the shuffle mask 2015 // where H is in the range [4,7] and L is in the range [0,3]. 2016 // H, 1, 2, 3 or L, 5, 6, 7 2017 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2018 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2019 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2020 InsertAtByte = IsLE ? 12 : 0; 2021 Swap = M0 < 4; 2022 return true; 2023 } 2024 // 0, H, 2, 3 or 4, L, 6, 7 2025 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2026 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2027 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2028 InsertAtByte = IsLE ? 8 : 4; 2029 Swap = M1 < 4; 2030 return true; 2031 } 2032 // 0, 1, H, 3 or 4, 5, L, 7 2033 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2034 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2035 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2036 InsertAtByte = IsLE ? 4 : 8; 2037 Swap = M2 < 4; 2038 return true; 2039 } 2040 // 0, 1, 2, H or 4, 5, 6, L 2041 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2042 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2043 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2044 InsertAtByte = IsLE ? 0 : 12; 2045 Swap = M3 < 4; 2046 return true; 2047 } 2048 2049 // If both vector operands for the shuffle are the same vector, the mask will 2050 // contain only elements from the first one and the second one will be undef. 2051 if (N->getOperand(1).isUndef()) { 2052 ShiftElts = 0; 2053 Swap = true; 2054 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2055 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2056 InsertAtByte = IsLE ? 12 : 0; 2057 return true; 2058 } 2059 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2060 InsertAtByte = IsLE ? 8 : 4; 2061 return true; 2062 } 2063 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2064 InsertAtByte = IsLE ? 4 : 8; 2065 return true; 2066 } 2067 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2068 InsertAtByte = IsLE ? 0 : 12; 2069 return true; 2070 } 2071 } 2072 2073 return false; 2074 } 2075 2076 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2077 bool &Swap, bool IsLE) { 2078 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2079 // Ensure each byte index of the word is consecutive. 2080 if (!isNByteElemShuffleMask(N, 4, 1)) 2081 return false; 2082 2083 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2084 unsigned M0 = N->getMaskElt(0) / 4; 2085 unsigned M1 = N->getMaskElt(4) / 4; 2086 unsigned M2 = N->getMaskElt(8) / 4; 2087 unsigned M3 = N->getMaskElt(12) / 4; 2088 2089 // If both vector operands for the shuffle are the same vector, the mask will 2090 // contain only elements from the first one and the second one will be undef. 2091 if (N->getOperand(1).isUndef()) { 2092 assert(M0 < 4 && "Indexing into an undef vector?"); 2093 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2094 return false; 2095 2096 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2097 Swap = false; 2098 return true; 2099 } 2100 2101 // Ensure each word index of the ShuffleVector Mask is consecutive. 2102 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2103 return false; 2104 2105 if (IsLE) { 2106 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2107 // Input vectors don't need to be swapped if the leading element 2108 // of the result is one of the 3 left elements of the second vector 2109 // (or if there is no shift to be done at all). 2110 Swap = false; 2111 ShiftElts = (8 - M0) % 8; 2112 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2113 // Input vectors need to be swapped if the leading element 2114 // of the result is one of the 3 left elements of the first vector 2115 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2116 Swap = true; 2117 ShiftElts = (4 - M0) % 4; 2118 } 2119 2120 return true; 2121 } else { // BE 2122 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2123 // Input vectors don't need to be swapped if the leading element 2124 // of the result is one of the 4 elements of the first vector. 2125 Swap = false; 2126 ShiftElts = M0; 2127 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2128 // Input vectors need to be swapped if the leading element 2129 // of the result is one of the 4 elements of the right vector. 2130 Swap = true; 2131 ShiftElts = M0 - 4; 2132 } 2133 2134 return true; 2135 } 2136 } 2137 2138 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2139 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2140 2141 if (!isNByteElemShuffleMask(N, Width, -1)) 2142 return false; 2143 2144 for (int i = 0; i < 16; i += Width) 2145 if (N->getMaskElt(i) != i + Width - 1) 2146 return false; 2147 2148 return true; 2149 } 2150 2151 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2152 return isXXBRShuffleMaskHelper(N, 2); 2153 } 2154 2155 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2156 return isXXBRShuffleMaskHelper(N, 4); 2157 } 2158 2159 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2160 return isXXBRShuffleMaskHelper(N, 8); 2161 } 2162 2163 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2164 return isXXBRShuffleMaskHelper(N, 16); 2165 } 2166 2167 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2168 /// if the inputs to the instruction should be swapped and set \p DM to the 2169 /// value for the immediate. 2170 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2171 /// AND element 0 of the result comes from the first input (LE) or second input 2172 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2173 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2174 /// mask. 2175 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2176 bool &Swap, bool IsLE) { 2177 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2178 2179 // Ensure each byte index of the double word is consecutive. 2180 if (!isNByteElemShuffleMask(N, 8, 1)) 2181 return false; 2182 2183 unsigned M0 = N->getMaskElt(0) / 8; 2184 unsigned M1 = N->getMaskElt(8) / 8; 2185 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2186 2187 // If both vector operands for the shuffle are the same vector, the mask will 2188 // contain only elements from the first one and the second one will be undef. 2189 if (N->getOperand(1).isUndef()) { 2190 if ((M0 | M1) < 2) { 2191 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2192 Swap = false; 2193 return true; 2194 } else 2195 return false; 2196 } 2197 2198 if (IsLE) { 2199 if (M0 > 1 && M1 < 2) { 2200 Swap = false; 2201 } else if (M0 < 2 && M1 > 1) { 2202 M0 = (M0 + 2) % 4; 2203 M1 = (M1 + 2) % 4; 2204 Swap = true; 2205 } else 2206 return false; 2207 2208 // Note: if control flow comes here that means Swap is already set above 2209 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2210 return true; 2211 } else { // BE 2212 if (M0 < 2 && M1 > 1) { 2213 Swap = false; 2214 } else if (M0 > 1 && M1 < 2) { 2215 M0 = (M0 + 2) % 4; 2216 M1 = (M1 + 2) % 4; 2217 Swap = true; 2218 } else 2219 return false; 2220 2221 // Note: if control flow comes here that means Swap is already set above 2222 DM = (M0 << 1) + (M1 & 1); 2223 return true; 2224 } 2225 } 2226 2227 2228 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2229 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2230 /// elements are counted from the left of the vector register). 2231 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2232 SelectionDAG &DAG) { 2233 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2234 assert(isSplatShuffleMask(SVOp, EltSize)); 2235 if (DAG.getDataLayout().isLittleEndian()) 2236 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2237 else 2238 return SVOp->getMaskElt(0) / EltSize; 2239 } 2240 2241 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2242 /// by using a vspltis[bhw] instruction of the specified element size, return 2243 /// the constant being splatted. The ByteSize field indicates the number of 2244 /// bytes of each element [124] -> [bhw]. 2245 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2246 SDValue OpVal(nullptr, 0); 2247 2248 // If ByteSize of the splat is bigger than the element size of the 2249 // build_vector, then we have a case where we are checking for a splat where 2250 // multiple elements of the buildvector are folded together into a single 2251 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2252 unsigned EltSize = 16/N->getNumOperands(); 2253 if (EltSize < ByteSize) { 2254 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2255 SDValue UniquedVals[4]; 2256 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2257 2258 // See if all of the elements in the buildvector agree across. 2259 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2260 if (N->getOperand(i).isUndef()) continue; 2261 // If the element isn't a constant, bail fully out. 2262 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2263 2264 if (!UniquedVals[i&(Multiple-1)].getNode()) 2265 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2266 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2267 return SDValue(); // no match. 2268 } 2269 2270 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2271 // either constant or undef values that are identical for each chunk. See 2272 // if these chunks can form into a larger vspltis*. 2273 2274 // Check to see if all of the leading entries are either 0 or -1. If 2275 // neither, then this won't fit into the immediate field. 2276 bool LeadingZero = true; 2277 bool LeadingOnes = true; 2278 for (unsigned i = 0; i != Multiple-1; ++i) { 2279 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2280 2281 LeadingZero &= isNullConstant(UniquedVals[i]); 2282 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2283 } 2284 // Finally, check the least significant entry. 2285 if (LeadingZero) { 2286 if (!UniquedVals[Multiple-1].getNode()) 2287 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2288 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2289 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2290 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2291 } 2292 if (LeadingOnes) { 2293 if (!UniquedVals[Multiple-1].getNode()) 2294 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2295 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2296 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2297 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2298 } 2299 2300 return SDValue(); 2301 } 2302 2303 // Check to see if this buildvec has a single non-undef value in its elements. 2304 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2305 if (N->getOperand(i).isUndef()) continue; 2306 if (!OpVal.getNode()) 2307 OpVal = N->getOperand(i); 2308 else if (OpVal != N->getOperand(i)) 2309 return SDValue(); 2310 } 2311 2312 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2313 2314 unsigned ValSizeInBytes = EltSize; 2315 uint64_t Value = 0; 2316 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2317 Value = CN->getZExtValue(); 2318 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2319 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2320 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2321 } 2322 2323 // If the splat value is larger than the element value, then we can never do 2324 // this splat. The only case that we could fit the replicated bits into our 2325 // immediate field for would be zero, and we prefer to use vxor for it. 2326 if (ValSizeInBytes < ByteSize) return SDValue(); 2327 2328 // If the element value is larger than the splat value, check if it consists 2329 // of a repeated bit pattern of size ByteSize. 2330 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2331 return SDValue(); 2332 2333 // Properly sign extend the value. 2334 int MaskVal = SignExtend32(Value, ByteSize * 8); 2335 2336 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2337 if (MaskVal == 0) return SDValue(); 2338 2339 // Finally, if this value fits in a 5 bit sext field, return it 2340 if (SignExtend32<5>(MaskVal) == MaskVal) 2341 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2342 return SDValue(); 2343 } 2344 2345 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2346 /// amount, otherwise return -1. 2347 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2348 EVT VT = N->getValueType(0); 2349 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2350 return -1; 2351 2352 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2353 2354 // Find the first non-undef value in the shuffle mask. 2355 unsigned i; 2356 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2357 /*search*/; 2358 2359 if (i == 4) return -1; // all undef. 2360 2361 // Otherwise, check to see if the rest of the elements are consecutively 2362 // numbered from this value. 2363 unsigned ShiftAmt = SVOp->getMaskElt(i); 2364 if (ShiftAmt < i) return -1; 2365 ShiftAmt -= i; 2366 2367 // Check the rest of the elements to see if they are consecutive. 2368 for (++i; i != 4; ++i) 2369 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2370 return -1; 2371 2372 return ShiftAmt; 2373 } 2374 2375 //===----------------------------------------------------------------------===// 2376 // Addressing Mode Selection 2377 //===----------------------------------------------------------------------===// 2378 2379 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2380 /// or 64-bit immediate, and if the value can be accurately represented as a 2381 /// sign extension from a 16-bit value. If so, this returns true and the 2382 /// immediate. 2383 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2384 if (!isa<ConstantSDNode>(N)) 2385 return false; 2386 2387 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2388 if (N->getValueType(0) == MVT::i32) 2389 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2390 else 2391 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2392 } 2393 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2394 return isIntS16Immediate(Op.getNode(), Imm); 2395 } 2396 2397 2398 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2399 /// be represented as an indexed [r+r] operation. 2400 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2401 SDValue &Index, 2402 SelectionDAG &DAG) const { 2403 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2404 UI != E; ++UI) { 2405 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2406 if (Memop->getMemoryVT() == MVT::f64) { 2407 Base = N.getOperand(0); 2408 Index = N.getOperand(1); 2409 return true; 2410 } 2411 } 2412 } 2413 return false; 2414 } 2415 2416 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2417 /// can be represented as an indexed [r+r] operation. Returns false if it 2418 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2419 /// non-zero and N can be represented by a base register plus a signed 16-bit 2420 /// displacement, make a more precise judgement by checking (displacement % \p 2421 /// EncodingAlignment). 2422 bool PPCTargetLowering::SelectAddressRegReg( 2423 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2424 MaybeAlign EncodingAlignment) const { 2425 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2426 // a [pc+imm]. 2427 if (SelectAddressPCRel(N, Base)) 2428 return false; 2429 2430 int16_t Imm = 0; 2431 if (N.getOpcode() == ISD::ADD) { 2432 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2433 // SPE load/store can only handle 8-bit offsets. 2434 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2435 return true; 2436 if (isIntS16Immediate(N.getOperand(1), Imm) && 2437 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2438 return false; // r+i 2439 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2440 return false; // r+i 2441 2442 Base = N.getOperand(0); 2443 Index = N.getOperand(1); 2444 return true; 2445 } else if (N.getOpcode() == ISD::OR) { 2446 if (isIntS16Immediate(N.getOperand(1), Imm) && 2447 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2448 return false; // r+i can fold it if we can. 2449 2450 // If this is an or of disjoint bitfields, we can codegen this as an add 2451 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2452 // disjoint. 2453 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2454 2455 if (LHSKnown.Zero.getBoolValue()) { 2456 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2457 // If all of the bits are known zero on the LHS or RHS, the add won't 2458 // carry. 2459 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2460 Base = N.getOperand(0); 2461 Index = N.getOperand(1); 2462 return true; 2463 } 2464 } 2465 } 2466 2467 return false; 2468 } 2469 2470 // If we happen to be doing an i64 load or store into a stack slot that has 2471 // less than a 4-byte alignment, then the frame-index elimination may need to 2472 // use an indexed load or store instruction (because the offset may not be a 2473 // multiple of 4). The extra register needed to hold the offset comes from the 2474 // register scavenger, and it is possible that the scavenger will need to use 2475 // an emergency spill slot. As a result, we need to make sure that a spill slot 2476 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2477 // stack slot. 2478 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2479 // FIXME: This does not handle the LWA case. 2480 if (VT != MVT::i64) 2481 return; 2482 2483 // NOTE: We'll exclude negative FIs here, which come from argument 2484 // lowering, because there are no known test cases triggering this problem 2485 // using packed structures (or similar). We can remove this exclusion if 2486 // we find such a test case. The reason why this is so test-case driven is 2487 // because this entire 'fixup' is only to prevent crashes (from the 2488 // register scavenger) on not-really-valid inputs. For example, if we have: 2489 // %a = alloca i1 2490 // %b = bitcast i1* %a to i64* 2491 // store i64* a, i64 b 2492 // then the store should really be marked as 'align 1', but is not. If it 2493 // were marked as 'align 1' then the indexed form would have been 2494 // instruction-selected initially, and the problem this 'fixup' is preventing 2495 // won't happen regardless. 2496 if (FrameIdx < 0) 2497 return; 2498 2499 MachineFunction &MF = DAG.getMachineFunction(); 2500 MachineFrameInfo &MFI = MF.getFrameInfo(); 2501 2502 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2503 return; 2504 2505 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2506 FuncInfo->setHasNonRISpills(); 2507 } 2508 2509 /// Returns true if the address N can be represented by a base register plus 2510 /// a signed 16-bit displacement [r+imm], and if it is not better 2511 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2512 /// displacements that are multiples of that value. 2513 bool PPCTargetLowering::SelectAddressRegImm( 2514 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2515 MaybeAlign EncodingAlignment) const { 2516 // FIXME dl should come from parent load or store, not from address 2517 SDLoc dl(N); 2518 2519 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2520 // a [pc+imm]. 2521 if (SelectAddressPCRel(N, Base)) 2522 return false; 2523 2524 // If this can be more profitably realized as r+r, fail. 2525 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2526 return false; 2527 2528 if (N.getOpcode() == ISD::ADD) { 2529 int16_t imm = 0; 2530 if (isIntS16Immediate(N.getOperand(1), imm) && 2531 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2532 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2533 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2534 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2535 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2536 } else { 2537 Base = N.getOperand(0); 2538 } 2539 return true; // [r+i] 2540 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2541 // Match LOAD (ADD (X, Lo(G))). 2542 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2543 && "Cannot handle constant offsets yet!"); 2544 Disp = N.getOperand(1).getOperand(0); // The global address. 2545 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2546 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2547 Disp.getOpcode() == ISD::TargetConstantPool || 2548 Disp.getOpcode() == ISD::TargetJumpTable); 2549 Base = N.getOperand(0); 2550 return true; // [&g+r] 2551 } 2552 } else if (N.getOpcode() == ISD::OR) { 2553 int16_t imm = 0; 2554 if (isIntS16Immediate(N.getOperand(1), imm) && 2555 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2556 // If this is an or of disjoint bitfields, we can codegen this as an add 2557 // (for better address arithmetic) if the LHS and RHS of the OR are 2558 // provably disjoint. 2559 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2560 2561 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2562 // If all of the bits are known zero on the LHS or RHS, the add won't 2563 // carry. 2564 if (FrameIndexSDNode *FI = 2565 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2566 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2567 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2568 } else { 2569 Base = N.getOperand(0); 2570 } 2571 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2572 return true; 2573 } 2574 } 2575 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2576 // Loading from a constant address. 2577 2578 // If this address fits entirely in a 16-bit sext immediate field, codegen 2579 // this as "d, 0" 2580 int16_t Imm; 2581 if (isIntS16Immediate(CN, Imm) && 2582 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2583 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2584 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2585 CN->getValueType(0)); 2586 return true; 2587 } 2588 2589 // Handle 32-bit sext immediates with LIS + addr mode. 2590 if ((CN->getValueType(0) == MVT::i32 || 2591 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2592 (!EncodingAlignment || 2593 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2594 int Addr = (int)CN->getZExtValue(); 2595 2596 // Otherwise, break this down into an LIS + disp. 2597 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2598 2599 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2600 MVT::i32); 2601 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2602 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2603 return true; 2604 } 2605 } 2606 2607 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2608 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2609 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2610 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2611 } else 2612 Base = N; 2613 return true; // [r+0] 2614 } 2615 2616 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2617 /// represented as an indexed [r+r] operation. 2618 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2619 SDValue &Index, 2620 SelectionDAG &DAG) const { 2621 // Check to see if we can easily represent this as an [r+r] address. This 2622 // will fail if it thinks that the address is more profitably represented as 2623 // reg+imm, e.g. where imm = 0. 2624 if (SelectAddressRegReg(N, Base, Index, DAG)) 2625 return true; 2626 2627 // If the address is the result of an add, we will utilize the fact that the 2628 // address calculation includes an implicit add. However, we can reduce 2629 // register pressure if we do not materialize a constant just for use as the 2630 // index register. We only get rid of the add if it is not an add of a 2631 // value and a 16-bit signed constant and both have a single use. 2632 int16_t imm = 0; 2633 if (N.getOpcode() == ISD::ADD && 2634 (!isIntS16Immediate(N.getOperand(1), imm) || 2635 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2636 Base = N.getOperand(0); 2637 Index = N.getOperand(1); 2638 return true; 2639 } 2640 2641 // Otherwise, do it the hard way, using R0 as the base register. 2642 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2643 N.getValueType()); 2644 Index = N; 2645 return true; 2646 } 2647 2648 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2649 Ty *PCRelCand = dyn_cast<Ty>(N); 2650 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2651 } 2652 2653 /// Returns true if this address is a PC Relative address. 2654 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2655 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2656 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2657 // This is a materialize PC Relative node. Always select this as PC Relative. 2658 Base = N; 2659 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2660 return true; 2661 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2662 isValidPCRelNode<GlobalAddressSDNode>(N) || 2663 isValidPCRelNode<JumpTableSDNode>(N) || 2664 isValidPCRelNode<BlockAddressSDNode>(N)) 2665 return true; 2666 return false; 2667 } 2668 2669 /// Returns true if we should use a direct load into vector instruction 2670 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2671 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2672 2673 // If there are any other uses other than scalar to vector, then we should 2674 // keep it as a scalar load -> direct move pattern to prevent multiple 2675 // loads. 2676 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2677 if (!LD) 2678 return false; 2679 2680 EVT MemVT = LD->getMemoryVT(); 2681 if (!MemVT.isSimple()) 2682 return false; 2683 switch(MemVT.getSimpleVT().SimpleTy) { 2684 case MVT::i64: 2685 break; 2686 case MVT::i32: 2687 if (!ST.hasP8Vector()) 2688 return false; 2689 break; 2690 case MVT::i16: 2691 case MVT::i8: 2692 if (!ST.hasP9Vector()) 2693 return false; 2694 break; 2695 default: 2696 return false; 2697 } 2698 2699 SDValue LoadedVal(N, 0); 2700 if (!LoadedVal.hasOneUse()) 2701 return false; 2702 2703 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2704 UI != UE; ++UI) 2705 if (UI.getUse().get().getResNo() == 0 && 2706 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2707 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2708 return false; 2709 2710 return true; 2711 } 2712 2713 /// getPreIndexedAddressParts - returns true by value, base pointer and 2714 /// offset pointer and addressing mode by reference if the node's address 2715 /// can be legally represented as pre-indexed load / store address. 2716 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2717 SDValue &Offset, 2718 ISD::MemIndexedMode &AM, 2719 SelectionDAG &DAG) const { 2720 if (DisablePPCPreinc) return false; 2721 2722 bool isLoad = true; 2723 SDValue Ptr; 2724 EVT VT; 2725 unsigned Alignment; 2726 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2727 Ptr = LD->getBasePtr(); 2728 VT = LD->getMemoryVT(); 2729 Alignment = LD->getAlignment(); 2730 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2731 Ptr = ST->getBasePtr(); 2732 VT = ST->getMemoryVT(); 2733 Alignment = ST->getAlignment(); 2734 isLoad = false; 2735 } else 2736 return false; 2737 2738 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2739 // instructions because we can fold these into a more efficient instruction 2740 // instead, (such as LXSD). 2741 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2742 return false; 2743 } 2744 2745 // PowerPC doesn't have preinc load/store instructions for vectors 2746 if (VT.isVector()) 2747 return false; 2748 2749 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2750 // Common code will reject creating a pre-inc form if the base pointer 2751 // is a frame index, or if N is a store and the base pointer is either 2752 // the same as or a predecessor of the value being stored. Check for 2753 // those situations here, and try with swapped Base/Offset instead. 2754 bool Swap = false; 2755 2756 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2757 Swap = true; 2758 else if (!isLoad) { 2759 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2760 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2761 Swap = true; 2762 } 2763 2764 if (Swap) 2765 std::swap(Base, Offset); 2766 2767 AM = ISD::PRE_INC; 2768 return true; 2769 } 2770 2771 // LDU/STU can only handle immediates that are a multiple of 4. 2772 if (VT != MVT::i64) { 2773 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2774 return false; 2775 } else { 2776 // LDU/STU need an address with at least 4-byte alignment. 2777 if (Alignment < 4) 2778 return false; 2779 2780 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2781 return false; 2782 } 2783 2784 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2785 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2786 // sext i32 to i64 when addr mode is r+i. 2787 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2788 LD->getExtensionType() == ISD::SEXTLOAD && 2789 isa<ConstantSDNode>(Offset)) 2790 return false; 2791 } 2792 2793 AM = ISD::PRE_INC; 2794 return true; 2795 } 2796 2797 //===----------------------------------------------------------------------===// 2798 // LowerOperation implementation 2799 //===----------------------------------------------------------------------===// 2800 2801 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2802 /// and LoOpFlags to the target MO flags. 2803 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2804 unsigned &HiOpFlags, unsigned &LoOpFlags, 2805 const GlobalValue *GV = nullptr) { 2806 HiOpFlags = PPCII::MO_HA; 2807 LoOpFlags = PPCII::MO_LO; 2808 2809 // Don't use the pic base if not in PIC relocation model. 2810 if (IsPIC) { 2811 HiOpFlags |= PPCII::MO_PIC_FLAG; 2812 LoOpFlags |= PPCII::MO_PIC_FLAG; 2813 } 2814 } 2815 2816 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2817 SelectionDAG &DAG) { 2818 SDLoc DL(HiPart); 2819 EVT PtrVT = HiPart.getValueType(); 2820 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2821 2822 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2823 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2824 2825 // With PIC, the first instruction is actually "GR+hi(&G)". 2826 if (isPIC) 2827 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2828 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2829 2830 // Generate non-pic code that has direct accesses to the constant pool. 2831 // The address of the global is just (hi(&g)+lo(&g)). 2832 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2833 } 2834 2835 static void setUsesTOCBasePtr(MachineFunction &MF) { 2836 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2837 FuncInfo->setUsesTOCBasePtr(); 2838 } 2839 2840 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2841 setUsesTOCBasePtr(DAG.getMachineFunction()); 2842 } 2843 2844 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2845 SDValue GA) const { 2846 const bool Is64Bit = Subtarget.isPPC64(); 2847 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2848 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2849 : Subtarget.isAIXABI() 2850 ? DAG.getRegister(PPC::R2, VT) 2851 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2852 SDValue Ops[] = { GA, Reg }; 2853 return DAG.getMemIntrinsicNode( 2854 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2855 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2856 MachineMemOperand::MOLoad); 2857 } 2858 2859 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2860 SelectionDAG &DAG) const { 2861 EVT PtrVT = Op.getValueType(); 2862 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2863 const Constant *C = CP->getConstVal(); 2864 2865 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2866 // The actual address of the GlobalValue is stored in the TOC. 2867 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2868 if (Subtarget.isUsingPCRelativeCalls()) { 2869 SDLoc DL(CP); 2870 EVT Ty = getPointerTy(DAG.getDataLayout()); 2871 SDValue ConstPool = DAG.getTargetConstantPool( 2872 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2873 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2874 } 2875 setUsesTOCBasePtr(DAG); 2876 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2877 return getTOCEntry(DAG, SDLoc(CP), GA); 2878 } 2879 2880 unsigned MOHiFlag, MOLoFlag; 2881 bool IsPIC = isPositionIndependent(); 2882 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2883 2884 if (IsPIC && Subtarget.isSVR4ABI()) { 2885 SDValue GA = 2886 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2887 return getTOCEntry(DAG, SDLoc(CP), GA); 2888 } 2889 2890 SDValue CPIHi = 2891 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2892 SDValue CPILo = 2893 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2894 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2895 } 2896 2897 // For 64-bit PowerPC, prefer the more compact relative encodings. 2898 // This trades 32 bits per jump table entry for one or two instructions 2899 // on the jump site. 2900 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2901 if (isJumpTableRelative()) 2902 return MachineJumpTableInfo::EK_LabelDifference32; 2903 2904 return TargetLowering::getJumpTableEncoding(); 2905 } 2906 2907 bool PPCTargetLowering::isJumpTableRelative() const { 2908 if (UseAbsoluteJumpTables) 2909 return false; 2910 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2911 return true; 2912 return TargetLowering::isJumpTableRelative(); 2913 } 2914 2915 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2916 SelectionDAG &DAG) const { 2917 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2918 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2919 2920 switch (getTargetMachine().getCodeModel()) { 2921 case CodeModel::Small: 2922 case CodeModel::Medium: 2923 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2924 default: 2925 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2926 getPointerTy(DAG.getDataLayout())); 2927 } 2928 } 2929 2930 const MCExpr * 2931 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2932 unsigned JTI, 2933 MCContext &Ctx) const { 2934 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2935 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2936 2937 switch (getTargetMachine().getCodeModel()) { 2938 case CodeModel::Small: 2939 case CodeModel::Medium: 2940 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2941 default: 2942 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2943 } 2944 } 2945 2946 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2947 EVT PtrVT = Op.getValueType(); 2948 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2949 2950 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2951 if (Subtarget.isUsingPCRelativeCalls()) { 2952 SDLoc DL(JT); 2953 EVT Ty = getPointerTy(DAG.getDataLayout()); 2954 SDValue GA = 2955 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2956 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2957 return MatAddr; 2958 } 2959 2960 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2961 // The actual address of the GlobalValue is stored in the TOC. 2962 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2963 setUsesTOCBasePtr(DAG); 2964 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2965 return getTOCEntry(DAG, SDLoc(JT), GA); 2966 } 2967 2968 unsigned MOHiFlag, MOLoFlag; 2969 bool IsPIC = isPositionIndependent(); 2970 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2971 2972 if (IsPIC && Subtarget.isSVR4ABI()) { 2973 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2974 PPCII::MO_PIC_FLAG); 2975 return getTOCEntry(DAG, SDLoc(GA), GA); 2976 } 2977 2978 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2979 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2980 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2981 } 2982 2983 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2984 SelectionDAG &DAG) const { 2985 EVT PtrVT = Op.getValueType(); 2986 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2987 const BlockAddress *BA = BASDN->getBlockAddress(); 2988 2989 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2990 if (Subtarget.isUsingPCRelativeCalls()) { 2991 SDLoc DL(BASDN); 2992 EVT Ty = getPointerTy(DAG.getDataLayout()); 2993 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2994 PPCII::MO_PCREL_FLAG); 2995 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2996 return MatAddr; 2997 } 2998 2999 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3000 // The actual BlockAddress is stored in the TOC. 3001 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3002 setUsesTOCBasePtr(DAG); 3003 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3004 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3005 } 3006 3007 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3008 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3009 return getTOCEntry( 3010 DAG, SDLoc(BASDN), 3011 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3012 3013 unsigned MOHiFlag, MOLoFlag; 3014 bool IsPIC = isPositionIndependent(); 3015 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3016 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3017 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3018 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3019 } 3020 3021 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3022 SelectionDAG &DAG) const { 3023 // FIXME: TLS addresses currently use medium model code sequences, 3024 // which is the most useful form. Eventually support for small and 3025 // large models could be added if users need it, at the cost of 3026 // additional complexity. 3027 if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS) 3028 report_fatal_error("Thread local storage is not supported with pc-relative" 3029 " addressing - please compile with -mno-pcrel"); 3030 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3031 if (DAG.getTarget().useEmulatedTLS()) 3032 return LowerToTLSEmulatedModel(GA, DAG); 3033 3034 SDLoc dl(GA); 3035 const GlobalValue *GV = GA->getGlobal(); 3036 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3037 bool is64bit = Subtarget.isPPC64(); 3038 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3039 PICLevel::Level picLevel = M->getPICLevel(); 3040 3041 const TargetMachine &TM = getTargetMachine(); 3042 TLSModel::Model Model = TM.getTLSModel(GV); 3043 3044 if (Model == TLSModel::LocalExec) { 3045 if (Subtarget.isUsingPCRelativeCalls()) { 3046 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3047 SDValue TGA = DAG.getTargetGlobalAddress( 3048 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3049 SDValue MatAddr = 3050 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3051 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3052 } 3053 3054 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3055 PPCII::MO_TPREL_HA); 3056 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3057 PPCII::MO_TPREL_LO); 3058 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3059 : DAG.getRegister(PPC::R2, MVT::i32); 3060 3061 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3062 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3063 } 3064 3065 if (Model == TLSModel::InitialExec) { 3066 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3067 SDValue TGA = DAG.getTargetGlobalAddress( 3068 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3069 SDValue TGATLS = DAG.getTargetGlobalAddress( 3070 GV, dl, PtrVT, 0, 3071 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3072 SDValue TPOffset; 3073 if (IsPCRel) { 3074 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3075 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3076 MachinePointerInfo()); 3077 } else { 3078 SDValue GOTPtr; 3079 if (is64bit) { 3080 setUsesTOCBasePtr(DAG); 3081 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3082 GOTPtr = 3083 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3084 } else { 3085 if (!TM.isPositionIndependent()) 3086 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3087 else if (picLevel == PICLevel::SmallPIC) 3088 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3089 else 3090 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3091 } 3092 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3093 } 3094 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3095 } 3096 3097 if (Model == TLSModel::GeneralDynamic) { 3098 if (Subtarget.isUsingPCRelativeCalls()) { 3099 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3100 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3101 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3102 } 3103 3104 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3105 SDValue GOTPtr; 3106 if (is64bit) { 3107 setUsesTOCBasePtr(DAG); 3108 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3109 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3110 GOTReg, TGA); 3111 } else { 3112 if (picLevel == PICLevel::SmallPIC) 3113 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3114 else 3115 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3116 } 3117 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3118 GOTPtr, TGA, TGA); 3119 } 3120 3121 if (Model == TLSModel::LocalDynamic) { 3122 if (Subtarget.isUsingPCRelativeCalls()) { 3123 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3124 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3125 SDValue MatPCRel = 3126 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3127 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3128 } 3129 3130 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3131 SDValue GOTPtr; 3132 if (is64bit) { 3133 setUsesTOCBasePtr(DAG); 3134 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3135 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3136 GOTReg, TGA); 3137 } else { 3138 if (picLevel == PICLevel::SmallPIC) 3139 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3140 else 3141 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3142 } 3143 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3144 PtrVT, GOTPtr, TGA, TGA); 3145 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3146 PtrVT, TLSAddr, TGA); 3147 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3148 } 3149 3150 llvm_unreachable("Unknown TLS model!"); 3151 } 3152 3153 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3154 SelectionDAG &DAG) const { 3155 EVT PtrVT = Op.getValueType(); 3156 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3157 SDLoc DL(GSDN); 3158 const GlobalValue *GV = GSDN->getGlobal(); 3159 3160 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3161 // The actual address of the GlobalValue is stored in the TOC. 3162 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3163 if (Subtarget.isUsingPCRelativeCalls()) { 3164 EVT Ty = getPointerTy(DAG.getDataLayout()); 3165 if (isAccessedAsGotIndirect(Op)) { 3166 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3167 PPCII::MO_PCREL_FLAG | 3168 PPCII::MO_GOT_FLAG); 3169 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3170 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3171 MachinePointerInfo()); 3172 return Load; 3173 } else { 3174 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3175 PPCII::MO_PCREL_FLAG); 3176 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3177 } 3178 } 3179 setUsesTOCBasePtr(DAG); 3180 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3181 return getTOCEntry(DAG, DL, GA); 3182 } 3183 3184 unsigned MOHiFlag, MOLoFlag; 3185 bool IsPIC = isPositionIndependent(); 3186 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3187 3188 if (IsPIC && Subtarget.isSVR4ABI()) { 3189 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3190 GSDN->getOffset(), 3191 PPCII::MO_PIC_FLAG); 3192 return getTOCEntry(DAG, DL, GA); 3193 } 3194 3195 SDValue GAHi = 3196 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3197 SDValue GALo = 3198 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3199 3200 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3201 } 3202 3203 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3204 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3205 SDLoc dl(Op); 3206 3207 if (Op.getValueType() == MVT::v2i64) { 3208 // When the operands themselves are v2i64 values, we need to do something 3209 // special because VSX has no underlying comparison operations for these. 3210 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3211 // Equality can be handled by casting to the legal type for Altivec 3212 // comparisons, everything else needs to be expanded. 3213 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3214 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3215 DAG.getSetCC(dl, MVT::v4i32, 3216 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3217 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3218 CC)); 3219 } 3220 3221 return SDValue(); 3222 } 3223 3224 // We handle most of these in the usual way. 3225 return Op; 3226 } 3227 3228 // If we're comparing for equality to zero, expose the fact that this is 3229 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3230 // fold the new nodes. 3231 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3232 return V; 3233 3234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3235 // Leave comparisons against 0 and -1 alone for now, since they're usually 3236 // optimized. FIXME: revisit this when we can custom lower all setcc 3237 // optimizations. 3238 if (C->isAllOnesValue() || C->isNullValue()) 3239 return SDValue(); 3240 } 3241 3242 // If we have an integer seteq/setne, turn it into a compare against zero 3243 // by xor'ing the rhs with the lhs, which is faster than setting a 3244 // condition register, reading it back out, and masking the correct bit. The 3245 // normal approach here uses sub to do this instead of xor. Using xor exposes 3246 // the result to other bit-twiddling opportunities. 3247 EVT LHSVT = Op.getOperand(0).getValueType(); 3248 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3249 EVT VT = Op.getValueType(); 3250 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3251 Op.getOperand(1)); 3252 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3253 } 3254 return SDValue(); 3255 } 3256 3257 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3258 SDNode *Node = Op.getNode(); 3259 EVT VT = Node->getValueType(0); 3260 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3261 SDValue InChain = Node->getOperand(0); 3262 SDValue VAListPtr = Node->getOperand(1); 3263 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3264 SDLoc dl(Node); 3265 3266 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3267 3268 // gpr_index 3269 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3270 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3271 InChain = GprIndex.getValue(1); 3272 3273 if (VT == MVT::i64) { 3274 // Check if GprIndex is even 3275 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3276 DAG.getConstant(1, dl, MVT::i32)); 3277 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3278 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3279 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3280 DAG.getConstant(1, dl, MVT::i32)); 3281 // Align GprIndex to be even if it isn't 3282 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3283 GprIndex); 3284 } 3285 3286 // fpr index is 1 byte after gpr 3287 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3288 DAG.getConstant(1, dl, MVT::i32)); 3289 3290 // fpr 3291 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3292 FprPtr, MachinePointerInfo(SV), MVT::i8); 3293 InChain = FprIndex.getValue(1); 3294 3295 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3296 DAG.getConstant(8, dl, MVT::i32)); 3297 3298 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3299 DAG.getConstant(4, dl, MVT::i32)); 3300 3301 // areas 3302 SDValue OverflowArea = 3303 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3304 InChain = OverflowArea.getValue(1); 3305 3306 SDValue RegSaveArea = 3307 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3308 InChain = RegSaveArea.getValue(1); 3309 3310 // select overflow_area if index > 8 3311 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3312 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3313 3314 // adjustment constant gpr_index * 4/8 3315 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3316 VT.isInteger() ? GprIndex : FprIndex, 3317 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3318 MVT::i32)); 3319 3320 // OurReg = RegSaveArea + RegConstant 3321 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3322 RegConstant); 3323 3324 // Floating types are 32 bytes into RegSaveArea 3325 if (VT.isFloatingPoint()) 3326 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3327 DAG.getConstant(32, dl, MVT::i32)); 3328 3329 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3330 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3331 VT.isInteger() ? GprIndex : FprIndex, 3332 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3333 MVT::i32)); 3334 3335 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3336 VT.isInteger() ? VAListPtr : FprPtr, 3337 MachinePointerInfo(SV), MVT::i8); 3338 3339 // determine if we should load from reg_save_area or overflow_area 3340 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3341 3342 // increase overflow_area by 4/8 if gpr/fpr > 8 3343 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3344 DAG.getConstant(VT.isInteger() ? 4 : 8, 3345 dl, MVT::i32)); 3346 3347 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3348 OverflowAreaPlusN); 3349 3350 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3351 MachinePointerInfo(), MVT::i32); 3352 3353 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3354 } 3355 3356 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3357 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3358 3359 // We have to copy the entire va_list struct: 3360 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3361 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3362 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3363 false, true, false, MachinePointerInfo(), 3364 MachinePointerInfo()); 3365 } 3366 3367 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3368 SelectionDAG &DAG) const { 3369 if (Subtarget.isAIXABI()) 3370 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3371 3372 return Op.getOperand(0); 3373 } 3374 3375 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3376 SelectionDAG &DAG) const { 3377 if (Subtarget.isAIXABI()) 3378 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3379 3380 SDValue Chain = Op.getOperand(0); 3381 SDValue Trmp = Op.getOperand(1); // trampoline 3382 SDValue FPtr = Op.getOperand(2); // nested function 3383 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3384 SDLoc dl(Op); 3385 3386 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3387 bool isPPC64 = (PtrVT == MVT::i64); 3388 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3389 3390 TargetLowering::ArgListTy Args; 3391 TargetLowering::ArgListEntry Entry; 3392 3393 Entry.Ty = IntPtrTy; 3394 Entry.Node = Trmp; Args.push_back(Entry); 3395 3396 // TrampSize == (isPPC64 ? 48 : 40); 3397 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3398 isPPC64 ? MVT::i64 : MVT::i32); 3399 Args.push_back(Entry); 3400 3401 Entry.Node = FPtr; Args.push_back(Entry); 3402 Entry.Node = Nest; Args.push_back(Entry); 3403 3404 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3405 TargetLowering::CallLoweringInfo CLI(DAG); 3406 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3407 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3408 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3409 3410 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3411 return CallResult.second; 3412 } 3413 3414 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3415 MachineFunction &MF = DAG.getMachineFunction(); 3416 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3417 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3418 3419 SDLoc dl(Op); 3420 3421 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3422 // vastart just stores the address of the VarArgsFrameIndex slot into the 3423 // memory location argument. 3424 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3425 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3426 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3427 MachinePointerInfo(SV)); 3428 } 3429 3430 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3431 // We suppose the given va_list is already allocated. 3432 // 3433 // typedef struct { 3434 // char gpr; /* index into the array of 8 GPRs 3435 // * stored in the register save area 3436 // * gpr=0 corresponds to r3, 3437 // * gpr=1 to r4, etc. 3438 // */ 3439 // char fpr; /* index into the array of 8 FPRs 3440 // * stored in the register save area 3441 // * fpr=0 corresponds to f1, 3442 // * fpr=1 to f2, etc. 3443 // */ 3444 // char *overflow_arg_area; 3445 // /* location on stack that holds 3446 // * the next overflow argument 3447 // */ 3448 // char *reg_save_area; 3449 // /* where r3:r10 and f1:f8 (if saved) 3450 // * are stored 3451 // */ 3452 // } va_list[1]; 3453 3454 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3455 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3456 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3457 PtrVT); 3458 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3459 PtrVT); 3460 3461 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3462 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3463 3464 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3465 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3466 3467 uint64_t FPROffset = 1; 3468 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3469 3470 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3471 3472 // Store first byte : number of int regs 3473 SDValue firstStore = 3474 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3475 MachinePointerInfo(SV), MVT::i8); 3476 uint64_t nextOffset = FPROffset; 3477 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3478 ConstFPROffset); 3479 3480 // Store second byte : number of float regs 3481 SDValue secondStore = 3482 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3483 MachinePointerInfo(SV, nextOffset), MVT::i8); 3484 nextOffset += StackOffset; 3485 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3486 3487 // Store second word : arguments given on stack 3488 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3489 MachinePointerInfo(SV, nextOffset)); 3490 nextOffset += FrameOffset; 3491 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3492 3493 // Store third word : arguments given in registers 3494 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3495 MachinePointerInfo(SV, nextOffset)); 3496 } 3497 3498 /// FPR - The set of FP registers that should be allocated for arguments 3499 /// on Darwin and AIX. 3500 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3501 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3502 PPC::F11, PPC::F12, PPC::F13}; 3503 3504 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3505 /// the stack. 3506 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3507 unsigned PtrByteSize) { 3508 unsigned ArgSize = ArgVT.getStoreSize(); 3509 if (Flags.isByVal()) 3510 ArgSize = Flags.getByValSize(); 3511 3512 // Round up to multiples of the pointer size, except for array members, 3513 // which are always packed. 3514 if (!Flags.isInConsecutiveRegs()) 3515 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3516 3517 return ArgSize; 3518 } 3519 3520 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3521 /// on the stack. 3522 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3523 ISD::ArgFlagsTy Flags, 3524 unsigned PtrByteSize) { 3525 Align Alignment(PtrByteSize); 3526 3527 // Altivec parameters are padded to a 16 byte boundary. 3528 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3529 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3530 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3531 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3532 Alignment = Align(16); 3533 3534 // ByVal parameters are aligned as requested. 3535 if (Flags.isByVal()) { 3536 auto BVAlign = Flags.getNonZeroByValAlign(); 3537 if (BVAlign > PtrByteSize) { 3538 if (BVAlign.value() % PtrByteSize != 0) 3539 llvm_unreachable( 3540 "ByVal alignment is not a multiple of the pointer size"); 3541 3542 Alignment = BVAlign; 3543 } 3544 } 3545 3546 // Array members are always packed to their original alignment. 3547 if (Flags.isInConsecutiveRegs()) { 3548 // If the array member was split into multiple registers, the first 3549 // needs to be aligned to the size of the full type. (Except for 3550 // ppcf128, which is only aligned as its f64 components.) 3551 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3552 Alignment = Align(OrigVT.getStoreSize()); 3553 else 3554 Alignment = Align(ArgVT.getStoreSize()); 3555 } 3556 3557 return Alignment; 3558 } 3559 3560 /// CalculateStackSlotUsed - Return whether this argument will use its 3561 /// stack slot (instead of being passed in registers). ArgOffset, 3562 /// AvailableFPRs, and AvailableVRs must hold the current argument 3563 /// position, and will be updated to account for this argument. 3564 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3565 unsigned PtrByteSize, unsigned LinkageSize, 3566 unsigned ParamAreaSize, unsigned &ArgOffset, 3567 unsigned &AvailableFPRs, 3568 unsigned &AvailableVRs) { 3569 bool UseMemory = false; 3570 3571 // Respect alignment of argument on the stack. 3572 Align Alignment = 3573 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3574 ArgOffset = alignTo(ArgOffset, Alignment); 3575 // If there's no space left in the argument save area, we must 3576 // use memory (this check also catches zero-sized arguments). 3577 if (ArgOffset >= LinkageSize + ParamAreaSize) 3578 UseMemory = true; 3579 3580 // Allocate argument on the stack. 3581 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3582 if (Flags.isInConsecutiveRegsLast()) 3583 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3584 // If we overran the argument save area, we must use memory 3585 // (this check catches arguments passed partially in memory) 3586 if (ArgOffset > LinkageSize + ParamAreaSize) 3587 UseMemory = true; 3588 3589 // However, if the argument is actually passed in an FPR or a VR, 3590 // we don't use memory after all. 3591 if (!Flags.isByVal()) { 3592 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3593 if (AvailableFPRs > 0) { 3594 --AvailableFPRs; 3595 return false; 3596 } 3597 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3598 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3599 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3600 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3601 if (AvailableVRs > 0) { 3602 --AvailableVRs; 3603 return false; 3604 } 3605 } 3606 3607 return UseMemory; 3608 } 3609 3610 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3611 /// ensure minimum alignment required for target. 3612 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3613 unsigned NumBytes) { 3614 return alignTo(NumBytes, Lowering->getStackAlign()); 3615 } 3616 3617 SDValue PPCTargetLowering::LowerFormalArguments( 3618 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3619 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3620 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3621 if (Subtarget.isAIXABI()) 3622 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3623 InVals); 3624 if (Subtarget.is64BitELFABI()) 3625 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3626 InVals); 3627 if (Subtarget.is32BitELFABI()) 3628 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3629 InVals); 3630 3631 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3632 InVals); 3633 } 3634 3635 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3636 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3637 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3638 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3639 3640 // 32-bit SVR4 ABI Stack Frame Layout: 3641 // +-----------------------------------+ 3642 // +--> | Back chain | 3643 // | +-----------------------------------+ 3644 // | | Floating-point register save area | 3645 // | +-----------------------------------+ 3646 // | | General register save area | 3647 // | +-----------------------------------+ 3648 // | | CR save word | 3649 // | +-----------------------------------+ 3650 // | | VRSAVE save word | 3651 // | +-----------------------------------+ 3652 // | | Alignment padding | 3653 // | +-----------------------------------+ 3654 // | | Vector register save area | 3655 // | +-----------------------------------+ 3656 // | | Local variable space | 3657 // | +-----------------------------------+ 3658 // | | Parameter list area | 3659 // | +-----------------------------------+ 3660 // | | LR save word | 3661 // | +-----------------------------------+ 3662 // SP--> +--- | Back chain | 3663 // +-----------------------------------+ 3664 // 3665 // Specifications: 3666 // System V Application Binary Interface PowerPC Processor Supplement 3667 // AltiVec Technology Programming Interface Manual 3668 3669 MachineFunction &MF = DAG.getMachineFunction(); 3670 MachineFrameInfo &MFI = MF.getFrameInfo(); 3671 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3672 3673 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3674 // Potential tail calls could cause overwriting of argument stack slots. 3675 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3676 (CallConv == CallingConv::Fast)); 3677 const Align PtrAlign(4); 3678 3679 // Assign locations to all of the incoming arguments. 3680 SmallVector<CCValAssign, 16> ArgLocs; 3681 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3682 *DAG.getContext()); 3683 3684 // Reserve space for the linkage area on the stack. 3685 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3686 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3687 if (useSoftFloat()) 3688 CCInfo.PreAnalyzeFormalArguments(Ins); 3689 3690 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3691 CCInfo.clearWasPPCF128(); 3692 3693 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3694 CCValAssign &VA = ArgLocs[i]; 3695 3696 // Arguments stored in registers. 3697 if (VA.isRegLoc()) { 3698 const TargetRegisterClass *RC; 3699 EVT ValVT = VA.getValVT(); 3700 3701 switch (ValVT.getSimpleVT().SimpleTy) { 3702 default: 3703 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3704 case MVT::i1: 3705 case MVT::i32: 3706 RC = &PPC::GPRCRegClass; 3707 break; 3708 case MVT::f32: 3709 if (Subtarget.hasP8Vector()) 3710 RC = &PPC::VSSRCRegClass; 3711 else if (Subtarget.hasSPE()) 3712 RC = &PPC::GPRCRegClass; 3713 else 3714 RC = &PPC::F4RCRegClass; 3715 break; 3716 case MVT::f64: 3717 if (Subtarget.hasVSX()) 3718 RC = &PPC::VSFRCRegClass; 3719 else if (Subtarget.hasSPE()) 3720 // SPE passes doubles in GPR pairs. 3721 RC = &PPC::GPRCRegClass; 3722 else 3723 RC = &PPC::F8RCRegClass; 3724 break; 3725 case MVT::v16i8: 3726 case MVT::v8i16: 3727 case MVT::v4i32: 3728 RC = &PPC::VRRCRegClass; 3729 break; 3730 case MVT::v4f32: 3731 RC = &PPC::VRRCRegClass; 3732 break; 3733 case MVT::v2f64: 3734 case MVT::v2i64: 3735 RC = &PPC::VRRCRegClass; 3736 break; 3737 } 3738 3739 SDValue ArgValue; 3740 // Transform the arguments stored in physical registers into 3741 // virtual ones. 3742 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3743 assert(i + 1 < e && "No second half of double precision argument"); 3744 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3745 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3746 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3747 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3748 if (!Subtarget.isLittleEndian()) 3749 std::swap (ArgValueLo, ArgValueHi); 3750 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3751 ArgValueHi); 3752 } else { 3753 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3754 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3755 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3756 if (ValVT == MVT::i1) 3757 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3758 } 3759 3760 InVals.push_back(ArgValue); 3761 } else { 3762 // Argument stored in memory. 3763 assert(VA.isMemLoc()); 3764 3765 // Get the extended size of the argument type in stack 3766 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3767 // Get the actual size of the argument type 3768 unsigned ObjSize = VA.getValVT().getStoreSize(); 3769 unsigned ArgOffset = VA.getLocMemOffset(); 3770 // Stack objects in PPC32 are right justified. 3771 ArgOffset += ArgSize - ObjSize; 3772 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3773 3774 // Create load nodes to retrieve arguments from the stack. 3775 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3776 InVals.push_back( 3777 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3778 } 3779 } 3780 3781 // Assign locations to all of the incoming aggregate by value arguments. 3782 // Aggregates passed by value are stored in the local variable space of the 3783 // caller's stack frame, right above the parameter list area. 3784 SmallVector<CCValAssign, 16> ByValArgLocs; 3785 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3786 ByValArgLocs, *DAG.getContext()); 3787 3788 // Reserve stack space for the allocations in CCInfo. 3789 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3790 3791 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3792 3793 // Area that is at least reserved in the caller of this function. 3794 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3795 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3796 3797 // Set the size that is at least reserved in caller of this function. Tail 3798 // call optimized function's reserved stack space needs to be aligned so that 3799 // taking the difference between two stack areas will result in an aligned 3800 // stack. 3801 MinReservedArea = 3802 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3803 FuncInfo->setMinReservedArea(MinReservedArea); 3804 3805 SmallVector<SDValue, 8> MemOps; 3806 3807 // If the function takes variable number of arguments, make a frame index for 3808 // the start of the first vararg value... for expansion of llvm.va_start. 3809 if (isVarArg) { 3810 static const MCPhysReg GPArgRegs[] = { 3811 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3812 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3813 }; 3814 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3815 3816 static const MCPhysReg FPArgRegs[] = { 3817 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3818 PPC::F8 3819 }; 3820 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3821 3822 if (useSoftFloat() || hasSPE()) 3823 NumFPArgRegs = 0; 3824 3825 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3826 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3827 3828 // Make room for NumGPArgRegs and NumFPArgRegs. 3829 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3830 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3831 3832 FuncInfo->setVarArgsStackOffset( 3833 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3834 CCInfo.getNextStackOffset(), true)); 3835 3836 FuncInfo->setVarArgsFrameIndex( 3837 MFI.CreateStackObject(Depth, Align(8), false)); 3838 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3839 3840 // The fixed integer arguments of a variadic function are stored to the 3841 // VarArgsFrameIndex on the stack so that they may be loaded by 3842 // dereferencing the result of va_next. 3843 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3844 // Get an existing live-in vreg, or add a new one. 3845 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3846 if (!VReg) 3847 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3848 3849 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3850 SDValue Store = 3851 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3852 MemOps.push_back(Store); 3853 // Increment the address by four for the next argument to store 3854 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3855 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3856 } 3857 3858 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3859 // is set. 3860 // The double arguments are stored to the VarArgsFrameIndex 3861 // on the stack. 3862 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3863 // Get an existing live-in vreg, or add a new one. 3864 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3865 if (!VReg) 3866 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3867 3868 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3869 SDValue Store = 3870 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3871 MemOps.push_back(Store); 3872 // Increment the address by eight for the next argument to store 3873 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3874 PtrVT); 3875 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3876 } 3877 } 3878 3879 if (!MemOps.empty()) 3880 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3881 3882 return Chain; 3883 } 3884 3885 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3886 // value to MVT::i64 and then truncate to the correct register size. 3887 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3888 EVT ObjectVT, SelectionDAG &DAG, 3889 SDValue ArgVal, 3890 const SDLoc &dl) const { 3891 if (Flags.isSExt()) 3892 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3893 DAG.getValueType(ObjectVT)); 3894 else if (Flags.isZExt()) 3895 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3896 DAG.getValueType(ObjectVT)); 3897 3898 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3899 } 3900 3901 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3902 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3903 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3904 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3905 // TODO: add description of PPC stack frame format, or at least some docs. 3906 // 3907 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3908 bool isLittleEndian = Subtarget.isLittleEndian(); 3909 MachineFunction &MF = DAG.getMachineFunction(); 3910 MachineFrameInfo &MFI = MF.getFrameInfo(); 3911 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3912 3913 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3914 "fastcc not supported on varargs functions"); 3915 3916 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3917 // Potential tail calls could cause overwriting of argument stack slots. 3918 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3919 (CallConv == CallingConv::Fast)); 3920 unsigned PtrByteSize = 8; 3921 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3922 3923 static const MCPhysReg GPR[] = { 3924 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3925 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3926 }; 3927 static const MCPhysReg VR[] = { 3928 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3929 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3930 }; 3931 3932 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3933 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3934 const unsigned Num_VR_Regs = array_lengthof(VR); 3935 3936 // Do a first pass over the arguments to determine whether the ABI 3937 // guarantees that our caller has allocated the parameter save area 3938 // on its stack frame. In the ELFv1 ABI, this is always the case; 3939 // in the ELFv2 ABI, it is true if this is a vararg function or if 3940 // any parameter is located in a stack slot. 3941 3942 bool HasParameterArea = !isELFv2ABI || isVarArg; 3943 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3944 unsigned NumBytes = LinkageSize; 3945 unsigned AvailableFPRs = Num_FPR_Regs; 3946 unsigned AvailableVRs = Num_VR_Regs; 3947 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3948 if (Ins[i].Flags.isNest()) 3949 continue; 3950 3951 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3952 PtrByteSize, LinkageSize, ParamAreaSize, 3953 NumBytes, AvailableFPRs, AvailableVRs)) 3954 HasParameterArea = true; 3955 } 3956 3957 // Add DAG nodes to load the arguments or copy them out of registers. On 3958 // entry to a function on PPC, the arguments start after the linkage area, 3959 // although the first ones are often in registers. 3960 3961 unsigned ArgOffset = LinkageSize; 3962 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3963 SmallVector<SDValue, 8> MemOps; 3964 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3965 unsigned CurArgIdx = 0; 3966 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3967 SDValue ArgVal; 3968 bool needsLoad = false; 3969 EVT ObjectVT = Ins[ArgNo].VT; 3970 EVT OrigVT = Ins[ArgNo].ArgVT; 3971 unsigned ObjSize = ObjectVT.getStoreSize(); 3972 unsigned ArgSize = ObjSize; 3973 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3974 if (Ins[ArgNo].isOrigArg()) { 3975 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3976 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3977 } 3978 // We re-align the argument offset for each argument, except when using the 3979 // fast calling convention, when we need to make sure we do that only when 3980 // we'll actually use a stack slot. 3981 unsigned CurArgOffset; 3982 Align Alignment; 3983 auto ComputeArgOffset = [&]() { 3984 /* Respect alignment of argument on the stack. */ 3985 Alignment = 3986 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3987 ArgOffset = alignTo(ArgOffset, Alignment); 3988 CurArgOffset = ArgOffset; 3989 }; 3990 3991 if (CallConv != CallingConv::Fast) { 3992 ComputeArgOffset(); 3993 3994 /* Compute GPR index associated with argument offset. */ 3995 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3996 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3997 } 3998 3999 // FIXME the codegen can be much improved in some cases. 4000 // We do not have to keep everything in memory. 4001 if (Flags.isByVal()) { 4002 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4003 4004 if (CallConv == CallingConv::Fast) 4005 ComputeArgOffset(); 4006 4007 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4008 ObjSize = Flags.getByValSize(); 4009 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4010 // Empty aggregate parameters do not take up registers. Examples: 4011 // struct { } a; 4012 // union { } b; 4013 // int c[0]; 4014 // etc. However, we have to provide a place-holder in InVals, so 4015 // pretend we have an 8-byte item at the current address for that 4016 // purpose. 4017 if (!ObjSize) { 4018 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4019 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4020 InVals.push_back(FIN); 4021 continue; 4022 } 4023 4024 // Create a stack object covering all stack doublewords occupied 4025 // by the argument. If the argument is (fully or partially) on 4026 // the stack, or if the argument is fully in registers but the 4027 // caller has allocated the parameter save anyway, we can refer 4028 // directly to the caller's stack frame. Otherwise, create a 4029 // local copy in our own frame. 4030 int FI; 4031 if (HasParameterArea || 4032 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4033 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4034 else 4035 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4036 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4037 4038 // Handle aggregates smaller than 8 bytes. 4039 if (ObjSize < PtrByteSize) { 4040 // The value of the object is its address, which differs from the 4041 // address of the enclosing doubleword on big-endian systems. 4042 SDValue Arg = FIN; 4043 if (!isLittleEndian) { 4044 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4045 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4046 } 4047 InVals.push_back(Arg); 4048 4049 if (GPR_idx != Num_GPR_Regs) { 4050 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4051 FuncInfo->addLiveInAttr(VReg, Flags); 4052 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4053 SDValue Store; 4054 4055 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4056 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4057 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4058 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4059 MachinePointerInfo(&*FuncArg), ObjType); 4060 } else { 4061 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4062 // store the whole register as-is to the parameter save area 4063 // slot. 4064 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4065 MachinePointerInfo(&*FuncArg)); 4066 } 4067 4068 MemOps.push_back(Store); 4069 } 4070 // Whether we copied from a register or not, advance the offset 4071 // into the parameter save area by a full doubleword. 4072 ArgOffset += PtrByteSize; 4073 continue; 4074 } 4075 4076 // The value of the object is its address, which is the address of 4077 // its first stack doubleword. 4078 InVals.push_back(FIN); 4079 4080 // Store whatever pieces of the object are in registers to memory. 4081 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4082 if (GPR_idx == Num_GPR_Regs) 4083 break; 4084 4085 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4086 FuncInfo->addLiveInAttr(VReg, Flags); 4087 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4088 SDValue Addr = FIN; 4089 if (j) { 4090 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4091 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4092 } 4093 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4094 MachinePointerInfo(&*FuncArg, j)); 4095 MemOps.push_back(Store); 4096 ++GPR_idx; 4097 } 4098 ArgOffset += ArgSize; 4099 continue; 4100 } 4101 4102 switch (ObjectVT.getSimpleVT().SimpleTy) { 4103 default: llvm_unreachable("Unhandled argument type!"); 4104 case MVT::i1: 4105 case MVT::i32: 4106 case MVT::i64: 4107 if (Flags.isNest()) { 4108 // The 'nest' parameter, if any, is passed in R11. 4109 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4110 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4111 4112 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4113 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4114 4115 break; 4116 } 4117 4118 // These can be scalar arguments or elements of an integer array type 4119 // passed directly. Clang may use those instead of "byval" aggregate 4120 // types to avoid forcing arguments to memory unnecessarily. 4121 if (GPR_idx != Num_GPR_Regs) { 4122 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4123 FuncInfo->addLiveInAttr(VReg, Flags); 4124 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4125 4126 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4127 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4128 // value to MVT::i64 and then truncate to the correct register size. 4129 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4130 } else { 4131 if (CallConv == CallingConv::Fast) 4132 ComputeArgOffset(); 4133 4134 needsLoad = true; 4135 ArgSize = PtrByteSize; 4136 } 4137 if (CallConv != CallingConv::Fast || needsLoad) 4138 ArgOffset += 8; 4139 break; 4140 4141 case MVT::f32: 4142 case MVT::f64: 4143 // These can be scalar arguments or elements of a float array type 4144 // passed directly. The latter are used to implement ELFv2 homogenous 4145 // float aggregates. 4146 if (FPR_idx != Num_FPR_Regs) { 4147 unsigned VReg; 4148 4149 if (ObjectVT == MVT::f32) 4150 VReg = MF.addLiveIn(FPR[FPR_idx], 4151 Subtarget.hasP8Vector() 4152 ? &PPC::VSSRCRegClass 4153 : &PPC::F4RCRegClass); 4154 else 4155 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4156 ? &PPC::VSFRCRegClass 4157 : &PPC::F8RCRegClass); 4158 4159 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4160 ++FPR_idx; 4161 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4162 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4163 // once we support fp <-> gpr moves. 4164 4165 // This can only ever happen in the presence of f32 array types, 4166 // since otherwise we never run out of FPRs before running out 4167 // of GPRs. 4168 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4169 FuncInfo->addLiveInAttr(VReg, Flags); 4170 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4171 4172 if (ObjectVT == MVT::f32) { 4173 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4174 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4175 DAG.getConstant(32, dl, MVT::i32)); 4176 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4177 } 4178 4179 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4180 } else { 4181 if (CallConv == CallingConv::Fast) 4182 ComputeArgOffset(); 4183 4184 needsLoad = true; 4185 } 4186 4187 // When passing an array of floats, the array occupies consecutive 4188 // space in the argument area; only round up to the next doubleword 4189 // at the end of the array. Otherwise, each float takes 8 bytes. 4190 if (CallConv != CallingConv::Fast || needsLoad) { 4191 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4192 ArgOffset += ArgSize; 4193 if (Flags.isInConsecutiveRegsLast()) 4194 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4195 } 4196 break; 4197 case MVT::v4f32: 4198 case MVT::v4i32: 4199 case MVT::v8i16: 4200 case MVT::v16i8: 4201 case MVT::v2f64: 4202 case MVT::v2i64: 4203 case MVT::v1i128: 4204 case MVT::f128: 4205 // These can be scalar arguments or elements of a vector array type 4206 // passed directly. The latter are used to implement ELFv2 homogenous 4207 // vector aggregates. 4208 if (VR_idx != Num_VR_Regs) { 4209 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4210 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4211 ++VR_idx; 4212 } else { 4213 if (CallConv == CallingConv::Fast) 4214 ComputeArgOffset(); 4215 needsLoad = true; 4216 } 4217 if (CallConv != CallingConv::Fast || needsLoad) 4218 ArgOffset += 16; 4219 break; 4220 } 4221 4222 // We need to load the argument to a virtual register if we determined 4223 // above that we ran out of physical registers of the appropriate type. 4224 if (needsLoad) { 4225 if (ObjSize < ArgSize && !isLittleEndian) 4226 CurArgOffset += ArgSize - ObjSize; 4227 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4228 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4229 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4230 } 4231 4232 InVals.push_back(ArgVal); 4233 } 4234 4235 // Area that is at least reserved in the caller of this function. 4236 unsigned MinReservedArea; 4237 if (HasParameterArea) 4238 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4239 else 4240 MinReservedArea = LinkageSize; 4241 4242 // Set the size that is at least reserved in caller of this function. Tail 4243 // call optimized functions' reserved stack space needs to be aligned so that 4244 // taking the difference between two stack areas will result in an aligned 4245 // stack. 4246 MinReservedArea = 4247 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4248 FuncInfo->setMinReservedArea(MinReservedArea); 4249 4250 // If the function takes variable number of arguments, make a frame index for 4251 // the start of the first vararg value... for expansion of llvm.va_start. 4252 // On ELFv2ABI spec, it writes: 4253 // C programs that are intended to be *portable* across different compilers 4254 // and architectures must use the header file <stdarg.h> to deal with variable 4255 // argument lists. 4256 if (isVarArg && MFI.hasVAStart()) { 4257 int Depth = ArgOffset; 4258 4259 FuncInfo->setVarArgsFrameIndex( 4260 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4261 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4262 4263 // If this function is vararg, store any remaining integer argument regs 4264 // to their spots on the stack so that they may be loaded by dereferencing 4265 // the result of va_next. 4266 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4267 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4268 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4269 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4270 SDValue Store = 4271 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4272 MemOps.push_back(Store); 4273 // Increment the address by four for the next argument to store 4274 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4275 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4276 } 4277 } 4278 4279 if (!MemOps.empty()) 4280 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4281 4282 return Chain; 4283 } 4284 4285 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4286 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4287 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4288 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4289 // TODO: add description of PPC stack frame format, or at least some docs. 4290 // 4291 MachineFunction &MF = DAG.getMachineFunction(); 4292 MachineFrameInfo &MFI = MF.getFrameInfo(); 4293 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4294 4295 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4296 bool isPPC64 = PtrVT == MVT::i64; 4297 // Potential tail calls could cause overwriting of argument stack slots. 4298 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4299 (CallConv == CallingConv::Fast)); 4300 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4301 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4302 unsigned ArgOffset = LinkageSize; 4303 // Area that is at least reserved in caller of this function. 4304 unsigned MinReservedArea = ArgOffset; 4305 4306 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4307 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4308 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4309 }; 4310 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4311 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4312 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4313 }; 4314 static const MCPhysReg VR[] = { 4315 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4316 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4317 }; 4318 4319 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4320 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4321 const unsigned Num_VR_Regs = array_lengthof( VR); 4322 4323 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4324 4325 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4326 4327 // In 32-bit non-varargs functions, the stack space for vectors is after the 4328 // stack space for non-vectors. We do not use this space unless we have 4329 // too many vectors to fit in registers, something that only occurs in 4330 // constructed examples:), but we have to walk the arglist to figure 4331 // that out...for the pathological case, compute VecArgOffset as the 4332 // start of the vector parameter area. Computing VecArgOffset is the 4333 // entire point of the following loop. 4334 unsigned VecArgOffset = ArgOffset; 4335 if (!isVarArg && !isPPC64) { 4336 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4337 ++ArgNo) { 4338 EVT ObjectVT = Ins[ArgNo].VT; 4339 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4340 4341 if (Flags.isByVal()) { 4342 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4343 unsigned ObjSize = Flags.getByValSize(); 4344 unsigned ArgSize = 4345 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4346 VecArgOffset += ArgSize; 4347 continue; 4348 } 4349 4350 switch(ObjectVT.getSimpleVT().SimpleTy) { 4351 default: llvm_unreachable("Unhandled argument type!"); 4352 case MVT::i1: 4353 case MVT::i32: 4354 case MVT::f32: 4355 VecArgOffset += 4; 4356 break; 4357 case MVT::i64: // PPC64 4358 case MVT::f64: 4359 // FIXME: We are guaranteed to be !isPPC64 at this point. 4360 // Does MVT::i64 apply? 4361 VecArgOffset += 8; 4362 break; 4363 case MVT::v4f32: 4364 case MVT::v4i32: 4365 case MVT::v8i16: 4366 case MVT::v16i8: 4367 // Nothing to do, we're only looking at Nonvector args here. 4368 break; 4369 } 4370 } 4371 } 4372 // We've found where the vector parameter area in memory is. Skip the 4373 // first 12 parameters; these don't use that memory. 4374 VecArgOffset = ((VecArgOffset+15)/16)*16; 4375 VecArgOffset += 12*16; 4376 4377 // Add DAG nodes to load the arguments or copy them out of registers. On 4378 // entry to a function on PPC, the arguments start after the linkage area, 4379 // although the first ones are often in registers. 4380 4381 SmallVector<SDValue, 8> MemOps; 4382 unsigned nAltivecParamsAtEnd = 0; 4383 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4384 unsigned CurArgIdx = 0; 4385 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4386 SDValue ArgVal; 4387 bool needsLoad = false; 4388 EVT ObjectVT = Ins[ArgNo].VT; 4389 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4390 unsigned ArgSize = ObjSize; 4391 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4392 if (Ins[ArgNo].isOrigArg()) { 4393 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4394 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4395 } 4396 unsigned CurArgOffset = ArgOffset; 4397 4398 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4399 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4400 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4401 if (isVarArg || isPPC64) { 4402 MinReservedArea = ((MinReservedArea+15)/16)*16; 4403 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4404 Flags, 4405 PtrByteSize); 4406 } else nAltivecParamsAtEnd++; 4407 } else 4408 // Calculate min reserved area. 4409 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4410 Flags, 4411 PtrByteSize); 4412 4413 // FIXME the codegen can be much improved in some cases. 4414 // We do not have to keep everything in memory. 4415 if (Flags.isByVal()) { 4416 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4417 4418 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4419 ObjSize = Flags.getByValSize(); 4420 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4421 // Objects of size 1 and 2 are right justified, everything else is 4422 // left justified. This means the memory address is adjusted forwards. 4423 if (ObjSize==1 || ObjSize==2) { 4424 CurArgOffset = CurArgOffset + (4 - ObjSize); 4425 } 4426 // The value of the object is its address. 4427 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4428 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4429 InVals.push_back(FIN); 4430 if (ObjSize==1 || ObjSize==2) { 4431 if (GPR_idx != Num_GPR_Regs) { 4432 unsigned VReg; 4433 if (isPPC64) 4434 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4435 else 4436 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4437 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4438 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4439 SDValue Store = 4440 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4441 MachinePointerInfo(&*FuncArg), ObjType); 4442 MemOps.push_back(Store); 4443 ++GPR_idx; 4444 } 4445 4446 ArgOffset += PtrByteSize; 4447 4448 continue; 4449 } 4450 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4451 // Store whatever pieces of the object are in registers 4452 // to memory. ArgOffset will be the address of the beginning 4453 // of the object. 4454 if (GPR_idx != Num_GPR_Regs) { 4455 unsigned VReg; 4456 if (isPPC64) 4457 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4458 else 4459 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4460 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4461 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4462 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4463 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4464 MachinePointerInfo(&*FuncArg, j)); 4465 MemOps.push_back(Store); 4466 ++GPR_idx; 4467 ArgOffset += PtrByteSize; 4468 } else { 4469 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4470 break; 4471 } 4472 } 4473 continue; 4474 } 4475 4476 switch (ObjectVT.getSimpleVT().SimpleTy) { 4477 default: llvm_unreachable("Unhandled argument type!"); 4478 case MVT::i1: 4479 case MVT::i32: 4480 if (!isPPC64) { 4481 if (GPR_idx != Num_GPR_Regs) { 4482 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4483 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4484 4485 if (ObjectVT == MVT::i1) 4486 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4487 4488 ++GPR_idx; 4489 } else { 4490 needsLoad = true; 4491 ArgSize = PtrByteSize; 4492 } 4493 // All int arguments reserve stack space in the Darwin ABI. 4494 ArgOffset += PtrByteSize; 4495 break; 4496 } 4497 LLVM_FALLTHROUGH; 4498 case MVT::i64: // PPC64 4499 if (GPR_idx != Num_GPR_Regs) { 4500 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4501 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4502 4503 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4504 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4505 // value to MVT::i64 and then truncate to the correct register size. 4506 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4507 4508 ++GPR_idx; 4509 } else { 4510 needsLoad = true; 4511 ArgSize = PtrByteSize; 4512 } 4513 // All int arguments reserve stack space in the Darwin ABI. 4514 ArgOffset += 8; 4515 break; 4516 4517 case MVT::f32: 4518 case MVT::f64: 4519 // Every 4 bytes of argument space consumes one of the GPRs available for 4520 // argument passing. 4521 if (GPR_idx != Num_GPR_Regs) { 4522 ++GPR_idx; 4523 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4524 ++GPR_idx; 4525 } 4526 if (FPR_idx != Num_FPR_Regs) { 4527 unsigned VReg; 4528 4529 if (ObjectVT == MVT::f32) 4530 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4531 else 4532 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4533 4534 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4535 ++FPR_idx; 4536 } else { 4537 needsLoad = true; 4538 } 4539 4540 // All FP arguments reserve stack space in the Darwin ABI. 4541 ArgOffset += isPPC64 ? 8 : ObjSize; 4542 break; 4543 case MVT::v4f32: 4544 case MVT::v4i32: 4545 case MVT::v8i16: 4546 case MVT::v16i8: 4547 // Note that vector arguments in registers don't reserve stack space, 4548 // except in varargs functions. 4549 if (VR_idx != Num_VR_Regs) { 4550 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4551 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4552 if (isVarArg) { 4553 while ((ArgOffset % 16) != 0) { 4554 ArgOffset += PtrByteSize; 4555 if (GPR_idx != Num_GPR_Regs) 4556 GPR_idx++; 4557 } 4558 ArgOffset += 16; 4559 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4560 } 4561 ++VR_idx; 4562 } else { 4563 if (!isVarArg && !isPPC64) { 4564 // Vectors go after all the nonvectors. 4565 CurArgOffset = VecArgOffset; 4566 VecArgOffset += 16; 4567 } else { 4568 // Vectors are aligned. 4569 ArgOffset = ((ArgOffset+15)/16)*16; 4570 CurArgOffset = ArgOffset; 4571 ArgOffset += 16; 4572 } 4573 needsLoad = true; 4574 } 4575 break; 4576 } 4577 4578 // We need to load the argument to a virtual register if we determined above 4579 // that we ran out of physical registers of the appropriate type. 4580 if (needsLoad) { 4581 int FI = MFI.CreateFixedObject(ObjSize, 4582 CurArgOffset + (ArgSize - ObjSize), 4583 isImmutable); 4584 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4585 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4586 } 4587 4588 InVals.push_back(ArgVal); 4589 } 4590 4591 // Allow for Altivec parameters at the end, if needed. 4592 if (nAltivecParamsAtEnd) { 4593 MinReservedArea = ((MinReservedArea+15)/16)*16; 4594 MinReservedArea += 16*nAltivecParamsAtEnd; 4595 } 4596 4597 // Area that is at least reserved in the caller of this function. 4598 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4599 4600 // Set the size that is at least reserved in caller of this function. Tail 4601 // call optimized functions' reserved stack space needs to be aligned so that 4602 // taking the difference between two stack areas will result in an aligned 4603 // stack. 4604 MinReservedArea = 4605 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4606 FuncInfo->setMinReservedArea(MinReservedArea); 4607 4608 // If the function takes variable number of arguments, make a frame index for 4609 // the start of the first vararg value... for expansion of llvm.va_start. 4610 if (isVarArg) { 4611 int Depth = ArgOffset; 4612 4613 FuncInfo->setVarArgsFrameIndex( 4614 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4615 Depth, true)); 4616 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4617 4618 // If this function is vararg, store any remaining integer argument regs 4619 // to their spots on the stack so that they may be loaded by dereferencing 4620 // the result of va_next. 4621 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4622 unsigned VReg; 4623 4624 if (isPPC64) 4625 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4626 else 4627 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4628 4629 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4630 SDValue Store = 4631 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4632 MemOps.push_back(Store); 4633 // Increment the address by four for the next argument to store 4634 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4635 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4636 } 4637 } 4638 4639 if (!MemOps.empty()) 4640 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4641 4642 return Chain; 4643 } 4644 4645 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4646 /// adjusted to accommodate the arguments for the tailcall. 4647 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4648 unsigned ParamSize) { 4649 4650 if (!isTailCall) return 0; 4651 4652 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4653 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4654 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4655 // Remember only if the new adjustment is bigger. 4656 if (SPDiff < FI->getTailCallSPDelta()) 4657 FI->setTailCallSPDelta(SPDiff); 4658 4659 return SPDiff; 4660 } 4661 4662 static bool isFunctionGlobalAddress(SDValue Callee); 4663 4664 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4665 const TargetMachine &TM) { 4666 // It does not make sense to call callsShareTOCBase() with a caller that 4667 // is PC Relative since PC Relative callers do not have a TOC. 4668 #ifndef NDEBUG 4669 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4670 assert(!STICaller->isUsingPCRelativeCalls() && 4671 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4672 #endif 4673 4674 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4675 // don't have enough information to determine if the caller and callee share 4676 // the same TOC base, so we have to pessimistically assume they don't for 4677 // correctness. 4678 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4679 if (!G) 4680 return false; 4681 4682 const GlobalValue *GV = G->getGlobal(); 4683 4684 // If the callee is preemptable, then the static linker will use a plt-stub 4685 // which saves the toc to the stack, and needs a nop after the call 4686 // instruction to convert to a toc-restore. 4687 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4688 return false; 4689 4690 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4691 // We may need a TOC restore in the situation where the caller requires a 4692 // valid TOC but the callee is PC Relative and does not. 4693 const Function *F = dyn_cast<Function>(GV); 4694 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4695 4696 // If we have an Alias we can try to get the function from there. 4697 if (Alias) { 4698 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4699 F = dyn_cast<Function>(GlobalObj); 4700 } 4701 4702 // If we still have no valid function pointer we do not have enough 4703 // information to determine if the callee uses PC Relative calls so we must 4704 // assume that it does. 4705 if (!F) 4706 return false; 4707 4708 // If the callee uses PC Relative we cannot guarantee that the callee won't 4709 // clobber the TOC of the caller and so we must assume that the two 4710 // functions do not share a TOC base. 4711 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4712 if (STICallee->isUsingPCRelativeCalls()) 4713 return false; 4714 4715 // The medium and large code models are expected to provide a sufficiently 4716 // large TOC to provide all data addressing needs of a module with a 4717 // single TOC. 4718 if (CodeModel::Medium == TM.getCodeModel() || 4719 CodeModel::Large == TM.getCodeModel()) 4720 return true; 4721 4722 // Otherwise we need to ensure callee and caller are in the same section, 4723 // since the linker may allocate multiple TOCs, and we don't know which 4724 // sections will belong to the same TOC base. 4725 if (!GV->isStrongDefinitionForLinker()) 4726 return false; 4727 4728 // Any explicitly-specified sections and section prefixes must also match. 4729 // Also, if we're using -ffunction-sections, then each function is always in 4730 // a different section (the same is true for COMDAT functions). 4731 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4732 GV->getSection() != Caller->getSection()) 4733 return false; 4734 if (const auto *F = dyn_cast<Function>(GV)) { 4735 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4736 return false; 4737 } 4738 4739 return true; 4740 } 4741 4742 static bool 4743 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4744 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4745 assert(Subtarget.is64BitELFABI()); 4746 4747 const unsigned PtrByteSize = 8; 4748 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4749 4750 static const MCPhysReg GPR[] = { 4751 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4752 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4753 }; 4754 static const MCPhysReg VR[] = { 4755 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4756 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4757 }; 4758 4759 const unsigned NumGPRs = array_lengthof(GPR); 4760 const unsigned NumFPRs = 13; 4761 const unsigned NumVRs = array_lengthof(VR); 4762 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4763 4764 unsigned NumBytes = LinkageSize; 4765 unsigned AvailableFPRs = NumFPRs; 4766 unsigned AvailableVRs = NumVRs; 4767 4768 for (const ISD::OutputArg& Param : Outs) { 4769 if (Param.Flags.isNest()) continue; 4770 4771 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4772 LinkageSize, ParamAreaSize, NumBytes, 4773 AvailableFPRs, AvailableVRs)) 4774 return true; 4775 } 4776 return false; 4777 } 4778 4779 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4780 if (CB.arg_size() != CallerFn->arg_size()) 4781 return false; 4782 4783 auto CalleeArgIter = CB.arg_begin(); 4784 auto CalleeArgEnd = CB.arg_end(); 4785 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4786 4787 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4788 const Value* CalleeArg = *CalleeArgIter; 4789 const Value* CallerArg = &(*CallerArgIter); 4790 if (CalleeArg == CallerArg) 4791 continue; 4792 4793 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4794 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4795 // } 4796 // 1st argument of callee is undef and has the same type as caller. 4797 if (CalleeArg->getType() == CallerArg->getType() && 4798 isa<UndefValue>(CalleeArg)) 4799 continue; 4800 4801 return false; 4802 } 4803 4804 return true; 4805 } 4806 4807 // Returns true if TCO is possible between the callers and callees 4808 // calling conventions. 4809 static bool 4810 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4811 CallingConv::ID CalleeCC) { 4812 // Tail calls are possible with fastcc and ccc. 4813 auto isTailCallableCC = [] (CallingConv::ID CC){ 4814 return CC == CallingConv::C || CC == CallingConv::Fast; 4815 }; 4816 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4817 return false; 4818 4819 // We can safely tail call both fastcc and ccc callees from a c calling 4820 // convention caller. If the caller is fastcc, we may have less stack space 4821 // than a non-fastcc caller with the same signature so disable tail-calls in 4822 // that case. 4823 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4824 } 4825 4826 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4827 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4828 const SmallVectorImpl<ISD::OutputArg> &Outs, 4829 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4830 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4831 4832 if (DisableSCO && !TailCallOpt) return false; 4833 4834 // Variadic argument functions are not supported. 4835 if (isVarArg) return false; 4836 4837 auto &Caller = DAG.getMachineFunction().getFunction(); 4838 // Check that the calling conventions are compatible for tco. 4839 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4840 return false; 4841 4842 // Caller contains any byval parameter is not supported. 4843 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4844 return false; 4845 4846 // Callee contains any byval parameter is not supported, too. 4847 // Note: This is a quick work around, because in some cases, e.g. 4848 // caller's stack size > callee's stack size, we are still able to apply 4849 // sibling call optimization. For example, gcc is able to do SCO for caller1 4850 // in the following example, but not for caller2. 4851 // struct test { 4852 // long int a; 4853 // char ary[56]; 4854 // } gTest; 4855 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4856 // b->a = v.a; 4857 // return 0; 4858 // } 4859 // void caller1(struct test a, struct test c, struct test *b) { 4860 // callee(gTest, b); } 4861 // void caller2(struct test *b) { callee(gTest, b); } 4862 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4863 return false; 4864 4865 // If callee and caller use different calling conventions, we cannot pass 4866 // parameters on stack since offsets for the parameter area may be different. 4867 if (Caller.getCallingConv() != CalleeCC && 4868 needStackSlotPassParameters(Subtarget, Outs)) 4869 return false; 4870 4871 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4872 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4873 // callee potentially have different TOC bases then we cannot tail call since 4874 // we need to restore the TOC pointer after the call. 4875 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4876 // We cannot guarantee this for indirect calls or calls to external functions. 4877 // When PC-Relative addressing is used, the concept of the TOC is no longer 4878 // applicable so this check is not required. 4879 // Check first for indirect calls. 4880 if (!Subtarget.isUsingPCRelativeCalls() && 4881 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4882 return false; 4883 4884 // Check if we share the TOC base. 4885 if (!Subtarget.isUsingPCRelativeCalls() && 4886 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4887 return false; 4888 4889 // TCO allows altering callee ABI, so we don't have to check further. 4890 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4891 return true; 4892 4893 if (DisableSCO) return false; 4894 4895 // If callee use the same argument list that caller is using, then we can 4896 // apply SCO on this case. If it is not, then we need to check if callee needs 4897 // stack for passing arguments. 4898 // PC Relative tail calls may not have a CallBase. 4899 // If there is no CallBase we cannot verify if we have the same argument 4900 // list so assume that we don't have the same argument list. 4901 if (CB && !hasSameArgumentList(&Caller, *CB) && 4902 needStackSlotPassParameters(Subtarget, Outs)) 4903 return false; 4904 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4905 return false; 4906 4907 return true; 4908 } 4909 4910 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4911 /// for tail call optimization. Targets which want to do tail call 4912 /// optimization should implement this function. 4913 bool 4914 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4915 CallingConv::ID CalleeCC, 4916 bool isVarArg, 4917 const SmallVectorImpl<ISD::InputArg> &Ins, 4918 SelectionDAG& DAG) const { 4919 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4920 return false; 4921 4922 // Variable argument functions are not supported. 4923 if (isVarArg) 4924 return false; 4925 4926 MachineFunction &MF = DAG.getMachineFunction(); 4927 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4928 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4929 // Functions containing by val parameters are not supported. 4930 for (unsigned i = 0; i != Ins.size(); i++) { 4931 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4932 if (Flags.isByVal()) return false; 4933 } 4934 4935 // Non-PIC/GOT tail calls are supported. 4936 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4937 return true; 4938 4939 // At the moment we can only do local tail calls (in same module, hidden 4940 // or protected) if we are generating PIC. 4941 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4942 return G->getGlobal()->hasHiddenVisibility() 4943 || G->getGlobal()->hasProtectedVisibility(); 4944 } 4945 4946 return false; 4947 } 4948 4949 /// isCallCompatibleAddress - Return the immediate to use if the specified 4950 /// 32-bit value is representable in the immediate field of a BxA instruction. 4951 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4952 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4953 if (!C) return nullptr; 4954 4955 int Addr = C->getZExtValue(); 4956 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4957 SignExtend32<26>(Addr) != Addr) 4958 return nullptr; // Top 6 bits have to be sext of immediate. 4959 4960 return DAG 4961 .getConstant( 4962 (int)C->getZExtValue() >> 2, SDLoc(Op), 4963 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4964 .getNode(); 4965 } 4966 4967 namespace { 4968 4969 struct TailCallArgumentInfo { 4970 SDValue Arg; 4971 SDValue FrameIdxOp; 4972 int FrameIdx = 0; 4973 4974 TailCallArgumentInfo() = default; 4975 }; 4976 4977 } // end anonymous namespace 4978 4979 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4980 static void StoreTailCallArgumentsToStackSlot( 4981 SelectionDAG &DAG, SDValue Chain, 4982 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4983 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4984 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4985 SDValue Arg = TailCallArgs[i].Arg; 4986 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4987 int FI = TailCallArgs[i].FrameIdx; 4988 // Store relative to framepointer. 4989 MemOpChains.push_back(DAG.getStore( 4990 Chain, dl, Arg, FIN, 4991 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4992 } 4993 } 4994 4995 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4996 /// the appropriate stack slot for the tail call optimized function call. 4997 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4998 SDValue OldRetAddr, SDValue OldFP, 4999 int SPDiff, const SDLoc &dl) { 5000 if (SPDiff) { 5001 // Calculate the new stack slot for the return address. 5002 MachineFunction &MF = DAG.getMachineFunction(); 5003 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 5004 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 5005 bool isPPC64 = Subtarget.isPPC64(); 5006 int SlotSize = isPPC64 ? 8 : 4; 5007 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 5008 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 5009 NewRetAddrLoc, true); 5010 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5011 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5012 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5013 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5014 } 5015 return Chain; 5016 } 5017 5018 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5019 /// the position of the argument. 5020 static void 5021 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5022 SDValue Arg, int SPDiff, unsigned ArgOffset, 5023 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5024 int Offset = ArgOffset + SPDiff; 5025 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5026 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5027 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5028 SDValue FIN = DAG.getFrameIndex(FI, VT); 5029 TailCallArgumentInfo Info; 5030 Info.Arg = Arg; 5031 Info.FrameIdxOp = FIN; 5032 Info.FrameIdx = FI; 5033 TailCallArguments.push_back(Info); 5034 } 5035 5036 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5037 /// stack slot. Returns the chain as result and the loaded frame pointers in 5038 /// LROpOut/FPOpout. Used when tail calling. 5039 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5040 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5041 SDValue &FPOpOut, const SDLoc &dl) const { 5042 if (SPDiff) { 5043 // Load the LR and FP stack slot for later adjusting. 5044 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5045 LROpOut = getReturnAddrFrameIndex(DAG); 5046 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5047 Chain = SDValue(LROpOut.getNode(), 1); 5048 } 5049 return Chain; 5050 } 5051 5052 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5053 /// by "Src" to address "Dst" of size "Size". Alignment information is 5054 /// specified by the specific parameter attribute. The copy will be passed as 5055 /// a byval function parameter. 5056 /// Sometimes what we are copying is the end of a larger object, the part that 5057 /// does not fit in registers. 5058 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5059 SDValue Chain, ISD::ArgFlagsTy Flags, 5060 SelectionDAG &DAG, const SDLoc &dl) { 5061 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5062 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5063 Flags.getNonZeroByValAlign(), false, false, false, 5064 MachinePointerInfo(), MachinePointerInfo()); 5065 } 5066 5067 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5068 /// tail calls. 5069 static void LowerMemOpCallTo( 5070 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5071 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5072 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5073 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5074 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5075 if (!isTailCall) { 5076 if (isVector) { 5077 SDValue StackPtr; 5078 if (isPPC64) 5079 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5080 else 5081 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5082 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5083 DAG.getConstant(ArgOffset, dl, PtrVT)); 5084 } 5085 MemOpChains.push_back( 5086 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5087 // Calculate and remember argument location. 5088 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5089 TailCallArguments); 5090 } 5091 5092 static void 5093 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5094 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5095 SDValue FPOp, 5096 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5097 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5098 // might overwrite each other in case of tail call optimization. 5099 SmallVector<SDValue, 8> MemOpChains2; 5100 // Do not flag preceding copytoreg stuff together with the following stuff. 5101 InFlag = SDValue(); 5102 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5103 MemOpChains2, dl); 5104 if (!MemOpChains2.empty()) 5105 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5106 5107 // Store the return address to the appropriate stack slot. 5108 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5109 5110 // Emit callseq_end just before tailcall node. 5111 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5112 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5113 InFlag = Chain.getValue(1); 5114 } 5115 5116 // Is this global address that of a function that can be called by name? (as 5117 // opposed to something that must hold a descriptor for an indirect call). 5118 static bool isFunctionGlobalAddress(SDValue Callee) { 5119 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5120 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5121 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5122 return false; 5123 5124 return G->getGlobal()->getValueType()->isFunctionTy(); 5125 } 5126 5127 return false; 5128 } 5129 5130 SDValue PPCTargetLowering::LowerCallResult( 5131 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5132 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5133 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5134 SmallVector<CCValAssign, 16> RVLocs; 5135 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5136 *DAG.getContext()); 5137 5138 CCRetInfo.AnalyzeCallResult( 5139 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5140 ? RetCC_PPC_Cold 5141 : RetCC_PPC); 5142 5143 // Copy all of the result registers out of their specified physreg. 5144 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5145 CCValAssign &VA = RVLocs[i]; 5146 assert(VA.isRegLoc() && "Can only return in registers!"); 5147 5148 SDValue Val; 5149 5150 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5151 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5152 InFlag); 5153 Chain = Lo.getValue(1); 5154 InFlag = Lo.getValue(2); 5155 VA = RVLocs[++i]; // skip ahead to next loc 5156 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5157 InFlag); 5158 Chain = Hi.getValue(1); 5159 InFlag = Hi.getValue(2); 5160 if (!Subtarget.isLittleEndian()) 5161 std::swap (Lo, Hi); 5162 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5163 } else { 5164 Val = DAG.getCopyFromReg(Chain, dl, 5165 VA.getLocReg(), VA.getLocVT(), InFlag); 5166 Chain = Val.getValue(1); 5167 InFlag = Val.getValue(2); 5168 } 5169 5170 switch (VA.getLocInfo()) { 5171 default: llvm_unreachable("Unknown loc info!"); 5172 case CCValAssign::Full: break; 5173 case CCValAssign::AExt: 5174 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5175 break; 5176 case CCValAssign::ZExt: 5177 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5178 DAG.getValueType(VA.getValVT())); 5179 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5180 break; 5181 case CCValAssign::SExt: 5182 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5183 DAG.getValueType(VA.getValVT())); 5184 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5185 break; 5186 } 5187 5188 InVals.push_back(Val); 5189 } 5190 5191 return Chain; 5192 } 5193 5194 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5195 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5196 // PatchPoint calls are not indirect. 5197 if (isPatchPoint) 5198 return false; 5199 5200 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5201 return false; 5202 5203 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5204 // becuase the immediate function pointer points to a descriptor instead of 5205 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5206 // pointer immediate points to the global entry point, while the BLA would 5207 // need to jump to the local entry point (see rL211174). 5208 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5209 isBLACompatibleAddress(Callee, DAG)) 5210 return false; 5211 5212 return true; 5213 } 5214 5215 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5216 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5217 return Subtarget.isAIXABI() || 5218 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5219 } 5220 5221 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5222 const Function &Caller, 5223 const SDValue &Callee, 5224 const PPCSubtarget &Subtarget, 5225 const TargetMachine &TM) { 5226 if (CFlags.IsTailCall) 5227 return PPCISD::TC_RETURN; 5228 5229 // This is a call through a function pointer. 5230 if (CFlags.IsIndirect) { 5231 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5232 // indirect calls. The save of the caller's TOC pointer to the stack will be 5233 // inserted into the DAG as part of call lowering. The restore of the TOC 5234 // pointer is modeled by using a pseudo instruction for the call opcode that 5235 // represents the 2 instruction sequence of an indirect branch and link, 5236 // immediately followed by a load of the TOC pointer from the the stack save 5237 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5238 // as it is not saved or used. 5239 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5240 : PPCISD::BCTRL; 5241 } 5242 5243 if (Subtarget.isUsingPCRelativeCalls()) { 5244 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5245 return PPCISD::CALL_NOTOC; 5246 } 5247 5248 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5249 // immediately following the call instruction if the caller and callee may 5250 // have different TOC bases. At link time if the linker determines the calls 5251 // may not share a TOC base, the call is redirected to a trampoline inserted 5252 // by the linker. The trampoline will (among other things) save the callers 5253 // TOC pointer at an ABI designated offset in the linkage area and the linker 5254 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5255 // into gpr2. 5256 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5257 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5258 : PPCISD::CALL_NOP; 5259 5260 return PPCISD::CALL; 5261 } 5262 5263 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5264 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5265 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5266 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5267 return SDValue(Dest, 0); 5268 5269 // Returns true if the callee is local, and false otherwise. 5270 auto isLocalCallee = [&]() { 5271 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5272 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5273 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5274 5275 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5276 !dyn_cast_or_null<GlobalIFunc>(GV); 5277 }; 5278 5279 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5280 // a static relocation model causes some versions of GNU LD (2.17.50, at 5281 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5282 // built with secure-PLT. 5283 bool UsePlt = 5284 Subtarget.is32BitELFABI() && !isLocalCallee() && 5285 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5286 5287 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5288 const TargetMachine &TM = Subtarget.getTargetMachine(); 5289 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5290 MCSymbolXCOFF *S = 5291 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5292 5293 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5294 return DAG.getMCSymbol(S, PtrVT); 5295 }; 5296 5297 if (isFunctionGlobalAddress(Callee)) { 5298 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5299 5300 if (Subtarget.isAIXABI()) { 5301 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5302 return getAIXFuncEntryPointSymbolSDNode(GV); 5303 } 5304 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5305 UsePlt ? PPCII::MO_PLT : 0); 5306 } 5307 5308 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5309 const char *SymName = S->getSymbol(); 5310 if (Subtarget.isAIXABI()) { 5311 // If there exists a user-declared function whose name is the same as the 5312 // ExternalSymbol's, then we pick up the user-declared version. 5313 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5314 if (const Function *F = 5315 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5316 return getAIXFuncEntryPointSymbolSDNode(F); 5317 5318 // On AIX, direct function calls reference the symbol for the function's 5319 // entry point, which is named by prepending a "." before the function's 5320 // C-linkage name. A Qualname is returned here because an external 5321 // function entry point is a csect with XTY_ER property. 5322 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5323 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5324 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5325 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5326 SectionKind::getMetadata()); 5327 return Sec->getQualNameSymbol(); 5328 }; 5329 5330 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5331 } 5332 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5333 UsePlt ? PPCII::MO_PLT : 0); 5334 } 5335 5336 // No transformation needed. 5337 assert(Callee.getNode() && "What no callee?"); 5338 return Callee; 5339 } 5340 5341 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5342 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5343 "Expected a CALLSEQ_STARTSDNode."); 5344 5345 // The last operand is the chain, except when the node has glue. If the node 5346 // has glue, then the last operand is the glue, and the chain is the second 5347 // last operand. 5348 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5349 if (LastValue.getValueType() != MVT::Glue) 5350 return LastValue; 5351 5352 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5353 } 5354 5355 // Creates the node that moves a functions address into the count register 5356 // to prepare for an indirect call instruction. 5357 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5358 SDValue &Glue, SDValue &Chain, 5359 const SDLoc &dl) { 5360 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5361 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5362 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5363 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5364 // The glue is the second value produced. 5365 Glue = Chain.getValue(1); 5366 } 5367 5368 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5369 SDValue &Glue, SDValue &Chain, 5370 SDValue CallSeqStart, 5371 const CallBase *CB, const SDLoc &dl, 5372 bool hasNest, 5373 const PPCSubtarget &Subtarget) { 5374 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5375 // entry point, but to the function descriptor (the function entry point 5376 // address is part of the function descriptor though). 5377 // The function descriptor is a three doubleword structure with the 5378 // following fields: function entry point, TOC base address and 5379 // environment pointer. 5380 // Thus for a call through a function pointer, the following actions need 5381 // to be performed: 5382 // 1. Save the TOC of the caller in the TOC save area of its stack 5383 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5384 // 2. Load the address of the function entry point from the function 5385 // descriptor. 5386 // 3. Load the TOC of the callee from the function descriptor into r2. 5387 // 4. Load the environment pointer from the function descriptor into 5388 // r11. 5389 // 5. Branch to the function entry point address. 5390 // 6. On return of the callee, the TOC of the caller needs to be 5391 // restored (this is done in FinishCall()). 5392 // 5393 // The loads are scheduled at the beginning of the call sequence, and the 5394 // register copies are flagged together to ensure that no other 5395 // operations can be scheduled in between. E.g. without flagging the 5396 // copies together, a TOC access in the caller could be scheduled between 5397 // the assignment of the callee TOC and the branch to the callee, which leads 5398 // to incorrect code. 5399 5400 // Start by loading the function address from the descriptor. 5401 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5402 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5403 ? (MachineMemOperand::MODereferenceable | 5404 MachineMemOperand::MOInvariant) 5405 : MachineMemOperand::MONone; 5406 5407 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5408 5409 // Registers used in building the DAG. 5410 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5411 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5412 5413 // Offsets of descriptor members. 5414 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5415 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5416 5417 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5418 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5419 5420 // One load for the functions entry point address. 5421 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5422 Alignment, MMOFlags); 5423 5424 // One for loading the TOC anchor for the module that contains the called 5425 // function. 5426 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5427 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5428 SDValue TOCPtr = 5429 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5430 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5431 5432 // One for loading the environment pointer. 5433 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5434 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5435 SDValue LoadEnvPtr = 5436 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5437 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5438 5439 5440 // Then copy the newly loaded TOC anchor to the TOC pointer. 5441 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5442 Chain = TOCVal.getValue(0); 5443 Glue = TOCVal.getValue(1); 5444 5445 // If the function call has an explicit 'nest' parameter, it takes the 5446 // place of the environment pointer. 5447 assert((!hasNest || !Subtarget.isAIXABI()) && 5448 "Nest parameter is not supported on AIX."); 5449 if (!hasNest) { 5450 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5451 Chain = EnvVal.getValue(0); 5452 Glue = EnvVal.getValue(1); 5453 } 5454 5455 // The rest of the indirect call sequence is the same as the non-descriptor 5456 // DAG. 5457 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5458 } 5459 5460 static void 5461 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5462 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5463 SelectionDAG &DAG, 5464 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5465 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5466 const PPCSubtarget &Subtarget) { 5467 const bool IsPPC64 = Subtarget.isPPC64(); 5468 // MVT for a general purpose register. 5469 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5470 5471 // First operand is always the chain. 5472 Ops.push_back(Chain); 5473 5474 // If it's a direct call pass the callee as the second operand. 5475 if (!CFlags.IsIndirect) 5476 Ops.push_back(Callee); 5477 else { 5478 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5479 5480 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5481 // on the stack (this would have been done in `LowerCall_64SVR4` or 5482 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5483 // represents both the indirect branch and a load that restores the TOC 5484 // pointer from the linkage area. The operand for the TOC restore is an add 5485 // of the TOC save offset to the stack pointer. This must be the second 5486 // operand: after the chain input but before any other variadic arguments. 5487 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5488 // saved or used. 5489 if (isTOCSaveRestoreRequired(Subtarget)) { 5490 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5491 5492 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5493 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5494 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5495 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5496 Ops.push_back(AddTOC); 5497 } 5498 5499 // Add the register used for the environment pointer. 5500 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5501 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5502 RegVT)); 5503 5504 5505 // Add CTR register as callee so a bctr can be emitted later. 5506 if (CFlags.IsTailCall) 5507 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5508 } 5509 5510 // If this is a tail call add stack pointer delta. 5511 if (CFlags.IsTailCall) 5512 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5513 5514 // Add argument registers to the end of the list so that they are known live 5515 // into the call. 5516 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5517 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5518 RegsToPass[i].second.getValueType())); 5519 5520 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5521 // no way to mark dependencies as implicit here. 5522 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5523 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5524 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5525 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5526 5527 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5528 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5529 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5530 5531 // Add a register mask operand representing the call-preserved registers. 5532 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5533 const uint32_t *Mask = 5534 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5535 assert(Mask && "Missing call preserved mask for calling convention"); 5536 Ops.push_back(DAG.getRegisterMask(Mask)); 5537 5538 // If the glue is valid, it is the last operand. 5539 if (Glue.getNode()) 5540 Ops.push_back(Glue); 5541 } 5542 5543 SDValue PPCTargetLowering::FinishCall( 5544 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5545 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5546 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5547 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5548 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5549 5550 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5551 Subtarget.isAIXABI()) 5552 setUsesTOCBasePtr(DAG); 5553 5554 unsigned CallOpc = 5555 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5556 Subtarget, DAG.getTarget()); 5557 5558 if (!CFlags.IsIndirect) 5559 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5560 else if (Subtarget.usesFunctionDescriptors()) 5561 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5562 dl, CFlags.HasNest, Subtarget); 5563 else 5564 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5565 5566 // Build the operand list for the call instruction. 5567 SmallVector<SDValue, 8> Ops; 5568 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5569 SPDiff, Subtarget); 5570 5571 // Emit tail call. 5572 if (CFlags.IsTailCall) { 5573 // Indirect tail call when using PC Relative calls do not have the same 5574 // constraints. 5575 assert(((Callee.getOpcode() == ISD::Register && 5576 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5577 Callee.getOpcode() == ISD::TargetExternalSymbol || 5578 Callee.getOpcode() == ISD::TargetGlobalAddress || 5579 isa<ConstantSDNode>(Callee) || 5580 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5581 "Expecting a global address, external symbol, absolute value, " 5582 "register or an indirect tail call when PC Relative calls are " 5583 "used."); 5584 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5585 assert(CallOpc == PPCISD::TC_RETURN && 5586 "Unexpected call opcode for a tail call."); 5587 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5588 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5589 } 5590 5591 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5592 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5593 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5594 Glue = Chain.getValue(1); 5595 5596 // When performing tail call optimization the callee pops its arguments off 5597 // the stack. Account for this here so these bytes can be pushed back on in 5598 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5599 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5600 getTargetMachine().Options.GuaranteedTailCallOpt) 5601 ? NumBytes 5602 : 0; 5603 5604 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5605 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5606 Glue, dl); 5607 Glue = Chain.getValue(1); 5608 5609 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5610 DAG, InVals); 5611 } 5612 5613 SDValue 5614 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5615 SmallVectorImpl<SDValue> &InVals) const { 5616 SelectionDAG &DAG = CLI.DAG; 5617 SDLoc &dl = CLI.DL; 5618 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5619 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5620 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5621 SDValue Chain = CLI.Chain; 5622 SDValue Callee = CLI.Callee; 5623 bool &isTailCall = CLI.IsTailCall; 5624 CallingConv::ID CallConv = CLI.CallConv; 5625 bool isVarArg = CLI.IsVarArg; 5626 bool isPatchPoint = CLI.IsPatchPoint; 5627 const CallBase *CB = CLI.CB; 5628 5629 if (isTailCall) { 5630 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5631 isTailCall = false; 5632 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5633 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5634 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5635 else 5636 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5637 Ins, DAG); 5638 if (isTailCall) { 5639 ++NumTailCalls; 5640 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5641 ++NumSiblingCalls; 5642 5643 // PC Relative calls no longer guarantee that the callee is a Global 5644 // Address Node. The callee could be an indirect tail call in which 5645 // case the SDValue for the callee could be a load (to load the address 5646 // of a function pointer) or it may be a register copy (to move the 5647 // address of the callee from a function parameter into a virtual 5648 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5649 assert((Subtarget.isUsingPCRelativeCalls() || 5650 isa<GlobalAddressSDNode>(Callee)) && 5651 "Callee should be an llvm::Function object."); 5652 5653 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5654 << "\nTCO callee: "); 5655 LLVM_DEBUG(Callee.dump()); 5656 } 5657 } 5658 5659 if (!isTailCall && CB && CB->isMustTailCall()) 5660 report_fatal_error("failed to perform tail call elimination on a call " 5661 "site marked musttail"); 5662 5663 // When long calls (i.e. indirect calls) are always used, calls are always 5664 // made via function pointer. If we have a function name, first translate it 5665 // into a pointer. 5666 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5667 !isTailCall) 5668 Callee = LowerGlobalAddress(Callee, DAG); 5669 5670 CallFlags CFlags( 5671 CallConv, isTailCall, isVarArg, isPatchPoint, 5672 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5673 // hasNest 5674 Subtarget.is64BitELFABI() && 5675 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5676 CLI.NoMerge); 5677 5678 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5679 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5680 InVals, CB); 5681 5682 if (Subtarget.isSVR4ABI()) 5683 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5684 InVals, CB); 5685 5686 if (Subtarget.isAIXABI()) 5687 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5688 InVals, CB); 5689 5690 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5691 InVals, CB); 5692 } 5693 5694 SDValue PPCTargetLowering::LowerCall_32SVR4( 5695 SDValue Chain, SDValue Callee, CallFlags CFlags, 5696 const SmallVectorImpl<ISD::OutputArg> &Outs, 5697 const SmallVectorImpl<SDValue> &OutVals, 5698 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5699 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5700 const CallBase *CB) const { 5701 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5702 // of the 32-bit SVR4 ABI stack frame layout. 5703 5704 const CallingConv::ID CallConv = CFlags.CallConv; 5705 const bool IsVarArg = CFlags.IsVarArg; 5706 const bool IsTailCall = CFlags.IsTailCall; 5707 5708 assert((CallConv == CallingConv::C || 5709 CallConv == CallingConv::Cold || 5710 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5711 5712 const Align PtrAlign(4); 5713 5714 MachineFunction &MF = DAG.getMachineFunction(); 5715 5716 // Mark this function as potentially containing a function that contains a 5717 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5718 // and restoring the callers stack pointer in this functions epilog. This is 5719 // done because by tail calling the called function might overwrite the value 5720 // in this function's (MF) stack pointer stack slot 0(SP). 5721 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5722 CallConv == CallingConv::Fast) 5723 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5724 5725 // Count how many bytes are to be pushed on the stack, including the linkage 5726 // area, parameter list area and the part of the local variable space which 5727 // contains copies of aggregates which are passed by value. 5728 5729 // Assign locations to all of the outgoing arguments. 5730 SmallVector<CCValAssign, 16> ArgLocs; 5731 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5732 5733 // Reserve space for the linkage area on the stack. 5734 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5735 PtrAlign); 5736 if (useSoftFloat()) 5737 CCInfo.PreAnalyzeCallOperands(Outs); 5738 5739 if (IsVarArg) { 5740 // Handle fixed and variable vector arguments differently. 5741 // Fixed vector arguments go into registers as long as registers are 5742 // available. Variable vector arguments always go into memory. 5743 unsigned NumArgs = Outs.size(); 5744 5745 for (unsigned i = 0; i != NumArgs; ++i) { 5746 MVT ArgVT = Outs[i].VT; 5747 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5748 bool Result; 5749 5750 if (Outs[i].IsFixed) { 5751 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5752 CCInfo); 5753 } else { 5754 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5755 ArgFlags, CCInfo); 5756 } 5757 5758 if (Result) { 5759 #ifndef NDEBUG 5760 errs() << "Call operand #" << i << " has unhandled type " 5761 << EVT(ArgVT).getEVTString() << "\n"; 5762 #endif 5763 llvm_unreachable(nullptr); 5764 } 5765 } 5766 } else { 5767 // All arguments are treated the same. 5768 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5769 } 5770 CCInfo.clearWasPPCF128(); 5771 5772 // Assign locations to all of the outgoing aggregate by value arguments. 5773 SmallVector<CCValAssign, 16> ByValArgLocs; 5774 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5775 5776 // Reserve stack space for the allocations in CCInfo. 5777 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5778 5779 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5780 5781 // Size of the linkage area, parameter list area and the part of the local 5782 // space variable where copies of aggregates which are passed by value are 5783 // stored. 5784 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5785 5786 // Calculate by how many bytes the stack has to be adjusted in case of tail 5787 // call optimization. 5788 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5789 5790 // Adjust the stack pointer for the new arguments... 5791 // These operations are automatically eliminated by the prolog/epilog pass 5792 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5793 SDValue CallSeqStart = Chain; 5794 5795 // Load the return address and frame pointer so it can be moved somewhere else 5796 // later. 5797 SDValue LROp, FPOp; 5798 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5799 5800 // Set up a copy of the stack pointer for use loading and storing any 5801 // arguments that may not fit in the registers available for argument 5802 // passing. 5803 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5804 5805 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5806 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5807 SmallVector<SDValue, 8> MemOpChains; 5808 5809 bool seenFloatArg = false; 5810 // Walk the register/memloc assignments, inserting copies/loads. 5811 // i - Tracks the index into the list of registers allocated for the call 5812 // RealArgIdx - Tracks the index into the list of actual function arguments 5813 // j - Tracks the index into the list of byval arguments 5814 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5815 i != e; 5816 ++i, ++RealArgIdx) { 5817 CCValAssign &VA = ArgLocs[i]; 5818 SDValue Arg = OutVals[RealArgIdx]; 5819 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5820 5821 if (Flags.isByVal()) { 5822 // Argument is an aggregate which is passed by value, thus we need to 5823 // create a copy of it in the local variable space of the current stack 5824 // frame (which is the stack frame of the caller) and pass the address of 5825 // this copy to the callee. 5826 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5827 CCValAssign &ByValVA = ByValArgLocs[j++]; 5828 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5829 5830 // Memory reserved in the local variable space of the callers stack frame. 5831 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5832 5833 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5834 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5835 StackPtr, PtrOff); 5836 5837 // Create a copy of the argument in the local area of the current 5838 // stack frame. 5839 SDValue MemcpyCall = 5840 CreateCopyOfByValArgument(Arg, PtrOff, 5841 CallSeqStart.getNode()->getOperand(0), 5842 Flags, DAG, dl); 5843 5844 // This must go outside the CALLSEQ_START..END. 5845 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5846 SDLoc(MemcpyCall)); 5847 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5848 NewCallSeqStart.getNode()); 5849 Chain = CallSeqStart = NewCallSeqStart; 5850 5851 // Pass the address of the aggregate copy on the stack either in a 5852 // physical register or in the parameter list area of the current stack 5853 // frame to the callee. 5854 Arg = PtrOff; 5855 } 5856 5857 // When useCRBits() is true, there can be i1 arguments. 5858 // It is because getRegisterType(MVT::i1) => MVT::i1, 5859 // and for other integer types getRegisterType() => MVT::i32. 5860 // Extend i1 and ensure callee will get i32. 5861 if (Arg.getValueType() == MVT::i1) 5862 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5863 dl, MVT::i32, Arg); 5864 5865 if (VA.isRegLoc()) { 5866 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5867 // Put argument in a physical register. 5868 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5869 bool IsLE = Subtarget.isLittleEndian(); 5870 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5871 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5872 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5873 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5874 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5875 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5876 SVal.getValue(0))); 5877 } else 5878 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5879 } else { 5880 // Put argument in the parameter list area of the current stack frame. 5881 assert(VA.isMemLoc()); 5882 unsigned LocMemOffset = VA.getLocMemOffset(); 5883 5884 if (!IsTailCall) { 5885 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5886 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5887 StackPtr, PtrOff); 5888 5889 MemOpChains.push_back( 5890 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5891 } else { 5892 // Calculate and remember argument location. 5893 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5894 TailCallArguments); 5895 } 5896 } 5897 } 5898 5899 if (!MemOpChains.empty()) 5900 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5901 5902 // Build a sequence of copy-to-reg nodes chained together with token chain 5903 // and flag operands which copy the outgoing args into the appropriate regs. 5904 SDValue InFlag; 5905 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5906 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5907 RegsToPass[i].second, InFlag); 5908 InFlag = Chain.getValue(1); 5909 } 5910 5911 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5912 // registers. 5913 if (IsVarArg) { 5914 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5915 SDValue Ops[] = { Chain, InFlag }; 5916 5917 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5918 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5919 5920 InFlag = Chain.getValue(1); 5921 } 5922 5923 if (IsTailCall) 5924 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5925 TailCallArguments); 5926 5927 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5928 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5929 } 5930 5931 // Copy an argument into memory, being careful to do this outside the 5932 // call sequence for the call to which the argument belongs. 5933 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5934 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5935 SelectionDAG &DAG, const SDLoc &dl) const { 5936 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5937 CallSeqStart.getNode()->getOperand(0), 5938 Flags, DAG, dl); 5939 // The MEMCPY must go outside the CALLSEQ_START..END. 5940 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5941 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5942 SDLoc(MemcpyCall)); 5943 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5944 NewCallSeqStart.getNode()); 5945 return NewCallSeqStart; 5946 } 5947 5948 SDValue PPCTargetLowering::LowerCall_64SVR4( 5949 SDValue Chain, SDValue Callee, CallFlags CFlags, 5950 const SmallVectorImpl<ISD::OutputArg> &Outs, 5951 const SmallVectorImpl<SDValue> &OutVals, 5952 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5953 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5954 const CallBase *CB) const { 5955 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5956 bool isLittleEndian = Subtarget.isLittleEndian(); 5957 unsigned NumOps = Outs.size(); 5958 bool IsSibCall = false; 5959 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5960 5961 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5962 unsigned PtrByteSize = 8; 5963 5964 MachineFunction &MF = DAG.getMachineFunction(); 5965 5966 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5967 IsSibCall = true; 5968 5969 // Mark this function as potentially containing a function that contains a 5970 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5971 // and restoring the callers stack pointer in this functions epilog. This is 5972 // done because by tail calling the called function might overwrite the value 5973 // in this function's (MF) stack pointer stack slot 0(SP). 5974 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5975 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5976 5977 assert(!(IsFastCall && CFlags.IsVarArg) && 5978 "fastcc not supported on varargs functions"); 5979 5980 // Count how many bytes are to be pushed on the stack, including the linkage 5981 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5982 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5983 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5984 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5985 unsigned NumBytes = LinkageSize; 5986 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5987 5988 static const MCPhysReg GPR[] = { 5989 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5990 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5991 }; 5992 static const MCPhysReg VR[] = { 5993 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5994 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5995 }; 5996 5997 const unsigned NumGPRs = array_lengthof(GPR); 5998 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5999 const unsigned NumVRs = array_lengthof(VR); 6000 6001 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6002 // can be passed to the callee in registers. 6003 // For the fast calling convention, there is another check below. 6004 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6005 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6006 if (!HasParameterArea) { 6007 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6008 unsigned AvailableFPRs = NumFPRs; 6009 unsigned AvailableVRs = NumVRs; 6010 unsigned NumBytesTmp = NumBytes; 6011 for (unsigned i = 0; i != NumOps; ++i) { 6012 if (Outs[i].Flags.isNest()) continue; 6013 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6014 PtrByteSize, LinkageSize, ParamAreaSize, 6015 NumBytesTmp, AvailableFPRs, AvailableVRs)) 6016 HasParameterArea = true; 6017 } 6018 } 6019 6020 // When using the fast calling convention, we don't provide backing for 6021 // arguments that will be in registers. 6022 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6023 6024 // Avoid allocating parameter area for fastcc functions if all the arguments 6025 // can be passed in the registers. 6026 if (IsFastCall) 6027 HasParameterArea = false; 6028 6029 // Add up all the space actually used. 6030 for (unsigned i = 0; i != NumOps; ++i) { 6031 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6032 EVT ArgVT = Outs[i].VT; 6033 EVT OrigVT = Outs[i].ArgVT; 6034 6035 if (Flags.isNest()) 6036 continue; 6037 6038 if (IsFastCall) { 6039 if (Flags.isByVal()) { 6040 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6041 if (NumGPRsUsed > NumGPRs) 6042 HasParameterArea = true; 6043 } else { 6044 switch (ArgVT.getSimpleVT().SimpleTy) { 6045 default: llvm_unreachable("Unexpected ValueType for argument!"); 6046 case MVT::i1: 6047 case MVT::i32: 6048 case MVT::i64: 6049 if (++NumGPRsUsed <= NumGPRs) 6050 continue; 6051 break; 6052 case MVT::v4i32: 6053 case MVT::v8i16: 6054 case MVT::v16i8: 6055 case MVT::v2f64: 6056 case MVT::v2i64: 6057 case MVT::v1i128: 6058 case MVT::f128: 6059 if (++NumVRsUsed <= NumVRs) 6060 continue; 6061 break; 6062 case MVT::v4f32: 6063 if (++NumVRsUsed <= NumVRs) 6064 continue; 6065 break; 6066 case MVT::f32: 6067 case MVT::f64: 6068 if (++NumFPRsUsed <= NumFPRs) 6069 continue; 6070 break; 6071 } 6072 HasParameterArea = true; 6073 } 6074 } 6075 6076 /* Respect alignment of argument on the stack. */ 6077 auto Alignement = 6078 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6079 NumBytes = alignTo(NumBytes, Alignement); 6080 6081 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6082 if (Flags.isInConsecutiveRegsLast()) 6083 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6084 } 6085 6086 unsigned NumBytesActuallyUsed = NumBytes; 6087 6088 // In the old ELFv1 ABI, 6089 // the prolog code of the callee may store up to 8 GPR argument registers to 6090 // the stack, allowing va_start to index over them in memory if its varargs. 6091 // Because we cannot tell if this is needed on the caller side, we have to 6092 // conservatively assume that it is needed. As such, make sure we have at 6093 // least enough stack space for the caller to store the 8 GPRs. 6094 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6095 // really requires memory operands, e.g. a vararg function. 6096 if (HasParameterArea) 6097 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6098 else 6099 NumBytes = LinkageSize; 6100 6101 // Tail call needs the stack to be aligned. 6102 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6103 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6104 6105 int SPDiff = 0; 6106 6107 // Calculate by how many bytes the stack has to be adjusted in case of tail 6108 // call optimization. 6109 if (!IsSibCall) 6110 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6111 6112 // To protect arguments on the stack from being clobbered in a tail call, 6113 // force all the loads to happen before doing any other lowering. 6114 if (CFlags.IsTailCall) 6115 Chain = DAG.getStackArgumentTokenFactor(Chain); 6116 6117 // Adjust the stack pointer for the new arguments... 6118 // These operations are automatically eliminated by the prolog/epilog pass 6119 if (!IsSibCall) 6120 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6121 SDValue CallSeqStart = Chain; 6122 6123 // Load the return address and frame pointer so it can be move somewhere else 6124 // later. 6125 SDValue LROp, FPOp; 6126 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6127 6128 // Set up a copy of the stack pointer for use loading and storing any 6129 // arguments that may not fit in the registers available for argument 6130 // passing. 6131 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6132 6133 // Figure out which arguments are going to go in registers, and which in 6134 // memory. Also, if this is a vararg function, floating point operations 6135 // must be stored to our stack, and loaded into integer regs as well, if 6136 // any integer regs are available for argument passing. 6137 unsigned ArgOffset = LinkageSize; 6138 6139 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6140 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6141 6142 SmallVector<SDValue, 8> MemOpChains; 6143 for (unsigned i = 0; i != NumOps; ++i) { 6144 SDValue Arg = OutVals[i]; 6145 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6146 EVT ArgVT = Outs[i].VT; 6147 EVT OrigVT = Outs[i].ArgVT; 6148 6149 // PtrOff will be used to store the current argument to the stack if a 6150 // register cannot be found for it. 6151 SDValue PtrOff; 6152 6153 // We re-align the argument offset for each argument, except when using the 6154 // fast calling convention, when we need to make sure we do that only when 6155 // we'll actually use a stack slot. 6156 auto ComputePtrOff = [&]() { 6157 /* Respect alignment of argument on the stack. */ 6158 auto Alignment = 6159 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6160 ArgOffset = alignTo(ArgOffset, Alignment); 6161 6162 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6163 6164 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6165 }; 6166 6167 if (!IsFastCall) { 6168 ComputePtrOff(); 6169 6170 /* Compute GPR index associated with argument offset. */ 6171 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6172 GPR_idx = std::min(GPR_idx, NumGPRs); 6173 } 6174 6175 // Promote integers to 64-bit values. 6176 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6177 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6178 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6179 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6180 } 6181 6182 // FIXME memcpy is used way more than necessary. Correctness first. 6183 // Note: "by value" is code for passing a structure by value, not 6184 // basic types. 6185 if (Flags.isByVal()) { 6186 // Note: Size includes alignment padding, so 6187 // struct x { short a; char b; } 6188 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6189 // These are the proper values we need for right-justifying the 6190 // aggregate in a parameter register. 6191 unsigned Size = Flags.getByValSize(); 6192 6193 // An empty aggregate parameter takes up no storage and no 6194 // registers. 6195 if (Size == 0) 6196 continue; 6197 6198 if (IsFastCall) 6199 ComputePtrOff(); 6200 6201 // All aggregates smaller than 8 bytes must be passed right-justified. 6202 if (Size==1 || Size==2 || Size==4) { 6203 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6204 if (GPR_idx != NumGPRs) { 6205 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6206 MachinePointerInfo(), VT); 6207 MemOpChains.push_back(Load.getValue(1)); 6208 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6209 6210 ArgOffset += PtrByteSize; 6211 continue; 6212 } 6213 } 6214 6215 if (GPR_idx == NumGPRs && Size < 8) { 6216 SDValue AddPtr = PtrOff; 6217 if (!isLittleEndian) { 6218 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6219 PtrOff.getValueType()); 6220 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6221 } 6222 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6223 CallSeqStart, 6224 Flags, DAG, dl); 6225 ArgOffset += PtrByteSize; 6226 continue; 6227 } 6228 // Copy entire object into memory. There are cases where gcc-generated 6229 // code assumes it is there, even if it could be put entirely into 6230 // registers. (This is not what the doc says.) 6231 6232 // FIXME: The above statement is likely due to a misunderstanding of the 6233 // documents. All arguments must be copied into the parameter area BY 6234 // THE CALLEE in the event that the callee takes the address of any 6235 // formal argument. That has not yet been implemented. However, it is 6236 // reasonable to use the stack area as a staging area for the register 6237 // load. 6238 6239 // Skip this for small aggregates, as we will use the same slot for a 6240 // right-justified copy, below. 6241 if (Size >= 8) 6242 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6243 CallSeqStart, 6244 Flags, DAG, dl); 6245 6246 // When a register is available, pass a small aggregate right-justified. 6247 if (Size < 8 && GPR_idx != NumGPRs) { 6248 // The easiest way to get this right-justified in a register 6249 // is to copy the structure into the rightmost portion of a 6250 // local variable slot, then load the whole slot into the 6251 // register. 6252 // FIXME: The memcpy seems to produce pretty awful code for 6253 // small aggregates, particularly for packed ones. 6254 // FIXME: It would be preferable to use the slot in the 6255 // parameter save area instead of a new local variable. 6256 SDValue AddPtr = PtrOff; 6257 if (!isLittleEndian) { 6258 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6259 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6260 } 6261 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6262 CallSeqStart, 6263 Flags, DAG, dl); 6264 6265 // Load the slot into the register. 6266 SDValue Load = 6267 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6268 MemOpChains.push_back(Load.getValue(1)); 6269 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6270 6271 // Done with this argument. 6272 ArgOffset += PtrByteSize; 6273 continue; 6274 } 6275 6276 // For aggregates larger than PtrByteSize, copy the pieces of the 6277 // object that fit into registers from the parameter save area. 6278 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6279 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6280 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6281 if (GPR_idx != NumGPRs) { 6282 SDValue Load = 6283 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6284 MemOpChains.push_back(Load.getValue(1)); 6285 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6286 ArgOffset += PtrByteSize; 6287 } else { 6288 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6289 break; 6290 } 6291 } 6292 continue; 6293 } 6294 6295 switch (Arg.getSimpleValueType().SimpleTy) { 6296 default: llvm_unreachable("Unexpected ValueType for argument!"); 6297 case MVT::i1: 6298 case MVT::i32: 6299 case MVT::i64: 6300 if (Flags.isNest()) { 6301 // The 'nest' parameter, if any, is passed in R11. 6302 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6303 break; 6304 } 6305 6306 // These can be scalar arguments or elements of an integer array type 6307 // passed directly. Clang may use those instead of "byval" aggregate 6308 // types to avoid forcing arguments to memory unnecessarily. 6309 if (GPR_idx != NumGPRs) { 6310 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6311 } else { 6312 if (IsFastCall) 6313 ComputePtrOff(); 6314 6315 assert(HasParameterArea && 6316 "Parameter area must exist to pass an argument in memory."); 6317 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6318 true, CFlags.IsTailCall, false, MemOpChains, 6319 TailCallArguments, dl); 6320 if (IsFastCall) 6321 ArgOffset += PtrByteSize; 6322 } 6323 if (!IsFastCall) 6324 ArgOffset += PtrByteSize; 6325 break; 6326 case MVT::f32: 6327 case MVT::f64: { 6328 // These can be scalar arguments or elements of a float array type 6329 // passed directly. The latter are used to implement ELFv2 homogenous 6330 // float aggregates. 6331 6332 // Named arguments go into FPRs first, and once they overflow, the 6333 // remaining arguments go into GPRs and then the parameter save area. 6334 // Unnamed arguments for vararg functions always go to GPRs and 6335 // then the parameter save area. For now, put all arguments to vararg 6336 // routines always in both locations (FPR *and* GPR or stack slot). 6337 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6338 bool NeededLoad = false; 6339 6340 // First load the argument into the next available FPR. 6341 if (FPR_idx != NumFPRs) 6342 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6343 6344 // Next, load the argument into GPR or stack slot if needed. 6345 if (!NeedGPROrStack) 6346 ; 6347 else if (GPR_idx != NumGPRs && !IsFastCall) { 6348 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6349 // once we support fp <-> gpr moves. 6350 6351 // In the non-vararg case, this can only ever happen in the 6352 // presence of f32 array types, since otherwise we never run 6353 // out of FPRs before running out of GPRs. 6354 SDValue ArgVal; 6355 6356 // Double values are always passed in a single GPR. 6357 if (Arg.getValueType() != MVT::f32) { 6358 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6359 6360 // Non-array float values are extended and passed in a GPR. 6361 } else if (!Flags.isInConsecutiveRegs()) { 6362 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6363 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6364 6365 // If we have an array of floats, we collect every odd element 6366 // together with its predecessor into one GPR. 6367 } else if (ArgOffset % PtrByteSize != 0) { 6368 SDValue Lo, Hi; 6369 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6370 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6371 if (!isLittleEndian) 6372 std::swap(Lo, Hi); 6373 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6374 6375 // The final element, if even, goes into the first half of a GPR. 6376 } else if (Flags.isInConsecutiveRegsLast()) { 6377 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6378 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6379 if (!isLittleEndian) 6380 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6381 DAG.getConstant(32, dl, MVT::i32)); 6382 6383 // Non-final even elements are skipped; they will be handled 6384 // together the with subsequent argument on the next go-around. 6385 } else 6386 ArgVal = SDValue(); 6387 6388 if (ArgVal.getNode()) 6389 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6390 } else { 6391 if (IsFastCall) 6392 ComputePtrOff(); 6393 6394 // Single-precision floating-point values are mapped to the 6395 // second (rightmost) word of the stack doubleword. 6396 if (Arg.getValueType() == MVT::f32 && 6397 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6398 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6399 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6400 } 6401 6402 assert(HasParameterArea && 6403 "Parameter area must exist to pass an argument in memory."); 6404 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6405 true, CFlags.IsTailCall, false, MemOpChains, 6406 TailCallArguments, dl); 6407 6408 NeededLoad = true; 6409 } 6410 // When passing an array of floats, the array occupies consecutive 6411 // space in the argument area; only round up to the next doubleword 6412 // at the end of the array. Otherwise, each float takes 8 bytes. 6413 if (!IsFastCall || NeededLoad) { 6414 ArgOffset += (Arg.getValueType() == MVT::f32 && 6415 Flags.isInConsecutiveRegs()) ? 4 : 8; 6416 if (Flags.isInConsecutiveRegsLast()) 6417 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6418 } 6419 break; 6420 } 6421 case MVT::v4f32: 6422 case MVT::v4i32: 6423 case MVT::v8i16: 6424 case MVT::v16i8: 6425 case MVT::v2f64: 6426 case MVT::v2i64: 6427 case MVT::v1i128: 6428 case MVT::f128: 6429 // These can be scalar arguments or elements of a vector array type 6430 // passed directly. The latter are used to implement ELFv2 homogenous 6431 // vector aggregates. 6432 6433 // For a varargs call, named arguments go into VRs or on the stack as 6434 // usual; unnamed arguments always go to the stack or the corresponding 6435 // GPRs when within range. For now, we always put the value in both 6436 // locations (or even all three). 6437 if (CFlags.IsVarArg) { 6438 assert(HasParameterArea && 6439 "Parameter area must exist if we have a varargs call."); 6440 // We could elide this store in the case where the object fits 6441 // entirely in R registers. Maybe later. 6442 SDValue Store = 6443 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6444 MemOpChains.push_back(Store); 6445 if (VR_idx != NumVRs) { 6446 SDValue Load = 6447 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6448 MemOpChains.push_back(Load.getValue(1)); 6449 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6450 } 6451 ArgOffset += 16; 6452 for (unsigned i=0; i<16; i+=PtrByteSize) { 6453 if (GPR_idx == NumGPRs) 6454 break; 6455 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6456 DAG.getConstant(i, dl, PtrVT)); 6457 SDValue Load = 6458 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6459 MemOpChains.push_back(Load.getValue(1)); 6460 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6461 } 6462 break; 6463 } 6464 6465 // Non-varargs Altivec params go into VRs or on the stack. 6466 if (VR_idx != NumVRs) { 6467 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6468 } else { 6469 if (IsFastCall) 6470 ComputePtrOff(); 6471 6472 assert(HasParameterArea && 6473 "Parameter area must exist to pass an argument in memory."); 6474 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6475 true, CFlags.IsTailCall, true, MemOpChains, 6476 TailCallArguments, dl); 6477 if (IsFastCall) 6478 ArgOffset += 16; 6479 } 6480 6481 if (!IsFastCall) 6482 ArgOffset += 16; 6483 break; 6484 } 6485 } 6486 6487 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6488 "mismatch in size of parameter area"); 6489 (void)NumBytesActuallyUsed; 6490 6491 if (!MemOpChains.empty()) 6492 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6493 6494 // Check if this is an indirect call (MTCTR/BCTRL). 6495 // See prepareDescriptorIndirectCall and buildCallOperands for more 6496 // information about calls through function pointers in the 64-bit SVR4 ABI. 6497 if (CFlags.IsIndirect) { 6498 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6499 // caller in the TOC save area. 6500 if (isTOCSaveRestoreRequired(Subtarget)) { 6501 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6502 // Load r2 into a virtual register and store it to the TOC save area. 6503 setUsesTOCBasePtr(DAG); 6504 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6505 // TOC save area offset. 6506 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6507 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6508 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6509 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6510 MachinePointerInfo::getStack( 6511 DAG.getMachineFunction(), TOCSaveOffset)); 6512 } 6513 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6514 // This does not mean the MTCTR instruction must use R12; it's easier 6515 // to model this as an extra parameter, so do that. 6516 if (isELFv2ABI && !CFlags.IsPatchPoint) 6517 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6518 } 6519 6520 // Build a sequence of copy-to-reg nodes chained together with token chain 6521 // and flag operands which copy the outgoing args into the appropriate regs. 6522 SDValue InFlag; 6523 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6524 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6525 RegsToPass[i].second, InFlag); 6526 InFlag = Chain.getValue(1); 6527 } 6528 6529 if (CFlags.IsTailCall && !IsSibCall) 6530 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6531 TailCallArguments); 6532 6533 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6534 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6535 } 6536 6537 SDValue PPCTargetLowering::LowerCall_Darwin( 6538 SDValue Chain, SDValue Callee, CallFlags CFlags, 6539 const SmallVectorImpl<ISD::OutputArg> &Outs, 6540 const SmallVectorImpl<SDValue> &OutVals, 6541 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6542 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6543 const CallBase *CB) const { 6544 unsigned NumOps = Outs.size(); 6545 6546 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6547 bool isPPC64 = PtrVT == MVT::i64; 6548 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6549 6550 MachineFunction &MF = DAG.getMachineFunction(); 6551 6552 // Mark this function as potentially containing a function that contains a 6553 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6554 // and restoring the callers stack pointer in this functions epilog. This is 6555 // done because by tail calling the called function might overwrite the value 6556 // in this function's (MF) stack pointer stack slot 0(SP). 6557 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6558 CFlags.CallConv == CallingConv::Fast) 6559 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6560 6561 // Count how many bytes are to be pushed on the stack, including the linkage 6562 // area, and parameter passing area. We start with 24/48 bytes, which is 6563 // prereserved space for [SP][CR][LR][3 x unused]. 6564 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6565 unsigned NumBytes = LinkageSize; 6566 6567 // Add up all the space actually used. 6568 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6569 // they all go in registers, but we must reserve stack space for them for 6570 // possible use by the caller. In varargs or 64-bit calls, parameters are 6571 // assigned stack space in order, with padding so Altivec parameters are 6572 // 16-byte aligned. 6573 unsigned nAltivecParamsAtEnd = 0; 6574 for (unsigned i = 0; i != NumOps; ++i) { 6575 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6576 EVT ArgVT = Outs[i].VT; 6577 // Varargs Altivec parameters are padded to a 16 byte boundary. 6578 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6579 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6580 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6581 if (!CFlags.IsVarArg && !isPPC64) { 6582 // Non-varargs Altivec parameters go after all the non-Altivec 6583 // parameters; handle those later so we know how much padding we need. 6584 nAltivecParamsAtEnd++; 6585 continue; 6586 } 6587 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6588 NumBytes = ((NumBytes+15)/16)*16; 6589 } 6590 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6591 } 6592 6593 // Allow for Altivec parameters at the end, if needed. 6594 if (nAltivecParamsAtEnd) { 6595 NumBytes = ((NumBytes+15)/16)*16; 6596 NumBytes += 16*nAltivecParamsAtEnd; 6597 } 6598 6599 // The prolog code of the callee may store up to 8 GPR argument registers to 6600 // the stack, allowing va_start to index over them in memory if its varargs. 6601 // Because we cannot tell if this is needed on the caller side, we have to 6602 // conservatively assume that it is needed. As such, make sure we have at 6603 // least enough stack space for the caller to store the 8 GPRs. 6604 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6605 6606 // Tail call needs the stack to be aligned. 6607 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6608 CFlags.CallConv == CallingConv::Fast) 6609 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6610 6611 // Calculate by how many bytes the stack has to be adjusted in case of tail 6612 // call optimization. 6613 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6614 6615 // To protect arguments on the stack from being clobbered in a tail call, 6616 // force all the loads to happen before doing any other lowering. 6617 if (CFlags.IsTailCall) 6618 Chain = DAG.getStackArgumentTokenFactor(Chain); 6619 6620 // Adjust the stack pointer for the new arguments... 6621 // These operations are automatically eliminated by the prolog/epilog pass 6622 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6623 SDValue CallSeqStart = Chain; 6624 6625 // Load the return address and frame pointer so it can be move somewhere else 6626 // later. 6627 SDValue LROp, FPOp; 6628 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6629 6630 // Set up a copy of the stack pointer for use loading and storing any 6631 // arguments that may not fit in the registers available for argument 6632 // passing. 6633 SDValue StackPtr; 6634 if (isPPC64) 6635 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6636 else 6637 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6638 6639 // Figure out which arguments are going to go in registers, and which in 6640 // memory. Also, if this is a vararg function, floating point operations 6641 // must be stored to our stack, and loaded into integer regs as well, if 6642 // any integer regs are available for argument passing. 6643 unsigned ArgOffset = LinkageSize; 6644 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6645 6646 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6647 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6648 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6649 }; 6650 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6651 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6652 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6653 }; 6654 static const MCPhysReg VR[] = { 6655 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6656 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6657 }; 6658 const unsigned NumGPRs = array_lengthof(GPR_32); 6659 const unsigned NumFPRs = 13; 6660 const unsigned NumVRs = array_lengthof(VR); 6661 6662 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6663 6664 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6665 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6666 6667 SmallVector<SDValue, 8> MemOpChains; 6668 for (unsigned i = 0; i != NumOps; ++i) { 6669 SDValue Arg = OutVals[i]; 6670 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6671 6672 // PtrOff will be used to store the current argument to the stack if a 6673 // register cannot be found for it. 6674 SDValue PtrOff; 6675 6676 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6677 6678 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6679 6680 // On PPC64, promote integers to 64-bit values. 6681 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6682 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6683 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6684 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6685 } 6686 6687 // FIXME memcpy is used way more than necessary. Correctness first. 6688 // Note: "by value" is code for passing a structure by value, not 6689 // basic types. 6690 if (Flags.isByVal()) { 6691 unsigned Size = Flags.getByValSize(); 6692 // Very small objects are passed right-justified. Everything else is 6693 // passed left-justified. 6694 if (Size==1 || Size==2) { 6695 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6696 if (GPR_idx != NumGPRs) { 6697 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6698 MachinePointerInfo(), VT); 6699 MemOpChains.push_back(Load.getValue(1)); 6700 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6701 6702 ArgOffset += PtrByteSize; 6703 } else { 6704 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6705 PtrOff.getValueType()); 6706 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6707 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6708 CallSeqStart, 6709 Flags, DAG, dl); 6710 ArgOffset += PtrByteSize; 6711 } 6712 continue; 6713 } 6714 // Copy entire object into memory. There are cases where gcc-generated 6715 // code assumes it is there, even if it could be put entirely into 6716 // registers. (This is not what the doc says.) 6717 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6718 CallSeqStart, 6719 Flags, DAG, dl); 6720 6721 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6722 // copy the pieces of the object that fit into registers from the 6723 // parameter save area. 6724 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6725 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6726 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6727 if (GPR_idx != NumGPRs) { 6728 SDValue Load = 6729 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6730 MemOpChains.push_back(Load.getValue(1)); 6731 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6732 ArgOffset += PtrByteSize; 6733 } else { 6734 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6735 break; 6736 } 6737 } 6738 continue; 6739 } 6740 6741 switch (Arg.getSimpleValueType().SimpleTy) { 6742 default: llvm_unreachable("Unexpected ValueType for argument!"); 6743 case MVT::i1: 6744 case MVT::i32: 6745 case MVT::i64: 6746 if (GPR_idx != NumGPRs) { 6747 if (Arg.getValueType() == MVT::i1) 6748 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6749 6750 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6751 } else { 6752 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6753 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6754 TailCallArguments, dl); 6755 } 6756 ArgOffset += PtrByteSize; 6757 break; 6758 case MVT::f32: 6759 case MVT::f64: 6760 if (FPR_idx != NumFPRs) { 6761 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6762 6763 if (CFlags.IsVarArg) { 6764 SDValue Store = 6765 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6766 MemOpChains.push_back(Store); 6767 6768 // Float varargs are always shadowed in available integer registers 6769 if (GPR_idx != NumGPRs) { 6770 SDValue Load = 6771 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6772 MemOpChains.push_back(Load.getValue(1)); 6773 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6774 } 6775 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6776 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6777 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6778 SDValue Load = 6779 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6780 MemOpChains.push_back(Load.getValue(1)); 6781 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6782 } 6783 } else { 6784 // If we have any FPRs remaining, we may also have GPRs remaining. 6785 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6786 // GPRs. 6787 if (GPR_idx != NumGPRs) 6788 ++GPR_idx; 6789 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6790 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6791 ++GPR_idx; 6792 } 6793 } else 6794 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6795 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6796 TailCallArguments, dl); 6797 if (isPPC64) 6798 ArgOffset += 8; 6799 else 6800 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6801 break; 6802 case MVT::v4f32: 6803 case MVT::v4i32: 6804 case MVT::v8i16: 6805 case MVT::v16i8: 6806 if (CFlags.IsVarArg) { 6807 // These go aligned on the stack, or in the corresponding R registers 6808 // when within range. The Darwin PPC ABI doc claims they also go in 6809 // V registers; in fact gcc does this only for arguments that are 6810 // prototyped, not for those that match the ... We do it for all 6811 // arguments, seems to work. 6812 while (ArgOffset % 16 !=0) { 6813 ArgOffset += PtrByteSize; 6814 if (GPR_idx != NumGPRs) 6815 GPR_idx++; 6816 } 6817 // We could elide this store in the case where the object fits 6818 // entirely in R registers. Maybe later. 6819 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6820 DAG.getConstant(ArgOffset, dl, PtrVT)); 6821 SDValue Store = 6822 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6823 MemOpChains.push_back(Store); 6824 if (VR_idx != NumVRs) { 6825 SDValue Load = 6826 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6827 MemOpChains.push_back(Load.getValue(1)); 6828 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6829 } 6830 ArgOffset += 16; 6831 for (unsigned i=0; i<16; i+=PtrByteSize) { 6832 if (GPR_idx == NumGPRs) 6833 break; 6834 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6835 DAG.getConstant(i, dl, PtrVT)); 6836 SDValue Load = 6837 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6838 MemOpChains.push_back(Load.getValue(1)); 6839 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6840 } 6841 break; 6842 } 6843 6844 // Non-varargs Altivec params generally go in registers, but have 6845 // stack space allocated at the end. 6846 if (VR_idx != NumVRs) { 6847 // Doesn't have GPR space allocated. 6848 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6849 } else if (nAltivecParamsAtEnd==0) { 6850 // We are emitting Altivec params in order. 6851 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6852 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6853 TailCallArguments, dl); 6854 ArgOffset += 16; 6855 } 6856 break; 6857 } 6858 } 6859 // If all Altivec parameters fit in registers, as they usually do, 6860 // they get stack space following the non-Altivec parameters. We 6861 // don't track this here because nobody below needs it. 6862 // If there are more Altivec parameters than fit in registers emit 6863 // the stores here. 6864 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6865 unsigned j = 0; 6866 // Offset is aligned; skip 1st 12 params which go in V registers. 6867 ArgOffset = ((ArgOffset+15)/16)*16; 6868 ArgOffset += 12*16; 6869 for (unsigned i = 0; i != NumOps; ++i) { 6870 SDValue Arg = OutVals[i]; 6871 EVT ArgType = Outs[i].VT; 6872 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6873 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6874 if (++j > NumVRs) { 6875 SDValue PtrOff; 6876 // We are emitting Altivec params in order. 6877 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6878 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6879 TailCallArguments, dl); 6880 ArgOffset += 16; 6881 } 6882 } 6883 } 6884 } 6885 6886 if (!MemOpChains.empty()) 6887 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6888 6889 // On Darwin, R12 must contain the address of an indirect callee. This does 6890 // not mean the MTCTR instruction must use R12; it's easier to model this as 6891 // an extra parameter, so do that. 6892 if (CFlags.IsIndirect) { 6893 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6894 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6895 PPC::R12), Callee)); 6896 } 6897 6898 // Build a sequence of copy-to-reg nodes chained together with token chain 6899 // and flag operands which copy the outgoing args into the appropriate regs. 6900 SDValue InFlag; 6901 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6902 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6903 RegsToPass[i].second, InFlag); 6904 InFlag = Chain.getValue(1); 6905 } 6906 6907 if (CFlags.IsTailCall) 6908 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6909 TailCallArguments); 6910 6911 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6912 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6913 } 6914 6915 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6916 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6917 CCState &State) { 6918 6919 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6920 State.getMachineFunction().getSubtarget()); 6921 const bool IsPPC64 = Subtarget.isPPC64(); 6922 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6923 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6924 6925 assert((!ValVT.isInteger() || 6926 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6927 "Integer argument exceeds register size: should have been legalized"); 6928 6929 if (ValVT == MVT::f128) 6930 report_fatal_error("f128 is unimplemented on AIX."); 6931 6932 if (ArgFlags.isNest()) 6933 report_fatal_error("Nest arguments are unimplemented."); 6934 6935 if (ValVT.isVector() || LocVT.isVector()) 6936 report_fatal_error("Vector arguments are unimplemented on AIX."); 6937 6938 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6939 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6940 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6941 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6942 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6943 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6944 6945 if (ArgFlags.isByVal()) { 6946 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6947 report_fatal_error("Pass-by-value arguments with alignment greater than " 6948 "register width are not supported."); 6949 6950 const unsigned ByValSize = ArgFlags.getByValSize(); 6951 6952 // An empty aggregate parameter takes up no storage and no registers, 6953 // but needs a MemLoc for a stack slot for the formal arguments side. 6954 if (ByValSize == 0) { 6955 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6956 State.getNextStackOffset(), RegVT, 6957 LocInfo)); 6958 return false; 6959 } 6960 6961 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6962 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6963 for (const unsigned E = Offset + StackSize; Offset < E; 6964 Offset += PtrAlign.value()) { 6965 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6966 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6967 else { 6968 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6969 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6970 LocInfo)); 6971 break; 6972 } 6973 } 6974 return false; 6975 } 6976 6977 // Arguments always reserve parameter save area. 6978 switch (ValVT.SimpleTy) { 6979 default: 6980 report_fatal_error("Unhandled value type for argument."); 6981 case MVT::i64: 6982 // i64 arguments should have been split to i32 for PPC32. 6983 assert(IsPPC64 && "PPC32 should have split i64 values."); 6984 LLVM_FALLTHROUGH; 6985 case MVT::i1: 6986 case MVT::i32: { 6987 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6988 // AIX integer arguments are always passed in register width. 6989 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6990 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6991 : CCValAssign::LocInfo::ZExt; 6992 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6993 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6994 else 6995 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6996 6997 return false; 6998 } 6999 case MVT::f32: 7000 case MVT::f64: { 7001 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7002 const unsigned StoreSize = LocVT.getStoreSize(); 7003 // Floats are always 4-byte aligned in the PSA on AIX. 7004 // This includes f64 in 64-bit mode for ABI compatibility. 7005 const unsigned Offset = 7006 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 7007 unsigned FReg = State.AllocateReg(FPR); 7008 if (FReg) 7009 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7010 7011 // Reserve and initialize GPRs or initialize the PSA as required. 7012 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 7013 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7014 assert(FReg && "An FPR should be available when a GPR is reserved."); 7015 if (State.isVarArg()) { 7016 // Successfully reserved GPRs are only initialized for vararg calls. 7017 // Custom handling is required for: 7018 // f64 in PPC32 needs to be split into 2 GPRs. 7019 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7020 State.addLoc( 7021 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7022 } 7023 } else { 7024 // If there are insufficient GPRs, the PSA needs to be initialized. 7025 // Initialization occurs even if an FPR was initialized for 7026 // compatibility with the AIX XL compiler. The full memory for the 7027 // argument will be initialized even if a prior word is saved in GPR. 7028 // A custom memLoc is used when the argument also passes in FPR so 7029 // that the callee handling can skip over it easily. 7030 State.addLoc( 7031 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7032 LocInfo) 7033 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7034 break; 7035 } 7036 } 7037 7038 return false; 7039 } 7040 } 7041 return true; 7042 } 7043 7044 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7045 bool IsPPC64) { 7046 assert((IsPPC64 || SVT != MVT::i64) && 7047 "i64 should have been split for 32-bit codegen."); 7048 7049 switch (SVT) { 7050 default: 7051 report_fatal_error("Unexpected value type for formal argument"); 7052 case MVT::i1: 7053 case MVT::i32: 7054 case MVT::i64: 7055 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7056 case MVT::f32: 7057 return &PPC::F4RCRegClass; 7058 case MVT::f64: 7059 return &PPC::F8RCRegClass; 7060 } 7061 } 7062 7063 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7064 SelectionDAG &DAG, SDValue ArgValue, 7065 MVT LocVT, const SDLoc &dl) { 7066 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7067 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7068 7069 if (Flags.isSExt()) 7070 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7071 DAG.getValueType(ValVT)); 7072 else if (Flags.isZExt()) 7073 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7074 DAG.getValueType(ValVT)); 7075 7076 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7077 } 7078 7079 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7080 const unsigned LASize = FL->getLinkageSize(); 7081 7082 if (PPC::GPRCRegClass.contains(Reg)) { 7083 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7084 "Reg must be a valid argument register!"); 7085 return LASize + 4 * (Reg - PPC::R3); 7086 } 7087 7088 if (PPC::G8RCRegClass.contains(Reg)) { 7089 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7090 "Reg must be a valid argument register!"); 7091 return LASize + 8 * (Reg - PPC::X3); 7092 } 7093 7094 llvm_unreachable("Only general purpose registers expected."); 7095 } 7096 7097 // AIX ABI Stack Frame Layout: 7098 // 7099 // Low Memory +--------------------------------------------+ 7100 // SP +---> | Back chain | ---+ 7101 // | +--------------------------------------------+ | 7102 // | | Saved Condition Register | | 7103 // | +--------------------------------------------+ | 7104 // | | Saved Linkage Register | | 7105 // | +--------------------------------------------+ | Linkage Area 7106 // | | Reserved for compilers | | 7107 // | +--------------------------------------------+ | 7108 // | | Reserved for binders | | 7109 // | +--------------------------------------------+ | 7110 // | | Saved TOC pointer | ---+ 7111 // | +--------------------------------------------+ 7112 // | | Parameter save area | 7113 // | +--------------------------------------------+ 7114 // | | Alloca space | 7115 // | +--------------------------------------------+ 7116 // | | Local variable space | 7117 // | +--------------------------------------------+ 7118 // | | Float/int conversion temporary | 7119 // | +--------------------------------------------+ 7120 // | | Save area for AltiVec registers | 7121 // | +--------------------------------------------+ 7122 // | | AltiVec alignment padding | 7123 // | +--------------------------------------------+ 7124 // | | Save area for VRSAVE register | 7125 // | +--------------------------------------------+ 7126 // | | Save area for General Purpose registers | 7127 // | +--------------------------------------------+ 7128 // | | Save area for Floating Point registers | 7129 // | +--------------------------------------------+ 7130 // +---- | Back chain | 7131 // High Memory +--------------------------------------------+ 7132 // 7133 // Specifications: 7134 // AIX 7.2 Assembler Language Reference 7135 // Subroutine linkage convention 7136 7137 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7138 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7139 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7140 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7141 7142 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7143 CallConv == CallingConv::Fast) && 7144 "Unexpected calling convention!"); 7145 7146 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7147 report_fatal_error("Tail call support is unimplemented on AIX."); 7148 7149 if (useSoftFloat()) 7150 report_fatal_error("Soft float support is unimplemented on AIX."); 7151 7152 const PPCSubtarget &Subtarget = 7153 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7154 7155 const bool IsPPC64 = Subtarget.isPPC64(); 7156 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7157 7158 // Assign locations to all of the incoming arguments. 7159 SmallVector<CCValAssign, 16> ArgLocs; 7160 MachineFunction &MF = DAG.getMachineFunction(); 7161 MachineFrameInfo &MFI = MF.getFrameInfo(); 7162 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7163 7164 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7165 // Reserve space for the linkage area on the stack. 7166 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7167 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7168 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7169 7170 SmallVector<SDValue, 8> MemOps; 7171 7172 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7173 CCValAssign &VA = ArgLocs[I++]; 7174 MVT LocVT = VA.getLocVT(); 7175 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7176 7177 // For compatibility with the AIX XL compiler, the float args in the 7178 // parameter save area are initialized even if the argument is available 7179 // in register. The caller is required to initialize both the register 7180 // and memory, however, the callee can choose to expect it in either. 7181 // The memloc is dismissed here because the argument is retrieved from 7182 // the register. 7183 if (VA.isMemLoc() && VA.needsCustom()) 7184 continue; 7185 7186 if (Flags.isByVal() && VA.isMemLoc()) { 7187 const unsigned Size = 7188 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7189 PtrByteSize); 7190 const int FI = MF.getFrameInfo().CreateFixedObject( 7191 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7192 /* IsAliased */ true); 7193 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7194 InVals.push_back(FIN); 7195 7196 continue; 7197 } 7198 7199 if (Flags.isByVal()) { 7200 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7201 7202 const MCPhysReg ArgReg = VA.getLocReg(); 7203 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7204 7205 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7206 report_fatal_error("Over aligned byvals not supported yet."); 7207 7208 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7209 const int FI = MF.getFrameInfo().CreateFixedObject( 7210 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7211 /* IsAliased */ true); 7212 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7213 InVals.push_back(FIN); 7214 7215 // Add live ins for all the RegLocs for the same ByVal. 7216 const TargetRegisterClass *RegClass = 7217 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7218 7219 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7220 unsigned Offset) { 7221 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7222 // Since the callers side has left justified the aggregate in the 7223 // register, we can simply store the entire register into the stack 7224 // slot. 7225 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7226 // The store to the fixedstack object is needed becuase accessing a 7227 // field of the ByVal will use a gep and load. Ideally we will optimize 7228 // to extracting the value from the register directly, and elide the 7229 // stores when the arguments address is not taken, but that will need to 7230 // be future work. 7231 SDValue Store = DAG.getStore( 7232 CopyFrom.getValue(1), dl, CopyFrom, 7233 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7234 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7235 7236 MemOps.push_back(Store); 7237 }; 7238 7239 unsigned Offset = 0; 7240 HandleRegLoc(VA.getLocReg(), Offset); 7241 Offset += PtrByteSize; 7242 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7243 Offset += PtrByteSize) { 7244 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7245 "RegLocs should be for ByVal argument."); 7246 7247 const CCValAssign RL = ArgLocs[I++]; 7248 HandleRegLoc(RL.getLocReg(), Offset); 7249 } 7250 7251 if (Offset != StackSize) { 7252 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7253 "Expected MemLoc for remaining bytes."); 7254 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7255 // Consume the MemLoc.The InVal has already been emitted, so nothing 7256 // more needs to be done. 7257 ++I; 7258 } 7259 7260 continue; 7261 } 7262 7263 EVT ValVT = VA.getValVT(); 7264 if (VA.isRegLoc() && !VA.needsCustom()) { 7265 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7266 unsigned VReg = 7267 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7268 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7269 if (ValVT.isScalarInteger() && 7270 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7271 ArgValue = 7272 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7273 } 7274 InVals.push_back(ArgValue); 7275 continue; 7276 } 7277 if (VA.isMemLoc()) { 7278 const unsigned LocSize = LocVT.getStoreSize(); 7279 const unsigned ValSize = ValVT.getStoreSize(); 7280 assert((ValSize <= LocSize) && 7281 "Object size is larger than size of MemLoc"); 7282 int CurArgOffset = VA.getLocMemOffset(); 7283 // Objects are right-justified because AIX is big-endian. 7284 if (LocSize > ValSize) 7285 CurArgOffset += LocSize - ValSize; 7286 // Potential tail calls could cause overwriting of argument stack slots. 7287 const bool IsImmutable = 7288 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7289 (CallConv == CallingConv::Fast)); 7290 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7291 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7292 SDValue ArgValue = 7293 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7294 InVals.push_back(ArgValue); 7295 continue; 7296 } 7297 } 7298 7299 // On AIX a minimum of 8 words is saved to the parameter save area. 7300 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7301 // Area that is at least reserved in the caller of this function. 7302 unsigned CallerReservedArea = 7303 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7304 7305 // Set the size that is at least reserved in caller of this function. Tail 7306 // call optimized function's reserved stack space needs to be aligned so 7307 // that taking the difference between two stack areas will result in an 7308 // aligned stack. 7309 CallerReservedArea = 7310 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7311 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7312 FuncInfo->setMinReservedArea(CallerReservedArea); 7313 7314 if (isVarArg) { 7315 FuncInfo->setVarArgsFrameIndex( 7316 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7317 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7318 7319 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7320 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7321 7322 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7323 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7324 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7325 7326 // The fixed integer arguments of a variadic function are stored to the 7327 // VarArgsFrameIndex on the stack so that they may be loaded by 7328 // dereferencing the result of va_next. 7329 for (unsigned GPRIndex = 7330 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7331 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7332 7333 const unsigned VReg = 7334 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7335 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7336 7337 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7338 SDValue Store = 7339 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7340 MemOps.push_back(Store); 7341 // Increment the address for the next argument to store. 7342 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7343 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7344 } 7345 } 7346 7347 if (!MemOps.empty()) 7348 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7349 7350 return Chain; 7351 } 7352 7353 SDValue PPCTargetLowering::LowerCall_AIX( 7354 SDValue Chain, SDValue Callee, CallFlags CFlags, 7355 const SmallVectorImpl<ISD::OutputArg> &Outs, 7356 const SmallVectorImpl<SDValue> &OutVals, 7357 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7358 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7359 const CallBase *CB) const { 7360 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7361 // AIX ABI stack frame layout. 7362 7363 assert((CFlags.CallConv == CallingConv::C || 7364 CFlags.CallConv == CallingConv::Cold || 7365 CFlags.CallConv == CallingConv::Fast) && 7366 "Unexpected calling convention!"); 7367 7368 if (CFlags.IsPatchPoint) 7369 report_fatal_error("This call type is unimplemented on AIX."); 7370 7371 const PPCSubtarget& Subtarget = 7372 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7373 if (Subtarget.hasAltivec()) 7374 report_fatal_error("Altivec support is unimplemented on AIX."); 7375 7376 MachineFunction &MF = DAG.getMachineFunction(); 7377 SmallVector<CCValAssign, 16> ArgLocs; 7378 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7379 *DAG.getContext()); 7380 7381 // Reserve space for the linkage save area (LSA) on the stack. 7382 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7383 // [SP][CR][LR][2 x reserved][TOC]. 7384 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7385 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7386 const bool IsPPC64 = Subtarget.isPPC64(); 7387 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7388 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7389 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7390 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7391 7392 // The prolog code of the callee may store up to 8 GPR argument registers to 7393 // the stack, allowing va_start to index over them in memory if the callee 7394 // is variadic. 7395 // Because we cannot tell if this is needed on the caller side, we have to 7396 // conservatively assume that it is needed. As such, make sure we have at 7397 // least enough stack space for the caller to store the 8 GPRs. 7398 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7399 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7400 CCInfo.getNextStackOffset()); 7401 7402 // Adjust the stack pointer for the new arguments... 7403 // These operations are automatically eliminated by the prolog/epilog pass. 7404 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7405 SDValue CallSeqStart = Chain; 7406 7407 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7408 SmallVector<SDValue, 8> MemOpChains; 7409 7410 // Set up a copy of the stack pointer for loading and storing any 7411 // arguments that may not fit in the registers available for argument 7412 // passing. 7413 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7414 : DAG.getRegister(PPC::R1, MVT::i32); 7415 7416 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7417 const unsigned ValNo = ArgLocs[I].getValNo(); 7418 SDValue Arg = OutVals[ValNo]; 7419 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7420 7421 if (Flags.isByVal()) { 7422 const unsigned ByValSize = Flags.getByValSize(); 7423 7424 // Nothing to do for zero-sized ByVals on the caller side. 7425 if (!ByValSize) { 7426 ++I; 7427 continue; 7428 } 7429 7430 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7431 return DAG.getExtLoad( 7432 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7433 (LoadOffset != 0) 7434 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7435 : Arg, 7436 MachinePointerInfo(), VT); 7437 }; 7438 7439 unsigned LoadOffset = 0; 7440 7441 // Initialize registers, which are fully occupied by the by-val argument. 7442 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7443 SDValue Load = GetLoad(PtrVT, LoadOffset); 7444 MemOpChains.push_back(Load.getValue(1)); 7445 LoadOffset += PtrByteSize; 7446 const CCValAssign &ByValVA = ArgLocs[I++]; 7447 assert(ByValVA.getValNo() == ValNo && 7448 "Unexpected location for pass-by-value argument."); 7449 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7450 } 7451 7452 if (LoadOffset == ByValSize) 7453 continue; 7454 7455 // There must be one more loc to handle the remainder. 7456 assert(ArgLocs[I].getValNo() == ValNo && 7457 "Expected additional location for by-value argument."); 7458 7459 if (ArgLocs[I].isMemLoc()) { 7460 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7461 const CCValAssign &ByValVA = ArgLocs[I++]; 7462 ISD::ArgFlagsTy MemcpyFlags = Flags; 7463 // Only memcpy the bytes that don't pass in register. 7464 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7465 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7466 (LoadOffset != 0) 7467 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7468 : Arg, 7469 DAG.getObjectPtrOffset(dl, StackPtr, 7470 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7471 CallSeqStart, MemcpyFlags, DAG, dl); 7472 continue; 7473 } 7474 7475 // Initialize the final register residue. 7476 // Any residue that occupies the final by-val arg register must be 7477 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7478 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7479 // 2 and 1 byte loads. 7480 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7481 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7482 "Unexpected register residue for by-value argument."); 7483 SDValue ResidueVal; 7484 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7485 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7486 const MVT VT = 7487 N == 1 ? MVT::i8 7488 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7489 SDValue Load = GetLoad(VT, LoadOffset); 7490 MemOpChains.push_back(Load.getValue(1)); 7491 LoadOffset += N; 7492 Bytes += N; 7493 7494 // By-val arguments are passed left-justfied in register. 7495 // Every load here needs to be shifted, otherwise a full register load 7496 // should have been used. 7497 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7498 "Unexpected load emitted during handling of pass-by-value " 7499 "argument."); 7500 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7501 EVT ShiftAmountTy = 7502 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7503 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7504 SDValue ShiftedLoad = 7505 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7506 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7507 ShiftedLoad) 7508 : ShiftedLoad; 7509 } 7510 7511 const CCValAssign &ByValVA = ArgLocs[I++]; 7512 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7513 continue; 7514 } 7515 7516 CCValAssign &VA = ArgLocs[I++]; 7517 const MVT LocVT = VA.getLocVT(); 7518 const MVT ValVT = VA.getValVT(); 7519 7520 switch (VA.getLocInfo()) { 7521 default: 7522 report_fatal_error("Unexpected argument extension type."); 7523 case CCValAssign::Full: 7524 break; 7525 case CCValAssign::ZExt: 7526 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7527 break; 7528 case CCValAssign::SExt: 7529 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7530 break; 7531 } 7532 7533 if (VA.isRegLoc() && !VA.needsCustom()) { 7534 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7535 continue; 7536 } 7537 7538 if (VA.isMemLoc()) { 7539 SDValue PtrOff = 7540 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7541 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7542 MemOpChains.push_back( 7543 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7544 7545 continue; 7546 } 7547 7548 // Custom handling is used for GPR initializations for vararg float 7549 // arguments. 7550 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7551 ValVT.isFloatingPoint() && LocVT.isInteger() && 7552 "Unexpected register handling for calling convention."); 7553 7554 SDValue ArgAsInt = 7555 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7556 7557 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7558 // f32 in 32-bit GPR 7559 // f64 in 64-bit GPR 7560 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7561 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7562 // f32 in 64-bit GPR. 7563 RegsToPass.push_back(std::make_pair( 7564 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7565 else { 7566 // f64 in two 32-bit GPRs 7567 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7568 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7569 "Unexpected custom register for argument!"); 7570 CCValAssign &GPR1 = VA; 7571 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7572 DAG.getConstant(32, dl, MVT::i8)); 7573 RegsToPass.push_back(std::make_pair( 7574 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7575 7576 if (I != E) { 7577 // If only 1 GPR was available, there will only be one custom GPR and 7578 // the argument will also pass in memory. 7579 CCValAssign &PeekArg = ArgLocs[I]; 7580 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7581 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7582 CCValAssign &GPR2 = ArgLocs[I++]; 7583 RegsToPass.push_back(std::make_pair( 7584 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7585 } 7586 } 7587 } 7588 } 7589 7590 if (!MemOpChains.empty()) 7591 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7592 7593 // For indirect calls, we need to save the TOC base to the stack for 7594 // restoration after the call. 7595 if (CFlags.IsIndirect) { 7596 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7597 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7598 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7599 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7600 const unsigned TOCSaveOffset = 7601 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7602 7603 setUsesTOCBasePtr(DAG); 7604 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7605 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7606 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7607 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7608 Chain = DAG.getStore( 7609 Val.getValue(1), dl, Val, AddPtr, 7610 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7611 } 7612 7613 // Build a sequence of copy-to-reg nodes chained together with token chain 7614 // and flag operands which copy the outgoing args into the appropriate regs. 7615 SDValue InFlag; 7616 for (auto Reg : RegsToPass) { 7617 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7618 InFlag = Chain.getValue(1); 7619 } 7620 7621 const int SPDiff = 0; 7622 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7623 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7624 } 7625 7626 bool 7627 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7628 MachineFunction &MF, bool isVarArg, 7629 const SmallVectorImpl<ISD::OutputArg> &Outs, 7630 LLVMContext &Context) const { 7631 SmallVector<CCValAssign, 16> RVLocs; 7632 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7633 return CCInfo.CheckReturn( 7634 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7635 ? RetCC_PPC_Cold 7636 : RetCC_PPC); 7637 } 7638 7639 SDValue 7640 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7641 bool isVarArg, 7642 const SmallVectorImpl<ISD::OutputArg> &Outs, 7643 const SmallVectorImpl<SDValue> &OutVals, 7644 const SDLoc &dl, SelectionDAG &DAG) const { 7645 SmallVector<CCValAssign, 16> RVLocs; 7646 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7647 *DAG.getContext()); 7648 CCInfo.AnalyzeReturn(Outs, 7649 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7650 ? RetCC_PPC_Cold 7651 : RetCC_PPC); 7652 7653 SDValue Flag; 7654 SmallVector<SDValue, 4> RetOps(1, Chain); 7655 7656 // Copy the result values into the output registers. 7657 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7658 CCValAssign &VA = RVLocs[i]; 7659 assert(VA.isRegLoc() && "Can only return in registers!"); 7660 7661 SDValue Arg = OutVals[RealResIdx]; 7662 7663 switch (VA.getLocInfo()) { 7664 default: llvm_unreachable("Unknown loc info!"); 7665 case CCValAssign::Full: break; 7666 case CCValAssign::AExt: 7667 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7668 break; 7669 case CCValAssign::ZExt: 7670 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7671 break; 7672 case CCValAssign::SExt: 7673 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7674 break; 7675 } 7676 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7677 bool isLittleEndian = Subtarget.isLittleEndian(); 7678 // Legalize ret f64 -> ret 2 x i32. 7679 SDValue SVal = 7680 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7681 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7682 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7683 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7684 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7685 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7686 Flag = Chain.getValue(1); 7687 VA = RVLocs[++i]; // skip ahead to next loc 7688 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7689 } else 7690 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7691 Flag = Chain.getValue(1); 7692 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7693 } 7694 7695 RetOps[0] = Chain; // Update chain. 7696 7697 // Add the flag if we have it. 7698 if (Flag.getNode()) 7699 RetOps.push_back(Flag); 7700 7701 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7702 } 7703 7704 SDValue 7705 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7706 SelectionDAG &DAG) const { 7707 SDLoc dl(Op); 7708 7709 // Get the correct type for integers. 7710 EVT IntVT = Op.getValueType(); 7711 7712 // Get the inputs. 7713 SDValue Chain = Op.getOperand(0); 7714 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7715 // Build a DYNAREAOFFSET node. 7716 SDValue Ops[2] = {Chain, FPSIdx}; 7717 SDVTList VTs = DAG.getVTList(IntVT); 7718 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7719 } 7720 7721 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7722 SelectionDAG &DAG) const { 7723 // When we pop the dynamic allocation we need to restore the SP link. 7724 SDLoc dl(Op); 7725 7726 // Get the correct type for pointers. 7727 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7728 7729 // Construct the stack pointer operand. 7730 bool isPPC64 = Subtarget.isPPC64(); 7731 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7732 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7733 7734 // Get the operands for the STACKRESTORE. 7735 SDValue Chain = Op.getOperand(0); 7736 SDValue SaveSP = Op.getOperand(1); 7737 7738 // Load the old link SP. 7739 SDValue LoadLinkSP = 7740 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7741 7742 // Restore the stack pointer. 7743 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7744 7745 // Store the old link SP. 7746 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7747 } 7748 7749 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7750 MachineFunction &MF = DAG.getMachineFunction(); 7751 bool isPPC64 = Subtarget.isPPC64(); 7752 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7753 7754 // Get current frame pointer save index. The users of this index will be 7755 // primarily DYNALLOC instructions. 7756 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7757 int RASI = FI->getReturnAddrSaveIndex(); 7758 7759 // If the frame pointer save index hasn't been defined yet. 7760 if (!RASI) { 7761 // Find out what the fix offset of the frame pointer save area. 7762 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7763 // Allocate the frame index for frame pointer save area. 7764 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7765 // Save the result. 7766 FI->setReturnAddrSaveIndex(RASI); 7767 } 7768 return DAG.getFrameIndex(RASI, PtrVT); 7769 } 7770 7771 SDValue 7772 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7773 MachineFunction &MF = DAG.getMachineFunction(); 7774 bool isPPC64 = Subtarget.isPPC64(); 7775 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7776 7777 // Get current frame pointer save index. The users of this index will be 7778 // primarily DYNALLOC instructions. 7779 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7780 int FPSI = FI->getFramePointerSaveIndex(); 7781 7782 // If the frame pointer save index hasn't been defined yet. 7783 if (!FPSI) { 7784 // Find out what the fix offset of the frame pointer save area. 7785 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7786 // Allocate the frame index for frame pointer save area. 7787 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7788 // Save the result. 7789 FI->setFramePointerSaveIndex(FPSI); 7790 } 7791 return DAG.getFrameIndex(FPSI, PtrVT); 7792 } 7793 7794 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7795 SelectionDAG &DAG) const { 7796 MachineFunction &MF = DAG.getMachineFunction(); 7797 // Get the inputs. 7798 SDValue Chain = Op.getOperand(0); 7799 SDValue Size = Op.getOperand(1); 7800 SDLoc dl(Op); 7801 7802 // Get the correct type for pointers. 7803 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7804 // Negate the size. 7805 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7806 DAG.getConstant(0, dl, PtrVT), Size); 7807 // Construct a node for the frame pointer save index. 7808 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7809 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7810 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7811 if (hasInlineStackProbe(MF)) 7812 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7813 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7814 } 7815 7816 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7817 SelectionDAG &DAG) const { 7818 MachineFunction &MF = DAG.getMachineFunction(); 7819 7820 bool isPPC64 = Subtarget.isPPC64(); 7821 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7822 7823 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7824 return DAG.getFrameIndex(FI, PtrVT); 7825 } 7826 7827 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7828 SelectionDAG &DAG) const { 7829 SDLoc DL(Op); 7830 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7831 DAG.getVTList(MVT::i32, MVT::Other), 7832 Op.getOperand(0), Op.getOperand(1)); 7833 } 7834 7835 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7836 SelectionDAG &DAG) const { 7837 SDLoc DL(Op); 7838 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7839 Op.getOperand(0), Op.getOperand(1)); 7840 } 7841 7842 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7843 if (Op.getValueType().isVector()) 7844 return LowerVectorLoad(Op, DAG); 7845 7846 assert(Op.getValueType() == MVT::i1 && 7847 "Custom lowering only for i1 loads"); 7848 7849 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7850 7851 SDLoc dl(Op); 7852 LoadSDNode *LD = cast<LoadSDNode>(Op); 7853 7854 SDValue Chain = LD->getChain(); 7855 SDValue BasePtr = LD->getBasePtr(); 7856 MachineMemOperand *MMO = LD->getMemOperand(); 7857 7858 SDValue NewLD = 7859 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7860 BasePtr, MVT::i8, MMO); 7861 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7862 7863 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7864 return DAG.getMergeValues(Ops, dl); 7865 } 7866 7867 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7868 if (Op.getOperand(1).getValueType().isVector()) 7869 return LowerVectorStore(Op, DAG); 7870 7871 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7872 "Custom lowering only for i1 stores"); 7873 7874 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7875 7876 SDLoc dl(Op); 7877 StoreSDNode *ST = cast<StoreSDNode>(Op); 7878 7879 SDValue Chain = ST->getChain(); 7880 SDValue BasePtr = ST->getBasePtr(); 7881 SDValue Value = ST->getValue(); 7882 MachineMemOperand *MMO = ST->getMemOperand(); 7883 7884 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7885 Value); 7886 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7887 } 7888 7889 // FIXME: Remove this once the ANDI glue bug is fixed: 7890 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7891 assert(Op.getValueType() == MVT::i1 && 7892 "Custom lowering only for i1 results"); 7893 7894 SDLoc DL(Op); 7895 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7896 } 7897 7898 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7899 SelectionDAG &DAG) const { 7900 7901 // Implements a vector truncate that fits in a vector register as a shuffle. 7902 // We want to legalize vector truncates down to where the source fits in 7903 // a vector register (and target is therefore smaller than vector register 7904 // size). At that point legalization will try to custom lower the sub-legal 7905 // result and get here - where we can contain the truncate as a single target 7906 // operation. 7907 7908 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7909 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7910 // 7911 // We will implement it for big-endian ordering as this (where x denotes 7912 // undefined): 7913 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7914 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7915 // 7916 // The same operation in little-endian ordering will be: 7917 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7918 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7919 7920 EVT TrgVT = Op.getValueType(); 7921 assert(TrgVT.isVector() && "Vector type expected."); 7922 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7923 EVT EltVT = TrgVT.getVectorElementType(); 7924 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7925 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7926 !isPowerOf2_32(EltVT.getSizeInBits())) 7927 return SDValue(); 7928 7929 SDValue N1 = Op.getOperand(0); 7930 EVT SrcVT = N1.getValueType(); 7931 unsigned SrcSize = SrcVT.getSizeInBits(); 7932 if (SrcSize > 256 || 7933 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7934 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7935 return SDValue(); 7936 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7937 return SDValue(); 7938 7939 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7940 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7941 7942 SDLoc DL(Op); 7943 SDValue Op1, Op2; 7944 if (SrcSize == 256) { 7945 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7946 EVT SplitVT = 7947 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7948 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7949 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7950 DAG.getConstant(0, DL, VecIdxTy)); 7951 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7952 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7953 } 7954 else { 7955 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7956 Op2 = DAG.getUNDEF(WideVT); 7957 } 7958 7959 // First list the elements we want to keep. 7960 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7961 SmallVector<int, 16> ShuffV; 7962 if (Subtarget.isLittleEndian()) 7963 for (unsigned i = 0; i < TrgNumElts; ++i) 7964 ShuffV.push_back(i * SizeMult); 7965 else 7966 for (unsigned i = 1; i <= TrgNumElts; ++i) 7967 ShuffV.push_back(i * SizeMult - 1); 7968 7969 // Populate the remaining elements with undefs. 7970 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7971 // ShuffV.push_back(i + WideNumElts); 7972 ShuffV.push_back(WideNumElts + 1); 7973 7974 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7975 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7976 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7977 } 7978 7979 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7980 /// possible. 7981 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7982 // Not FP, or using SPE? Not a fsel. 7983 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7984 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7985 return Op; 7986 7987 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7988 7989 EVT ResVT = Op.getValueType(); 7990 EVT CmpVT = Op.getOperand(0).getValueType(); 7991 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7992 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7993 SDLoc dl(Op); 7994 SDNodeFlags Flags = Op.getNode()->getFlags(); 7995 7996 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7997 // presence of infinities. 7998 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7999 switch (CC) { 8000 default: 8001 break; 8002 case ISD::SETOGT: 8003 case ISD::SETGT: 8004 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 8005 case ISD::SETOLT: 8006 case ISD::SETLT: 8007 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8008 } 8009 } 8010 8011 // We might be able to do better than this under some circumstances, but in 8012 // general, fsel-based lowering of select is a finite-math-only optimization. 8013 // For more information, see section F.3 of the 2.06 ISA specification. 8014 // With ISA 3.0 8015 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 8016 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 8017 return Op; 8018 8019 // If the RHS of the comparison is a 0.0, we don't need to do the 8020 // subtraction at all. 8021 SDValue Sel1; 8022 if (isFloatingPointZero(RHS)) 8023 switch (CC) { 8024 default: break; // SETUO etc aren't handled by fsel. 8025 case ISD::SETNE: 8026 std::swap(TV, FV); 8027 LLVM_FALLTHROUGH; 8028 case ISD::SETEQ: 8029 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8030 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8031 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8032 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8033 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8034 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8035 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8036 case ISD::SETULT: 8037 case ISD::SETLT: 8038 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8039 LLVM_FALLTHROUGH; 8040 case ISD::SETOGE: 8041 case ISD::SETGE: 8042 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8043 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8044 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8045 case ISD::SETUGT: 8046 case ISD::SETGT: 8047 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8048 LLVM_FALLTHROUGH; 8049 case ISD::SETOLE: 8050 case ISD::SETLE: 8051 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8052 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8053 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8054 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8055 } 8056 8057 SDValue Cmp; 8058 switch (CC) { 8059 default: break; // SETUO etc aren't handled by fsel. 8060 case ISD::SETNE: 8061 std::swap(TV, FV); 8062 LLVM_FALLTHROUGH; 8063 case ISD::SETEQ: 8064 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8065 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8066 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8067 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8068 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8069 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8070 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8071 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8072 case ISD::SETULT: 8073 case ISD::SETLT: 8074 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8075 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8076 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8077 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8078 case ISD::SETOGE: 8079 case ISD::SETGE: 8080 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8081 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8082 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8083 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8084 case ISD::SETUGT: 8085 case ISD::SETGT: 8086 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8087 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8088 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8089 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8090 case ISD::SETOLE: 8091 case ISD::SETLE: 8092 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8093 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8094 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8095 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8096 } 8097 return Op; 8098 } 8099 8100 static unsigned getPPCStrictOpcode(unsigned Opc) { 8101 switch (Opc) { 8102 default: 8103 llvm_unreachable("No strict version of this opcode!"); 8104 case PPCISD::FCTIDZ: 8105 return PPCISD::STRICT_FCTIDZ; 8106 case PPCISD::FCTIWZ: 8107 return PPCISD::STRICT_FCTIWZ; 8108 case PPCISD::FCTIDUZ: 8109 return PPCISD::STRICT_FCTIDUZ; 8110 case PPCISD::FCTIWUZ: 8111 return PPCISD::STRICT_FCTIWUZ; 8112 case PPCISD::FCFID: 8113 return PPCISD::STRICT_FCFID; 8114 case PPCISD::FCFIDU: 8115 return PPCISD::STRICT_FCFIDU; 8116 case PPCISD::FCFIDS: 8117 return PPCISD::STRICT_FCFIDS; 8118 case PPCISD::FCFIDUS: 8119 return PPCISD::STRICT_FCFIDUS; 8120 } 8121 } 8122 8123 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8124 const PPCSubtarget &Subtarget) { 8125 SDLoc dl(Op); 8126 bool IsStrict = Op->isStrictFPOpcode(); 8127 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8128 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8129 8130 // TODO: Any other flags to propagate? 8131 SDNodeFlags Flags; 8132 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8133 8134 // For strict nodes, source is the second operand. 8135 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8136 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8137 assert(Src.getValueType().isFloatingPoint()); 8138 if (Src.getValueType() == MVT::f32) { 8139 if (IsStrict) { 8140 Src = 8141 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8142 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8143 Chain = Src.getValue(1); 8144 } else 8145 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8146 } 8147 SDValue Conv; 8148 unsigned Opc = ISD::DELETED_NODE; 8149 switch (Op.getSimpleValueType().SimpleTy) { 8150 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8151 case MVT::i32: 8152 Opc = IsSigned ? PPCISD::FCTIWZ 8153 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8154 break; 8155 case MVT::i64: 8156 assert((IsSigned || Subtarget.hasFPCVT()) && 8157 "i64 FP_TO_UINT is supported only with FPCVT"); 8158 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8159 } 8160 if (IsStrict) { 8161 Opc = getPPCStrictOpcode(Opc); 8162 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8163 {Chain, Src}, Flags); 8164 } else { 8165 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8166 } 8167 return Conv; 8168 } 8169 8170 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8171 SelectionDAG &DAG, 8172 const SDLoc &dl) const { 8173 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8174 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8175 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8176 bool IsStrict = Op->isStrictFPOpcode(); 8177 8178 // Convert the FP value to an int value through memory. 8179 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8180 (IsSigned || Subtarget.hasFPCVT()); 8181 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8182 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8183 MachinePointerInfo MPI = 8184 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8185 8186 // Emit a store to the stack slot. 8187 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8188 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8189 if (i32Stack) { 8190 MachineFunction &MF = DAG.getMachineFunction(); 8191 Alignment = Align(4); 8192 MachineMemOperand *MMO = 8193 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8194 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8195 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8196 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8197 } else 8198 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8199 8200 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8201 // add in a bias on big endian. 8202 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8203 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8204 DAG.getConstant(4, dl, FIPtr.getValueType())); 8205 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8206 } 8207 8208 RLI.Chain = Chain; 8209 RLI.Ptr = FIPtr; 8210 RLI.MPI = MPI; 8211 RLI.Alignment = Alignment; 8212 } 8213 8214 /// Custom lowers floating point to integer conversions to use 8215 /// the direct move instructions available in ISA 2.07 to avoid the 8216 /// need for load/store combinations. 8217 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8218 SelectionDAG &DAG, 8219 const SDLoc &dl) const { 8220 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8221 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8222 if (Op->isStrictFPOpcode()) 8223 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8224 else 8225 return Mov; 8226 } 8227 8228 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8229 const SDLoc &dl) const { 8230 bool IsStrict = Op->isStrictFPOpcode(); 8231 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8232 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8233 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8234 EVT SrcVT = Src.getValueType(); 8235 EVT DstVT = Op.getValueType(); 8236 8237 // FP to INT conversions are legal for f128. 8238 if (SrcVT == MVT::f128) 8239 return Op; 8240 8241 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8242 // PPC (the libcall is not available). 8243 if (SrcVT == MVT::ppcf128) { 8244 if (DstVT == MVT::i32) { 8245 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8246 // set other fast-math flags to FP operations in both strict and 8247 // non-strict cases. (FP_TO_SINT, FSUB) 8248 SDNodeFlags Flags; 8249 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8250 8251 if (IsSigned) { 8252 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8253 DAG.getIntPtrConstant(0, dl)); 8254 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8255 DAG.getIntPtrConstant(1, dl)); 8256 8257 // Add the two halves of the long double in round-to-zero mode, and use 8258 // a smaller FP_TO_SINT. 8259 if (IsStrict) { 8260 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8261 DAG.getVTList(MVT::f64, MVT::Other), 8262 {Op.getOperand(0), Lo, Hi}, Flags); 8263 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8264 DAG.getVTList(MVT::i32, MVT::Other), 8265 {Res.getValue(1), Res}, Flags); 8266 } else { 8267 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8268 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8269 } 8270 } else { 8271 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8272 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8273 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8274 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8275 if (IsStrict) { 8276 // Sel = Src < 0x80000000 8277 // FltOfs = select Sel, 0.0, 0x80000000 8278 // IntOfs = select Sel, 0, 0x80000000 8279 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8280 SDValue Chain = Op.getOperand(0); 8281 EVT SetCCVT = 8282 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8283 EVT DstSetCCVT = 8284 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8285 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8286 SDNodeFlags(), Chain, true); 8287 Chain = Sel.getValue(1); 8288 8289 SDValue FltOfs = DAG.getSelect( 8290 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8291 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8292 8293 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8294 DAG.getVTList(SrcVT, MVT::Other), 8295 {Chain, Src, FltOfs}, Flags); 8296 Chain = Val.getValue(1); 8297 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8298 DAG.getVTList(DstVT, MVT::Other), 8299 {Chain, Val}, Flags); 8300 Chain = SInt.getValue(1); 8301 SDValue IntOfs = DAG.getSelect( 8302 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8303 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8304 return DAG.getMergeValues({Result, Chain}, dl); 8305 } else { 8306 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8307 // FIXME: generated code sucks. 8308 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8309 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8310 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8311 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8312 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8313 } 8314 } 8315 } 8316 8317 return SDValue(); 8318 } 8319 8320 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8321 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8322 8323 ReuseLoadInfo RLI; 8324 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8325 8326 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8327 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8328 } 8329 8330 // We're trying to insert a regular store, S, and then a load, L. If the 8331 // incoming value, O, is a load, we might just be able to have our load use the 8332 // address used by O. However, we don't know if anything else will store to 8333 // that address before we can load from it. To prevent this situation, we need 8334 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8335 // the same chain operand as O, we create a token factor from the chain results 8336 // of O and L, and we replace all uses of O's chain result with that token 8337 // factor (see spliceIntoChain below for this last part). 8338 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8339 ReuseLoadInfo &RLI, 8340 SelectionDAG &DAG, 8341 ISD::LoadExtType ET) const { 8342 // Conservatively skip reusing for constrained FP nodes. 8343 if (Op->isStrictFPOpcode()) 8344 return false; 8345 8346 SDLoc dl(Op); 8347 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8348 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8349 if (ET == ISD::NON_EXTLOAD && 8350 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8351 isOperationLegalOrCustom(Op.getOpcode(), 8352 Op.getOperand(0).getValueType())) { 8353 8354 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8355 return true; 8356 } 8357 8358 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8359 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8360 LD->isNonTemporal()) 8361 return false; 8362 if (LD->getMemoryVT() != MemVT) 8363 return false; 8364 8365 RLI.Ptr = LD->getBasePtr(); 8366 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8367 assert(LD->getAddressingMode() == ISD::PRE_INC && 8368 "Non-pre-inc AM on PPC?"); 8369 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8370 LD->getOffset()); 8371 } 8372 8373 RLI.Chain = LD->getChain(); 8374 RLI.MPI = LD->getPointerInfo(); 8375 RLI.IsDereferenceable = LD->isDereferenceable(); 8376 RLI.IsInvariant = LD->isInvariant(); 8377 RLI.Alignment = LD->getAlign(); 8378 RLI.AAInfo = LD->getAAInfo(); 8379 RLI.Ranges = LD->getRanges(); 8380 8381 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8382 return true; 8383 } 8384 8385 // Given the head of the old chain, ResChain, insert a token factor containing 8386 // it and NewResChain, and make users of ResChain now be users of that token 8387 // factor. 8388 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8389 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8390 SDValue NewResChain, 8391 SelectionDAG &DAG) const { 8392 if (!ResChain) 8393 return; 8394 8395 SDLoc dl(NewResChain); 8396 8397 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8398 NewResChain, DAG.getUNDEF(MVT::Other)); 8399 assert(TF.getNode() != NewResChain.getNode() && 8400 "A new TF really is required here"); 8401 8402 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8403 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8404 } 8405 8406 /// Analyze profitability of direct move 8407 /// prefer float load to int load plus direct move 8408 /// when there is no integer use of int load 8409 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8410 SDNode *Origin = Op.getOperand(0).getNode(); 8411 if (Origin->getOpcode() != ISD::LOAD) 8412 return true; 8413 8414 // If there is no LXSIBZX/LXSIHZX, like Power8, 8415 // prefer direct move if the memory size is 1 or 2 bytes. 8416 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8417 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8418 return true; 8419 8420 for (SDNode::use_iterator UI = Origin->use_begin(), 8421 UE = Origin->use_end(); 8422 UI != UE; ++UI) { 8423 8424 // Only look at the users of the loaded value. 8425 if (UI.getUse().get().getResNo() != 0) 8426 continue; 8427 8428 if (UI->getOpcode() != ISD::SINT_TO_FP && 8429 UI->getOpcode() != ISD::UINT_TO_FP && 8430 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8431 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8432 return true; 8433 } 8434 8435 return false; 8436 } 8437 8438 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8439 const PPCSubtarget &Subtarget, 8440 SDValue Chain = SDValue()) { 8441 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8442 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8443 SDLoc dl(Op); 8444 8445 // TODO: Any other flags to propagate? 8446 SDNodeFlags Flags; 8447 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8448 8449 // If we have FCFIDS, then use it when converting to single-precision. 8450 // Otherwise, convert to double-precision and then round. 8451 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8452 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8453 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8454 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8455 if (Op->isStrictFPOpcode()) { 8456 if (!Chain) 8457 Chain = Op.getOperand(0); 8458 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8459 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8460 } else 8461 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8462 } 8463 8464 /// Custom lowers integer to floating point conversions to use 8465 /// the direct move instructions available in ISA 2.07 to avoid the 8466 /// need for load/store combinations. 8467 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8468 SelectionDAG &DAG, 8469 const SDLoc &dl) const { 8470 assert((Op.getValueType() == MVT::f32 || 8471 Op.getValueType() == MVT::f64) && 8472 "Invalid floating point type as target of conversion"); 8473 assert(Subtarget.hasFPCVT() && 8474 "Int to FP conversions with direct moves require FPCVT"); 8475 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8476 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8477 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8478 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8479 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8480 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8481 return convertIntToFP(Op, Mov, DAG, Subtarget); 8482 } 8483 8484 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8485 8486 EVT VecVT = Vec.getValueType(); 8487 assert(VecVT.isVector() && "Expected a vector type."); 8488 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8489 8490 EVT EltVT = VecVT.getVectorElementType(); 8491 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8492 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8493 8494 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8495 SmallVector<SDValue, 16> Ops(NumConcat); 8496 Ops[0] = Vec; 8497 SDValue UndefVec = DAG.getUNDEF(VecVT); 8498 for (unsigned i = 1; i < NumConcat; ++i) 8499 Ops[i] = UndefVec; 8500 8501 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8502 } 8503 8504 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8505 const SDLoc &dl) const { 8506 bool IsStrict = Op->isStrictFPOpcode(); 8507 unsigned Opc = Op.getOpcode(); 8508 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8509 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8510 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8511 "Unexpected conversion type"); 8512 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8513 "Supports conversions to v2f64/v4f32 only."); 8514 8515 // TODO: Any other flags to propagate? 8516 SDNodeFlags Flags; 8517 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8518 8519 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8520 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8521 8522 SDValue Wide = widenVec(DAG, Src, dl); 8523 EVT WideVT = Wide.getValueType(); 8524 unsigned WideNumElts = WideVT.getVectorNumElements(); 8525 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8526 8527 SmallVector<int, 16> ShuffV; 8528 for (unsigned i = 0; i < WideNumElts; ++i) 8529 ShuffV.push_back(i + WideNumElts); 8530 8531 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8532 int SaveElts = FourEltRes ? 4 : 2; 8533 if (Subtarget.isLittleEndian()) 8534 for (int i = 0; i < SaveElts; i++) 8535 ShuffV[i * Stride] = i; 8536 else 8537 for (int i = 1; i <= SaveElts; i++) 8538 ShuffV[i * Stride - 1] = i - 1; 8539 8540 SDValue ShuffleSrc2 = 8541 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8542 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8543 8544 SDValue Extend; 8545 if (SignedConv) { 8546 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8547 EVT ExtVT = Src.getValueType(); 8548 if (Subtarget.hasP9Altivec()) 8549 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8550 IntermediateVT.getVectorNumElements()); 8551 8552 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8553 DAG.getValueType(ExtVT)); 8554 } else 8555 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8556 8557 if (IsStrict) 8558 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8559 {Op.getOperand(0), Extend}, Flags); 8560 8561 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8562 } 8563 8564 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8565 SelectionDAG &DAG) const { 8566 SDLoc dl(Op); 8567 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8568 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8569 bool IsStrict = Op->isStrictFPOpcode(); 8570 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8571 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8572 8573 // TODO: Any other flags to propagate? 8574 SDNodeFlags Flags; 8575 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8576 8577 EVT InVT = Src.getValueType(); 8578 EVT OutVT = Op.getValueType(); 8579 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8580 isOperationCustom(Op.getOpcode(), InVT)) 8581 return LowerINT_TO_FPVector(Op, DAG, dl); 8582 8583 // Conversions to f128 are legal. 8584 if (Op.getValueType() == MVT::f128) 8585 return Op; 8586 8587 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8588 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8589 return SDValue(); 8590 8591 if (Src.getValueType() == MVT::i1) 8592 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8593 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8594 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8595 8596 // If we have direct moves, we can do all the conversion, skip the store/load 8597 // however, without FPCVT we can't do most conversions. 8598 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8599 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8600 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8601 8602 assert((IsSigned || Subtarget.hasFPCVT()) && 8603 "UINT_TO_FP is supported only with FPCVT"); 8604 8605 if (Src.getValueType() == MVT::i64) { 8606 SDValue SINT = Src; 8607 // When converting to single-precision, we actually need to convert 8608 // to double-precision first and then round to single-precision. 8609 // To avoid double-rounding effects during that operation, we have 8610 // to prepare the input operand. Bits that might be truncated when 8611 // converting to double-precision are replaced by a bit that won't 8612 // be lost at this stage, but is below the single-precision rounding 8613 // position. 8614 // 8615 // However, if -enable-unsafe-fp-math is in effect, accept double 8616 // rounding to avoid the extra overhead. 8617 if (Op.getValueType() == MVT::f32 && 8618 !Subtarget.hasFPCVT() && 8619 !DAG.getTarget().Options.UnsafeFPMath) { 8620 8621 // Twiddle input to make sure the low 11 bits are zero. (If this 8622 // is the case, we are guaranteed the value will fit into the 53 bit 8623 // mantissa of an IEEE double-precision value without rounding.) 8624 // If any of those low 11 bits were not zero originally, make sure 8625 // bit 12 (value 2048) is set instead, so that the final rounding 8626 // to single-precision gets the correct result. 8627 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8628 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8629 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8630 Round, DAG.getConstant(2047, dl, MVT::i64)); 8631 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8632 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8633 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8634 8635 // However, we cannot use that value unconditionally: if the magnitude 8636 // of the input value is small, the bit-twiddling we did above might 8637 // end up visibly changing the output. Fortunately, in that case, we 8638 // don't need to twiddle bits since the original input will convert 8639 // exactly to double-precision floating-point already. Therefore, 8640 // construct a conditional to use the original value if the top 11 8641 // bits are all sign-bit copies, and use the rounded value computed 8642 // above otherwise. 8643 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8644 SINT, DAG.getConstant(53, dl, MVT::i32)); 8645 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8646 Cond, DAG.getConstant(1, dl, MVT::i64)); 8647 Cond = DAG.getSetCC( 8648 dl, 8649 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8650 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8651 8652 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8653 } 8654 8655 ReuseLoadInfo RLI; 8656 SDValue Bits; 8657 8658 MachineFunction &MF = DAG.getMachineFunction(); 8659 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8660 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8661 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8662 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8663 } else if (Subtarget.hasLFIWAX() && 8664 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8665 MachineMemOperand *MMO = 8666 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8667 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8668 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8669 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8670 DAG.getVTList(MVT::f64, MVT::Other), 8671 Ops, MVT::i32, MMO); 8672 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8673 } else if (Subtarget.hasFPCVT() && 8674 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8675 MachineMemOperand *MMO = 8676 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8677 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8678 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8679 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8680 DAG.getVTList(MVT::f64, MVT::Other), 8681 Ops, MVT::i32, MMO); 8682 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8683 } else if (((Subtarget.hasLFIWAX() && 8684 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8685 (Subtarget.hasFPCVT() && 8686 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8687 SINT.getOperand(0).getValueType() == MVT::i32) { 8688 MachineFrameInfo &MFI = MF.getFrameInfo(); 8689 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8690 8691 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8692 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8693 8694 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8695 MachinePointerInfo::getFixedStack( 8696 DAG.getMachineFunction(), FrameIdx)); 8697 Chain = Store; 8698 8699 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8700 "Expected an i32 store"); 8701 8702 RLI.Ptr = FIdx; 8703 RLI.Chain = Chain; 8704 RLI.MPI = 8705 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8706 RLI.Alignment = Align(4); 8707 8708 MachineMemOperand *MMO = 8709 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8710 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8711 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8712 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8713 PPCISD::LFIWZX : PPCISD::LFIWAX, 8714 dl, DAG.getVTList(MVT::f64, MVT::Other), 8715 Ops, MVT::i32, MMO); 8716 Chain = Bits.getValue(1); 8717 } else 8718 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8719 8720 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8721 if (IsStrict) 8722 Chain = FP.getValue(1); 8723 8724 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8725 if (IsStrict) 8726 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8727 DAG.getVTList(MVT::f32, MVT::Other), 8728 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8729 else 8730 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8731 DAG.getIntPtrConstant(0, dl)); 8732 } 8733 return FP; 8734 } 8735 8736 assert(Src.getValueType() == MVT::i32 && 8737 "Unhandled INT_TO_FP type in custom expander!"); 8738 // Since we only generate this in 64-bit mode, we can take advantage of 8739 // 64-bit registers. In particular, sign extend the input value into the 8740 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8741 // then lfd it and fcfid it. 8742 MachineFunction &MF = DAG.getMachineFunction(); 8743 MachineFrameInfo &MFI = MF.getFrameInfo(); 8744 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8745 8746 SDValue Ld; 8747 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8748 ReuseLoadInfo RLI; 8749 bool ReusingLoad; 8750 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8751 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8752 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8753 8754 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8755 MachinePointerInfo::getFixedStack( 8756 DAG.getMachineFunction(), FrameIdx)); 8757 Chain = Store; 8758 8759 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8760 "Expected an i32 store"); 8761 8762 RLI.Ptr = FIdx; 8763 RLI.Chain = Chain; 8764 RLI.MPI = 8765 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8766 RLI.Alignment = Align(4); 8767 } 8768 8769 MachineMemOperand *MMO = 8770 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8771 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8772 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8773 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8774 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8775 MVT::i32, MMO); 8776 Chain = Ld.getValue(1); 8777 if (ReusingLoad) 8778 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8779 } else { 8780 assert(Subtarget.isPPC64() && 8781 "i32->FP without LFIWAX supported only on PPC64"); 8782 8783 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8784 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8785 8786 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8787 8788 // STD the extended value into the stack slot. 8789 SDValue Store = DAG.getStore( 8790 Chain, dl, Ext64, FIdx, 8791 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8792 Chain = Store; 8793 8794 // Load the value as a double. 8795 Ld = DAG.getLoad( 8796 MVT::f64, dl, Chain, FIdx, 8797 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8798 Chain = Ld.getValue(1); 8799 } 8800 8801 // FCFID it and return it. 8802 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8803 if (IsStrict) 8804 Chain = FP.getValue(1); 8805 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8806 if (IsStrict) 8807 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8808 DAG.getVTList(MVT::f32, MVT::Other), 8809 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8810 else 8811 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8812 DAG.getIntPtrConstant(0, dl)); 8813 } 8814 return FP; 8815 } 8816 8817 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8818 SelectionDAG &DAG) const { 8819 SDLoc dl(Op); 8820 /* 8821 The rounding mode is in bits 30:31 of FPSR, and has the following 8822 settings: 8823 00 Round to nearest 8824 01 Round to 0 8825 10 Round to +inf 8826 11 Round to -inf 8827 8828 FLT_ROUNDS, on the other hand, expects the following: 8829 -1 Undefined 8830 0 Round to 0 8831 1 Round to nearest 8832 2 Round to +inf 8833 3 Round to -inf 8834 8835 To perform the conversion, we do: 8836 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8837 */ 8838 8839 MachineFunction &MF = DAG.getMachineFunction(); 8840 EVT VT = Op.getValueType(); 8841 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8842 8843 // Save FP Control Word to register 8844 SDValue Chain = Op.getOperand(0); 8845 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8846 Chain = MFFS.getValue(1); 8847 8848 // Save FP register to stack slot 8849 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8850 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8851 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8852 8853 // Load FP Control Word from low 32 bits of stack slot. 8854 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8855 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8856 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8857 Chain = CWD.getValue(1); 8858 8859 // Transform as necessary 8860 SDValue CWD1 = 8861 DAG.getNode(ISD::AND, dl, MVT::i32, 8862 CWD, DAG.getConstant(3, dl, MVT::i32)); 8863 SDValue CWD2 = 8864 DAG.getNode(ISD::SRL, dl, MVT::i32, 8865 DAG.getNode(ISD::AND, dl, MVT::i32, 8866 DAG.getNode(ISD::XOR, dl, MVT::i32, 8867 CWD, DAG.getConstant(3, dl, MVT::i32)), 8868 DAG.getConstant(3, dl, MVT::i32)), 8869 DAG.getConstant(1, dl, MVT::i32)); 8870 8871 SDValue RetVal = 8872 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8873 8874 RetVal = 8875 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8876 dl, VT, RetVal); 8877 8878 return DAG.getMergeValues({RetVal, Chain}, dl); 8879 } 8880 8881 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8882 EVT VT = Op.getValueType(); 8883 unsigned BitWidth = VT.getSizeInBits(); 8884 SDLoc dl(Op); 8885 assert(Op.getNumOperands() == 3 && 8886 VT == Op.getOperand(1).getValueType() && 8887 "Unexpected SHL!"); 8888 8889 // Expand into a bunch of logical ops. Note that these ops 8890 // depend on the PPC behavior for oversized shift amounts. 8891 SDValue Lo = Op.getOperand(0); 8892 SDValue Hi = Op.getOperand(1); 8893 SDValue Amt = Op.getOperand(2); 8894 EVT AmtVT = Amt.getValueType(); 8895 8896 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8897 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8898 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8899 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8900 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8901 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8902 DAG.getConstant(-BitWidth, dl, AmtVT)); 8903 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8904 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8905 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8906 SDValue OutOps[] = { OutLo, OutHi }; 8907 return DAG.getMergeValues(OutOps, dl); 8908 } 8909 8910 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8911 EVT VT = Op.getValueType(); 8912 SDLoc dl(Op); 8913 unsigned BitWidth = VT.getSizeInBits(); 8914 assert(Op.getNumOperands() == 3 && 8915 VT == Op.getOperand(1).getValueType() && 8916 "Unexpected SRL!"); 8917 8918 // Expand into a bunch of logical ops. Note that these ops 8919 // depend on the PPC behavior for oversized shift amounts. 8920 SDValue Lo = Op.getOperand(0); 8921 SDValue Hi = Op.getOperand(1); 8922 SDValue Amt = Op.getOperand(2); 8923 EVT AmtVT = Amt.getValueType(); 8924 8925 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8926 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8927 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8928 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8929 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8930 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8931 DAG.getConstant(-BitWidth, dl, AmtVT)); 8932 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8933 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8934 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8935 SDValue OutOps[] = { OutLo, OutHi }; 8936 return DAG.getMergeValues(OutOps, dl); 8937 } 8938 8939 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8940 SDLoc dl(Op); 8941 EVT VT = Op.getValueType(); 8942 unsigned BitWidth = VT.getSizeInBits(); 8943 assert(Op.getNumOperands() == 3 && 8944 VT == Op.getOperand(1).getValueType() && 8945 "Unexpected SRA!"); 8946 8947 // Expand into a bunch of logical ops, followed by a select_cc. 8948 SDValue Lo = Op.getOperand(0); 8949 SDValue Hi = Op.getOperand(1); 8950 SDValue Amt = Op.getOperand(2); 8951 EVT AmtVT = Amt.getValueType(); 8952 8953 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8954 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8955 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8956 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8957 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8958 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8959 DAG.getConstant(-BitWidth, dl, AmtVT)); 8960 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8961 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8962 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8963 Tmp4, Tmp6, ISD::SETLE); 8964 SDValue OutOps[] = { OutLo, OutHi }; 8965 return DAG.getMergeValues(OutOps, dl); 8966 } 8967 8968 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8969 SelectionDAG &DAG) const { 8970 SDLoc dl(Op); 8971 EVT VT = Op.getValueType(); 8972 unsigned BitWidth = VT.getSizeInBits(); 8973 8974 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8975 SDValue X = Op.getOperand(0); 8976 SDValue Y = Op.getOperand(1); 8977 SDValue Z = Op.getOperand(2); 8978 EVT AmtVT = Z.getValueType(); 8979 8980 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8981 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8982 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8983 // on PowerPC shift by BW being well defined. 8984 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8985 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8986 SDValue SubZ = 8987 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8988 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8989 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8990 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8991 } 8992 8993 //===----------------------------------------------------------------------===// 8994 // Vector related lowering. 8995 // 8996 8997 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8998 /// element size of SplatSize. Cast the result to VT. 8999 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 9000 SelectionDAG &DAG, const SDLoc &dl) { 9001 static const MVT VTys[] = { // canonical VT to use for each size. 9002 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 9003 }; 9004 9005 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 9006 9007 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 9008 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 9009 SplatSize = 1; 9010 Val = 0xFF; 9011 } 9012 9013 EVT CanonicalVT = VTys[SplatSize-1]; 9014 9015 // Build a canonical splat for this value. 9016 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 9017 } 9018 9019 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 9020 /// specified intrinsic ID. 9021 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 9022 const SDLoc &dl, EVT DestVT = MVT::Other) { 9023 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 9024 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9025 DAG.getConstant(IID, dl, MVT::i32), Op); 9026 } 9027 9028 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 9029 /// specified intrinsic ID. 9030 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 9031 SelectionDAG &DAG, const SDLoc &dl, 9032 EVT DestVT = MVT::Other) { 9033 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 9034 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9035 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 9036 } 9037 9038 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 9039 /// specified intrinsic ID. 9040 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 9041 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 9042 EVT DestVT = MVT::Other) { 9043 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 9044 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9045 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 9046 } 9047 9048 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 9049 /// amount. The result has the specified value type. 9050 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 9051 SelectionDAG &DAG, const SDLoc &dl) { 9052 // Force LHS/RHS to be the right type. 9053 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 9054 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 9055 9056 int Ops[16]; 9057 for (unsigned i = 0; i != 16; ++i) 9058 Ops[i] = i + Amt; 9059 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 9060 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9061 } 9062 9063 /// Do we have an efficient pattern in a .td file for this node? 9064 /// 9065 /// \param V - pointer to the BuildVectorSDNode being matched 9066 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9067 /// 9068 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9069 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9070 /// the opposite is true (expansion is beneficial) are: 9071 /// - The node builds a vector out of integers that are not 32 or 64-bits 9072 /// - The node builds a vector out of constants 9073 /// - The node is a "load-and-splat" 9074 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9075 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9076 bool HasDirectMove, 9077 bool HasP8Vector) { 9078 EVT VecVT = V->getValueType(0); 9079 bool RightType = VecVT == MVT::v2f64 || 9080 (HasP8Vector && VecVT == MVT::v4f32) || 9081 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9082 if (!RightType) 9083 return false; 9084 9085 bool IsSplat = true; 9086 bool IsLoad = false; 9087 SDValue Op0 = V->getOperand(0); 9088 9089 // This function is called in a block that confirms the node is not a constant 9090 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9091 // different constants. 9092 if (V->isConstant()) 9093 return false; 9094 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9095 if (V->getOperand(i).isUndef()) 9096 return false; 9097 // We want to expand nodes that represent load-and-splat even if the 9098 // loaded value is a floating point truncation or conversion to int. 9099 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9100 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9101 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9102 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9103 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9104 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9105 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9106 IsLoad = true; 9107 // If the operands are different or the input is not a load and has more 9108 // uses than just this BV node, then it isn't a splat. 9109 if (V->getOperand(i) != Op0 || 9110 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9111 IsSplat = false; 9112 } 9113 return !(IsSplat && IsLoad); 9114 } 9115 9116 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9117 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9118 9119 SDLoc dl(Op); 9120 SDValue Op0 = Op->getOperand(0); 9121 9122 if ((Op.getValueType() != MVT::f128) || 9123 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9124 (Op0.getOperand(0).getValueType() != MVT::i64) || 9125 (Op0.getOperand(1).getValueType() != MVT::i64)) 9126 return SDValue(); 9127 9128 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9129 Op0.getOperand(1)); 9130 } 9131 9132 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9133 const SDValue *InputLoad = &Op; 9134 if (InputLoad->getOpcode() == ISD::BITCAST) 9135 InputLoad = &InputLoad->getOperand(0); 9136 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9137 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9138 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9139 InputLoad = &InputLoad->getOperand(0); 9140 } 9141 if (InputLoad->getOpcode() != ISD::LOAD) 9142 return nullptr; 9143 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9144 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9145 } 9146 9147 // Convert the argument APFloat to a single precision APFloat if there is no 9148 // loss in information during the conversion to single precision APFloat and the 9149 // resulting number is not a denormal number. Return true if successful. 9150 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9151 APFloat APFloatToConvert = ArgAPFloat; 9152 bool LosesInfo = true; 9153 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9154 &LosesInfo); 9155 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9156 if (Success) 9157 ArgAPFloat = APFloatToConvert; 9158 return Success; 9159 } 9160 9161 // Bitcast the argument APInt to a double and convert it to a single precision 9162 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9163 // argument if there is no loss in information during the conversion from 9164 // double to single precision APFloat and the resulting number is not a denormal 9165 // number. Return true if successful. 9166 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9167 double DpValue = ArgAPInt.bitsToDouble(); 9168 APFloat APFloatDp(DpValue); 9169 bool Success = convertToNonDenormSingle(APFloatDp); 9170 if (Success) 9171 ArgAPInt = APFloatDp.bitcastToAPInt(); 9172 return Success; 9173 } 9174 9175 // If this is a case we can't handle, return null and let the default 9176 // expansion code take care of it. If we CAN select this case, and if it 9177 // selects to a single instruction, return Op. Otherwise, if we can codegen 9178 // this case more efficiently than a constant pool load, lower it to the 9179 // sequence of ops that should be used. 9180 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9181 SelectionDAG &DAG) const { 9182 SDLoc dl(Op); 9183 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9184 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9185 9186 // Check if this is a splat of a constant value. 9187 APInt APSplatBits, APSplatUndef; 9188 unsigned SplatBitSize; 9189 bool HasAnyUndefs; 9190 bool BVNIsConstantSplat = 9191 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9192 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9193 9194 // If it is a splat of a double, check if we can shrink it to a 32 bit 9195 // non-denormal float which when converted back to double gives us the same 9196 // double. This is to exploit the XXSPLTIDP instruction. 9197 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 9198 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 9199 convertToNonDenormSingle(APSplatBits)) { 9200 SDValue SplatNode = DAG.getNode( 9201 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9202 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9203 return DAG.getBitcast(Op.getValueType(), SplatNode); 9204 } 9205 9206 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9207 9208 bool IsPermutedLoad = false; 9209 const SDValue *InputLoad = 9210 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9211 // Handle load-and-splat patterns as we have instructions that will do this 9212 // in one go. 9213 if (InputLoad && DAG.isSplatValue(Op, true)) { 9214 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9215 9216 // We have handling for 4 and 8 byte elements. 9217 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9218 9219 // Checking for a single use of this load, we have to check for vector 9220 // width (128 bits) / ElementSize uses (since each operand of the 9221 // BUILD_VECTOR is a separate use of the value. 9222 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9223 ((Subtarget.hasVSX() && ElementSize == 64) || 9224 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9225 SDValue Ops[] = { 9226 LD->getChain(), // Chain 9227 LD->getBasePtr(), // Ptr 9228 DAG.getValueType(Op.getValueType()) // VT 9229 }; 9230 return 9231 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9232 DAG.getVTList(Op.getValueType(), MVT::Other), 9233 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9234 } 9235 } 9236 9237 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9238 // lowered to VSX instructions under certain conditions. 9239 // Without VSX, there is no pattern more efficient than expanding the node. 9240 if (Subtarget.hasVSX() && 9241 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9242 Subtarget.hasP8Vector())) 9243 return Op; 9244 return SDValue(); 9245 } 9246 9247 uint64_t SplatBits = APSplatBits.getZExtValue(); 9248 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9249 unsigned SplatSize = SplatBitSize / 8; 9250 9251 // First, handle single instruction cases. 9252 9253 // All zeros? 9254 if (SplatBits == 0) { 9255 // Canonicalize all zero vectors to be v4i32. 9256 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9257 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9258 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9259 } 9260 return Op; 9261 } 9262 9263 // We have XXSPLTIW for constant splats four bytes wide. 9264 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9265 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9266 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9267 // turned into a 4-byte splat of 0xABABABAB. 9268 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9269 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 9270 Op.getValueType(), DAG, dl); 9271 9272 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9273 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9274 dl); 9275 9276 // We have XXSPLTIB for constant splats one byte wide. 9277 if (Subtarget.hasP9Vector() && SplatSize == 1) 9278 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9279 dl); 9280 9281 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9282 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9283 (32-SplatBitSize)); 9284 if (SextVal >= -16 && SextVal <= 15) 9285 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9286 dl); 9287 9288 // Two instruction sequences. 9289 9290 // If this value is in the range [-32,30] and is even, use: 9291 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9292 // If this value is in the range [17,31] and is odd, use: 9293 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9294 // If this value is in the range [-31,-17] and is odd, use: 9295 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9296 // Note the last two are three-instruction sequences. 9297 if (SextVal >= -32 && SextVal <= 31) { 9298 // To avoid having these optimizations undone by constant folding, 9299 // we convert to a pseudo that will be expanded later into one of 9300 // the above forms. 9301 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9302 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9303 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9304 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9305 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9306 if (VT == Op.getValueType()) 9307 return RetVal; 9308 else 9309 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9310 } 9311 9312 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9313 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9314 // for fneg/fabs. 9315 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9316 // Make -1 and vspltisw -1: 9317 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9318 9319 // Make the VSLW intrinsic, computing 0x8000_0000. 9320 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9321 OnesV, DAG, dl); 9322 9323 // xor by OnesV to invert it. 9324 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9325 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9326 } 9327 9328 // Check to see if this is a wide variety of vsplti*, binop self cases. 9329 static const signed char SplatCsts[] = { 9330 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9331 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9332 }; 9333 9334 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9335 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9336 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9337 int i = SplatCsts[idx]; 9338 9339 // Figure out what shift amount will be used by altivec if shifted by i in 9340 // this splat size. 9341 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9342 9343 // vsplti + shl self. 9344 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9345 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9346 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9347 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9348 Intrinsic::ppc_altivec_vslw 9349 }; 9350 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9351 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9352 } 9353 9354 // vsplti + srl self. 9355 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9356 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9357 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9358 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9359 Intrinsic::ppc_altivec_vsrw 9360 }; 9361 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9362 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9363 } 9364 9365 // vsplti + sra self. 9366 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9367 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9368 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9369 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9370 Intrinsic::ppc_altivec_vsraw 9371 }; 9372 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9373 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9374 } 9375 9376 // vsplti + rol self. 9377 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9378 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9379 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9380 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9381 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9382 Intrinsic::ppc_altivec_vrlw 9383 }; 9384 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9385 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9386 } 9387 9388 // t = vsplti c, result = vsldoi t, t, 1 9389 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9390 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9391 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9392 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9393 } 9394 // t = vsplti c, result = vsldoi t, t, 2 9395 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9396 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9397 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9398 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9399 } 9400 // t = vsplti c, result = vsldoi t, t, 3 9401 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9402 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9403 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9404 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9405 } 9406 } 9407 9408 return SDValue(); 9409 } 9410 9411 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9412 /// the specified operations to build the shuffle. 9413 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9414 SDValue RHS, SelectionDAG &DAG, 9415 const SDLoc &dl) { 9416 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9417 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9418 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9419 9420 enum { 9421 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9422 OP_VMRGHW, 9423 OP_VMRGLW, 9424 OP_VSPLTISW0, 9425 OP_VSPLTISW1, 9426 OP_VSPLTISW2, 9427 OP_VSPLTISW3, 9428 OP_VSLDOI4, 9429 OP_VSLDOI8, 9430 OP_VSLDOI12 9431 }; 9432 9433 if (OpNum == OP_COPY) { 9434 if (LHSID == (1*9+2)*9+3) return LHS; 9435 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9436 return RHS; 9437 } 9438 9439 SDValue OpLHS, OpRHS; 9440 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9441 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9442 9443 int ShufIdxs[16]; 9444 switch (OpNum) { 9445 default: llvm_unreachable("Unknown i32 permute!"); 9446 case OP_VMRGHW: 9447 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9448 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9449 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9450 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9451 break; 9452 case OP_VMRGLW: 9453 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9454 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9455 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9456 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9457 break; 9458 case OP_VSPLTISW0: 9459 for (unsigned i = 0; i != 16; ++i) 9460 ShufIdxs[i] = (i&3)+0; 9461 break; 9462 case OP_VSPLTISW1: 9463 for (unsigned i = 0; i != 16; ++i) 9464 ShufIdxs[i] = (i&3)+4; 9465 break; 9466 case OP_VSPLTISW2: 9467 for (unsigned i = 0; i != 16; ++i) 9468 ShufIdxs[i] = (i&3)+8; 9469 break; 9470 case OP_VSPLTISW3: 9471 for (unsigned i = 0; i != 16; ++i) 9472 ShufIdxs[i] = (i&3)+12; 9473 break; 9474 case OP_VSLDOI4: 9475 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9476 case OP_VSLDOI8: 9477 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9478 case OP_VSLDOI12: 9479 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9480 } 9481 EVT VT = OpLHS.getValueType(); 9482 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9483 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9484 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9485 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9486 } 9487 9488 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9489 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9490 /// SDValue. 9491 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9492 SelectionDAG &DAG) const { 9493 const unsigned BytesInVector = 16; 9494 bool IsLE = Subtarget.isLittleEndian(); 9495 SDLoc dl(N); 9496 SDValue V1 = N->getOperand(0); 9497 SDValue V2 = N->getOperand(1); 9498 unsigned ShiftElts = 0, InsertAtByte = 0; 9499 bool Swap = false; 9500 9501 // Shifts required to get the byte we want at element 7. 9502 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9503 0, 15, 14, 13, 12, 11, 10, 9}; 9504 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9505 1, 2, 3, 4, 5, 6, 7, 8}; 9506 9507 ArrayRef<int> Mask = N->getMask(); 9508 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9509 9510 // For each mask element, find out if we're just inserting something 9511 // from V2 into V1 or vice versa. 9512 // Possible permutations inserting an element from V2 into V1: 9513 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9514 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9515 // ... 9516 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9517 // Inserting from V1 into V2 will be similar, except mask range will be 9518 // [16,31]. 9519 9520 bool FoundCandidate = false; 9521 // If both vector operands for the shuffle are the same vector, the mask 9522 // will contain only elements from the first one and the second one will be 9523 // undef. 9524 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9525 // Go through the mask of half-words to find an element that's being moved 9526 // from one vector to the other. 9527 for (unsigned i = 0; i < BytesInVector; ++i) { 9528 unsigned CurrentElement = Mask[i]; 9529 // If 2nd operand is undefined, we should only look for element 7 in the 9530 // Mask. 9531 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9532 continue; 9533 9534 bool OtherElementsInOrder = true; 9535 // Examine the other elements in the Mask to see if they're in original 9536 // order. 9537 for (unsigned j = 0; j < BytesInVector; ++j) { 9538 if (j == i) 9539 continue; 9540 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9541 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9542 // in which we always assume we're always picking from the 1st operand. 9543 int MaskOffset = 9544 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9545 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9546 OtherElementsInOrder = false; 9547 break; 9548 } 9549 } 9550 // If other elements are in original order, we record the number of shifts 9551 // we need to get the element we want into element 7. Also record which byte 9552 // in the vector we should insert into. 9553 if (OtherElementsInOrder) { 9554 // If 2nd operand is undefined, we assume no shifts and no swapping. 9555 if (V2.isUndef()) { 9556 ShiftElts = 0; 9557 Swap = false; 9558 } else { 9559 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9560 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9561 : BigEndianShifts[CurrentElement & 0xF]; 9562 Swap = CurrentElement < BytesInVector; 9563 } 9564 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9565 FoundCandidate = true; 9566 break; 9567 } 9568 } 9569 9570 if (!FoundCandidate) 9571 return SDValue(); 9572 9573 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9574 // optionally with VECSHL if shift is required. 9575 if (Swap) 9576 std::swap(V1, V2); 9577 if (V2.isUndef()) 9578 V2 = V1; 9579 if (ShiftElts) { 9580 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9581 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9582 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9583 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9584 } 9585 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9586 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9587 } 9588 9589 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9590 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9591 /// SDValue. 9592 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9593 SelectionDAG &DAG) const { 9594 const unsigned NumHalfWords = 8; 9595 const unsigned BytesInVector = NumHalfWords * 2; 9596 // Check that the shuffle is on half-words. 9597 if (!isNByteElemShuffleMask(N, 2, 1)) 9598 return SDValue(); 9599 9600 bool IsLE = Subtarget.isLittleEndian(); 9601 SDLoc dl(N); 9602 SDValue V1 = N->getOperand(0); 9603 SDValue V2 = N->getOperand(1); 9604 unsigned ShiftElts = 0, InsertAtByte = 0; 9605 bool Swap = false; 9606 9607 // Shifts required to get the half-word we want at element 3. 9608 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9609 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9610 9611 uint32_t Mask = 0; 9612 uint32_t OriginalOrderLow = 0x1234567; 9613 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9614 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9615 // 32-bit space, only need 4-bit nibbles per element. 9616 for (unsigned i = 0; i < NumHalfWords; ++i) { 9617 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9618 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9619 } 9620 9621 // For each mask element, find out if we're just inserting something 9622 // from V2 into V1 or vice versa. Possible permutations inserting an element 9623 // from V2 into V1: 9624 // X, 1, 2, 3, 4, 5, 6, 7 9625 // 0, X, 2, 3, 4, 5, 6, 7 9626 // 0, 1, X, 3, 4, 5, 6, 7 9627 // 0, 1, 2, X, 4, 5, 6, 7 9628 // 0, 1, 2, 3, X, 5, 6, 7 9629 // 0, 1, 2, 3, 4, X, 6, 7 9630 // 0, 1, 2, 3, 4, 5, X, 7 9631 // 0, 1, 2, 3, 4, 5, 6, X 9632 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9633 9634 bool FoundCandidate = false; 9635 // Go through the mask of half-words to find an element that's being moved 9636 // from one vector to the other. 9637 for (unsigned i = 0; i < NumHalfWords; ++i) { 9638 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9639 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9640 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9641 uint32_t TargetOrder = 0x0; 9642 9643 // If both vector operands for the shuffle are the same vector, the mask 9644 // will contain only elements from the first one and the second one will be 9645 // undef. 9646 if (V2.isUndef()) { 9647 ShiftElts = 0; 9648 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9649 TargetOrder = OriginalOrderLow; 9650 Swap = false; 9651 // Skip if not the correct element or mask of other elements don't equal 9652 // to our expected order. 9653 if (MaskOneElt == VINSERTHSrcElem && 9654 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9655 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9656 FoundCandidate = true; 9657 break; 9658 } 9659 } else { // If both operands are defined. 9660 // Target order is [8,15] if the current mask is between [0,7]. 9661 TargetOrder = 9662 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9663 // Skip if mask of other elements don't equal our expected order. 9664 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9665 // We only need the last 3 bits for the number of shifts. 9666 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9667 : BigEndianShifts[MaskOneElt & 0x7]; 9668 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9669 Swap = MaskOneElt < NumHalfWords; 9670 FoundCandidate = true; 9671 break; 9672 } 9673 } 9674 } 9675 9676 if (!FoundCandidate) 9677 return SDValue(); 9678 9679 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9680 // optionally with VECSHL if shift is required. 9681 if (Swap) 9682 std::swap(V1, V2); 9683 if (V2.isUndef()) 9684 V2 = V1; 9685 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9686 if (ShiftElts) { 9687 // Double ShiftElts because we're left shifting on v16i8 type. 9688 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9689 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9690 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9691 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9692 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9693 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9694 } 9695 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9696 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9697 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9698 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9699 } 9700 9701 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9702 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9703 /// return the default SDValue. 9704 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9705 SelectionDAG &DAG) const { 9706 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9707 // to v16i8. Peek through the bitcasts to get the actual operands. 9708 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9709 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9710 9711 auto ShuffleMask = SVN->getMask(); 9712 SDValue VecShuffle(SVN, 0); 9713 SDLoc DL(SVN); 9714 9715 // Check that we have a four byte shuffle. 9716 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9717 return SDValue(); 9718 9719 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9720 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9721 std::swap(LHS, RHS); 9722 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9723 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9724 } 9725 9726 // Ensure that the RHS is a vector of constants. 9727 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9728 if (!BVN) 9729 return SDValue(); 9730 9731 // Check if RHS is a splat of 4-bytes (or smaller). 9732 APInt APSplatValue, APSplatUndef; 9733 unsigned SplatBitSize; 9734 bool HasAnyUndefs; 9735 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9736 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9737 SplatBitSize > 32) 9738 return SDValue(); 9739 9740 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9741 // The instruction splats a constant C into two words of the source vector 9742 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9743 // Thus we check that the shuffle mask is the equivalent of 9744 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9745 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9746 // within each word are consecutive, so we only need to check the first byte. 9747 SDValue Index; 9748 bool IsLE = Subtarget.isLittleEndian(); 9749 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9750 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9751 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9752 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9753 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9754 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9755 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9756 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9757 else 9758 return SDValue(); 9759 9760 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9761 // for XXSPLTI32DX. 9762 unsigned SplatVal = APSplatValue.getZExtValue(); 9763 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9764 SplatVal |= (SplatVal << SplatBitSize); 9765 9766 SDValue SplatNode = DAG.getNode( 9767 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9768 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9769 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9770 } 9771 9772 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9773 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9774 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9775 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9776 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9777 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9778 assert(Op.getValueType() == MVT::v1i128 && 9779 "Only set v1i128 as custom, other type shouldn't reach here!"); 9780 SDLoc dl(Op); 9781 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9782 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9783 unsigned SHLAmt = N1.getConstantOperandVal(0); 9784 if (SHLAmt % 8 == 0) { 9785 SmallVector<int, 16> Mask(16, 0); 9786 std::iota(Mask.begin(), Mask.end(), 0); 9787 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9788 if (SDValue Shuffle = 9789 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9790 DAG.getUNDEF(MVT::v16i8), Mask)) 9791 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9792 } 9793 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9794 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9795 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9796 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9797 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9798 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9799 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9800 } 9801 9802 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9803 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9804 /// return the code it can be lowered into. Worst case, it can always be 9805 /// lowered into a vperm. 9806 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9807 SelectionDAG &DAG) const { 9808 SDLoc dl(Op); 9809 SDValue V1 = Op.getOperand(0); 9810 SDValue V2 = Op.getOperand(1); 9811 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9812 9813 // Any nodes that were combined in the target-independent combiner prior 9814 // to vector legalization will not be sent to the target combine. Try to 9815 // combine it here. 9816 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9817 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9818 return NewShuffle; 9819 Op = NewShuffle; 9820 SVOp = cast<ShuffleVectorSDNode>(Op); 9821 V1 = Op.getOperand(0); 9822 V2 = Op.getOperand(1); 9823 } 9824 EVT VT = Op.getValueType(); 9825 bool isLittleEndian = Subtarget.isLittleEndian(); 9826 9827 unsigned ShiftElts, InsertAtByte; 9828 bool Swap = false; 9829 9830 // If this is a load-and-splat, we can do that with a single instruction 9831 // in some cases. However if the load has multiple uses, we don't want to 9832 // combine it because that will just produce multiple loads. 9833 bool IsPermutedLoad = false; 9834 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9835 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9836 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9837 InputLoad->hasOneUse()) { 9838 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9839 int SplatIdx = 9840 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9841 9842 // The splat index for permuted loads will be in the left half of the vector 9843 // which is strictly wider than the loaded value by 8 bytes. So we need to 9844 // adjust the splat index to point to the correct address in memory. 9845 if (IsPermutedLoad) { 9846 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9847 SplatIdx += IsFourByte ? 2 : 1; 9848 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9849 "Splat of a value outside of the loaded memory"); 9850 } 9851 9852 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9853 // For 4-byte load-and-splat, we need Power9. 9854 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9855 uint64_t Offset = 0; 9856 if (IsFourByte) 9857 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9858 else 9859 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9860 9861 SDValue BasePtr = LD->getBasePtr(); 9862 if (Offset != 0) 9863 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9864 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9865 SDValue Ops[] = { 9866 LD->getChain(), // Chain 9867 BasePtr, // BasePtr 9868 DAG.getValueType(Op.getValueType()) // VT 9869 }; 9870 SDVTList VTL = 9871 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9872 SDValue LdSplt = 9873 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9874 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9875 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9876 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9877 return LdSplt; 9878 } 9879 } 9880 if (Subtarget.hasP9Vector() && 9881 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9882 isLittleEndian)) { 9883 if (Swap) 9884 std::swap(V1, V2); 9885 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9886 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9887 if (ShiftElts) { 9888 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9889 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9890 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9891 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9892 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9893 } 9894 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9895 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9896 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9897 } 9898 9899 if (Subtarget.hasPrefixInstrs()) { 9900 SDValue SplatInsertNode; 9901 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9902 return SplatInsertNode; 9903 } 9904 9905 if (Subtarget.hasP9Altivec()) { 9906 SDValue NewISDNode; 9907 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9908 return NewISDNode; 9909 9910 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9911 return NewISDNode; 9912 } 9913 9914 if (Subtarget.hasVSX() && 9915 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9916 if (Swap) 9917 std::swap(V1, V2); 9918 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9919 SDValue Conv2 = 9920 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9921 9922 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9923 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9924 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9925 } 9926 9927 if (Subtarget.hasVSX() && 9928 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9929 if (Swap) 9930 std::swap(V1, V2); 9931 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9932 SDValue Conv2 = 9933 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9934 9935 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9936 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9937 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9938 } 9939 9940 if (Subtarget.hasP9Vector()) { 9941 if (PPC::isXXBRHShuffleMask(SVOp)) { 9942 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9943 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9944 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9945 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9946 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9947 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9948 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9949 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9950 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9951 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9952 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9953 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9954 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9955 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9956 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9957 } 9958 } 9959 9960 if (Subtarget.hasVSX()) { 9961 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9962 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9963 9964 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9965 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9966 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9967 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9968 } 9969 9970 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9971 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9972 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9973 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9974 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9975 } 9976 } 9977 9978 // Cases that are handled by instructions that take permute immediates 9979 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9980 // selected by the instruction selector. 9981 if (V2.isUndef()) { 9982 if (PPC::isSplatShuffleMask(SVOp, 1) || 9983 PPC::isSplatShuffleMask(SVOp, 2) || 9984 PPC::isSplatShuffleMask(SVOp, 4) || 9985 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9986 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9987 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9988 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9989 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9990 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9991 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9992 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9993 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9994 (Subtarget.hasP8Altivec() && ( 9995 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9996 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9997 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9998 return Op; 9999 } 10000 } 10001 10002 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10003 // and produce a fixed permutation. If any of these match, do not lower to 10004 // VPERM. 10005 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10006 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10007 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10008 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10009 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10010 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10011 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10012 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10013 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10014 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10015 (Subtarget.hasP8Altivec() && ( 10016 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10017 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10018 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10019 return Op; 10020 10021 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10022 // perfect shuffle table to emit an optimal matching sequence. 10023 ArrayRef<int> PermMask = SVOp->getMask(); 10024 10025 unsigned PFIndexes[4]; 10026 bool isFourElementShuffle = true; 10027 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 10028 unsigned EltNo = 8; // Start out undef. 10029 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10030 if (PermMask[i*4+j] < 0) 10031 continue; // Undef, ignore it. 10032 10033 unsigned ByteSource = PermMask[i*4+j]; 10034 if ((ByteSource & 3) != j) { 10035 isFourElementShuffle = false; 10036 break; 10037 } 10038 10039 if (EltNo == 8) { 10040 EltNo = ByteSource/4; 10041 } else if (EltNo != ByteSource/4) { 10042 isFourElementShuffle = false; 10043 break; 10044 } 10045 } 10046 PFIndexes[i] = EltNo; 10047 } 10048 10049 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10050 // perfect shuffle vector to determine if it is cost effective to do this as 10051 // discrete instructions, or whether we should use a vperm. 10052 // For now, we skip this for little endian until such time as we have a 10053 // little-endian perfect shuffle table. 10054 if (isFourElementShuffle && !isLittleEndian) { 10055 // Compute the index in the perfect shuffle table. 10056 unsigned PFTableIndex = 10057 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10058 10059 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10060 unsigned Cost = (PFEntry >> 30); 10061 10062 // Determining when to avoid vperm is tricky. Many things affect the cost 10063 // of vperm, particularly how many times the perm mask needs to be computed. 10064 // For example, if the perm mask can be hoisted out of a loop or is already 10065 // used (perhaps because there are multiple permutes with the same shuffle 10066 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10067 // the loop requires an extra register. 10068 // 10069 // As a compromise, we only emit discrete instructions if the shuffle can be 10070 // generated in 3 or fewer operations. When we have loop information 10071 // available, if this block is within a loop, we should avoid using vperm 10072 // for 3-operation perms and use a constant pool load instead. 10073 if (Cost < 3) 10074 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10075 } 10076 10077 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10078 // vector that will get spilled to the constant pool. 10079 if (V2.isUndef()) V2 = V1; 10080 10081 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10082 // that it is in input element units, not in bytes. Convert now. 10083 10084 // For little endian, the order of the input vectors is reversed, and 10085 // the permutation mask is complemented with respect to 31. This is 10086 // necessary to produce proper semantics with the big-endian-biased vperm 10087 // instruction. 10088 EVT EltVT = V1.getValueType().getVectorElementType(); 10089 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10090 10091 SmallVector<SDValue, 16> ResultMask; 10092 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10093 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10094 10095 for (unsigned j = 0; j != BytesPerElement; ++j) 10096 if (isLittleEndian) 10097 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10098 dl, MVT::i32)); 10099 else 10100 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10101 MVT::i32)); 10102 } 10103 10104 ShufflesHandledWithVPERM++; 10105 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10106 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10107 LLVM_DEBUG(SVOp->dump()); 10108 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10109 LLVM_DEBUG(VPermMask.dump()); 10110 10111 if (isLittleEndian) 10112 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10113 V2, V1, VPermMask); 10114 else 10115 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10116 V1, V2, VPermMask); 10117 } 10118 10119 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10120 /// vector comparison. If it is, return true and fill in Opc/isDot with 10121 /// information about the intrinsic. 10122 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10123 bool &isDot, const PPCSubtarget &Subtarget) { 10124 unsigned IntrinsicID = 10125 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10126 CompareOpc = -1; 10127 isDot = false; 10128 switch (IntrinsicID) { 10129 default: 10130 return false; 10131 // Comparison predicates. 10132 case Intrinsic::ppc_altivec_vcmpbfp_p: 10133 CompareOpc = 966; 10134 isDot = true; 10135 break; 10136 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10137 CompareOpc = 198; 10138 isDot = true; 10139 break; 10140 case Intrinsic::ppc_altivec_vcmpequb_p: 10141 CompareOpc = 6; 10142 isDot = true; 10143 break; 10144 case Intrinsic::ppc_altivec_vcmpequh_p: 10145 CompareOpc = 70; 10146 isDot = true; 10147 break; 10148 case Intrinsic::ppc_altivec_vcmpequw_p: 10149 CompareOpc = 134; 10150 isDot = true; 10151 break; 10152 case Intrinsic::ppc_altivec_vcmpequd_p: 10153 if (Subtarget.hasP8Altivec()) { 10154 CompareOpc = 199; 10155 isDot = true; 10156 } else 10157 return false; 10158 break; 10159 case Intrinsic::ppc_altivec_vcmpneb_p: 10160 case Intrinsic::ppc_altivec_vcmpneh_p: 10161 case Intrinsic::ppc_altivec_vcmpnew_p: 10162 case Intrinsic::ppc_altivec_vcmpnezb_p: 10163 case Intrinsic::ppc_altivec_vcmpnezh_p: 10164 case Intrinsic::ppc_altivec_vcmpnezw_p: 10165 if (Subtarget.hasP9Altivec()) { 10166 switch (IntrinsicID) { 10167 default: 10168 llvm_unreachable("Unknown comparison intrinsic."); 10169 case Intrinsic::ppc_altivec_vcmpneb_p: 10170 CompareOpc = 7; 10171 break; 10172 case Intrinsic::ppc_altivec_vcmpneh_p: 10173 CompareOpc = 71; 10174 break; 10175 case Intrinsic::ppc_altivec_vcmpnew_p: 10176 CompareOpc = 135; 10177 break; 10178 case Intrinsic::ppc_altivec_vcmpnezb_p: 10179 CompareOpc = 263; 10180 break; 10181 case Intrinsic::ppc_altivec_vcmpnezh_p: 10182 CompareOpc = 327; 10183 break; 10184 case Intrinsic::ppc_altivec_vcmpnezw_p: 10185 CompareOpc = 391; 10186 break; 10187 } 10188 isDot = true; 10189 } else 10190 return false; 10191 break; 10192 case Intrinsic::ppc_altivec_vcmpgefp_p: 10193 CompareOpc = 454; 10194 isDot = true; 10195 break; 10196 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10197 CompareOpc = 710; 10198 isDot = true; 10199 break; 10200 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10201 CompareOpc = 774; 10202 isDot = true; 10203 break; 10204 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10205 CompareOpc = 838; 10206 isDot = true; 10207 break; 10208 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10209 CompareOpc = 902; 10210 isDot = true; 10211 break; 10212 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10213 if (Subtarget.hasP8Altivec()) { 10214 CompareOpc = 967; 10215 isDot = true; 10216 } else 10217 return false; 10218 break; 10219 case Intrinsic::ppc_altivec_vcmpgtub_p: 10220 CompareOpc = 518; 10221 isDot = true; 10222 break; 10223 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10224 CompareOpc = 582; 10225 isDot = true; 10226 break; 10227 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10228 CompareOpc = 646; 10229 isDot = true; 10230 break; 10231 case Intrinsic::ppc_altivec_vcmpgtud_p: 10232 if (Subtarget.hasP8Altivec()) { 10233 CompareOpc = 711; 10234 isDot = true; 10235 } else 10236 return false; 10237 break; 10238 10239 case Intrinsic::ppc_altivec_vcmpequq: 10240 case Intrinsic::ppc_altivec_vcmpgtsq: 10241 case Intrinsic::ppc_altivec_vcmpgtuq: 10242 if (!Subtarget.isISA3_1()) 10243 return false; 10244 switch (IntrinsicID) { 10245 default: 10246 llvm_unreachable("Unknown comparison intrinsic."); 10247 case Intrinsic::ppc_altivec_vcmpequq: 10248 CompareOpc = 455; 10249 break; 10250 case Intrinsic::ppc_altivec_vcmpgtsq: 10251 CompareOpc = 903; 10252 break; 10253 case Intrinsic::ppc_altivec_vcmpgtuq: 10254 CompareOpc = 647; 10255 break; 10256 } 10257 break; 10258 10259 // VSX predicate comparisons use the same infrastructure 10260 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10261 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10262 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10263 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10264 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10265 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10266 if (Subtarget.hasVSX()) { 10267 switch (IntrinsicID) { 10268 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10269 CompareOpc = 99; 10270 break; 10271 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10272 CompareOpc = 115; 10273 break; 10274 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10275 CompareOpc = 107; 10276 break; 10277 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10278 CompareOpc = 67; 10279 break; 10280 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10281 CompareOpc = 83; 10282 break; 10283 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10284 CompareOpc = 75; 10285 break; 10286 } 10287 isDot = true; 10288 } else 10289 return false; 10290 break; 10291 10292 // Normal Comparisons. 10293 case Intrinsic::ppc_altivec_vcmpbfp: 10294 CompareOpc = 966; 10295 break; 10296 case Intrinsic::ppc_altivec_vcmpeqfp: 10297 CompareOpc = 198; 10298 break; 10299 case Intrinsic::ppc_altivec_vcmpequb: 10300 CompareOpc = 6; 10301 break; 10302 case Intrinsic::ppc_altivec_vcmpequh: 10303 CompareOpc = 70; 10304 break; 10305 case Intrinsic::ppc_altivec_vcmpequw: 10306 CompareOpc = 134; 10307 break; 10308 case Intrinsic::ppc_altivec_vcmpequd: 10309 if (Subtarget.hasP8Altivec()) 10310 CompareOpc = 199; 10311 else 10312 return false; 10313 break; 10314 case Intrinsic::ppc_altivec_vcmpneb: 10315 case Intrinsic::ppc_altivec_vcmpneh: 10316 case Intrinsic::ppc_altivec_vcmpnew: 10317 case Intrinsic::ppc_altivec_vcmpnezb: 10318 case Intrinsic::ppc_altivec_vcmpnezh: 10319 case Intrinsic::ppc_altivec_vcmpnezw: 10320 if (Subtarget.hasP9Altivec()) 10321 switch (IntrinsicID) { 10322 default: 10323 llvm_unreachable("Unknown comparison intrinsic."); 10324 case Intrinsic::ppc_altivec_vcmpneb: 10325 CompareOpc = 7; 10326 break; 10327 case Intrinsic::ppc_altivec_vcmpneh: 10328 CompareOpc = 71; 10329 break; 10330 case Intrinsic::ppc_altivec_vcmpnew: 10331 CompareOpc = 135; 10332 break; 10333 case Intrinsic::ppc_altivec_vcmpnezb: 10334 CompareOpc = 263; 10335 break; 10336 case Intrinsic::ppc_altivec_vcmpnezh: 10337 CompareOpc = 327; 10338 break; 10339 case Intrinsic::ppc_altivec_vcmpnezw: 10340 CompareOpc = 391; 10341 break; 10342 } 10343 else 10344 return false; 10345 break; 10346 case Intrinsic::ppc_altivec_vcmpgefp: 10347 CompareOpc = 454; 10348 break; 10349 case Intrinsic::ppc_altivec_vcmpgtfp: 10350 CompareOpc = 710; 10351 break; 10352 case Intrinsic::ppc_altivec_vcmpgtsb: 10353 CompareOpc = 774; 10354 break; 10355 case Intrinsic::ppc_altivec_vcmpgtsh: 10356 CompareOpc = 838; 10357 break; 10358 case Intrinsic::ppc_altivec_vcmpgtsw: 10359 CompareOpc = 902; 10360 break; 10361 case Intrinsic::ppc_altivec_vcmpgtsd: 10362 if (Subtarget.hasP8Altivec()) 10363 CompareOpc = 967; 10364 else 10365 return false; 10366 break; 10367 case Intrinsic::ppc_altivec_vcmpgtub: 10368 CompareOpc = 518; 10369 break; 10370 case Intrinsic::ppc_altivec_vcmpgtuh: 10371 CompareOpc = 582; 10372 break; 10373 case Intrinsic::ppc_altivec_vcmpgtuw: 10374 CompareOpc = 646; 10375 break; 10376 case Intrinsic::ppc_altivec_vcmpgtud: 10377 if (Subtarget.hasP8Altivec()) 10378 CompareOpc = 711; 10379 else 10380 return false; 10381 break; 10382 case Intrinsic::ppc_altivec_vcmpequq_p: 10383 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10384 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10385 if (!Subtarget.isISA3_1()) 10386 return false; 10387 switch (IntrinsicID) { 10388 default: 10389 llvm_unreachable("Unknown comparison intrinsic."); 10390 case Intrinsic::ppc_altivec_vcmpequq_p: 10391 CompareOpc = 455; 10392 break; 10393 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10394 CompareOpc = 903; 10395 break; 10396 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10397 CompareOpc = 647; 10398 break; 10399 } 10400 isDot = true; 10401 break; 10402 } 10403 return true; 10404 } 10405 10406 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10407 /// lower, do it, otherwise return null. 10408 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10409 SelectionDAG &DAG) const { 10410 unsigned IntrinsicID = 10411 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10412 10413 SDLoc dl(Op); 10414 10415 if (IntrinsicID == Intrinsic::thread_pointer) { 10416 // Reads the thread pointer register, used for __builtin_thread_pointer. 10417 if (Subtarget.isPPC64()) 10418 return DAG.getRegister(PPC::X13, MVT::i64); 10419 return DAG.getRegister(PPC::R2, MVT::i32); 10420 } 10421 10422 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10423 // opcode number of the comparison. 10424 int CompareOpc; 10425 bool isDot; 10426 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10427 return SDValue(); // Don't custom lower most intrinsics. 10428 10429 // If this is a non-dot comparison, make the VCMP node and we are done. 10430 if (!isDot) { 10431 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10432 Op.getOperand(1), Op.getOperand(2), 10433 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10434 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10435 } 10436 10437 // Create the PPCISD altivec 'dot' comparison node. 10438 SDValue Ops[] = { 10439 Op.getOperand(2), // LHS 10440 Op.getOperand(3), // RHS 10441 DAG.getConstant(CompareOpc, dl, MVT::i32) 10442 }; 10443 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10444 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10445 10446 // Now that we have the comparison, emit a copy from the CR to a GPR. 10447 // This is flagged to the above dot comparison. 10448 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10449 DAG.getRegister(PPC::CR6, MVT::i32), 10450 CompNode.getValue(1)); 10451 10452 // Unpack the result based on how the target uses it. 10453 unsigned BitNo; // Bit # of CR6. 10454 bool InvertBit; // Invert result? 10455 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10456 default: // Can't happen, don't crash on invalid number though. 10457 case 0: // Return the value of the EQ bit of CR6. 10458 BitNo = 0; InvertBit = false; 10459 break; 10460 case 1: // Return the inverted value of the EQ bit of CR6. 10461 BitNo = 0; InvertBit = true; 10462 break; 10463 case 2: // Return the value of the LT bit of CR6. 10464 BitNo = 2; InvertBit = false; 10465 break; 10466 case 3: // Return the inverted value of the LT bit of CR6. 10467 BitNo = 2; InvertBit = true; 10468 break; 10469 } 10470 10471 // Shift the bit into the low position. 10472 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10473 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10474 // Isolate the bit. 10475 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10476 DAG.getConstant(1, dl, MVT::i32)); 10477 10478 // If we are supposed to, toggle the bit. 10479 if (InvertBit) 10480 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10481 DAG.getConstant(1, dl, MVT::i32)); 10482 return Flags; 10483 } 10484 10485 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10486 SelectionDAG &DAG) const { 10487 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10488 // the beginning of the argument list. 10489 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10490 SDLoc DL(Op); 10491 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10492 case Intrinsic::ppc_cfence: { 10493 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10494 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10495 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10496 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10497 Op.getOperand(ArgStart + 1)), 10498 Op.getOperand(0)), 10499 0); 10500 } 10501 default: 10502 break; 10503 } 10504 return SDValue(); 10505 } 10506 10507 // Lower scalar BSWAP64 to xxbrd. 10508 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10509 SDLoc dl(Op); 10510 // MTVSRDD 10511 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10512 Op.getOperand(0)); 10513 // XXBRD 10514 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10515 // MFVSRD 10516 int VectorIndex = 0; 10517 if (Subtarget.isLittleEndian()) 10518 VectorIndex = 1; 10519 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10520 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10521 return Op; 10522 } 10523 10524 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10525 // compared to a value that is atomically loaded (atomic loads zero-extend). 10526 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10527 SelectionDAG &DAG) const { 10528 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10529 "Expecting an atomic compare-and-swap here."); 10530 SDLoc dl(Op); 10531 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10532 EVT MemVT = AtomicNode->getMemoryVT(); 10533 if (MemVT.getSizeInBits() >= 32) 10534 return Op; 10535 10536 SDValue CmpOp = Op.getOperand(2); 10537 // If this is already correctly zero-extended, leave it alone. 10538 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10539 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10540 return Op; 10541 10542 // Clear the high bits of the compare operand. 10543 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10544 SDValue NewCmpOp = 10545 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10546 DAG.getConstant(MaskVal, dl, MVT::i32)); 10547 10548 // Replace the existing compare operand with the properly zero-extended one. 10549 SmallVector<SDValue, 4> Ops; 10550 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10551 Ops.push_back(AtomicNode->getOperand(i)); 10552 Ops[2] = NewCmpOp; 10553 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10554 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10555 auto NodeTy = 10556 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10557 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10558 } 10559 10560 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10561 SelectionDAG &DAG) const { 10562 SDLoc dl(Op); 10563 // Create a stack slot that is 16-byte aligned. 10564 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10565 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10566 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10567 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10568 10569 // Store the input value into Value#0 of the stack slot. 10570 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10571 MachinePointerInfo()); 10572 // Load it out. 10573 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10574 } 10575 10576 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10577 SelectionDAG &DAG) const { 10578 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10579 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10580 10581 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10582 // We have legal lowering for constant indices but not for variable ones. 10583 if (!C) 10584 return SDValue(); 10585 10586 EVT VT = Op.getValueType(); 10587 SDLoc dl(Op); 10588 SDValue V1 = Op.getOperand(0); 10589 SDValue V2 = Op.getOperand(1); 10590 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10591 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10592 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10593 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10594 unsigned InsertAtElement = C->getZExtValue(); 10595 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10596 if (Subtarget.isLittleEndian()) { 10597 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10598 } 10599 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10600 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10601 } 10602 return Op; 10603 } 10604 10605 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10606 SelectionDAG &DAG) const { 10607 SDLoc dl(Op); 10608 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10609 SDValue LoadChain = LN->getChain(); 10610 SDValue BasePtr = LN->getBasePtr(); 10611 EVT VT = Op.getValueType(); 10612 10613 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10614 return Op; 10615 10616 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10617 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10618 // 2 or 4 vsx registers. 10619 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10620 "Type unsupported without MMA"); 10621 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10622 "Type unsupported without paired vector support"); 10623 Align Alignment = LN->getAlign(); 10624 SmallVector<SDValue, 4> Loads; 10625 SmallVector<SDValue, 4> LoadChains; 10626 unsigned NumVecs = VT.getSizeInBits() / 128; 10627 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10628 SDValue Load = 10629 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10630 LN->getPointerInfo().getWithOffset(Idx * 16), 10631 commonAlignment(Alignment, Idx * 16), 10632 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10633 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10634 DAG.getConstant(16, dl, BasePtr.getValueType())); 10635 Loads.push_back(Load); 10636 LoadChains.push_back(Load.getValue(1)); 10637 } 10638 if (Subtarget.isLittleEndian()) { 10639 std::reverse(Loads.begin(), Loads.end()); 10640 std::reverse(LoadChains.begin(), LoadChains.end()); 10641 } 10642 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10643 SDValue Value = 10644 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10645 dl, VT, Loads); 10646 SDValue RetOps[] = {Value, TF}; 10647 return DAG.getMergeValues(RetOps, dl); 10648 } 10649 10650 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10651 SelectionDAG &DAG) const { 10652 SDLoc dl(Op); 10653 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10654 SDValue StoreChain = SN->getChain(); 10655 SDValue BasePtr = SN->getBasePtr(); 10656 SDValue Value = SN->getValue(); 10657 EVT StoreVT = Value.getValueType(); 10658 10659 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10660 return Op; 10661 10662 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10663 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10664 // underlying registers individually. 10665 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10666 "Type unsupported without MMA"); 10667 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10668 "Type unsupported without paired vector support"); 10669 Align Alignment = SN->getAlign(); 10670 SmallVector<SDValue, 4> Stores; 10671 unsigned NumVecs = 2; 10672 if (StoreVT == MVT::v512i1) { 10673 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10674 NumVecs = 4; 10675 } 10676 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10677 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10678 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10679 DAG.getConstant(VecNum, dl, MVT::i64)); 10680 SDValue Store = 10681 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10682 SN->getPointerInfo().getWithOffset(Idx * 16), 10683 commonAlignment(Alignment, Idx * 16), 10684 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10685 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10686 DAG.getConstant(16, dl, BasePtr.getValueType())); 10687 Stores.push_back(Store); 10688 } 10689 SDValue TF = DAG.getTokenFactor(dl, Stores); 10690 return TF; 10691 } 10692 10693 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10694 SDLoc dl(Op); 10695 if (Op.getValueType() == MVT::v4i32) { 10696 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10697 10698 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10699 // +16 as shift amt. 10700 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10701 SDValue RHSSwap = // = vrlw RHS, 16 10702 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10703 10704 // Shrinkify inputs to v8i16. 10705 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10706 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10707 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10708 10709 // Low parts multiplied together, generating 32-bit results (we ignore the 10710 // top parts). 10711 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10712 LHS, RHS, DAG, dl, MVT::v4i32); 10713 10714 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10715 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10716 // Shift the high parts up 16 bits. 10717 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10718 Neg16, DAG, dl); 10719 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10720 } else if (Op.getValueType() == MVT::v16i8) { 10721 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10722 bool isLittleEndian = Subtarget.isLittleEndian(); 10723 10724 // Multiply the even 8-bit parts, producing 16-bit sums. 10725 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10726 LHS, RHS, DAG, dl, MVT::v8i16); 10727 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10728 10729 // Multiply the odd 8-bit parts, producing 16-bit sums. 10730 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10731 LHS, RHS, DAG, dl, MVT::v8i16); 10732 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10733 10734 // Merge the results together. Because vmuleub and vmuloub are 10735 // instructions with a big-endian bias, we must reverse the 10736 // element numbering and reverse the meaning of "odd" and "even" 10737 // when generating little endian code. 10738 int Ops[16]; 10739 for (unsigned i = 0; i != 8; ++i) { 10740 if (isLittleEndian) { 10741 Ops[i*2 ] = 2*i; 10742 Ops[i*2+1] = 2*i+16; 10743 } else { 10744 Ops[i*2 ] = 2*i+1; 10745 Ops[i*2+1] = 2*i+1+16; 10746 } 10747 } 10748 if (isLittleEndian) 10749 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10750 else 10751 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10752 } else { 10753 llvm_unreachable("Unknown mul to lower!"); 10754 } 10755 } 10756 10757 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10758 10759 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10760 10761 EVT VT = Op.getValueType(); 10762 assert(VT.isVector() && 10763 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10764 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10765 VT == MVT::v16i8) && 10766 "Unexpected vector element type!"); 10767 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10768 "Current subtarget doesn't support smax v2i64!"); 10769 10770 // For vector abs, it can be lowered to: 10771 // abs x 10772 // ==> 10773 // y = -x 10774 // smax(x, y) 10775 10776 SDLoc dl(Op); 10777 SDValue X = Op.getOperand(0); 10778 SDValue Zero = DAG.getConstant(0, dl, VT); 10779 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10780 10781 // SMAX patch https://reviews.llvm.org/D47332 10782 // hasn't landed yet, so use intrinsic first here. 10783 // TODO: Should use SMAX directly once SMAX patch landed 10784 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10785 if (VT == MVT::v2i64) 10786 BifID = Intrinsic::ppc_altivec_vmaxsd; 10787 else if (VT == MVT::v8i16) 10788 BifID = Intrinsic::ppc_altivec_vmaxsh; 10789 else if (VT == MVT::v16i8) 10790 BifID = Intrinsic::ppc_altivec_vmaxsb; 10791 10792 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10793 } 10794 10795 // Custom lowering for fpext vf32 to v2f64 10796 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10797 10798 assert(Op.getOpcode() == ISD::FP_EXTEND && 10799 "Should only be called for ISD::FP_EXTEND"); 10800 10801 // FIXME: handle extends from half precision float vectors on P9. 10802 // We only want to custom lower an extend from v2f32 to v2f64. 10803 if (Op.getValueType() != MVT::v2f64 || 10804 Op.getOperand(0).getValueType() != MVT::v2f32) 10805 return SDValue(); 10806 10807 SDLoc dl(Op); 10808 SDValue Op0 = Op.getOperand(0); 10809 10810 switch (Op0.getOpcode()) { 10811 default: 10812 return SDValue(); 10813 case ISD::EXTRACT_SUBVECTOR: { 10814 assert(Op0.getNumOperands() == 2 && 10815 isa<ConstantSDNode>(Op0->getOperand(1)) && 10816 "Node should have 2 operands with second one being a constant!"); 10817 10818 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10819 return SDValue(); 10820 10821 // Custom lower is only done for high or low doubleword. 10822 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10823 if (Idx % 2 != 0) 10824 return SDValue(); 10825 10826 // Since input is v4f32, at this point Idx is either 0 or 2. 10827 // Shift to get the doubleword position we want. 10828 int DWord = Idx >> 1; 10829 10830 // High and low word positions are different on little endian. 10831 if (Subtarget.isLittleEndian()) 10832 DWord ^= 0x1; 10833 10834 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10835 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10836 } 10837 case ISD::FADD: 10838 case ISD::FMUL: 10839 case ISD::FSUB: { 10840 SDValue NewLoad[2]; 10841 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10842 // Ensure both input are loads. 10843 SDValue LdOp = Op0.getOperand(i); 10844 if (LdOp.getOpcode() != ISD::LOAD) 10845 return SDValue(); 10846 // Generate new load node. 10847 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10848 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10849 NewLoad[i] = DAG.getMemIntrinsicNode( 10850 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10851 LD->getMemoryVT(), LD->getMemOperand()); 10852 } 10853 SDValue NewOp = 10854 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10855 NewLoad[1], Op0.getNode()->getFlags()); 10856 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10857 DAG.getConstant(0, dl, MVT::i32)); 10858 } 10859 case ISD::LOAD: { 10860 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10861 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10862 SDValue NewLd = DAG.getMemIntrinsicNode( 10863 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10864 LD->getMemoryVT(), LD->getMemOperand()); 10865 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10866 DAG.getConstant(0, dl, MVT::i32)); 10867 } 10868 } 10869 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10870 } 10871 10872 /// LowerOperation - Provide custom lowering hooks for some operations. 10873 /// 10874 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10875 switch (Op.getOpcode()) { 10876 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10877 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10878 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10879 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10880 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10881 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10882 case ISD::SETCC: return LowerSETCC(Op, DAG); 10883 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10884 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10885 10886 // Variable argument lowering. 10887 case ISD::VASTART: return LowerVASTART(Op, DAG); 10888 case ISD::VAARG: return LowerVAARG(Op, DAG); 10889 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10890 10891 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10892 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10893 case ISD::GET_DYNAMIC_AREA_OFFSET: 10894 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10895 10896 // Exception handling lowering. 10897 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10898 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10899 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10900 10901 case ISD::LOAD: return LowerLOAD(Op, DAG); 10902 case ISD::STORE: return LowerSTORE(Op, DAG); 10903 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10904 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10905 case ISD::STRICT_FP_TO_UINT: 10906 case ISD::STRICT_FP_TO_SINT: 10907 case ISD::FP_TO_UINT: 10908 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10909 case ISD::STRICT_UINT_TO_FP: 10910 case ISD::STRICT_SINT_TO_FP: 10911 case ISD::UINT_TO_FP: 10912 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10913 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10914 10915 // Lower 64-bit shifts. 10916 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10917 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10918 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10919 10920 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10921 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10922 10923 // Vector-related lowering. 10924 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10925 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10926 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10927 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10928 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10929 case ISD::MUL: return LowerMUL(Op, DAG); 10930 case ISD::ABS: return LowerABS(Op, DAG); 10931 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10932 case ISD::ROTL: return LowerROTL(Op, DAG); 10933 10934 // For counter-based loop handling. 10935 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10936 10937 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10938 10939 // Frame & Return address. 10940 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10941 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10942 10943 case ISD::INTRINSIC_VOID: 10944 return LowerINTRINSIC_VOID(Op, DAG); 10945 case ISD::BSWAP: 10946 return LowerBSWAP(Op, DAG); 10947 case ISD::ATOMIC_CMP_SWAP: 10948 return LowerATOMIC_CMP_SWAP(Op, DAG); 10949 } 10950 } 10951 10952 void PPCTargetLowering::LowerOperationWrapper(SDNode *N, 10953 SmallVectorImpl<SDValue> &Results, 10954 SelectionDAG &DAG) const { 10955 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10956 10957 if (!Res.getNode()) 10958 return; 10959 10960 // Take the return value as-is if original node has only one result. 10961 if (N->getNumValues() == 1) { 10962 Results.push_back(Res); 10963 return; 10964 } 10965 10966 // New node should have the same number of results. 10967 assert((N->getNumValues() == Res->getNumValues()) && 10968 "Lowering returned the wrong number of results!"); 10969 10970 for (unsigned i = 0; i < N->getNumValues(); ++i) 10971 Results.push_back(Res.getValue(i)); 10972 } 10973 10974 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10975 SmallVectorImpl<SDValue>&Results, 10976 SelectionDAG &DAG) const { 10977 SDLoc dl(N); 10978 switch (N->getOpcode()) { 10979 default: 10980 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10981 case ISD::READCYCLECOUNTER: { 10982 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10983 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10984 10985 Results.push_back( 10986 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10987 Results.push_back(RTB.getValue(2)); 10988 break; 10989 } 10990 case ISD::INTRINSIC_W_CHAIN: { 10991 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10992 Intrinsic::loop_decrement) 10993 break; 10994 10995 assert(N->getValueType(0) == MVT::i1 && 10996 "Unexpected result type for CTR decrement intrinsic"); 10997 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10998 N->getValueType(0)); 10999 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11000 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11001 N->getOperand(1)); 11002 11003 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11004 Results.push_back(NewInt.getValue(1)); 11005 break; 11006 } 11007 case ISD::VAARG: { 11008 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11009 return; 11010 11011 EVT VT = N->getValueType(0); 11012 11013 if (VT == MVT::i64) { 11014 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11015 11016 Results.push_back(NewNode); 11017 Results.push_back(NewNode.getValue(1)); 11018 } 11019 return; 11020 } 11021 case ISD::STRICT_FP_TO_SINT: 11022 case ISD::STRICT_FP_TO_UINT: 11023 case ISD::FP_TO_SINT: 11024 case ISD::FP_TO_UINT: 11025 // LowerFP_TO_INT() can only handle f32 and f64. 11026 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11027 MVT::ppcf128) 11028 return; 11029 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 11030 return; 11031 case ISD::TRUNCATE: { 11032 if (!N->getValueType(0).isVector()) 11033 return; 11034 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11035 if (Lowered) 11036 Results.push_back(Lowered); 11037 return; 11038 } 11039 case ISD::BITCAST: 11040 // Don't handle bitcast here. 11041 return; 11042 case ISD::FP_EXTEND: 11043 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11044 if (Lowered) 11045 Results.push_back(Lowered); 11046 return; 11047 } 11048 } 11049 11050 //===----------------------------------------------------------------------===// 11051 // Other Lowering Code 11052 //===----------------------------------------------------------------------===// 11053 11054 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 11055 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11056 Function *Func = Intrinsic::getDeclaration(M, Id); 11057 return Builder.CreateCall(Func, {}); 11058 } 11059 11060 // The mappings for emitLeading/TrailingFence is taken from 11061 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11062 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11063 Instruction *Inst, 11064 AtomicOrdering Ord) const { 11065 if (Ord == AtomicOrdering::SequentiallyConsistent) 11066 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11067 if (isReleaseOrStronger(Ord)) 11068 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11069 return nullptr; 11070 } 11071 11072 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11073 Instruction *Inst, 11074 AtomicOrdering Ord) const { 11075 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11076 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11077 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11078 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11079 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11080 return Builder.CreateCall( 11081 Intrinsic::getDeclaration( 11082 Builder.GetInsertBlock()->getParent()->getParent(), 11083 Intrinsic::ppc_cfence, {Inst->getType()}), 11084 {Inst}); 11085 // FIXME: Can use isync for rmw operation. 11086 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11087 } 11088 return nullptr; 11089 } 11090 11091 MachineBasicBlock * 11092 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11093 unsigned AtomicSize, 11094 unsigned BinOpcode, 11095 unsigned CmpOpcode, 11096 unsigned CmpPred) const { 11097 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11098 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11099 11100 auto LoadMnemonic = PPC::LDARX; 11101 auto StoreMnemonic = PPC::STDCX; 11102 switch (AtomicSize) { 11103 default: 11104 llvm_unreachable("Unexpected size of atomic entity"); 11105 case 1: 11106 LoadMnemonic = PPC::LBARX; 11107 StoreMnemonic = PPC::STBCX; 11108 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11109 break; 11110 case 2: 11111 LoadMnemonic = PPC::LHARX; 11112 StoreMnemonic = PPC::STHCX; 11113 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11114 break; 11115 case 4: 11116 LoadMnemonic = PPC::LWARX; 11117 StoreMnemonic = PPC::STWCX; 11118 break; 11119 case 8: 11120 LoadMnemonic = PPC::LDARX; 11121 StoreMnemonic = PPC::STDCX; 11122 break; 11123 } 11124 11125 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11126 MachineFunction *F = BB->getParent(); 11127 MachineFunction::iterator It = ++BB->getIterator(); 11128 11129 Register dest = MI.getOperand(0).getReg(); 11130 Register ptrA = MI.getOperand(1).getReg(); 11131 Register ptrB = MI.getOperand(2).getReg(); 11132 Register incr = MI.getOperand(3).getReg(); 11133 DebugLoc dl = MI.getDebugLoc(); 11134 11135 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11136 MachineBasicBlock *loop2MBB = 11137 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11138 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11139 F->insert(It, loopMBB); 11140 if (CmpOpcode) 11141 F->insert(It, loop2MBB); 11142 F->insert(It, exitMBB); 11143 exitMBB->splice(exitMBB->begin(), BB, 11144 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11145 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11146 11147 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11148 Register TmpReg = (!BinOpcode) ? incr : 11149 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11150 : &PPC::GPRCRegClass); 11151 11152 // thisMBB: 11153 // ... 11154 // fallthrough --> loopMBB 11155 BB->addSuccessor(loopMBB); 11156 11157 // loopMBB: 11158 // l[wd]arx dest, ptr 11159 // add r0, dest, incr 11160 // st[wd]cx. r0, ptr 11161 // bne- loopMBB 11162 // fallthrough --> exitMBB 11163 11164 // For max/min... 11165 // loopMBB: 11166 // l[wd]arx dest, ptr 11167 // cmpl?[wd] incr, dest 11168 // bgt exitMBB 11169 // loop2MBB: 11170 // st[wd]cx. dest, ptr 11171 // bne- loopMBB 11172 // fallthrough --> exitMBB 11173 11174 BB = loopMBB; 11175 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11176 .addReg(ptrA).addReg(ptrB); 11177 if (BinOpcode) 11178 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11179 if (CmpOpcode) { 11180 // Signed comparisons of byte or halfword values must be sign-extended. 11181 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11182 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11183 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11184 ExtReg).addReg(dest); 11185 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11186 .addReg(incr).addReg(ExtReg); 11187 } else 11188 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11189 .addReg(incr).addReg(dest); 11190 11191 BuildMI(BB, dl, TII->get(PPC::BCC)) 11192 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11193 BB->addSuccessor(loop2MBB); 11194 BB->addSuccessor(exitMBB); 11195 BB = loop2MBB; 11196 } 11197 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11198 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11199 BuildMI(BB, dl, TII->get(PPC::BCC)) 11200 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11201 BB->addSuccessor(loopMBB); 11202 BB->addSuccessor(exitMBB); 11203 11204 // exitMBB: 11205 // ... 11206 BB = exitMBB; 11207 return BB; 11208 } 11209 11210 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11211 MachineInstr &MI, MachineBasicBlock *BB, 11212 bool is8bit, // operation 11213 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11214 // If we support part-word atomic mnemonics, just use them 11215 if (Subtarget.hasPartwordAtomics()) 11216 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11217 CmpPred); 11218 11219 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11220 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11221 // In 64 bit mode we have to use 64 bits for addresses, even though the 11222 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11223 // registers without caring whether they're 32 or 64, but here we're 11224 // doing actual arithmetic on the addresses. 11225 bool is64bit = Subtarget.isPPC64(); 11226 bool isLittleEndian = Subtarget.isLittleEndian(); 11227 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11228 11229 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11230 MachineFunction *F = BB->getParent(); 11231 MachineFunction::iterator It = ++BB->getIterator(); 11232 11233 Register dest = MI.getOperand(0).getReg(); 11234 Register ptrA = MI.getOperand(1).getReg(); 11235 Register ptrB = MI.getOperand(2).getReg(); 11236 Register incr = MI.getOperand(3).getReg(); 11237 DebugLoc dl = MI.getDebugLoc(); 11238 11239 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11240 MachineBasicBlock *loop2MBB = 11241 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11242 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11243 F->insert(It, loopMBB); 11244 if (CmpOpcode) 11245 F->insert(It, loop2MBB); 11246 F->insert(It, exitMBB); 11247 exitMBB->splice(exitMBB->begin(), BB, 11248 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11249 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11250 11251 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11252 const TargetRegisterClass *RC = 11253 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11254 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11255 11256 Register PtrReg = RegInfo.createVirtualRegister(RC); 11257 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11258 Register ShiftReg = 11259 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11260 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11261 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11262 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11263 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11264 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11265 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11266 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11267 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11268 Register Ptr1Reg; 11269 Register TmpReg = 11270 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11271 11272 // thisMBB: 11273 // ... 11274 // fallthrough --> loopMBB 11275 BB->addSuccessor(loopMBB); 11276 11277 // The 4-byte load must be aligned, while a char or short may be 11278 // anywhere in the word. Hence all this nasty bookkeeping code. 11279 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11280 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11281 // xori shift, shift1, 24 [16] 11282 // rlwinm ptr, ptr1, 0, 0, 29 11283 // slw incr2, incr, shift 11284 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11285 // slw mask, mask2, shift 11286 // loopMBB: 11287 // lwarx tmpDest, ptr 11288 // add tmp, tmpDest, incr2 11289 // andc tmp2, tmpDest, mask 11290 // and tmp3, tmp, mask 11291 // or tmp4, tmp3, tmp2 11292 // stwcx. tmp4, ptr 11293 // bne- loopMBB 11294 // fallthrough --> exitMBB 11295 // srw dest, tmpDest, shift 11296 if (ptrA != ZeroReg) { 11297 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11298 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11299 .addReg(ptrA) 11300 .addReg(ptrB); 11301 } else { 11302 Ptr1Reg = ptrB; 11303 } 11304 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11305 // mode. 11306 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11307 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11308 .addImm(3) 11309 .addImm(27) 11310 .addImm(is8bit ? 28 : 27); 11311 if (!isLittleEndian) 11312 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11313 .addReg(Shift1Reg) 11314 .addImm(is8bit ? 24 : 16); 11315 if (is64bit) 11316 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11317 .addReg(Ptr1Reg) 11318 .addImm(0) 11319 .addImm(61); 11320 else 11321 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11322 .addReg(Ptr1Reg) 11323 .addImm(0) 11324 .addImm(0) 11325 .addImm(29); 11326 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11327 if (is8bit) 11328 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11329 else { 11330 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11331 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11332 .addReg(Mask3Reg) 11333 .addImm(65535); 11334 } 11335 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11336 .addReg(Mask2Reg) 11337 .addReg(ShiftReg); 11338 11339 BB = loopMBB; 11340 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11341 .addReg(ZeroReg) 11342 .addReg(PtrReg); 11343 if (BinOpcode) 11344 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11345 .addReg(Incr2Reg) 11346 .addReg(TmpDestReg); 11347 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11348 .addReg(TmpDestReg) 11349 .addReg(MaskReg); 11350 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11351 if (CmpOpcode) { 11352 // For unsigned comparisons, we can directly compare the shifted values. 11353 // For signed comparisons we shift and sign extend. 11354 Register SReg = RegInfo.createVirtualRegister(GPRC); 11355 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11356 .addReg(TmpDestReg) 11357 .addReg(MaskReg); 11358 unsigned ValueReg = SReg; 11359 unsigned CmpReg = Incr2Reg; 11360 if (CmpOpcode == PPC::CMPW) { 11361 ValueReg = RegInfo.createVirtualRegister(GPRC); 11362 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11363 .addReg(SReg) 11364 .addReg(ShiftReg); 11365 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11366 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11367 .addReg(ValueReg); 11368 ValueReg = ValueSReg; 11369 CmpReg = incr; 11370 } 11371 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11372 .addReg(CmpReg) 11373 .addReg(ValueReg); 11374 BuildMI(BB, dl, TII->get(PPC::BCC)) 11375 .addImm(CmpPred) 11376 .addReg(PPC::CR0) 11377 .addMBB(exitMBB); 11378 BB->addSuccessor(loop2MBB); 11379 BB->addSuccessor(exitMBB); 11380 BB = loop2MBB; 11381 } 11382 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11383 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11384 .addReg(Tmp4Reg) 11385 .addReg(ZeroReg) 11386 .addReg(PtrReg); 11387 BuildMI(BB, dl, TII->get(PPC::BCC)) 11388 .addImm(PPC::PRED_NE) 11389 .addReg(PPC::CR0) 11390 .addMBB(loopMBB); 11391 BB->addSuccessor(loopMBB); 11392 BB->addSuccessor(exitMBB); 11393 11394 // exitMBB: 11395 // ... 11396 BB = exitMBB; 11397 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11398 .addReg(TmpDestReg) 11399 .addReg(ShiftReg); 11400 return BB; 11401 } 11402 11403 llvm::MachineBasicBlock * 11404 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11405 MachineBasicBlock *MBB) const { 11406 DebugLoc DL = MI.getDebugLoc(); 11407 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11408 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11409 11410 MachineFunction *MF = MBB->getParent(); 11411 MachineRegisterInfo &MRI = MF->getRegInfo(); 11412 11413 const BasicBlock *BB = MBB->getBasicBlock(); 11414 MachineFunction::iterator I = ++MBB->getIterator(); 11415 11416 Register DstReg = MI.getOperand(0).getReg(); 11417 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11418 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11419 Register mainDstReg = MRI.createVirtualRegister(RC); 11420 Register restoreDstReg = MRI.createVirtualRegister(RC); 11421 11422 MVT PVT = getPointerTy(MF->getDataLayout()); 11423 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11424 "Invalid Pointer Size!"); 11425 // For v = setjmp(buf), we generate 11426 // 11427 // thisMBB: 11428 // SjLjSetup mainMBB 11429 // bl mainMBB 11430 // v_restore = 1 11431 // b sinkMBB 11432 // 11433 // mainMBB: 11434 // buf[LabelOffset] = LR 11435 // v_main = 0 11436 // 11437 // sinkMBB: 11438 // v = phi(main, restore) 11439 // 11440 11441 MachineBasicBlock *thisMBB = MBB; 11442 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11443 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11444 MF->insert(I, mainMBB); 11445 MF->insert(I, sinkMBB); 11446 11447 MachineInstrBuilder MIB; 11448 11449 // Transfer the remainder of BB and its successor edges to sinkMBB. 11450 sinkMBB->splice(sinkMBB->begin(), MBB, 11451 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11452 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11453 11454 // Note that the structure of the jmp_buf used here is not compatible 11455 // with that used by libc, and is not designed to be. Specifically, it 11456 // stores only those 'reserved' registers that LLVM does not otherwise 11457 // understand how to spill. Also, by convention, by the time this 11458 // intrinsic is called, Clang has already stored the frame address in the 11459 // first slot of the buffer and stack address in the third. Following the 11460 // X86 target code, we'll store the jump address in the second slot. We also 11461 // need to save the TOC pointer (R2) to handle jumps between shared 11462 // libraries, and that will be stored in the fourth slot. The thread 11463 // identifier (R13) is not affected. 11464 11465 // thisMBB: 11466 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11467 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11468 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11469 11470 // Prepare IP either in reg. 11471 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11472 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11473 Register BufReg = MI.getOperand(1).getReg(); 11474 11475 if (Subtarget.is64BitELFABI()) { 11476 setUsesTOCBasePtr(*MBB->getParent()); 11477 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11478 .addReg(PPC::X2) 11479 .addImm(TOCOffset) 11480 .addReg(BufReg) 11481 .cloneMemRefs(MI); 11482 } 11483 11484 // Naked functions never have a base pointer, and so we use r1. For all 11485 // other functions, this decision must be delayed until during PEI. 11486 unsigned BaseReg; 11487 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11488 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11489 else 11490 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11491 11492 MIB = BuildMI(*thisMBB, MI, DL, 11493 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11494 .addReg(BaseReg) 11495 .addImm(BPOffset) 11496 .addReg(BufReg) 11497 .cloneMemRefs(MI); 11498 11499 // Setup 11500 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11501 MIB.addRegMask(TRI->getNoPreservedMask()); 11502 11503 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11504 11505 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11506 .addMBB(mainMBB); 11507 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11508 11509 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11510 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11511 11512 // mainMBB: 11513 // mainDstReg = 0 11514 MIB = 11515 BuildMI(mainMBB, DL, 11516 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11517 11518 // Store IP 11519 if (Subtarget.isPPC64()) { 11520 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11521 .addReg(LabelReg) 11522 .addImm(LabelOffset) 11523 .addReg(BufReg); 11524 } else { 11525 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11526 .addReg(LabelReg) 11527 .addImm(LabelOffset) 11528 .addReg(BufReg); 11529 } 11530 MIB.cloneMemRefs(MI); 11531 11532 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11533 mainMBB->addSuccessor(sinkMBB); 11534 11535 // sinkMBB: 11536 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11537 TII->get(PPC::PHI), DstReg) 11538 .addReg(mainDstReg).addMBB(mainMBB) 11539 .addReg(restoreDstReg).addMBB(thisMBB); 11540 11541 MI.eraseFromParent(); 11542 return sinkMBB; 11543 } 11544 11545 MachineBasicBlock * 11546 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11547 MachineBasicBlock *MBB) const { 11548 DebugLoc DL = MI.getDebugLoc(); 11549 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11550 11551 MachineFunction *MF = MBB->getParent(); 11552 MachineRegisterInfo &MRI = MF->getRegInfo(); 11553 11554 MVT PVT = getPointerTy(MF->getDataLayout()); 11555 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11556 "Invalid Pointer Size!"); 11557 11558 const TargetRegisterClass *RC = 11559 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11560 Register Tmp = MRI.createVirtualRegister(RC); 11561 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11562 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11563 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11564 unsigned BP = 11565 (PVT == MVT::i64) 11566 ? PPC::X30 11567 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11568 : PPC::R30); 11569 11570 MachineInstrBuilder MIB; 11571 11572 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11573 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11574 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11575 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11576 11577 Register BufReg = MI.getOperand(0).getReg(); 11578 11579 // Reload FP (the jumped-to function may not have had a 11580 // frame pointer, and if so, then its r31 will be restored 11581 // as necessary). 11582 if (PVT == MVT::i64) { 11583 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11584 .addImm(0) 11585 .addReg(BufReg); 11586 } else { 11587 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11588 .addImm(0) 11589 .addReg(BufReg); 11590 } 11591 MIB.cloneMemRefs(MI); 11592 11593 // Reload IP 11594 if (PVT == MVT::i64) { 11595 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11596 .addImm(LabelOffset) 11597 .addReg(BufReg); 11598 } else { 11599 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11600 .addImm(LabelOffset) 11601 .addReg(BufReg); 11602 } 11603 MIB.cloneMemRefs(MI); 11604 11605 // Reload SP 11606 if (PVT == MVT::i64) { 11607 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11608 .addImm(SPOffset) 11609 .addReg(BufReg); 11610 } else { 11611 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11612 .addImm(SPOffset) 11613 .addReg(BufReg); 11614 } 11615 MIB.cloneMemRefs(MI); 11616 11617 // Reload BP 11618 if (PVT == MVT::i64) { 11619 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11620 .addImm(BPOffset) 11621 .addReg(BufReg); 11622 } else { 11623 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11624 .addImm(BPOffset) 11625 .addReg(BufReg); 11626 } 11627 MIB.cloneMemRefs(MI); 11628 11629 // Reload TOC 11630 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11631 setUsesTOCBasePtr(*MBB->getParent()); 11632 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11633 .addImm(TOCOffset) 11634 .addReg(BufReg) 11635 .cloneMemRefs(MI); 11636 } 11637 11638 // Jump 11639 BuildMI(*MBB, MI, DL, 11640 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11641 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11642 11643 MI.eraseFromParent(); 11644 return MBB; 11645 } 11646 11647 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11648 // If the function specifically requests inline stack probes, emit them. 11649 if (MF.getFunction().hasFnAttribute("probe-stack")) 11650 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11651 "inline-asm"; 11652 return false; 11653 } 11654 11655 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11656 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11657 unsigned StackAlign = TFI->getStackAlignment(); 11658 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11659 "Unexpected stack alignment"); 11660 // The default stack probe size is 4096 if the function has no 11661 // stack-probe-size attribute. 11662 unsigned StackProbeSize = 4096; 11663 const Function &Fn = MF.getFunction(); 11664 if (Fn.hasFnAttribute("stack-probe-size")) 11665 Fn.getFnAttribute("stack-probe-size") 11666 .getValueAsString() 11667 .getAsInteger(0, StackProbeSize); 11668 // Round down to the stack alignment. 11669 StackProbeSize &= ~(StackAlign - 1); 11670 return StackProbeSize ? StackProbeSize : StackAlign; 11671 } 11672 11673 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11674 // into three phases. In the first phase, it uses pseudo instruction 11675 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11676 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11677 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11678 // MaxCallFrameSize so that it can calculate correct data area pointer. 11679 MachineBasicBlock * 11680 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11681 MachineBasicBlock *MBB) const { 11682 const bool isPPC64 = Subtarget.isPPC64(); 11683 MachineFunction *MF = MBB->getParent(); 11684 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11685 DebugLoc DL = MI.getDebugLoc(); 11686 const unsigned ProbeSize = getStackProbeSize(*MF); 11687 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11688 MachineRegisterInfo &MRI = MF->getRegInfo(); 11689 // The CFG of probing stack looks as 11690 // +-----+ 11691 // | MBB | 11692 // +--+--+ 11693 // | 11694 // +----v----+ 11695 // +--->+ TestMBB +---+ 11696 // | +----+----+ | 11697 // | | | 11698 // | +-----v----+ | 11699 // +---+ BlockMBB | | 11700 // +----------+ | 11701 // | 11702 // +---------+ | 11703 // | TailMBB +<--+ 11704 // +---------+ 11705 // In MBB, calculate previous frame pointer and final stack pointer. 11706 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11707 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11708 // TailMBB is spliced via \p MI. 11709 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11710 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11711 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11712 11713 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11714 MF->insert(MBBIter, TestMBB); 11715 MF->insert(MBBIter, BlockMBB); 11716 MF->insert(MBBIter, TailMBB); 11717 11718 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11719 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11720 11721 Register DstReg = MI.getOperand(0).getReg(); 11722 Register NegSizeReg = MI.getOperand(1).getReg(); 11723 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11724 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11725 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11726 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11727 11728 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11729 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11730 // NegSize. 11731 unsigned ProbeOpc; 11732 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11733 ProbeOpc = 11734 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11735 else 11736 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11737 // and NegSizeReg will be allocated in the same phyreg to avoid 11738 // redundant copy when NegSizeReg has only one use which is current MI and 11739 // will be replaced by PREPARE_PROBED_ALLOCA then. 11740 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11741 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11742 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11743 .addDef(ActualNegSizeReg) 11744 .addReg(NegSizeReg) 11745 .add(MI.getOperand(2)) 11746 .add(MI.getOperand(3)); 11747 11748 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11749 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11750 FinalStackPtr) 11751 .addReg(SPReg) 11752 .addReg(ActualNegSizeReg); 11753 11754 // Materialize a scratch register for update. 11755 int64_t NegProbeSize = -(int64_t)ProbeSize; 11756 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11757 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11758 if (!isInt<16>(NegProbeSize)) { 11759 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11760 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11761 .addImm(NegProbeSize >> 16); 11762 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11763 ScratchReg) 11764 .addReg(TempReg) 11765 .addImm(NegProbeSize & 0xFFFF); 11766 } else 11767 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11768 .addImm(NegProbeSize); 11769 11770 { 11771 // Probing leading residual part. 11772 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11773 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11774 .addReg(ActualNegSizeReg) 11775 .addReg(ScratchReg); 11776 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11777 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11778 .addReg(Div) 11779 .addReg(ScratchReg); 11780 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11781 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11782 .addReg(Mul) 11783 .addReg(ActualNegSizeReg); 11784 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11785 .addReg(FramePointer) 11786 .addReg(SPReg) 11787 .addReg(NegMod); 11788 } 11789 11790 { 11791 // Remaining part should be multiple of ProbeSize. 11792 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11793 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11794 .addReg(SPReg) 11795 .addReg(FinalStackPtr); 11796 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11797 .addImm(PPC::PRED_EQ) 11798 .addReg(CmpResult) 11799 .addMBB(TailMBB); 11800 TestMBB->addSuccessor(BlockMBB); 11801 TestMBB->addSuccessor(TailMBB); 11802 } 11803 11804 { 11805 // Touch the block. 11806 // |P...|P...|P... 11807 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11808 .addReg(FramePointer) 11809 .addReg(SPReg) 11810 .addReg(ScratchReg); 11811 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11812 BlockMBB->addSuccessor(TestMBB); 11813 } 11814 11815 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11816 // DYNAREAOFFSET pseudo instruction to get the future result. 11817 Register MaxCallFrameSizeReg = 11818 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11819 BuildMI(TailMBB, DL, 11820 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11821 MaxCallFrameSizeReg) 11822 .add(MI.getOperand(2)) 11823 .add(MI.getOperand(3)); 11824 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11825 .addReg(SPReg) 11826 .addReg(MaxCallFrameSizeReg); 11827 11828 // Splice instructions after MI to TailMBB. 11829 TailMBB->splice(TailMBB->end(), MBB, 11830 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11831 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11832 MBB->addSuccessor(TestMBB); 11833 11834 // Delete the pseudo instruction. 11835 MI.eraseFromParent(); 11836 11837 ++NumDynamicAllocaProbed; 11838 return TailMBB; 11839 } 11840 11841 MachineBasicBlock * 11842 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11843 MachineBasicBlock *BB) const { 11844 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11845 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11846 if (Subtarget.is64BitELFABI() && 11847 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11848 !Subtarget.isUsingPCRelativeCalls()) { 11849 // Call lowering should have added an r2 operand to indicate a dependence 11850 // on the TOC base pointer value. It can't however, because there is no 11851 // way to mark the dependence as implicit there, and so the stackmap code 11852 // will confuse it with a regular operand. Instead, add the dependence 11853 // here. 11854 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11855 } 11856 11857 return emitPatchPoint(MI, BB); 11858 } 11859 11860 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11861 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11862 return emitEHSjLjSetJmp(MI, BB); 11863 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11864 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11865 return emitEHSjLjLongJmp(MI, BB); 11866 } 11867 11868 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11869 11870 // To "insert" these instructions we actually have to insert their 11871 // control-flow patterns. 11872 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11873 MachineFunction::iterator It = ++BB->getIterator(); 11874 11875 MachineFunction *F = BB->getParent(); 11876 11877 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11878 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11879 MI.getOpcode() == PPC::SELECT_I8) { 11880 SmallVector<MachineOperand, 2> Cond; 11881 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11882 MI.getOpcode() == PPC::SELECT_CC_I8) 11883 Cond.push_back(MI.getOperand(4)); 11884 else 11885 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11886 Cond.push_back(MI.getOperand(1)); 11887 11888 DebugLoc dl = MI.getDebugLoc(); 11889 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11890 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11891 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11892 MI.getOpcode() == PPC::SELECT_CC_F8 || 11893 MI.getOpcode() == PPC::SELECT_CC_F16 || 11894 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11895 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11896 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11897 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11898 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11899 MI.getOpcode() == PPC::SELECT_CC_SPE || 11900 MI.getOpcode() == PPC::SELECT_F4 || 11901 MI.getOpcode() == PPC::SELECT_F8 || 11902 MI.getOpcode() == PPC::SELECT_F16 || 11903 MI.getOpcode() == PPC::SELECT_SPE || 11904 MI.getOpcode() == PPC::SELECT_SPE4 || 11905 MI.getOpcode() == PPC::SELECT_VRRC || 11906 MI.getOpcode() == PPC::SELECT_VSFRC || 11907 MI.getOpcode() == PPC::SELECT_VSSRC || 11908 MI.getOpcode() == PPC::SELECT_VSRC) { 11909 // The incoming instruction knows the destination vreg to set, the 11910 // condition code register to branch on, the true/false values to 11911 // select between, and a branch opcode to use. 11912 11913 // thisMBB: 11914 // ... 11915 // TrueVal = ... 11916 // cmpTY ccX, r1, r2 11917 // bCC copy1MBB 11918 // fallthrough --> copy0MBB 11919 MachineBasicBlock *thisMBB = BB; 11920 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11921 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11922 DebugLoc dl = MI.getDebugLoc(); 11923 F->insert(It, copy0MBB); 11924 F->insert(It, sinkMBB); 11925 11926 // Transfer the remainder of BB and its successor edges to sinkMBB. 11927 sinkMBB->splice(sinkMBB->begin(), BB, 11928 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11929 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11930 11931 // Next, add the true and fallthrough blocks as its successors. 11932 BB->addSuccessor(copy0MBB); 11933 BB->addSuccessor(sinkMBB); 11934 11935 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11936 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11937 MI.getOpcode() == PPC::SELECT_F16 || 11938 MI.getOpcode() == PPC::SELECT_SPE4 || 11939 MI.getOpcode() == PPC::SELECT_SPE || 11940 MI.getOpcode() == PPC::SELECT_VRRC || 11941 MI.getOpcode() == PPC::SELECT_VSFRC || 11942 MI.getOpcode() == PPC::SELECT_VSSRC || 11943 MI.getOpcode() == PPC::SELECT_VSRC) { 11944 BuildMI(BB, dl, TII->get(PPC::BC)) 11945 .addReg(MI.getOperand(1).getReg()) 11946 .addMBB(sinkMBB); 11947 } else { 11948 unsigned SelectPred = MI.getOperand(4).getImm(); 11949 BuildMI(BB, dl, TII->get(PPC::BCC)) 11950 .addImm(SelectPred) 11951 .addReg(MI.getOperand(1).getReg()) 11952 .addMBB(sinkMBB); 11953 } 11954 11955 // copy0MBB: 11956 // %FalseValue = ... 11957 // # fallthrough to sinkMBB 11958 BB = copy0MBB; 11959 11960 // Update machine-CFG edges 11961 BB->addSuccessor(sinkMBB); 11962 11963 // sinkMBB: 11964 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11965 // ... 11966 BB = sinkMBB; 11967 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11968 .addReg(MI.getOperand(3).getReg()) 11969 .addMBB(copy0MBB) 11970 .addReg(MI.getOperand(2).getReg()) 11971 .addMBB(thisMBB); 11972 } else if (MI.getOpcode() == PPC::ReadTB) { 11973 // To read the 64-bit time-base register on a 32-bit target, we read the 11974 // two halves. Should the counter have wrapped while it was being read, we 11975 // need to try again. 11976 // ... 11977 // readLoop: 11978 // mfspr Rx,TBU # load from TBU 11979 // mfspr Ry,TB # load from TB 11980 // mfspr Rz,TBU # load from TBU 11981 // cmpw crX,Rx,Rz # check if 'old'='new' 11982 // bne readLoop # branch if they're not equal 11983 // ... 11984 11985 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11986 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11987 DebugLoc dl = MI.getDebugLoc(); 11988 F->insert(It, readMBB); 11989 F->insert(It, sinkMBB); 11990 11991 // Transfer the remainder of BB and its successor edges to sinkMBB. 11992 sinkMBB->splice(sinkMBB->begin(), BB, 11993 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11994 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11995 11996 BB->addSuccessor(readMBB); 11997 BB = readMBB; 11998 11999 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12000 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12001 Register LoReg = MI.getOperand(0).getReg(); 12002 Register HiReg = MI.getOperand(1).getReg(); 12003 12004 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12005 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12006 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12007 12008 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12009 12010 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12011 .addReg(HiReg) 12012 .addReg(ReadAgainReg); 12013 BuildMI(BB, dl, TII->get(PPC::BCC)) 12014 .addImm(PPC::PRED_NE) 12015 .addReg(CmpReg) 12016 .addMBB(readMBB); 12017 12018 BB->addSuccessor(readMBB); 12019 BB->addSuccessor(sinkMBB); 12020 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12021 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12022 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12023 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12024 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12025 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12026 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12027 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12028 12029 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12030 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12031 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12032 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12033 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12034 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12035 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12036 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12037 12038 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12039 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12040 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12041 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12042 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12043 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12044 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12045 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12046 12047 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12048 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12049 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12050 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12051 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12052 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12053 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12054 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12055 12056 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12057 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12058 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12059 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12060 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12061 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12062 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12063 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12064 12065 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12066 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12067 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12068 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12069 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12070 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12071 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12072 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12073 12074 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12075 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12076 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12077 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12078 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12079 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12080 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12081 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12082 12083 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12084 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12085 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12086 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12087 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12088 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12089 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12090 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12091 12092 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12093 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12094 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12095 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12096 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12097 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12098 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12099 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12100 12101 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12102 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12103 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12104 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12105 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12106 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12107 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12108 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12109 12110 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12111 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12112 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12113 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12114 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12115 BB = EmitAtomicBinary(MI, BB, 4, 0); 12116 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12117 BB = EmitAtomicBinary(MI, BB, 8, 0); 12118 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12119 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12120 (Subtarget.hasPartwordAtomics() && 12121 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12122 (Subtarget.hasPartwordAtomics() && 12123 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12124 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12125 12126 auto LoadMnemonic = PPC::LDARX; 12127 auto StoreMnemonic = PPC::STDCX; 12128 switch (MI.getOpcode()) { 12129 default: 12130 llvm_unreachable("Compare and swap of unknown size"); 12131 case PPC::ATOMIC_CMP_SWAP_I8: 12132 LoadMnemonic = PPC::LBARX; 12133 StoreMnemonic = PPC::STBCX; 12134 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12135 break; 12136 case PPC::ATOMIC_CMP_SWAP_I16: 12137 LoadMnemonic = PPC::LHARX; 12138 StoreMnemonic = PPC::STHCX; 12139 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12140 break; 12141 case PPC::ATOMIC_CMP_SWAP_I32: 12142 LoadMnemonic = PPC::LWARX; 12143 StoreMnemonic = PPC::STWCX; 12144 break; 12145 case PPC::ATOMIC_CMP_SWAP_I64: 12146 LoadMnemonic = PPC::LDARX; 12147 StoreMnemonic = PPC::STDCX; 12148 break; 12149 } 12150 Register dest = MI.getOperand(0).getReg(); 12151 Register ptrA = MI.getOperand(1).getReg(); 12152 Register ptrB = MI.getOperand(2).getReg(); 12153 Register oldval = MI.getOperand(3).getReg(); 12154 Register newval = MI.getOperand(4).getReg(); 12155 DebugLoc dl = MI.getDebugLoc(); 12156 12157 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12158 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12159 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12160 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12161 F->insert(It, loop1MBB); 12162 F->insert(It, loop2MBB); 12163 F->insert(It, midMBB); 12164 F->insert(It, exitMBB); 12165 exitMBB->splice(exitMBB->begin(), BB, 12166 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12167 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12168 12169 // thisMBB: 12170 // ... 12171 // fallthrough --> loopMBB 12172 BB->addSuccessor(loop1MBB); 12173 12174 // loop1MBB: 12175 // l[bhwd]arx dest, ptr 12176 // cmp[wd] dest, oldval 12177 // bne- midMBB 12178 // loop2MBB: 12179 // st[bhwd]cx. newval, ptr 12180 // bne- loopMBB 12181 // b exitBB 12182 // midMBB: 12183 // st[bhwd]cx. dest, ptr 12184 // exitBB: 12185 BB = loop1MBB; 12186 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12187 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12188 .addReg(oldval) 12189 .addReg(dest); 12190 BuildMI(BB, dl, TII->get(PPC::BCC)) 12191 .addImm(PPC::PRED_NE) 12192 .addReg(PPC::CR0) 12193 .addMBB(midMBB); 12194 BB->addSuccessor(loop2MBB); 12195 BB->addSuccessor(midMBB); 12196 12197 BB = loop2MBB; 12198 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12199 .addReg(newval) 12200 .addReg(ptrA) 12201 .addReg(ptrB); 12202 BuildMI(BB, dl, TII->get(PPC::BCC)) 12203 .addImm(PPC::PRED_NE) 12204 .addReg(PPC::CR0) 12205 .addMBB(loop1MBB); 12206 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12207 BB->addSuccessor(loop1MBB); 12208 BB->addSuccessor(exitMBB); 12209 12210 BB = midMBB; 12211 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12212 .addReg(dest) 12213 .addReg(ptrA) 12214 .addReg(ptrB); 12215 BB->addSuccessor(exitMBB); 12216 12217 // exitMBB: 12218 // ... 12219 BB = exitMBB; 12220 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12221 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12222 // We must use 64-bit registers for addresses when targeting 64-bit, 12223 // since we're actually doing arithmetic on them. Other registers 12224 // can be 32-bit. 12225 bool is64bit = Subtarget.isPPC64(); 12226 bool isLittleEndian = Subtarget.isLittleEndian(); 12227 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12228 12229 Register dest = MI.getOperand(0).getReg(); 12230 Register ptrA = MI.getOperand(1).getReg(); 12231 Register ptrB = MI.getOperand(2).getReg(); 12232 Register oldval = MI.getOperand(3).getReg(); 12233 Register newval = MI.getOperand(4).getReg(); 12234 DebugLoc dl = MI.getDebugLoc(); 12235 12236 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12237 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12238 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12239 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12240 F->insert(It, loop1MBB); 12241 F->insert(It, loop2MBB); 12242 F->insert(It, midMBB); 12243 F->insert(It, exitMBB); 12244 exitMBB->splice(exitMBB->begin(), BB, 12245 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12246 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12247 12248 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12249 const TargetRegisterClass *RC = 12250 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12251 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12252 12253 Register PtrReg = RegInfo.createVirtualRegister(RC); 12254 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12255 Register ShiftReg = 12256 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12257 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12258 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12259 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12260 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12261 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12262 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12263 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12264 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12265 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12266 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12267 Register Ptr1Reg; 12268 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12269 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12270 // thisMBB: 12271 // ... 12272 // fallthrough --> loopMBB 12273 BB->addSuccessor(loop1MBB); 12274 12275 // The 4-byte load must be aligned, while a char or short may be 12276 // anywhere in the word. Hence all this nasty bookkeeping code. 12277 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12278 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12279 // xori shift, shift1, 24 [16] 12280 // rlwinm ptr, ptr1, 0, 0, 29 12281 // slw newval2, newval, shift 12282 // slw oldval2, oldval,shift 12283 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12284 // slw mask, mask2, shift 12285 // and newval3, newval2, mask 12286 // and oldval3, oldval2, mask 12287 // loop1MBB: 12288 // lwarx tmpDest, ptr 12289 // and tmp, tmpDest, mask 12290 // cmpw tmp, oldval3 12291 // bne- midMBB 12292 // loop2MBB: 12293 // andc tmp2, tmpDest, mask 12294 // or tmp4, tmp2, newval3 12295 // stwcx. tmp4, ptr 12296 // bne- loop1MBB 12297 // b exitBB 12298 // midMBB: 12299 // stwcx. tmpDest, ptr 12300 // exitBB: 12301 // srw dest, tmpDest, shift 12302 if (ptrA != ZeroReg) { 12303 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12304 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12305 .addReg(ptrA) 12306 .addReg(ptrB); 12307 } else { 12308 Ptr1Reg = ptrB; 12309 } 12310 12311 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12312 // mode. 12313 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12314 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12315 .addImm(3) 12316 .addImm(27) 12317 .addImm(is8bit ? 28 : 27); 12318 if (!isLittleEndian) 12319 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12320 .addReg(Shift1Reg) 12321 .addImm(is8bit ? 24 : 16); 12322 if (is64bit) 12323 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12324 .addReg(Ptr1Reg) 12325 .addImm(0) 12326 .addImm(61); 12327 else 12328 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12329 .addReg(Ptr1Reg) 12330 .addImm(0) 12331 .addImm(0) 12332 .addImm(29); 12333 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12334 .addReg(newval) 12335 .addReg(ShiftReg); 12336 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12337 .addReg(oldval) 12338 .addReg(ShiftReg); 12339 if (is8bit) 12340 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12341 else { 12342 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12343 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12344 .addReg(Mask3Reg) 12345 .addImm(65535); 12346 } 12347 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12348 .addReg(Mask2Reg) 12349 .addReg(ShiftReg); 12350 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12351 .addReg(NewVal2Reg) 12352 .addReg(MaskReg); 12353 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12354 .addReg(OldVal2Reg) 12355 .addReg(MaskReg); 12356 12357 BB = loop1MBB; 12358 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12359 .addReg(ZeroReg) 12360 .addReg(PtrReg); 12361 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12362 .addReg(TmpDestReg) 12363 .addReg(MaskReg); 12364 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12365 .addReg(TmpReg) 12366 .addReg(OldVal3Reg); 12367 BuildMI(BB, dl, TII->get(PPC::BCC)) 12368 .addImm(PPC::PRED_NE) 12369 .addReg(PPC::CR0) 12370 .addMBB(midMBB); 12371 BB->addSuccessor(loop2MBB); 12372 BB->addSuccessor(midMBB); 12373 12374 BB = loop2MBB; 12375 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12376 .addReg(TmpDestReg) 12377 .addReg(MaskReg); 12378 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12379 .addReg(Tmp2Reg) 12380 .addReg(NewVal3Reg); 12381 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12382 .addReg(Tmp4Reg) 12383 .addReg(ZeroReg) 12384 .addReg(PtrReg); 12385 BuildMI(BB, dl, TII->get(PPC::BCC)) 12386 .addImm(PPC::PRED_NE) 12387 .addReg(PPC::CR0) 12388 .addMBB(loop1MBB); 12389 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12390 BB->addSuccessor(loop1MBB); 12391 BB->addSuccessor(exitMBB); 12392 12393 BB = midMBB; 12394 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12395 .addReg(TmpDestReg) 12396 .addReg(ZeroReg) 12397 .addReg(PtrReg); 12398 BB->addSuccessor(exitMBB); 12399 12400 // exitMBB: 12401 // ... 12402 BB = exitMBB; 12403 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12404 .addReg(TmpReg) 12405 .addReg(ShiftReg); 12406 } else if (MI.getOpcode() == PPC::FADDrtz) { 12407 // This pseudo performs an FADD with rounding mode temporarily forced 12408 // to round-to-zero. We emit this via custom inserter since the FPSCR 12409 // is not modeled at the SelectionDAG level. 12410 Register Dest = MI.getOperand(0).getReg(); 12411 Register Src1 = MI.getOperand(1).getReg(); 12412 Register Src2 = MI.getOperand(2).getReg(); 12413 DebugLoc dl = MI.getDebugLoc(); 12414 12415 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12416 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12417 12418 // Save FPSCR value. 12419 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12420 12421 // Set rounding mode to round-to-zero. 12422 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12423 .addImm(31) 12424 .addReg(PPC::RM, RegState::ImplicitDefine); 12425 12426 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12427 .addImm(30) 12428 .addReg(PPC::RM, RegState::ImplicitDefine); 12429 12430 // Perform addition. 12431 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12432 .addReg(Src1) 12433 .addReg(Src2); 12434 if (MI.getFlag(MachineInstr::NoFPExcept)) 12435 MIB.setMIFlag(MachineInstr::NoFPExcept); 12436 12437 // Restore FPSCR value. 12438 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12439 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12440 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12441 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12442 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12443 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12444 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12445 ? PPC::ANDI8_rec 12446 : PPC::ANDI_rec; 12447 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12448 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12449 12450 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12451 Register Dest = RegInfo.createVirtualRegister( 12452 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12453 12454 DebugLoc Dl = MI.getDebugLoc(); 12455 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12456 .addReg(MI.getOperand(1).getReg()) 12457 .addImm(1); 12458 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12459 MI.getOperand(0).getReg()) 12460 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12461 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12462 DebugLoc Dl = MI.getDebugLoc(); 12463 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12464 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12465 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12466 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12467 MI.getOperand(0).getReg()) 12468 .addReg(CRReg); 12469 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12470 DebugLoc Dl = MI.getDebugLoc(); 12471 unsigned Imm = MI.getOperand(1).getImm(); 12472 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12473 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12474 MI.getOperand(0).getReg()) 12475 .addReg(PPC::CR0EQ); 12476 } else if (MI.getOpcode() == PPC::SETRNDi) { 12477 DebugLoc dl = MI.getDebugLoc(); 12478 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12479 12480 // Save FPSCR value. 12481 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12482 12483 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12484 // the following settings: 12485 // 00 Round to nearest 12486 // 01 Round to 0 12487 // 10 Round to +inf 12488 // 11 Round to -inf 12489 12490 // When the operand is immediate, using the two least significant bits of 12491 // the immediate to set the bits 62:63 of FPSCR. 12492 unsigned Mode = MI.getOperand(1).getImm(); 12493 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12494 .addImm(31) 12495 .addReg(PPC::RM, RegState::ImplicitDefine); 12496 12497 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12498 .addImm(30) 12499 .addReg(PPC::RM, RegState::ImplicitDefine); 12500 } else if (MI.getOpcode() == PPC::SETRND) { 12501 DebugLoc dl = MI.getDebugLoc(); 12502 12503 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12504 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12505 // If the target doesn't have DirectMove, we should use stack to do the 12506 // conversion, because the target doesn't have the instructions like mtvsrd 12507 // or mfvsrd to do this conversion directly. 12508 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12509 if (Subtarget.hasDirectMove()) { 12510 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12511 .addReg(SrcReg); 12512 } else { 12513 // Use stack to do the register copy. 12514 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12515 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12516 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12517 if (RC == &PPC::F8RCRegClass) { 12518 // Copy register from F8RCRegClass to G8RCRegclass. 12519 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12520 "Unsupported RegClass."); 12521 12522 StoreOp = PPC::STFD; 12523 LoadOp = PPC::LD; 12524 } else { 12525 // Copy register from G8RCRegClass to F8RCRegclass. 12526 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12527 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12528 "Unsupported RegClass."); 12529 } 12530 12531 MachineFrameInfo &MFI = F->getFrameInfo(); 12532 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12533 12534 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12535 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12536 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12537 MFI.getObjectAlign(FrameIdx)); 12538 12539 // Store the SrcReg into the stack. 12540 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12541 .addReg(SrcReg) 12542 .addImm(0) 12543 .addFrameIndex(FrameIdx) 12544 .addMemOperand(MMOStore); 12545 12546 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12547 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12548 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12549 MFI.getObjectAlign(FrameIdx)); 12550 12551 // Load from the stack where SrcReg is stored, and save to DestReg, 12552 // so we have done the RegClass conversion from RegClass::SrcReg to 12553 // RegClass::DestReg. 12554 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12555 .addImm(0) 12556 .addFrameIndex(FrameIdx) 12557 .addMemOperand(MMOLoad); 12558 } 12559 }; 12560 12561 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12562 12563 // Save FPSCR value. 12564 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12565 12566 // When the operand is gprc register, use two least significant bits of the 12567 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12568 // 12569 // copy OldFPSCRTmpReg, OldFPSCRReg 12570 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12571 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12572 // copy NewFPSCRReg, NewFPSCRTmpReg 12573 // mtfsf 255, NewFPSCRReg 12574 MachineOperand SrcOp = MI.getOperand(1); 12575 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12576 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12577 12578 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12579 12580 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12581 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12582 12583 // The first operand of INSERT_SUBREG should be a register which has 12584 // subregisters, we only care about its RegClass, so we should use an 12585 // IMPLICIT_DEF register. 12586 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12587 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12588 .addReg(ImDefReg) 12589 .add(SrcOp) 12590 .addImm(1); 12591 12592 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12593 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12594 .addReg(OldFPSCRTmpReg) 12595 .addReg(ExtSrcReg) 12596 .addImm(0) 12597 .addImm(62); 12598 12599 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12600 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12601 12602 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12603 // bits of FPSCR. 12604 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12605 .addImm(255) 12606 .addReg(NewFPSCRReg) 12607 .addImm(0) 12608 .addImm(0); 12609 } else if (MI.getOpcode() == PPC::SETFLM) { 12610 DebugLoc Dl = MI.getDebugLoc(); 12611 12612 // Result of setflm is previous FPSCR content, so we need to save it first. 12613 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12614 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12615 12616 // Put bits in 32:63 to FPSCR. 12617 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12618 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12619 .addImm(255) 12620 .addReg(NewFPSCRReg) 12621 .addImm(0) 12622 .addImm(0); 12623 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12624 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12625 return emitProbedAlloca(MI, BB); 12626 } else { 12627 llvm_unreachable("Unexpected instr type to insert"); 12628 } 12629 12630 MI.eraseFromParent(); // The pseudo instruction is gone now. 12631 return BB; 12632 } 12633 12634 //===----------------------------------------------------------------------===// 12635 // Target Optimization Hooks 12636 //===----------------------------------------------------------------------===// 12637 12638 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12639 // For the estimates, convergence is quadratic, so we essentially double the 12640 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12641 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12642 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12643 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12644 if (VT.getScalarType() == MVT::f64) 12645 RefinementSteps++; 12646 return RefinementSteps; 12647 } 12648 12649 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12650 int Enabled, int &RefinementSteps, 12651 bool &UseOneConstNR, 12652 bool Reciprocal) const { 12653 EVT VT = Operand.getValueType(); 12654 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12655 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12656 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12657 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12658 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12659 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12660 12661 // The Newton-Raphson computation with a single constant does not provide 12662 // enough accuracy on some CPUs. 12663 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12664 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12665 } 12666 return SDValue(); 12667 } 12668 12669 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12670 int Enabled, 12671 int &RefinementSteps) const { 12672 EVT VT = Operand.getValueType(); 12673 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12674 (VT == MVT::f64 && Subtarget.hasFRE()) || 12675 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12676 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12677 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12678 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12679 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12680 } 12681 return SDValue(); 12682 } 12683 12684 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12685 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12686 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12687 // enabled for division), this functionality is redundant with the default 12688 // combiner logic (once the division -> reciprocal/multiply transformation 12689 // has taken place). As a result, this matters more for older cores than for 12690 // newer ones. 12691 12692 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12693 // reciprocal if there are two or more FDIVs (for embedded cores with only 12694 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12695 switch (Subtarget.getCPUDirective()) { 12696 default: 12697 return 3; 12698 case PPC::DIR_440: 12699 case PPC::DIR_A2: 12700 case PPC::DIR_E500: 12701 case PPC::DIR_E500mc: 12702 case PPC::DIR_E5500: 12703 return 2; 12704 } 12705 } 12706 12707 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12708 // collapsed, and so we need to look through chains of them. 12709 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12710 int64_t& Offset, SelectionDAG &DAG) { 12711 if (DAG.isBaseWithConstantOffset(Loc)) { 12712 Base = Loc.getOperand(0); 12713 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12714 12715 // The base might itself be a base plus an offset, and if so, accumulate 12716 // that as well. 12717 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12718 } 12719 } 12720 12721 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12722 unsigned Bytes, int Dist, 12723 SelectionDAG &DAG) { 12724 if (VT.getSizeInBits() / 8 != Bytes) 12725 return false; 12726 12727 SDValue BaseLoc = Base->getBasePtr(); 12728 if (Loc.getOpcode() == ISD::FrameIndex) { 12729 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12730 return false; 12731 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12732 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12733 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12734 int FS = MFI.getObjectSize(FI); 12735 int BFS = MFI.getObjectSize(BFI); 12736 if (FS != BFS || FS != (int)Bytes) return false; 12737 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12738 } 12739 12740 SDValue Base1 = Loc, Base2 = BaseLoc; 12741 int64_t Offset1 = 0, Offset2 = 0; 12742 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12743 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12744 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12745 return true; 12746 12747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12748 const GlobalValue *GV1 = nullptr; 12749 const GlobalValue *GV2 = nullptr; 12750 Offset1 = 0; 12751 Offset2 = 0; 12752 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12753 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12754 if (isGA1 && isGA2 && GV1 == GV2) 12755 return Offset1 == (Offset2 + Dist*Bytes); 12756 return false; 12757 } 12758 12759 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12760 // not enforce equality of the chain operands. 12761 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12762 unsigned Bytes, int Dist, 12763 SelectionDAG &DAG) { 12764 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12765 EVT VT = LS->getMemoryVT(); 12766 SDValue Loc = LS->getBasePtr(); 12767 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12768 } 12769 12770 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12771 EVT VT; 12772 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12773 default: return false; 12774 case Intrinsic::ppc_altivec_lvx: 12775 case Intrinsic::ppc_altivec_lvxl: 12776 case Intrinsic::ppc_vsx_lxvw4x: 12777 case Intrinsic::ppc_vsx_lxvw4x_be: 12778 VT = MVT::v4i32; 12779 break; 12780 case Intrinsic::ppc_vsx_lxvd2x: 12781 case Intrinsic::ppc_vsx_lxvd2x_be: 12782 VT = MVT::v2f64; 12783 break; 12784 case Intrinsic::ppc_altivec_lvebx: 12785 VT = MVT::i8; 12786 break; 12787 case Intrinsic::ppc_altivec_lvehx: 12788 VT = MVT::i16; 12789 break; 12790 case Intrinsic::ppc_altivec_lvewx: 12791 VT = MVT::i32; 12792 break; 12793 } 12794 12795 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12796 } 12797 12798 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12799 EVT VT; 12800 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12801 default: return false; 12802 case Intrinsic::ppc_altivec_stvx: 12803 case Intrinsic::ppc_altivec_stvxl: 12804 case Intrinsic::ppc_vsx_stxvw4x: 12805 VT = MVT::v4i32; 12806 break; 12807 case Intrinsic::ppc_vsx_stxvd2x: 12808 VT = MVT::v2f64; 12809 break; 12810 case Intrinsic::ppc_vsx_stxvw4x_be: 12811 VT = MVT::v4i32; 12812 break; 12813 case Intrinsic::ppc_vsx_stxvd2x_be: 12814 VT = MVT::v2f64; 12815 break; 12816 case Intrinsic::ppc_altivec_stvebx: 12817 VT = MVT::i8; 12818 break; 12819 case Intrinsic::ppc_altivec_stvehx: 12820 VT = MVT::i16; 12821 break; 12822 case Intrinsic::ppc_altivec_stvewx: 12823 VT = MVT::i32; 12824 break; 12825 } 12826 12827 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12828 } 12829 12830 return false; 12831 } 12832 12833 // Return true is there is a nearyby consecutive load to the one provided 12834 // (regardless of alignment). We search up and down the chain, looking though 12835 // token factors and other loads (but nothing else). As a result, a true result 12836 // indicates that it is safe to create a new consecutive load adjacent to the 12837 // load provided. 12838 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12839 SDValue Chain = LD->getChain(); 12840 EVT VT = LD->getMemoryVT(); 12841 12842 SmallSet<SDNode *, 16> LoadRoots; 12843 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12844 SmallSet<SDNode *, 16> Visited; 12845 12846 // First, search up the chain, branching to follow all token-factor operands. 12847 // If we find a consecutive load, then we're done, otherwise, record all 12848 // nodes just above the top-level loads and token factors. 12849 while (!Queue.empty()) { 12850 SDNode *ChainNext = Queue.pop_back_val(); 12851 if (!Visited.insert(ChainNext).second) 12852 continue; 12853 12854 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12855 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12856 return true; 12857 12858 if (!Visited.count(ChainLD->getChain().getNode())) 12859 Queue.push_back(ChainLD->getChain().getNode()); 12860 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12861 for (const SDUse &O : ChainNext->ops()) 12862 if (!Visited.count(O.getNode())) 12863 Queue.push_back(O.getNode()); 12864 } else 12865 LoadRoots.insert(ChainNext); 12866 } 12867 12868 // Second, search down the chain, starting from the top-level nodes recorded 12869 // in the first phase. These top-level nodes are the nodes just above all 12870 // loads and token factors. Starting with their uses, recursively look though 12871 // all loads (just the chain uses) and token factors to find a consecutive 12872 // load. 12873 Visited.clear(); 12874 Queue.clear(); 12875 12876 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12877 IE = LoadRoots.end(); I != IE; ++I) { 12878 Queue.push_back(*I); 12879 12880 while (!Queue.empty()) { 12881 SDNode *LoadRoot = Queue.pop_back_val(); 12882 if (!Visited.insert(LoadRoot).second) 12883 continue; 12884 12885 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12886 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12887 return true; 12888 12889 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12890 UE = LoadRoot->use_end(); UI != UE; ++UI) 12891 if (((isa<MemSDNode>(*UI) && 12892 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12893 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12894 Queue.push_back(*UI); 12895 } 12896 } 12897 12898 return false; 12899 } 12900 12901 /// This function is called when we have proved that a SETCC node can be replaced 12902 /// by subtraction (and other supporting instructions) so that the result of 12903 /// comparison is kept in a GPR instead of CR. This function is purely for 12904 /// codegen purposes and has some flags to guide the codegen process. 12905 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12906 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12907 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12908 12909 // Zero extend the operands to the largest legal integer. Originally, they 12910 // must be of a strictly smaller size. 12911 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12912 DAG.getConstant(Size, DL, MVT::i32)); 12913 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12914 DAG.getConstant(Size, DL, MVT::i32)); 12915 12916 // Swap if needed. Depends on the condition code. 12917 if (Swap) 12918 std::swap(Op0, Op1); 12919 12920 // Subtract extended integers. 12921 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12922 12923 // Move the sign bit to the least significant position and zero out the rest. 12924 // Now the least significant bit carries the result of original comparison. 12925 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12926 DAG.getConstant(Size - 1, DL, MVT::i32)); 12927 auto Final = Shifted; 12928 12929 // Complement the result if needed. Based on the condition code. 12930 if (Complement) 12931 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12932 DAG.getConstant(1, DL, MVT::i64)); 12933 12934 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12935 } 12936 12937 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12938 DAGCombinerInfo &DCI) const { 12939 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12940 12941 SelectionDAG &DAG = DCI.DAG; 12942 SDLoc DL(N); 12943 12944 // Size of integers being compared has a critical role in the following 12945 // analysis, so we prefer to do this when all types are legal. 12946 if (!DCI.isAfterLegalizeDAG()) 12947 return SDValue(); 12948 12949 // If all users of SETCC extend its value to a legal integer type 12950 // then we replace SETCC with a subtraction 12951 for (SDNode::use_iterator UI = N->use_begin(), 12952 UE = N->use_end(); UI != UE; ++UI) { 12953 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12954 return SDValue(); 12955 } 12956 12957 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12958 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12959 12960 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12961 12962 if (OpSize < Size) { 12963 switch (CC) { 12964 default: break; 12965 case ISD::SETULT: 12966 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12967 case ISD::SETULE: 12968 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12969 case ISD::SETUGT: 12970 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12971 case ISD::SETUGE: 12972 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12973 } 12974 } 12975 12976 return SDValue(); 12977 } 12978 12979 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12980 DAGCombinerInfo &DCI) const { 12981 SelectionDAG &DAG = DCI.DAG; 12982 SDLoc dl(N); 12983 12984 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12985 // If we're tracking CR bits, we need to be careful that we don't have: 12986 // trunc(binary-ops(zext(x), zext(y))) 12987 // or 12988 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12989 // such that we're unnecessarily moving things into GPRs when it would be 12990 // better to keep them in CR bits. 12991 12992 // Note that trunc here can be an actual i1 trunc, or can be the effective 12993 // truncation that comes from a setcc or select_cc. 12994 if (N->getOpcode() == ISD::TRUNCATE && 12995 N->getValueType(0) != MVT::i1) 12996 return SDValue(); 12997 12998 if (N->getOperand(0).getValueType() != MVT::i32 && 12999 N->getOperand(0).getValueType() != MVT::i64) 13000 return SDValue(); 13001 13002 if (N->getOpcode() == ISD::SETCC || 13003 N->getOpcode() == ISD::SELECT_CC) { 13004 // If we're looking at a comparison, then we need to make sure that the 13005 // high bits (all except for the first) don't matter the result. 13006 ISD::CondCode CC = 13007 cast<CondCodeSDNode>(N->getOperand( 13008 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13009 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13010 13011 if (ISD::isSignedIntSetCC(CC)) { 13012 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13013 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13014 return SDValue(); 13015 } else if (ISD::isUnsignedIntSetCC(CC)) { 13016 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13017 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13018 !DAG.MaskedValueIsZero(N->getOperand(1), 13019 APInt::getHighBitsSet(OpBits, OpBits-1))) 13020 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13021 : SDValue()); 13022 } else { 13023 // This is neither a signed nor an unsigned comparison, just make sure 13024 // that the high bits are equal. 13025 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13026 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13027 13028 // We don't really care about what is known about the first bit (if 13029 // anything), so clear it in all masks prior to comparing them. 13030 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 13031 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 13032 13033 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 13034 return SDValue(); 13035 } 13036 } 13037 13038 // We now know that the higher-order bits are irrelevant, we just need to 13039 // make sure that all of the intermediate operations are bit operations, and 13040 // all inputs are extensions. 13041 if (N->getOperand(0).getOpcode() != ISD::AND && 13042 N->getOperand(0).getOpcode() != ISD::OR && 13043 N->getOperand(0).getOpcode() != ISD::XOR && 13044 N->getOperand(0).getOpcode() != ISD::SELECT && 13045 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13046 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13047 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13048 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13049 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13050 return SDValue(); 13051 13052 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13053 N->getOperand(1).getOpcode() != ISD::AND && 13054 N->getOperand(1).getOpcode() != ISD::OR && 13055 N->getOperand(1).getOpcode() != ISD::XOR && 13056 N->getOperand(1).getOpcode() != ISD::SELECT && 13057 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13058 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13059 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13060 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13061 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13062 return SDValue(); 13063 13064 SmallVector<SDValue, 4> Inputs; 13065 SmallVector<SDValue, 8> BinOps, PromOps; 13066 SmallPtrSet<SDNode *, 16> Visited; 13067 13068 for (unsigned i = 0; i < 2; ++i) { 13069 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13070 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13071 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13072 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13073 isa<ConstantSDNode>(N->getOperand(i))) 13074 Inputs.push_back(N->getOperand(i)); 13075 else 13076 BinOps.push_back(N->getOperand(i)); 13077 13078 if (N->getOpcode() == ISD::TRUNCATE) 13079 break; 13080 } 13081 13082 // Visit all inputs, collect all binary operations (and, or, xor and 13083 // select) that are all fed by extensions. 13084 while (!BinOps.empty()) { 13085 SDValue BinOp = BinOps.back(); 13086 BinOps.pop_back(); 13087 13088 if (!Visited.insert(BinOp.getNode()).second) 13089 continue; 13090 13091 PromOps.push_back(BinOp); 13092 13093 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13094 // The condition of the select is not promoted. 13095 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13096 continue; 13097 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13098 continue; 13099 13100 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13101 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13102 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13103 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13104 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13105 Inputs.push_back(BinOp.getOperand(i)); 13106 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13107 BinOp.getOperand(i).getOpcode() == ISD::OR || 13108 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13109 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13110 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13111 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13112 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13113 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13114 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13115 BinOps.push_back(BinOp.getOperand(i)); 13116 } else { 13117 // We have an input that is not an extension or another binary 13118 // operation; we'll abort this transformation. 13119 return SDValue(); 13120 } 13121 } 13122 } 13123 13124 // Make sure that this is a self-contained cluster of operations (which 13125 // is not quite the same thing as saying that everything has only one 13126 // use). 13127 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13128 if (isa<ConstantSDNode>(Inputs[i])) 13129 continue; 13130 13131 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13132 UE = Inputs[i].getNode()->use_end(); 13133 UI != UE; ++UI) { 13134 SDNode *User = *UI; 13135 if (User != N && !Visited.count(User)) 13136 return SDValue(); 13137 13138 // Make sure that we're not going to promote the non-output-value 13139 // operand(s) or SELECT or SELECT_CC. 13140 // FIXME: Although we could sometimes handle this, and it does occur in 13141 // practice that one of the condition inputs to the select is also one of 13142 // the outputs, we currently can't deal with this. 13143 if (User->getOpcode() == ISD::SELECT) { 13144 if (User->getOperand(0) == Inputs[i]) 13145 return SDValue(); 13146 } else if (User->getOpcode() == ISD::SELECT_CC) { 13147 if (User->getOperand(0) == Inputs[i] || 13148 User->getOperand(1) == Inputs[i]) 13149 return SDValue(); 13150 } 13151 } 13152 } 13153 13154 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13155 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13156 UE = PromOps[i].getNode()->use_end(); 13157 UI != UE; ++UI) { 13158 SDNode *User = *UI; 13159 if (User != N && !Visited.count(User)) 13160 return SDValue(); 13161 13162 // Make sure that we're not going to promote the non-output-value 13163 // operand(s) or SELECT or SELECT_CC. 13164 // FIXME: Although we could sometimes handle this, and it does occur in 13165 // practice that one of the condition inputs to the select is also one of 13166 // the outputs, we currently can't deal with this. 13167 if (User->getOpcode() == ISD::SELECT) { 13168 if (User->getOperand(0) == PromOps[i]) 13169 return SDValue(); 13170 } else if (User->getOpcode() == ISD::SELECT_CC) { 13171 if (User->getOperand(0) == PromOps[i] || 13172 User->getOperand(1) == PromOps[i]) 13173 return SDValue(); 13174 } 13175 } 13176 } 13177 13178 // Replace all inputs with the extension operand. 13179 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13180 // Constants may have users outside the cluster of to-be-promoted nodes, 13181 // and so we need to replace those as we do the promotions. 13182 if (isa<ConstantSDNode>(Inputs[i])) 13183 continue; 13184 else 13185 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13186 } 13187 13188 std::list<HandleSDNode> PromOpHandles; 13189 for (auto &PromOp : PromOps) 13190 PromOpHandles.emplace_back(PromOp); 13191 13192 // Replace all operations (these are all the same, but have a different 13193 // (i1) return type). DAG.getNode will validate that the types of 13194 // a binary operator match, so go through the list in reverse so that 13195 // we've likely promoted both operands first. Any intermediate truncations or 13196 // extensions disappear. 13197 while (!PromOpHandles.empty()) { 13198 SDValue PromOp = PromOpHandles.back().getValue(); 13199 PromOpHandles.pop_back(); 13200 13201 if (PromOp.getOpcode() == ISD::TRUNCATE || 13202 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13203 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13204 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13205 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13206 PromOp.getOperand(0).getValueType() != MVT::i1) { 13207 // The operand is not yet ready (see comment below). 13208 PromOpHandles.emplace_front(PromOp); 13209 continue; 13210 } 13211 13212 SDValue RepValue = PromOp.getOperand(0); 13213 if (isa<ConstantSDNode>(RepValue)) 13214 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13215 13216 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13217 continue; 13218 } 13219 13220 unsigned C; 13221 switch (PromOp.getOpcode()) { 13222 default: C = 0; break; 13223 case ISD::SELECT: C = 1; break; 13224 case ISD::SELECT_CC: C = 2; break; 13225 } 13226 13227 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13228 PromOp.getOperand(C).getValueType() != MVT::i1) || 13229 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13230 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13231 // The to-be-promoted operands of this node have not yet been 13232 // promoted (this should be rare because we're going through the 13233 // list backward, but if one of the operands has several users in 13234 // this cluster of to-be-promoted nodes, it is possible). 13235 PromOpHandles.emplace_front(PromOp); 13236 continue; 13237 } 13238 13239 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13240 PromOp.getNode()->op_end()); 13241 13242 // If there are any constant inputs, make sure they're replaced now. 13243 for (unsigned i = 0; i < 2; ++i) 13244 if (isa<ConstantSDNode>(Ops[C+i])) 13245 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13246 13247 DAG.ReplaceAllUsesOfValueWith(PromOp, 13248 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13249 } 13250 13251 // Now we're left with the initial truncation itself. 13252 if (N->getOpcode() == ISD::TRUNCATE) 13253 return N->getOperand(0); 13254 13255 // Otherwise, this is a comparison. The operands to be compared have just 13256 // changed type (to i1), but everything else is the same. 13257 return SDValue(N, 0); 13258 } 13259 13260 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13261 DAGCombinerInfo &DCI) const { 13262 SelectionDAG &DAG = DCI.DAG; 13263 SDLoc dl(N); 13264 13265 // If we're tracking CR bits, we need to be careful that we don't have: 13266 // zext(binary-ops(trunc(x), trunc(y))) 13267 // or 13268 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13269 // such that we're unnecessarily moving things into CR bits that can more 13270 // efficiently stay in GPRs. Note that if we're not certain that the high 13271 // bits are set as required by the final extension, we still may need to do 13272 // some masking to get the proper behavior. 13273 13274 // This same functionality is important on PPC64 when dealing with 13275 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13276 // the return values of functions. Because it is so similar, it is handled 13277 // here as well. 13278 13279 if (N->getValueType(0) != MVT::i32 && 13280 N->getValueType(0) != MVT::i64) 13281 return SDValue(); 13282 13283 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13284 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13285 return SDValue(); 13286 13287 if (N->getOperand(0).getOpcode() != ISD::AND && 13288 N->getOperand(0).getOpcode() != ISD::OR && 13289 N->getOperand(0).getOpcode() != ISD::XOR && 13290 N->getOperand(0).getOpcode() != ISD::SELECT && 13291 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13292 return SDValue(); 13293 13294 SmallVector<SDValue, 4> Inputs; 13295 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13296 SmallPtrSet<SDNode *, 16> Visited; 13297 13298 // Visit all inputs, collect all binary operations (and, or, xor and 13299 // select) that are all fed by truncations. 13300 while (!BinOps.empty()) { 13301 SDValue BinOp = BinOps.back(); 13302 BinOps.pop_back(); 13303 13304 if (!Visited.insert(BinOp.getNode()).second) 13305 continue; 13306 13307 PromOps.push_back(BinOp); 13308 13309 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13310 // The condition of the select is not promoted. 13311 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13312 continue; 13313 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13314 continue; 13315 13316 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13317 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13318 Inputs.push_back(BinOp.getOperand(i)); 13319 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13320 BinOp.getOperand(i).getOpcode() == ISD::OR || 13321 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13322 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13323 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13324 BinOps.push_back(BinOp.getOperand(i)); 13325 } else { 13326 // We have an input that is not a truncation or another binary 13327 // operation; we'll abort this transformation. 13328 return SDValue(); 13329 } 13330 } 13331 } 13332 13333 // The operands of a select that must be truncated when the select is 13334 // promoted because the operand is actually part of the to-be-promoted set. 13335 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13336 13337 // Make sure that this is a self-contained cluster of operations (which 13338 // is not quite the same thing as saying that everything has only one 13339 // use). 13340 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13341 if (isa<ConstantSDNode>(Inputs[i])) 13342 continue; 13343 13344 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13345 UE = Inputs[i].getNode()->use_end(); 13346 UI != UE; ++UI) { 13347 SDNode *User = *UI; 13348 if (User != N && !Visited.count(User)) 13349 return SDValue(); 13350 13351 // If we're going to promote the non-output-value operand(s) or SELECT or 13352 // SELECT_CC, record them for truncation. 13353 if (User->getOpcode() == ISD::SELECT) { 13354 if (User->getOperand(0) == Inputs[i]) 13355 SelectTruncOp[0].insert(std::make_pair(User, 13356 User->getOperand(0).getValueType())); 13357 } else if (User->getOpcode() == ISD::SELECT_CC) { 13358 if (User->getOperand(0) == Inputs[i]) 13359 SelectTruncOp[0].insert(std::make_pair(User, 13360 User->getOperand(0).getValueType())); 13361 if (User->getOperand(1) == Inputs[i]) 13362 SelectTruncOp[1].insert(std::make_pair(User, 13363 User->getOperand(1).getValueType())); 13364 } 13365 } 13366 } 13367 13368 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13369 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13370 UE = PromOps[i].getNode()->use_end(); 13371 UI != UE; ++UI) { 13372 SDNode *User = *UI; 13373 if (User != N && !Visited.count(User)) 13374 return SDValue(); 13375 13376 // If we're going to promote the non-output-value operand(s) or SELECT or 13377 // SELECT_CC, record them for truncation. 13378 if (User->getOpcode() == ISD::SELECT) { 13379 if (User->getOperand(0) == PromOps[i]) 13380 SelectTruncOp[0].insert(std::make_pair(User, 13381 User->getOperand(0).getValueType())); 13382 } else if (User->getOpcode() == ISD::SELECT_CC) { 13383 if (User->getOperand(0) == PromOps[i]) 13384 SelectTruncOp[0].insert(std::make_pair(User, 13385 User->getOperand(0).getValueType())); 13386 if (User->getOperand(1) == PromOps[i]) 13387 SelectTruncOp[1].insert(std::make_pair(User, 13388 User->getOperand(1).getValueType())); 13389 } 13390 } 13391 } 13392 13393 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13394 bool ReallyNeedsExt = false; 13395 if (N->getOpcode() != ISD::ANY_EXTEND) { 13396 // If all of the inputs are not already sign/zero extended, then 13397 // we'll still need to do that at the end. 13398 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13399 if (isa<ConstantSDNode>(Inputs[i])) 13400 continue; 13401 13402 unsigned OpBits = 13403 Inputs[i].getOperand(0).getValueSizeInBits(); 13404 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13405 13406 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13407 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13408 APInt::getHighBitsSet(OpBits, 13409 OpBits-PromBits))) || 13410 (N->getOpcode() == ISD::SIGN_EXTEND && 13411 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13412 (OpBits-(PromBits-1)))) { 13413 ReallyNeedsExt = true; 13414 break; 13415 } 13416 } 13417 } 13418 13419 // Replace all inputs, either with the truncation operand, or a 13420 // truncation or extension to the final output type. 13421 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13422 // Constant inputs need to be replaced with the to-be-promoted nodes that 13423 // use them because they might have users outside of the cluster of 13424 // promoted nodes. 13425 if (isa<ConstantSDNode>(Inputs[i])) 13426 continue; 13427 13428 SDValue InSrc = Inputs[i].getOperand(0); 13429 if (Inputs[i].getValueType() == N->getValueType(0)) 13430 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13431 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13432 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13433 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13434 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13435 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13436 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13437 else 13438 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13439 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13440 } 13441 13442 std::list<HandleSDNode> PromOpHandles; 13443 for (auto &PromOp : PromOps) 13444 PromOpHandles.emplace_back(PromOp); 13445 13446 // Replace all operations (these are all the same, but have a different 13447 // (promoted) return type). DAG.getNode will validate that the types of 13448 // a binary operator match, so go through the list in reverse so that 13449 // we've likely promoted both operands first. 13450 while (!PromOpHandles.empty()) { 13451 SDValue PromOp = PromOpHandles.back().getValue(); 13452 PromOpHandles.pop_back(); 13453 13454 unsigned C; 13455 switch (PromOp.getOpcode()) { 13456 default: C = 0; break; 13457 case ISD::SELECT: C = 1; break; 13458 case ISD::SELECT_CC: C = 2; break; 13459 } 13460 13461 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13462 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13463 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13464 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13465 // The to-be-promoted operands of this node have not yet been 13466 // promoted (this should be rare because we're going through the 13467 // list backward, but if one of the operands has several users in 13468 // this cluster of to-be-promoted nodes, it is possible). 13469 PromOpHandles.emplace_front(PromOp); 13470 continue; 13471 } 13472 13473 // For SELECT and SELECT_CC nodes, we do a similar check for any 13474 // to-be-promoted comparison inputs. 13475 if (PromOp.getOpcode() == ISD::SELECT || 13476 PromOp.getOpcode() == ISD::SELECT_CC) { 13477 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13478 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13479 (SelectTruncOp[1].count(PromOp.getNode()) && 13480 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13481 PromOpHandles.emplace_front(PromOp); 13482 continue; 13483 } 13484 } 13485 13486 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13487 PromOp.getNode()->op_end()); 13488 13489 // If this node has constant inputs, then they'll need to be promoted here. 13490 for (unsigned i = 0; i < 2; ++i) { 13491 if (!isa<ConstantSDNode>(Ops[C+i])) 13492 continue; 13493 if (Ops[C+i].getValueType() == N->getValueType(0)) 13494 continue; 13495 13496 if (N->getOpcode() == ISD::SIGN_EXTEND) 13497 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13498 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13499 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13500 else 13501 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13502 } 13503 13504 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13505 // truncate them again to the original value type. 13506 if (PromOp.getOpcode() == ISD::SELECT || 13507 PromOp.getOpcode() == ISD::SELECT_CC) { 13508 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13509 if (SI0 != SelectTruncOp[0].end()) 13510 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13511 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13512 if (SI1 != SelectTruncOp[1].end()) 13513 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13514 } 13515 13516 DAG.ReplaceAllUsesOfValueWith(PromOp, 13517 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13518 } 13519 13520 // Now we're left with the initial extension itself. 13521 if (!ReallyNeedsExt) 13522 return N->getOperand(0); 13523 13524 // To zero extend, just mask off everything except for the first bit (in the 13525 // i1 case). 13526 if (N->getOpcode() == ISD::ZERO_EXTEND) 13527 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13528 DAG.getConstant(APInt::getLowBitsSet( 13529 N->getValueSizeInBits(0), PromBits), 13530 dl, N->getValueType(0))); 13531 13532 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13533 "Invalid extension type"); 13534 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13535 SDValue ShiftCst = 13536 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13537 return DAG.getNode( 13538 ISD::SRA, dl, N->getValueType(0), 13539 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13540 ShiftCst); 13541 } 13542 13543 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13544 DAGCombinerInfo &DCI) const { 13545 assert(N->getOpcode() == ISD::SETCC && 13546 "Should be called with a SETCC node"); 13547 13548 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13549 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13550 SDValue LHS = N->getOperand(0); 13551 SDValue RHS = N->getOperand(1); 13552 13553 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13554 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13555 LHS.hasOneUse()) 13556 std::swap(LHS, RHS); 13557 13558 // x == 0-y --> x+y == 0 13559 // x != 0-y --> x+y != 0 13560 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13561 RHS.hasOneUse()) { 13562 SDLoc DL(N); 13563 SelectionDAG &DAG = DCI.DAG; 13564 EVT VT = N->getValueType(0); 13565 EVT OpVT = LHS.getValueType(); 13566 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13567 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13568 } 13569 } 13570 13571 return DAGCombineTruncBoolExt(N, DCI); 13572 } 13573 13574 // Is this an extending load from an f32 to an f64? 13575 static bool isFPExtLoad(SDValue Op) { 13576 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13577 return LD->getExtensionType() == ISD::EXTLOAD && 13578 Op.getValueType() == MVT::f64; 13579 return false; 13580 } 13581 13582 /// Reduces the number of fp-to-int conversion when building a vector. 13583 /// 13584 /// If this vector is built out of floating to integer conversions, 13585 /// transform it to a vector built out of floating point values followed by a 13586 /// single floating to integer conversion of the vector. 13587 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13588 /// becomes (fptosi (build_vector ($A, $B, ...))) 13589 SDValue PPCTargetLowering:: 13590 combineElementTruncationToVectorTruncation(SDNode *N, 13591 DAGCombinerInfo &DCI) const { 13592 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13593 "Should be called with a BUILD_VECTOR node"); 13594 13595 SelectionDAG &DAG = DCI.DAG; 13596 SDLoc dl(N); 13597 13598 SDValue FirstInput = N->getOperand(0); 13599 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13600 "The input operand must be an fp-to-int conversion."); 13601 13602 // This combine happens after legalization so the fp_to_[su]i nodes are 13603 // already converted to PPCSISD nodes. 13604 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13605 if (FirstConversion == PPCISD::FCTIDZ || 13606 FirstConversion == PPCISD::FCTIDUZ || 13607 FirstConversion == PPCISD::FCTIWZ || 13608 FirstConversion == PPCISD::FCTIWUZ) { 13609 bool IsSplat = true; 13610 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13611 FirstConversion == PPCISD::FCTIWUZ; 13612 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13613 SmallVector<SDValue, 4> Ops; 13614 EVT TargetVT = N->getValueType(0); 13615 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13616 SDValue NextOp = N->getOperand(i); 13617 if (NextOp.getOpcode() != PPCISD::MFVSR) 13618 return SDValue(); 13619 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13620 if (NextConversion != FirstConversion) 13621 return SDValue(); 13622 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13623 // This is not valid if the input was originally double precision. It is 13624 // also not profitable to do unless this is an extending load in which 13625 // case doing this combine will allow us to combine consecutive loads. 13626 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13627 return SDValue(); 13628 if (N->getOperand(i) != FirstInput) 13629 IsSplat = false; 13630 } 13631 13632 // If this is a splat, we leave it as-is since there will be only a single 13633 // fp-to-int conversion followed by a splat of the integer. This is better 13634 // for 32-bit and smaller ints and neutral for 64-bit ints. 13635 if (IsSplat) 13636 return SDValue(); 13637 13638 // Now that we know we have the right type of node, get its operands 13639 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13640 SDValue In = N->getOperand(i).getOperand(0); 13641 if (Is32Bit) { 13642 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13643 // here, we know that all inputs are extending loads so this is safe). 13644 if (In.isUndef()) 13645 Ops.push_back(DAG.getUNDEF(SrcVT)); 13646 else { 13647 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13648 MVT::f32, In.getOperand(0), 13649 DAG.getIntPtrConstant(1, dl)); 13650 Ops.push_back(Trunc); 13651 } 13652 } else 13653 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13654 } 13655 13656 unsigned Opcode; 13657 if (FirstConversion == PPCISD::FCTIDZ || 13658 FirstConversion == PPCISD::FCTIWZ) 13659 Opcode = ISD::FP_TO_SINT; 13660 else 13661 Opcode = ISD::FP_TO_UINT; 13662 13663 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13664 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13665 return DAG.getNode(Opcode, dl, TargetVT, BV); 13666 } 13667 return SDValue(); 13668 } 13669 13670 /// Reduce the number of loads when building a vector. 13671 /// 13672 /// Building a vector out of multiple loads can be converted to a load 13673 /// of the vector type if the loads are consecutive. If the loads are 13674 /// consecutive but in descending order, a shuffle is added at the end 13675 /// to reorder the vector. 13676 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13677 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13678 "Should be called with a BUILD_VECTOR node"); 13679 13680 SDLoc dl(N); 13681 13682 // Return early for non byte-sized type, as they can't be consecutive. 13683 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13684 return SDValue(); 13685 13686 bool InputsAreConsecutiveLoads = true; 13687 bool InputsAreReverseConsecutive = true; 13688 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13689 SDValue FirstInput = N->getOperand(0); 13690 bool IsRoundOfExtLoad = false; 13691 13692 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13693 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13694 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13695 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13696 } 13697 // Not a build vector of (possibly fp_rounded) loads. 13698 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13699 N->getNumOperands() == 1) 13700 return SDValue(); 13701 13702 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13703 // If any inputs are fp_round(extload), they all must be. 13704 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13705 return SDValue(); 13706 13707 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13708 N->getOperand(i); 13709 if (NextInput.getOpcode() != ISD::LOAD) 13710 return SDValue(); 13711 13712 SDValue PreviousInput = 13713 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13714 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13715 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13716 13717 // If any inputs are fp_round(extload), they all must be. 13718 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13719 return SDValue(); 13720 13721 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13722 InputsAreConsecutiveLoads = false; 13723 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13724 InputsAreReverseConsecutive = false; 13725 13726 // Exit early if the loads are neither consecutive nor reverse consecutive. 13727 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13728 return SDValue(); 13729 } 13730 13731 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13732 "The loads cannot be both consecutive and reverse consecutive."); 13733 13734 SDValue FirstLoadOp = 13735 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13736 SDValue LastLoadOp = 13737 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13738 N->getOperand(N->getNumOperands()-1); 13739 13740 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13741 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13742 if (InputsAreConsecutiveLoads) { 13743 assert(LD1 && "Input needs to be a LoadSDNode."); 13744 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13745 LD1->getBasePtr(), LD1->getPointerInfo(), 13746 LD1->getAlignment()); 13747 } 13748 if (InputsAreReverseConsecutive) { 13749 assert(LDL && "Input needs to be a LoadSDNode."); 13750 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13751 LDL->getBasePtr(), LDL->getPointerInfo(), 13752 LDL->getAlignment()); 13753 SmallVector<int, 16> Ops; 13754 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13755 Ops.push_back(i); 13756 13757 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13758 DAG.getUNDEF(N->getValueType(0)), Ops); 13759 } 13760 return SDValue(); 13761 } 13762 13763 // This function adds the required vector_shuffle needed to get 13764 // the elements of the vector extract in the correct position 13765 // as specified by the CorrectElems encoding. 13766 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13767 SDValue Input, uint64_t Elems, 13768 uint64_t CorrectElems) { 13769 SDLoc dl(N); 13770 13771 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13772 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13773 13774 // Knowing the element indices being extracted from the original 13775 // vector and the order in which they're being inserted, just put 13776 // them at element indices required for the instruction. 13777 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13778 if (DAG.getDataLayout().isLittleEndian()) 13779 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13780 else 13781 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13782 CorrectElems = CorrectElems >> 8; 13783 Elems = Elems >> 8; 13784 } 13785 13786 SDValue Shuffle = 13787 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13788 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13789 13790 EVT VT = N->getValueType(0); 13791 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13792 13793 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13794 Input.getValueType().getVectorElementType(), 13795 VT.getVectorNumElements()); 13796 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13797 DAG.getValueType(ExtVT)); 13798 } 13799 13800 // Look for build vector patterns where input operands come from sign 13801 // extended vector_extract elements of specific indices. If the correct indices 13802 // aren't used, add a vector shuffle to fix up the indices and create 13803 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13804 // during instruction selection. 13805 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13806 // This array encodes the indices that the vector sign extend instructions 13807 // extract from when extending from one type to another for both BE and LE. 13808 // The right nibble of each byte corresponds to the LE incides. 13809 // and the left nibble of each byte corresponds to the BE incides. 13810 // For example: 0x3074B8FC byte->word 13811 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13812 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13813 // For example: 0x000070F8 byte->double word 13814 // For LE: the allowed indices are: 0x0,0x8 13815 // For BE: the allowed indices are: 0x7,0xF 13816 uint64_t TargetElems[] = { 13817 0x3074B8FC, // b->w 13818 0x000070F8, // b->d 13819 0x10325476, // h->w 13820 0x00003074, // h->d 13821 0x00001032, // w->d 13822 }; 13823 13824 uint64_t Elems = 0; 13825 int Index; 13826 SDValue Input; 13827 13828 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13829 if (!Op) 13830 return false; 13831 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13832 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13833 return false; 13834 13835 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13836 // of the right width. 13837 SDValue Extract = Op.getOperand(0); 13838 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13839 Extract = Extract.getOperand(0); 13840 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13841 return false; 13842 13843 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13844 if (!ExtOp) 13845 return false; 13846 13847 Index = ExtOp->getZExtValue(); 13848 if (Input && Input != Extract.getOperand(0)) 13849 return false; 13850 13851 if (!Input) 13852 Input = Extract.getOperand(0); 13853 13854 Elems = Elems << 8; 13855 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13856 Elems |= Index; 13857 13858 return true; 13859 }; 13860 13861 // If the build vector operands aren't sign extended vector extracts, 13862 // of the same input vector, then return. 13863 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13864 if (!isSExtOfVecExtract(N->getOperand(i))) { 13865 return SDValue(); 13866 } 13867 } 13868 13869 // If the vector extract indicies are not correct, add the appropriate 13870 // vector_shuffle. 13871 int TgtElemArrayIdx; 13872 int InputSize = Input.getValueType().getScalarSizeInBits(); 13873 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13874 if (InputSize + OutputSize == 40) 13875 TgtElemArrayIdx = 0; 13876 else if (InputSize + OutputSize == 72) 13877 TgtElemArrayIdx = 1; 13878 else if (InputSize + OutputSize == 48) 13879 TgtElemArrayIdx = 2; 13880 else if (InputSize + OutputSize == 80) 13881 TgtElemArrayIdx = 3; 13882 else if (InputSize + OutputSize == 96) 13883 TgtElemArrayIdx = 4; 13884 else 13885 return SDValue(); 13886 13887 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13888 CorrectElems = DAG.getDataLayout().isLittleEndian() 13889 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13890 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13891 if (Elems != CorrectElems) { 13892 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13893 } 13894 13895 // Regular lowering will catch cases where a shuffle is not needed. 13896 return SDValue(); 13897 } 13898 13899 // Look for the pattern of a load from a narrow width to i128, feeding 13900 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13901 // (LXVRZX). This node represents a zero extending load that will be matched 13902 // to the Load VSX Vector Rightmost instructions. 13903 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13904 SDLoc DL(N); 13905 13906 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13907 if (N->getValueType(0) != MVT::v1i128) 13908 return SDValue(); 13909 13910 SDValue Operand = N->getOperand(0); 13911 // Proceed with the transformation if the operand to the BUILD_VECTOR 13912 // is a load instruction. 13913 if (Operand.getOpcode() != ISD::LOAD) 13914 return SDValue(); 13915 13916 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13917 EVT MemoryType = LD->getMemoryVT(); 13918 13919 // This transformation is only valid if the we are loading either a byte, 13920 // halfword, word, or doubleword. 13921 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13922 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13923 13924 // Ensure that the load from the narrow width is being zero extended to i128. 13925 if (!ValidLDType || 13926 (LD->getExtensionType() != ISD::ZEXTLOAD && 13927 LD->getExtensionType() != ISD::EXTLOAD)) 13928 return SDValue(); 13929 13930 SDValue LoadOps[] = { 13931 LD->getChain(), LD->getBasePtr(), 13932 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13933 13934 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13935 DAG.getVTList(MVT::v1i128, MVT::Other), 13936 LoadOps, MemoryType, LD->getMemOperand()); 13937 } 13938 13939 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13940 DAGCombinerInfo &DCI) const { 13941 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13942 "Should be called with a BUILD_VECTOR node"); 13943 13944 SelectionDAG &DAG = DCI.DAG; 13945 SDLoc dl(N); 13946 13947 if (!Subtarget.hasVSX()) 13948 return SDValue(); 13949 13950 // The target independent DAG combiner will leave a build_vector of 13951 // float-to-int conversions intact. We can generate MUCH better code for 13952 // a float-to-int conversion of a vector of floats. 13953 SDValue FirstInput = N->getOperand(0); 13954 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13955 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13956 if (Reduced) 13957 return Reduced; 13958 } 13959 13960 // If we're building a vector out of consecutive loads, just load that 13961 // vector type. 13962 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13963 if (Reduced) 13964 return Reduced; 13965 13966 // If we're building a vector out of extended elements from another vector 13967 // we have P9 vector integer extend instructions. The code assumes legal 13968 // input types (i.e. it can't handle things like v4i16) so do not run before 13969 // legalization. 13970 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13971 Reduced = combineBVOfVecSExt(N, DAG); 13972 if (Reduced) 13973 return Reduced; 13974 } 13975 13976 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13977 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13978 // is a load from <valid narrow width> to i128. 13979 if (Subtarget.isISA3_1()) { 13980 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13981 if (BVOfZLoad) 13982 return BVOfZLoad; 13983 } 13984 13985 if (N->getValueType(0) != MVT::v2f64) 13986 return SDValue(); 13987 13988 // Looking for: 13989 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13990 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13991 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13992 return SDValue(); 13993 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13994 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13995 return SDValue(); 13996 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13997 return SDValue(); 13998 13999 SDValue Ext1 = FirstInput.getOperand(0); 14000 SDValue Ext2 = N->getOperand(1).getOperand(0); 14001 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14002 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14003 return SDValue(); 14004 14005 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14006 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14007 if (!Ext1Op || !Ext2Op) 14008 return SDValue(); 14009 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14010 Ext1.getOperand(0) != Ext2.getOperand(0)) 14011 return SDValue(); 14012 14013 int FirstElem = Ext1Op->getZExtValue(); 14014 int SecondElem = Ext2Op->getZExtValue(); 14015 int SubvecIdx; 14016 if (FirstElem == 0 && SecondElem == 1) 14017 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14018 else if (FirstElem == 2 && SecondElem == 3) 14019 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14020 else 14021 return SDValue(); 14022 14023 SDValue SrcVec = Ext1.getOperand(0); 14024 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14025 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14026 return DAG.getNode(NodeType, dl, MVT::v2f64, 14027 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14028 } 14029 14030 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14031 DAGCombinerInfo &DCI) const { 14032 assert((N->getOpcode() == ISD::SINT_TO_FP || 14033 N->getOpcode() == ISD::UINT_TO_FP) && 14034 "Need an int -> FP conversion node here"); 14035 14036 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14037 return SDValue(); 14038 14039 SelectionDAG &DAG = DCI.DAG; 14040 SDLoc dl(N); 14041 SDValue Op(N, 0); 14042 14043 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14044 // from the hardware. 14045 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14046 return SDValue(); 14047 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14048 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14049 return SDValue(); 14050 14051 SDValue FirstOperand(Op.getOperand(0)); 14052 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14053 (FirstOperand.getValueType() == MVT::i8 || 14054 FirstOperand.getValueType() == MVT::i16); 14055 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14056 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14057 bool DstDouble = Op.getValueType() == MVT::f64; 14058 unsigned ConvOp = Signed ? 14059 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14060 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14061 SDValue WidthConst = 14062 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14063 dl, false); 14064 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14065 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14066 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14067 DAG.getVTList(MVT::f64, MVT::Other), 14068 Ops, MVT::i8, LDN->getMemOperand()); 14069 14070 // For signed conversion, we need to sign-extend the value in the VSR 14071 if (Signed) { 14072 SDValue ExtOps[] = { Ld, WidthConst }; 14073 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14074 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14075 } else 14076 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14077 } 14078 14079 14080 // For i32 intermediate values, unfortunately, the conversion functions 14081 // leave the upper 32 bits of the value are undefined. Within the set of 14082 // scalar instructions, we have no method for zero- or sign-extending the 14083 // value. Thus, we cannot handle i32 intermediate values here. 14084 if (Op.getOperand(0).getValueType() == MVT::i32) 14085 return SDValue(); 14086 14087 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14088 "UINT_TO_FP is supported only with FPCVT"); 14089 14090 // If we have FCFIDS, then use it when converting to single-precision. 14091 // Otherwise, convert to double-precision and then round. 14092 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14093 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14094 : PPCISD::FCFIDS) 14095 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14096 : PPCISD::FCFID); 14097 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14098 ? MVT::f32 14099 : MVT::f64; 14100 14101 // If we're converting from a float, to an int, and back to a float again, 14102 // then we don't need the store/load pair at all. 14103 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14104 Subtarget.hasFPCVT()) || 14105 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14106 SDValue Src = Op.getOperand(0).getOperand(0); 14107 if (Src.getValueType() == MVT::f32) { 14108 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14109 DCI.AddToWorklist(Src.getNode()); 14110 } else if (Src.getValueType() != MVT::f64) { 14111 // Make sure that we don't pick up a ppc_fp128 source value. 14112 return SDValue(); 14113 } 14114 14115 unsigned FCTOp = 14116 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14117 PPCISD::FCTIDUZ; 14118 14119 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14120 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14121 14122 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14123 FP = DAG.getNode(ISD::FP_ROUND, dl, 14124 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14125 DCI.AddToWorklist(FP.getNode()); 14126 } 14127 14128 return FP; 14129 } 14130 14131 return SDValue(); 14132 } 14133 14134 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14135 // builtins) into loads with swaps. 14136 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14137 DAGCombinerInfo &DCI) const { 14138 SelectionDAG &DAG = DCI.DAG; 14139 SDLoc dl(N); 14140 SDValue Chain; 14141 SDValue Base; 14142 MachineMemOperand *MMO; 14143 14144 switch (N->getOpcode()) { 14145 default: 14146 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14147 case ISD::LOAD: { 14148 LoadSDNode *LD = cast<LoadSDNode>(N); 14149 Chain = LD->getChain(); 14150 Base = LD->getBasePtr(); 14151 MMO = LD->getMemOperand(); 14152 // If the MMO suggests this isn't a load of a full vector, leave 14153 // things alone. For a built-in, we have to make the change for 14154 // correctness, so if there is a size problem that will be a bug. 14155 if (MMO->getSize() < 16) 14156 return SDValue(); 14157 break; 14158 } 14159 case ISD::INTRINSIC_W_CHAIN: { 14160 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14161 Chain = Intrin->getChain(); 14162 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14163 // us what we want. Get operand 2 instead. 14164 Base = Intrin->getOperand(2); 14165 MMO = Intrin->getMemOperand(); 14166 break; 14167 } 14168 } 14169 14170 MVT VecTy = N->getValueType(0).getSimpleVT(); 14171 14172 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14173 // aligned and the type is a vector with elements up to 4 bytes 14174 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14175 VecTy.getScalarSizeInBits() <= 32) { 14176 return SDValue(); 14177 } 14178 14179 SDValue LoadOps[] = { Chain, Base }; 14180 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14181 DAG.getVTList(MVT::v2f64, MVT::Other), 14182 LoadOps, MVT::v2f64, MMO); 14183 14184 DCI.AddToWorklist(Load.getNode()); 14185 Chain = Load.getValue(1); 14186 SDValue Swap = DAG.getNode( 14187 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14188 DCI.AddToWorklist(Swap.getNode()); 14189 14190 // Add a bitcast if the resulting load type doesn't match v2f64. 14191 if (VecTy != MVT::v2f64) { 14192 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14193 DCI.AddToWorklist(N.getNode()); 14194 // Package {bitcast value, swap's chain} to match Load's shape. 14195 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14196 N, Swap.getValue(1)); 14197 } 14198 14199 return Swap; 14200 } 14201 14202 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14203 // builtins) into stores with swaps. 14204 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14205 DAGCombinerInfo &DCI) const { 14206 SelectionDAG &DAG = DCI.DAG; 14207 SDLoc dl(N); 14208 SDValue Chain; 14209 SDValue Base; 14210 unsigned SrcOpnd; 14211 MachineMemOperand *MMO; 14212 14213 switch (N->getOpcode()) { 14214 default: 14215 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14216 case ISD::STORE: { 14217 StoreSDNode *ST = cast<StoreSDNode>(N); 14218 Chain = ST->getChain(); 14219 Base = ST->getBasePtr(); 14220 MMO = ST->getMemOperand(); 14221 SrcOpnd = 1; 14222 // If the MMO suggests this isn't a store of a full vector, leave 14223 // things alone. For a built-in, we have to make the change for 14224 // correctness, so if there is a size problem that will be a bug. 14225 if (MMO->getSize() < 16) 14226 return SDValue(); 14227 break; 14228 } 14229 case ISD::INTRINSIC_VOID: { 14230 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14231 Chain = Intrin->getChain(); 14232 // Intrin->getBasePtr() oddly does not get what we want. 14233 Base = Intrin->getOperand(3); 14234 MMO = Intrin->getMemOperand(); 14235 SrcOpnd = 2; 14236 break; 14237 } 14238 } 14239 14240 SDValue Src = N->getOperand(SrcOpnd); 14241 MVT VecTy = Src.getValueType().getSimpleVT(); 14242 14243 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14244 // aligned and the type is a vector with elements up to 4 bytes 14245 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14246 VecTy.getScalarSizeInBits() <= 32) { 14247 return SDValue(); 14248 } 14249 14250 // All stores are done as v2f64 and possible bit cast. 14251 if (VecTy != MVT::v2f64) { 14252 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14253 DCI.AddToWorklist(Src.getNode()); 14254 } 14255 14256 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14257 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14258 DCI.AddToWorklist(Swap.getNode()); 14259 Chain = Swap.getValue(1); 14260 SDValue StoreOps[] = { Chain, Swap, Base }; 14261 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14262 DAG.getVTList(MVT::Other), 14263 StoreOps, VecTy, MMO); 14264 DCI.AddToWorklist(Store.getNode()); 14265 return Store; 14266 } 14267 14268 // Handle DAG combine for STORE (FP_TO_INT F). 14269 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14270 DAGCombinerInfo &DCI) const { 14271 14272 SelectionDAG &DAG = DCI.DAG; 14273 SDLoc dl(N); 14274 unsigned Opcode = N->getOperand(1).getOpcode(); 14275 14276 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14277 && "Not a FP_TO_INT Instruction!"); 14278 14279 SDValue Val = N->getOperand(1).getOperand(0); 14280 EVT Op1VT = N->getOperand(1).getValueType(); 14281 EVT ResVT = Val.getValueType(); 14282 14283 if (!isTypeLegal(ResVT)) 14284 return SDValue(); 14285 14286 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14287 bool ValidTypeForStoreFltAsInt = 14288 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14289 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14290 14291 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14292 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14293 return SDValue(); 14294 14295 // Extend f32 values to f64 14296 if (ResVT.getScalarSizeInBits() == 32) { 14297 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14298 DCI.AddToWorklist(Val.getNode()); 14299 } 14300 14301 // Set signed or unsigned conversion opcode. 14302 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14303 PPCISD::FP_TO_SINT_IN_VSR : 14304 PPCISD::FP_TO_UINT_IN_VSR; 14305 14306 Val = DAG.getNode(ConvOpcode, 14307 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14308 DCI.AddToWorklist(Val.getNode()); 14309 14310 // Set number of bytes being converted. 14311 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14312 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14313 DAG.getIntPtrConstant(ByteSize, dl, false), 14314 DAG.getValueType(Op1VT) }; 14315 14316 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14317 DAG.getVTList(MVT::Other), Ops, 14318 cast<StoreSDNode>(N)->getMemoryVT(), 14319 cast<StoreSDNode>(N)->getMemOperand()); 14320 14321 DCI.AddToWorklist(Val.getNode()); 14322 return Val; 14323 } 14324 14325 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14326 // Check that the source of the element keeps flipping 14327 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14328 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14329 for (int i = 1, e = Mask.size(); i < e; i++) { 14330 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14331 return false; 14332 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14333 return false; 14334 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14335 } 14336 return true; 14337 } 14338 14339 static bool isSplatBV(SDValue Op) { 14340 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14341 return false; 14342 SDValue FirstOp; 14343 14344 // Find first non-undef input. 14345 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14346 FirstOp = Op.getOperand(i); 14347 if (!FirstOp.isUndef()) 14348 break; 14349 } 14350 14351 // All inputs are undef or the same as the first non-undef input. 14352 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14353 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14354 return false; 14355 return true; 14356 } 14357 14358 static SDValue isScalarToVec(SDValue Op) { 14359 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14360 return Op; 14361 if (Op.getOpcode() != ISD::BITCAST) 14362 return SDValue(); 14363 Op = Op.getOperand(0); 14364 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14365 return Op; 14366 return SDValue(); 14367 } 14368 14369 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14370 int LHSMaxIdx, int RHSMinIdx, 14371 int RHSMaxIdx, int HalfVec) { 14372 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14373 int Idx = ShuffV[i]; 14374 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14375 ShuffV[i] += HalfVec; 14376 } 14377 return; 14378 } 14379 14380 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14381 // the original is: 14382 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14383 // In such a case, just change the shuffle mask to extract the element 14384 // from the permuted index. 14385 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14386 SDLoc dl(OrigSToV); 14387 EVT VT = OrigSToV.getValueType(); 14388 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14389 "Expecting a SCALAR_TO_VECTOR here"); 14390 SDValue Input = OrigSToV.getOperand(0); 14391 14392 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14393 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14394 SDValue OrigVector = Input.getOperand(0); 14395 14396 // Can't handle non-const element indices or different vector types 14397 // for the input to the extract and the output of the scalar_to_vector. 14398 if (Idx && VT == OrigVector.getValueType()) { 14399 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14400 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14401 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14402 } 14403 } 14404 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14405 OrigSToV.getOperand(0)); 14406 } 14407 14408 // On little endian subtargets, combine shuffles such as: 14409 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14410 // into: 14411 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14412 // because the latter can be matched to a single instruction merge. 14413 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14414 // to put the value into element zero. Adjust the shuffle mask so that the 14415 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14416 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14417 SelectionDAG &DAG) const { 14418 SDValue LHS = SVN->getOperand(0); 14419 SDValue RHS = SVN->getOperand(1); 14420 auto Mask = SVN->getMask(); 14421 int NumElts = LHS.getValueType().getVectorNumElements(); 14422 SDValue Res(SVN, 0); 14423 SDLoc dl(SVN); 14424 14425 // None of these combines are useful on big endian systems since the ISA 14426 // already has a big endian bias. 14427 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14428 return Res; 14429 14430 // If this is not a shuffle of a shuffle and the first element comes from 14431 // the second vector, canonicalize to the commuted form. This will make it 14432 // more likely to match one of the single instruction patterns. 14433 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14434 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14435 std::swap(LHS, RHS); 14436 Res = DAG.getCommutedVectorShuffle(*SVN); 14437 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14438 } 14439 14440 // Adjust the shuffle mask if either input vector comes from a 14441 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14442 // form (to prevent the need for a swap). 14443 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14444 SDValue SToVLHS = isScalarToVec(LHS); 14445 SDValue SToVRHS = isScalarToVec(RHS); 14446 if (SToVLHS || SToVRHS) { 14447 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14448 : SToVRHS.getValueType().getVectorNumElements(); 14449 int NumEltsOut = ShuffV.size(); 14450 14451 // Initially assume that neither input is permuted. These will be adjusted 14452 // accordingly if either input is. 14453 int LHSMaxIdx = -1; 14454 int RHSMinIdx = -1; 14455 int RHSMaxIdx = -1; 14456 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14457 14458 // Get the permuted scalar to vector nodes for the source(s) that come from 14459 // ISD::SCALAR_TO_VECTOR. 14460 if (SToVLHS) { 14461 // Set up the values for the shuffle vector fixup. 14462 LHSMaxIdx = NumEltsOut / NumEltsIn; 14463 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14464 if (SToVLHS.getValueType() != LHS.getValueType()) 14465 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14466 LHS = SToVLHS; 14467 } 14468 if (SToVRHS) { 14469 RHSMinIdx = NumEltsOut; 14470 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14471 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14472 if (SToVRHS.getValueType() != RHS.getValueType()) 14473 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14474 RHS = SToVRHS; 14475 } 14476 14477 // Fix up the shuffle mask to reflect where the desired element actually is. 14478 // The minimum and maximum indices that correspond to element zero for both 14479 // the LHS and RHS are computed and will control which shuffle mask entries 14480 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14481 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14482 // HalfVec to refer to the corresponding element in the permuted vector. 14483 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14484 HalfVec); 14485 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14486 14487 // We may have simplified away the shuffle. We won't be able to do anything 14488 // further with it here. 14489 if (!isa<ShuffleVectorSDNode>(Res)) 14490 return Res; 14491 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14492 } 14493 14494 // The common case after we commuted the shuffle is that the RHS is a splat 14495 // and we have elements coming in from the splat at indices that are not 14496 // conducive to using a merge. 14497 // Example: 14498 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14499 if (!isSplatBV(RHS)) 14500 return Res; 14501 14502 // We are looking for a mask such that all even elements are from 14503 // one vector and all odd elements from the other. 14504 if (!isAlternatingShuffMask(Mask, NumElts)) 14505 return Res; 14506 14507 // Adjust the mask so we are pulling in the same index from the splat 14508 // as the index from the interesting vector in consecutive elements. 14509 // Example (even elements from first vector): 14510 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14511 if (Mask[0] < NumElts) 14512 for (int i = 1, e = Mask.size(); i < e; i += 2) 14513 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14514 // Example (odd elements from first vector): 14515 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14516 else 14517 for (int i = 0, e = Mask.size(); i < e; i += 2) 14518 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14519 14520 // If the RHS has undefs, we need to remove them since we may have created 14521 // a shuffle that adds those instead of the splat value. 14522 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14523 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14524 14525 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14526 return Res; 14527 } 14528 14529 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14530 LSBaseSDNode *LSBase, 14531 DAGCombinerInfo &DCI) const { 14532 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14533 "Not a reverse memop pattern!"); 14534 14535 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14536 auto Mask = SVN->getMask(); 14537 int i = 0; 14538 auto I = Mask.rbegin(); 14539 auto E = Mask.rend(); 14540 14541 for (; I != E; ++I) { 14542 if (*I != i) 14543 return false; 14544 i++; 14545 } 14546 return true; 14547 }; 14548 14549 SelectionDAG &DAG = DCI.DAG; 14550 EVT VT = SVN->getValueType(0); 14551 14552 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14553 return SDValue(); 14554 14555 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14556 // See comment in PPCVSXSwapRemoval.cpp. 14557 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14558 if (!Subtarget.hasP9Vector()) 14559 return SDValue(); 14560 14561 if(!IsElementReverse(SVN)) 14562 return SDValue(); 14563 14564 if (LSBase->getOpcode() == ISD::LOAD) { 14565 SDLoc dl(SVN); 14566 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14567 return DAG.getMemIntrinsicNode( 14568 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14569 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14570 } 14571 14572 if (LSBase->getOpcode() == ISD::STORE) { 14573 SDLoc dl(LSBase); 14574 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14575 LSBase->getBasePtr()}; 14576 return DAG.getMemIntrinsicNode( 14577 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14578 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14579 } 14580 14581 llvm_unreachable("Expected a load or store node here"); 14582 } 14583 14584 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14585 DAGCombinerInfo &DCI) const { 14586 SelectionDAG &DAG = DCI.DAG; 14587 SDLoc dl(N); 14588 switch (N->getOpcode()) { 14589 default: break; 14590 case ISD::ADD: 14591 return combineADD(N, DCI); 14592 case ISD::SHL: 14593 return combineSHL(N, DCI); 14594 case ISD::SRA: 14595 return combineSRA(N, DCI); 14596 case ISD::SRL: 14597 return combineSRL(N, DCI); 14598 case ISD::MUL: 14599 return combineMUL(N, DCI); 14600 case ISD::FMA: 14601 case PPCISD::FNMSUB: 14602 return combineFMALike(N, DCI); 14603 case PPCISD::SHL: 14604 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14605 return N->getOperand(0); 14606 break; 14607 case PPCISD::SRL: 14608 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14609 return N->getOperand(0); 14610 break; 14611 case PPCISD::SRA: 14612 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14613 if (C->isNullValue() || // 0 >>s V -> 0. 14614 C->isAllOnesValue()) // -1 >>s V -> -1. 14615 return N->getOperand(0); 14616 } 14617 break; 14618 case ISD::SIGN_EXTEND: 14619 case ISD::ZERO_EXTEND: 14620 case ISD::ANY_EXTEND: 14621 return DAGCombineExtBoolTrunc(N, DCI); 14622 case ISD::TRUNCATE: 14623 return combineTRUNCATE(N, DCI); 14624 case ISD::SETCC: 14625 if (SDValue CSCC = combineSetCC(N, DCI)) 14626 return CSCC; 14627 LLVM_FALLTHROUGH; 14628 case ISD::SELECT_CC: 14629 return DAGCombineTruncBoolExt(N, DCI); 14630 case ISD::SINT_TO_FP: 14631 case ISD::UINT_TO_FP: 14632 return combineFPToIntToFP(N, DCI); 14633 case ISD::VECTOR_SHUFFLE: 14634 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14635 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14636 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14637 } 14638 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14639 case ISD::STORE: { 14640 14641 EVT Op1VT = N->getOperand(1).getValueType(); 14642 unsigned Opcode = N->getOperand(1).getOpcode(); 14643 14644 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14645 SDValue Val= combineStoreFPToInt(N, DCI); 14646 if (Val) 14647 return Val; 14648 } 14649 14650 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14651 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14652 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14653 if (Val) 14654 return Val; 14655 } 14656 14657 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14658 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14659 N->getOperand(1).getNode()->hasOneUse() && 14660 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14661 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14662 14663 // STBRX can only handle simple types and it makes no sense to store less 14664 // two bytes in byte-reversed order. 14665 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14666 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14667 break; 14668 14669 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14670 // Do an any-extend to 32-bits if this is a half-word input. 14671 if (BSwapOp.getValueType() == MVT::i16) 14672 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14673 14674 // If the type of BSWAP operand is wider than stored memory width 14675 // it need to be shifted to the right side before STBRX. 14676 if (Op1VT.bitsGT(mVT)) { 14677 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14678 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14679 DAG.getConstant(Shift, dl, MVT::i32)); 14680 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14681 if (Op1VT == MVT::i64) 14682 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14683 } 14684 14685 SDValue Ops[] = { 14686 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14687 }; 14688 return 14689 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14690 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14691 cast<StoreSDNode>(N)->getMemOperand()); 14692 } 14693 14694 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14695 // So it can increase the chance of CSE constant construction. 14696 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14697 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14698 // Need to sign-extended to 64-bits to handle negative values. 14699 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14700 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14701 MemVT.getSizeInBits()); 14702 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14703 14704 // DAG.getTruncStore() can't be used here because it doesn't accept 14705 // the general (base + offset) addressing mode. 14706 // So we use UpdateNodeOperands and setTruncatingStore instead. 14707 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14708 N->getOperand(3)); 14709 cast<StoreSDNode>(N)->setTruncatingStore(true); 14710 return SDValue(N, 0); 14711 } 14712 14713 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14714 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14715 if (Op1VT.isSimple()) { 14716 MVT StoreVT = Op1VT.getSimpleVT(); 14717 if (Subtarget.needsSwapsForVSXMemOps() && 14718 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14719 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14720 return expandVSXStoreForLE(N, DCI); 14721 } 14722 break; 14723 } 14724 case ISD::LOAD: { 14725 LoadSDNode *LD = cast<LoadSDNode>(N); 14726 EVT VT = LD->getValueType(0); 14727 14728 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14729 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14730 if (VT.isSimple()) { 14731 MVT LoadVT = VT.getSimpleVT(); 14732 if (Subtarget.needsSwapsForVSXMemOps() && 14733 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14734 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14735 return expandVSXLoadForLE(N, DCI); 14736 } 14737 14738 // We sometimes end up with a 64-bit integer load, from which we extract 14739 // two single-precision floating-point numbers. This happens with 14740 // std::complex<float>, and other similar structures, because of the way we 14741 // canonicalize structure copies. However, if we lack direct moves, 14742 // then the final bitcasts from the extracted integer values to the 14743 // floating-point numbers turn into store/load pairs. Even with direct moves, 14744 // just loading the two floating-point numbers is likely better. 14745 auto ReplaceTwoFloatLoad = [&]() { 14746 if (VT != MVT::i64) 14747 return false; 14748 14749 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14750 LD->isVolatile()) 14751 return false; 14752 14753 // We're looking for a sequence like this: 14754 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14755 // t16: i64 = srl t13, Constant:i32<32> 14756 // t17: i32 = truncate t16 14757 // t18: f32 = bitcast t17 14758 // t19: i32 = truncate t13 14759 // t20: f32 = bitcast t19 14760 14761 if (!LD->hasNUsesOfValue(2, 0)) 14762 return false; 14763 14764 auto UI = LD->use_begin(); 14765 while (UI.getUse().getResNo() != 0) ++UI; 14766 SDNode *Trunc = *UI++; 14767 while (UI.getUse().getResNo() != 0) ++UI; 14768 SDNode *RightShift = *UI; 14769 if (Trunc->getOpcode() != ISD::TRUNCATE) 14770 std::swap(Trunc, RightShift); 14771 14772 if (Trunc->getOpcode() != ISD::TRUNCATE || 14773 Trunc->getValueType(0) != MVT::i32 || 14774 !Trunc->hasOneUse()) 14775 return false; 14776 if (RightShift->getOpcode() != ISD::SRL || 14777 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14778 RightShift->getConstantOperandVal(1) != 32 || 14779 !RightShift->hasOneUse()) 14780 return false; 14781 14782 SDNode *Trunc2 = *RightShift->use_begin(); 14783 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14784 Trunc2->getValueType(0) != MVT::i32 || 14785 !Trunc2->hasOneUse()) 14786 return false; 14787 14788 SDNode *Bitcast = *Trunc->use_begin(); 14789 SDNode *Bitcast2 = *Trunc2->use_begin(); 14790 14791 if (Bitcast->getOpcode() != ISD::BITCAST || 14792 Bitcast->getValueType(0) != MVT::f32) 14793 return false; 14794 if (Bitcast2->getOpcode() != ISD::BITCAST || 14795 Bitcast2->getValueType(0) != MVT::f32) 14796 return false; 14797 14798 if (Subtarget.isLittleEndian()) 14799 std::swap(Bitcast, Bitcast2); 14800 14801 // Bitcast has the second float (in memory-layout order) and Bitcast2 14802 // has the first one. 14803 14804 SDValue BasePtr = LD->getBasePtr(); 14805 if (LD->isIndexed()) { 14806 assert(LD->getAddressingMode() == ISD::PRE_INC && 14807 "Non-pre-inc AM on PPC?"); 14808 BasePtr = 14809 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14810 LD->getOffset()); 14811 } 14812 14813 auto MMOFlags = 14814 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14815 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14816 LD->getPointerInfo(), LD->getAlignment(), 14817 MMOFlags, LD->getAAInfo()); 14818 SDValue AddPtr = 14819 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14820 BasePtr, DAG.getIntPtrConstant(4, dl)); 14821 SDValue FloatLoad2 = DAG.getLoad( 14822 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14823 LD->getPointerInfo().getWithOffset(4), 14824 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14825 14826 if (LD->isIndexed()) { 14827 // Note that DAGCombine should re-form any pre-increment load(s) from 14828 // what is produced here if that makes sense. 14829 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14830 } 14831 14832 DCI.CombineTo(Bitcast2, FloatLoad); 14833 DCI.CombineTo(Bitcast, FloatLoad2); 14834 14835 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14836 SDValue(FloatLoad2.getNode(), 1)); 14837 return true; 14838 }; 14839 14840 if (ReplaceTwoFloatLoad()) 14841 return SDValue(N, 0); 14842 14843 EVT MemVT = LD->getMemoryVT(); 14844 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14845 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14846 if (LD->isUnindexed() && VT.isVector() && 14847 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14848 // P8 and later hardware should just use LOAD. 14849 !Subtarget.hasP8Vector() && 14850 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14851 VT == MVT::v4f32))) && 14852 LD->getAlign() < ABIAlignment) { 14853 // This is a type-legal unaligned Altivec load. 14854 SDValue Chain = LD->getChain(); 14855 SDValue Ptr = LD->getBasePtr(); 14856 bool isLittleEndian = Subtarget.isLittleEndian(); 14857 14858 // This implements the loading of unaligned vectors as described in 14859 // the venerable Apple Velocity Engine overview. Specifically: 14860 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14861 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14862 // 14863 // The general idea is to expand a sequence of one or more unaligned 14864 // loads into an alignment-based permutation-control instruction (lvsl 14865 // or lvsr), a series of regular vector loads (which always truncate 14866 // their input address to an aligned address), and a series of 14867 // permutations. The results of these permutations are the requested 14868 // loaded values. The trick is that the last "extra" load is not taken 14869 // from the address you might suspect (sizeof(vector) bytes after the 14870 // last requested load), but rather sizeof(vector) - 1 bytes after the 14871 // last requested vector. The point of this is to avoid a page fault if 14872 // the base address happened to be aligned. This works because if the 14873 // base address is aligned, then adding less than a full vector length 14874 // will cause the last vector in the sequence to be (re)loaded. 14875 // Otherwise, the next vector will be fetched as you might suspect was 14876 // necessary. 14877 14878 // We might be able to reuse the permutation generation from 14879 // a different base address offset from this one by an aligned amount. 14880 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14881 // optimization later. 14882 Intrinsic::ID Intr, IntrLD, IntrPerm; 14883 MVT PermCntlTy, PermTy, LDTy; 14884 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14885 : Intrinsic::ppc_altivec_lvsl; 14886 IntrLD = Intrinsic::ppc_altivec_lvx; 14887 IntrPerm = Intrinsic::ppc_altivec_vperm; 14888 PermCntlTy = MVT::v16i8; 14889 PermTy = MVT::v4i32; 14890 LDTy = MVT::v4i32; 14891 14892 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14893 14894 // Create the new MMO for the new base load. It is like the original MMO, 14895 // but represents an area in memory almost twice the vector size centered 14896 // on the original address. If the address is unaligned, we might start 14897 // reading up to (sizeof(vector)-1) bytes below the address of the 14898 // original unaligned load. 14899 MachineFunction &MF = DAG.getMachineFunction(); 14900 MachineMemOperand *BaseMMO = 14901 MF.getMachineMemOperand(LD->getMemOperand(), 14902 -(long)MemVT.getStoreSize()+1, 14903 2*MemVT.getStoreSize()-1); 14904 14905 // Create the new base load. 14906 SDValue LDXIntID = 14907 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14908 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14909 SDValue BaseLoad = 14910 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14911 DAG.getVTList(PermTy, MVT::Other), 14912 BaseLoadOps, LDTy, BaseMMO); 14913 14914 // Note that the value of IncOffset (which is provided to the next 14915 // load's pointer info offset value, and thus used to calculate the 14916 // alignment), and the value of IncValue (which is actually used to 14917 // increment the pointer value) are different! This is because we 14918 // require the next load to appear to be aligned, even though it 14919 // is actually offset from the base pointer by a lesser amount. 14920 int IncOffset = VT.getSizeInBits() / 8; 14921 int IncValue = IncOffset; 14922 14923 // Walk (both up and down) the chain looking for another load at the real 14924 // (aligned) offset (the alignment of the other load does not matter in 14925 // this case). If found, then do not use the offset reduction trick, as 14926 // that will prevent the loads from being later combined (as they would 14927 // otherwise be duplicates). 14928 if (!findConsecutiveLoad(LD, DAG)) 14929 --IncValue; 14930 14931 SDValue Increment = 14932 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14933 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14934 14935 MachineMemOperand *ExtraMMO = 14936 MF.getMachineMemOperand(LD->getMemOperand(), 14937 1, 2*MemVT.getStoreSize()-1); 14938 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14939 SDValue ExtraLoad = 14940 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14941 DAG.getVTList(PermTy, MVT::Other), 14942 ExtraLoadOps, LDTy, ExtraMMO); 14943 14944 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14945 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14946 14947 // Because vperm has a big-endian bias, we must reverse the order 14948 // of the input vectors and complement the permute control vector 14949 // when generating little endian code. We have already handled the 14950 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14951 // and ExtraLoad here. 14952 SDValue Perm; 14953 if (isLittleEndian) 14954 Perm = BuildIntrinsicOp(IntrPerm, 14955 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14956 else 14957 Perm = BuildIntrinsicOp(IntrPerm, 14958 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14959 14960 if (VT != PermTy) 14961 Perm = Subtarget.hasAltivec() 14962 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14963 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14964 DAG.getTargetConstant(1, dl, MVT::i64)); 14965 // second argument is 1 because this rounding 14966 // is always exact. 14967 14968 // The output of the permutation is our loaded result, the TokenFactor is 14969 // our new chain. 14970 DCI.CombineTo(N, Perm, TF); 14971 return SDValue(N, 0); 14972 } 14973 } 14974 break; 14975 case ISD::INTRINSIC_WO_CHAIN: { 14976 bool isLittleEndian = Subtarget.isLittleEndian(); 14977 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14978 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14979 : Intrinsic::ppc_altivec_lvsl); 14980 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14981 SDValue Add = N->getOperand(1); 14982 14983 int Bits = 4 /* 16 byte alignment */; 14984 14985 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14986 APInt::getAllOnesValue(Bits /* alignment */) 14987 .zext(Add.getScalarValueSizeInBits()))) { 14988 SDNode *BasePtr = Add->getOperand(0).getNode(); 14989 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14990 UE = BasePtr->use_end(); 14991 UI != UE; ++UI) { 14992 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14993 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14994 IID) { 14995 // We've found another LVSL/LVSR, and this address is an aligned 14996 // multiple of that one. The results will be the same, so use the 14997 // one we've just found instead. 14998 14999 return SDValue(*UI, 0); 15000 } 15001 } 15002 } 15003 15004 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15005 SDNode *BasePtr = Add->getOperand(0).getNode(); 15006 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15007 UE = BasePtr->use_end(); UI != UE; ++UI) { 15008 if (UI->getOpcode() == ISD::ADD && 15009 isa<ConstantSDNode>(UI->getOperand(1)) && 15010 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15011 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 15012 (1ULL << Bits) == 0) { 15013 SDNode *OtherAdd = *UI; 15014 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 15015 VE = OtherAdd->use_end(); VI != VE; ++VI) { 15016 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15017 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 15018 return SDValue(*VI, 0); 15019 } 15020 } 15021 } 15022 } 15023 } 15024 } 15025 15026 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15027 // Expose the vabsduw/h/b opportunity for down stream 15028 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15029 (IID == Intrinsic::ppc_altivec_vmaxsw || 15030 IID == Intrinsic::ppc_altivec_vmaxsh || 15031 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15032 SDValue V1 = N->getOperand(1); 15033 SDValue V2 = N->getOperand(2); 15034 if ((V1.getSimpleValueType() == MVT::v4i32 || 15035 V1.getSimpleValueType() == MVT::v8i16 || 15036 V1.getSimpleValueType() == MVT::v16i8) && 15037 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15038 // (0-a, a) 15039 if (V1.getOpcode() == ISD::SUB && 15040 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15041 V1.getOperand(1) == V2) { 15042 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15043 } 15044 // (a, 0-a) 15045 if (V2.getOpcode() == ISD::SUB && 15046 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15047 V2.getOperand(1) == V1) { 15048 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15049 } 15050 // (x-y, y-x) 15051 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15052 V1.getOperand(0) == V2.getOperand(1) && 15053 V1.getOperand(1) == V2.getOperand(0)) { 15054 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15055 } 15056 } 15057 } 15058 } 15059 15060 break; 15061 case ISD::INTRINSIC_W_CHAIN: 15062 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15063 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15064 if (Subtarget.needsSwapsForVSXMemOps()) { 15065 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15066 default: 15067 break; 15068 case Intrinsic::ppc_vsx_lxvw4x: 15069 case Intrinsic::ppc_vsx_lxvd2x: 15070 return expandVSXLoadForLE(N, DCI); 15071 } 15072 } 15073 break; 15074 case ISD::INTRINSIC_VOID: 15075 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15076 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15077 if (Subtarget.needsSwapsForVSXMemOps()) { 15078 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15079 default: 15080 break; 15081 case Intrinsic::ppc_vsx_stxvw4x: 15082 case Intrinsic::ppc_vsx_stxvd2x: 15083 return expandVSXStoreForLE(N, DCI); 15084 } 15085 } 15086 break; 15087 case ISD::BSWAP: 15088 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15089 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 15090 N->getOperand(0).hasOneUse() && 15091 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15092 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 15093 N->getValueType(0) == MVT::i64))) { 15094 SDValue Load = N->getOperand(0); 15095 LoadSDNode *LD = cast<LoadSDNode>(Load); 15096 // Create the byte-swapping load. 15097 SDValue Ops[] = { 15098 LD->getChain(), // Chain 15099 LD->getBasePtr(), // Ptr 15100 DAG.getValueType(N->getValueType(0)) // VT 15101 }; 15102 SDValue BSLoad = 15103 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15104 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15105 MVT::i64 : MVT::i32, MVT::Other), 15106 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15107 15108 // If this is an i16 load, insert the truncate. 15109 SDValue ResVal = BSLoad; 15110 if (N->getValueType(0) == MVT::i16) 15111 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15112 15113 // First, combine the bswap away. This makes the value produced by the 15114 // load dead. 15115 DCI.CombineTo(N, ResVal); 15116 15117 // Next, combine the load away, we give it a bogus result value but a real 15118 // chain result. The result value is dead because the bswap is dead. 15119 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15120 15121 // Return N so it doesn't get rechecked! 15122 return SDValue(N, 0); 15123 } 15124 break; 15125 case PPCISD::VCMP: 15126 // If a VCMPo node already exists with exactly the same operands as this 15127 // node, use its result instead of this node (VCMPo computes both a CR6 and 15128 // a normal output). 15129 // 15130 if (!N->getOperand(0).hasOneUse() && 15131 !N->getOperand(1).hasOneUse() && 15132 !N->getOperand(2).hasOneUse()) { 15133 15134 // Scan all of the users of the LHS, looking for VCMPo's that match. 15135 SDNode *VCMPoNode = nullptr; 15136 15137 SDNode *LHSN = N->getOperand(0).getNode(); 15138 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15139 UI != E; ++UI) 15140 if (UI->getOpcode() == PPCISD::VCMPo && 15141 UI->getOperand(1) == N->getOperand(1) && 15142 UI->getOperand(2) == N->getOperand(2) && 15143 UI->getOperand(0) == N->getOperand(0)) { 15144 VCMPoNode = *UI; 15145 break; 15146 } 15147 15148 // If there is no VCMPo node, or if the flag value has a single use, don't 15149 // transform this. 15150 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 15151 break; 15152 15153 // Look at the (necessarily single) use of the flag value. If it has a 15154 // chain, this transformation is more complex. Note that multiple things 15155 // could use the value result, which we should ignore. 15156 SDNode *FlagUser = nullptr; 15157 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 15158 FlagUser == nullptr; ++UI) { 15159 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 15160 SDNode *User = *UI; 15161 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15162 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 15163 FlagUser = User; 15164 break; 15165 } 15166 } 15167 } 15168 15169 // If the user is a MFOCRF instruction, we know this is safe. 15170 // Otherwise we give up for right now. 15171 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15172 return SDValue(VCMPoNode, 0); 15173 } 15174 break; 15175 case ISD::BRCOND: { 15176 SDValue Cond = N->getOperand(1); 15177 SDValue Target = N->getOperand(2); 15178 15179 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15180 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15181 Intrinsic::loop_decrement) { 15182 15183 // We now need to make the intrinsic dead (it cannot be instruction 15184 // selected). 15185 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15186 assert(Cond.getNode()->hasOneUse() && 15187 "Counter decrement has more than one use"); 15188 15189 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15190 N->getOperand(0), Target); 15191 } 15192 } 15193 break; 15194 case ISD::BR_CC: { 15195 // If this is a branch on an altivec predicate comparison, lower this so 15196 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15197 // lowering is done pre-legalize, because the legalizer lowers the predicate 15198 // compare down to code that is difficult to reassemble. 15199 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15200 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15201 15202 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15203 // value. If so, pass-through the AND to get to the intrinsic. 15204 if (LHS.getOpcode() == ISD::AND && 15205 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15206 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15207 Intrinsic::loop_decrement && 15208 isa<ConstantSDNode>(LHS.getOperand(1)) && 15209 !isNullConstant(LHS.getOperand(1))) 15210 LHS = LHS.getOperand(0); 15211 15212 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15213 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15214 Intrinsic::loop_decrement && 15215 isa<ConstantSDNode>(RHS)) { 15216 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15217 "Counter decrement comparison is not EQ or NE"); 15218 15219 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15220 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15221 (CC == ISD::SETNE && !Val); 15222 15223 // We now need to make the intrinsic dead (it cannot be instruction 15224 // selected). 15225 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15226 assert(LHS.getNode()->hasOneUse() && 15227 "Counter decrement has more than one use"); 15228 15229 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15230 N->getOperand(0), N->getOperand(4)); 15231 } 15232 15233 int CompareOpc; 15234 bool isDot; 15235 15236 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15237 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15238 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15239 assert(isDot && "Can't compare against a vector result!"); 15240 15241 // If this is a comparison against something other than 0/1, then we know 15242 // that the condition is never/always true. 15243 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15244 if (Val != 0 && Val != 1) { 15245 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15246 return N->getOperand(0); 15247 // Always !=, turn it into an unconditional branch. 15248 return DAG.getNode(ISD::BR, dl, MVT::Other, 15249 N->getOperand(0), N->getOperand(4)); 15250 } 15251 15252 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15253 15254 // Create the PPCISD altivec 'dot' comparison node. 15255 SDValue Ops[] = { 15256 LHS.getOperand(2), // LHS of compare 15257 LHS.getOperand(3), // RHS of compare 15258 DAG.getConstant(CompareOpc, dl, MVT::i32) 15259 }; 15260 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15261 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15262 15263 // Unpack the result based on how the target uses it. 15264 PPC::Predicate CompOpc; 15265 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15266 default: // Can't happen, don't crash on invalid number though. 15267 case 0: // Branch on the value of the EQ bit of CR6. 15268 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15269 break; 15270 case 1: // Branch on the inverted value of the EQ bit of CR6. 15271 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15272 break; 15273 case 2: // Branch on the value of the LT bit of CR6. 15274 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15275 break; 15276 case 3: // Branch on the inverted value of the LT bit of CR6. 15277 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15278 break; 15279 } 15280 15281 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15282 DAG.getConstant(CompOpc, dl, MVT::i32), 15283 DAG.getRegister(PPC::CR6, MVT::i32), 15284 N->getOperand(4), CompNode.getValue(1)); 15285 } 15286 break; 15287 } 15288 case ISD::BUILD_VECTOR: 15289 return DAGCombineBuildVector(N, DCI); 15290 case ISD::ABS: 15291 return combineABS(N, DCI); 15292 case ISD::VSELECT: 15293 return combineVSelect(N, DCI); 15294 } 15295 15296 return SDValue(); 15297 } 15298 15299 SDValue 15300 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15301 SelectionDAG &DAG, 15302 SmallVectorImpl<SDNode *> &Created) const { 15303 // fold (sdiv X, pow2) 15304 EVT VT = N->getValueType(0); 15305 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15306 return SDValue(); 15307 if ((VT != MVT::i32 && VT != MVT::i64) || 15308 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15309 return SDValue(); 15310 15311 SDLoc DL(N); 15312 SDValue N0 = N->getOperand(0); 15313 15314 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15315 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15316 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15317 15318 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15319 Created.push_back(Op.getNode()); 15320 15321 if (IsNegPow2) { 15322 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15323 Created.push_back(Op.getNode()); 15324 } 15325 15326 return Op; 15327 } 15328 15329 //===----------------------------------------------------------------------===// 15330 // Inline Assembly Support 15331 //===----------------------------------------------------------------------===// 15332 15333 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15334 KnownBits &Known, 15335 const APInt &DemandedElts, 15336 const SelectionDAG &DAG, 15337 unsigned Depth) const { 15338 Known.resetAll(); 15339 switch (Op.getOpcode()) { 15340 default: break; 15341 case PPCISD::LBRX: { 15342 // lhbrx is known to have the top bits cleared out. 15343 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15344 Known.Zero = 0xFFFF0000; 15345 break; 15346 } 15347 case ISD::INTRINSIC_WO_CHAIN: { 15348 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15349 default: break; 15350 case Intrinsic::ppc_altivec_vcmpbfp_p: 15351 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15352 case Intrinsic::ppc_altivec_vcmpequb_p: 15353 case Intrinsic::ppc_altivec_vcmpequh_p: 15354 case Intrinsic::ppc_altivec_vcmpequw_p: 15355 case Intrinsic::ppc_altivec_vcmpequd_p: 15356 case Intrinsic::ppc_altivec_vcmpequq_p: 15357 case Intrinsic::ppc_altivec_vcmpgefp_p: 15358 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15359 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15360 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15361 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15362 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15363 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15364 case Intrinsic::ppc_altivec_vcmpgtub_p: 15365 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15366 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15367 case Intrinsic::ppc_altivec_vcmpgtud_p: 15368 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15369 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15370 break; 15371 } 15372 } 15373 } 15374 } 15375 15376 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15377 switch (Subtarget.getCPUDirective()) { 15378 default: break; 15379 case PPC::DIR_970: 15380 case PPC::DIR_PWR4: 15381 case PPC::DIR_PWR5: 15382 case PPC::DIR_PWR5X: 15383 case PPC::DIR_PWR6: 15384 case PPC::DIR_PWR6X: 15385 case PPC::DIR_PWR7: 15386 case PPC::DIR_PWR8: 15387 case PPC::DIR_PWR9: 15388 case PPC::DIR_PWR10: 15389 case PPC::DIR_PWR_FUTURE: { 15390 if (!ML) 15391 break; 15392 15393 if (!DisableInnermostLoopAlign32) { 15394 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15395 // so that we can decrease cache misses and branch-prediction misses. 15396 // Actual alignment of the loop will depend on the hotness check and other 15397 // logic in alignBlocks. 15398 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15399 return Align(32); 15400 } 15401 15402 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15403 15404 // For small loops (between 5 and 8 instructions), align to a 32-byte 15405 // boundary so that the entire loop fits in one instruction-cache line. 15406 uint64_t LoopSize = 0; 15407 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15408 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15409 LoopSize += TII->getInstSizeInBytes(*J); 15410 if (LoopSize > 32) 15411 break; 15412 } 15413 15414 if (LoopSize > 16 && LoopSize <= 32) 15415 return Align(32); 15416 15417 break; 15418 } 15419 } 15420 15421 return TargetLowering::getPrefLoopAlignment(ML); 15422 } 15423 15424 /// getConstraintType - Given a constraint, return the type of 15425 /// constraint it is for this target. 15426 PPCTargetLowering::ConstraintType 15427 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15428 if (Constraint.size() == 1) { 15429 switch (Constraint[0]) { 15430 default: break; 15431 case 'b': 15432 case 'r': 15433 case 'f': 15434 case 'd': 15435 case 'v': 15436 case 'y': 15437 return C_RegisterClass; 15438 case 'Z': 15439 // FIXME: While Z does indicate a memory constraint, it specifically 15440 // indicates an r+r address (used in conjunction with the 'y' modifier 15441 // in the replacement string). Currently, we're forcing the base 15442 // register to be r0 in the asm printer (which is interpreted as zero) 15443 // and forming the complete address in the second register. This is 15444 // suboptimal. 15445 return C_Memory; 15446 } 15447 } else if (Constraint == "wc") { // individual CR bits. 15448 return C_RegisterClass; 15449 } else if (Constraint == "wa" || Constraint == "wd" || 15450 Constraint == "wf" || Constraint == "ws" || 15451 Constraint == "wi" || Constraint == "ww") { 15452 return C_RegisterClass; // VSX registers. 15453 } 15454 return TargetLowering::getConstraintType(Constraint); 15455 } 15456 15457 /// Examine constraint type and operand type and determine a weight value. 15458 /// This object must already have been set up with the operand type 15459 /// and the current alternative constraint selected. 15460 TargetLowering::ConstraintWeight 15461 PPCTargetLowering::getSingleConstraintMatchWeight( 15462 AsmOperandInfo &info, const char *constraint) const { 15463 ConstraintWeight weight = CW_Invalid; 15464 Value *CallOperandVal = info.CallOperandVal; 15465 // If we don't have a value, we can't do a match, 15466 // but allow it at the lowest weight. 15467 if (!CallOperandVal) 15468 return CW_Default; 15469 Type *type = CallOperandVal->getType(); 15470 15471 // Look at the constraint type. 15472 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15473 return CW_Register; // an individual CR bit. 15474 else if ((StringRef(constraint) == "wa" || 15475 StringRef(constraint) == "wd" || 15476 StringRef(constraint) == "wf") && 15477 type->isVectorTy()) 15478 return CW_Register; 15479 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15480 return CW_Register; // just hold 64-bit integers data. 15481 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15482 return CW_Register; 15483 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15484 return CW_Register; 15485 15486 switch (*constraint) { 15487 default: 15488 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15489 break; 15490 case 'b': 15491 if (type->isIntegerTy()) 15492 weight = CW_Register; 15493 break; 15494 case 'f': 15495 if (type->isFloatTy()) 15496 weight = CW_Register; 15497 break; 15498 case 'd': 15499 if (type->isDoubleTy()) 15500 weight = CW_Register; 15501 break; 15502 case 'v': 15503 if (type->isVectorTy()) 15504 weight = CW_Register; 15505 break; 15506 case 'y': 15507 weight = CW_Register; 15508 break; 15509 case 'Z': 15510 weight = CW_Memory; 15511 break; 15512 } 15513 return weight; 15514 } 15515 15516 std::pair<unsigned, const TargetRegisterClass *> 15517 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15518 StringRef Constraint, 15519 MVT VT) const { 15520 if (Constraint.size() == 1) { 15521 // GCC RS6000 Constraint Letters 15522 switch (Constraint[0]) { 15523 case 'b': // R1-R31 15524 if (VT == MVT::i64 && Subtarget.isPPC64()) 15525 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15526 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15527 case 'r': // R0-R31 15528 if (VT == MVT::i64 && Subtarget.isPPC64()) 15529 return std::make_pair(0U, &PPC::G8RCRegClass); 15530 return std::make_pair(0U, &PPC::GPRCRegClass); 15531 // 'd' and 'f' constraints are both defined to be "the floating point 15532 // registers", where one is for 32-bit and the other for 64-bit. We don't 15533 // really care overly much here so just give them all the same reg classes. 15534 case 'd': 15535 case 'f': 15536 if (Subtarget.hasSPE()) { 15537 if (VT == MVT::f32 || VT == MVT::i32) 15538 return std::make_pair(0U, &PPC::GPRCRegClass); 15539 if (VT == MVT::f64 || VT == MVT::i64) 15540 return std::make_pair(0U, &PPC::SPERCRegClass); 15541 } else { 15542 if (VT == MVT::f32 || VT == MVT::i32) 15543 return std::make_pair(0U, &PPC::F4RCRegClass); 15544 if (VT == MVT::f64 || VT == MVT::i64) 15545 return std::make_pair(0U, &PPC::F8RCRegClass); 15546 } 15547 break; 15548 case 'v': 15549 if (Subtarget.hasAltivec()) 15550 return std::make_pair(0U, &PPC::VRRCRegClass); 15551 break; 15552 case 'y': // crrc 15553 return std::make_pair(0U, &PPC::CRRCRegClass); 15554 } 15555 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15556 // An individual CR bit. 15557 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15558 } else if ((Constraint == "wa" || Constraint == "wd" || 15559 Constraint == "wf" || Constraint == "wi") && 15560 Subtarget.hasVSX()) { 15561 return std::make_pair(0U, &PPC::VSRCRegClass); 15562 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15563 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15564 return std::make_pair(0U, &PPC::VSSRCRegClass); 15565 else 15566 return std::make_pair(0U, &PPC::VSFRCRegClass); 15567 } 15568 15569 // If we name a VSX register, we can't defer to the base class because it 15570 // will not recognize the correct register (their names will be VSL{0-31} 15571 // and V{0-31} so they won't match). So we match them here. 15572 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15573 int VSNum = atoi(Constraint.data() + 3); 15574 assert(VSNum >= 0 && VSNum <= 63 && 15575 "Attempted to access a vsr out of range"); 15576 if (VSNum < 32) 15577 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15578 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15579 } 15580 std::pair<unsigned, const TargetRegisterClass *> R = 15581 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15582 15583 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15584 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15585 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15586 // register. 15587 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15588 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15589 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15590 PPC::GPRCRegClass.contains(R.first)) 15591 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15592 PPC::sub_32, &PPC::G8RCRegClass), 15593 &PPC::G8RCRegClass); 15594 15595 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15596 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15597 R.first = PPC::CR0; 15598 R.second = &PPC::CRRCRegClass; 15599 } 15600 15601 return R; 15602 } 15603 15604 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15605 /// vector. If it is invalid, don't add anything to Ops. 15606 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15607 std::string &Constraint, 15608 std::vector<SDValue>&Ops, 15609 SelectionDAG &DAG) const { 15610 SDValue Result; 15611 15612 // Only support length 1 constraints. 15613 if (Constraint.length() > 1) return; 15614 15615 char Letter = Constraint[0]; 15616 switch (Letter) { 15617 default: break; 15618 case 'I': 15619 case 'J': 15620 case 'K': 15621 case 'L': 15622 case 'M': 15623 case 'N': 15624 case 'O': 15625 case 'P': { 15626 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15627 if (!CST) return; // Must be an immediate to match. 15628 SDLoc dl(Op); 15629 int64_t Value = CST->getSExtValue(); 15630 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15631 // numbers are printed as such. 15632 switch (Letter) { 15633 default: llvm_unreachable("Unknown constraint letter!"); 15634 case 'I': // "I" is a signed 16-bit constant. 15635 if (isInt<16>(Value)) 15636 Result = DAG.getTargetConstant(Value, dl, TCVT); 15637 break; 15638 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15639 if (isShiftedUInt<16, 16>(Value)) 15640 Result = DAG.getTargetConstant(Value, dl, TCVT); 15641 break; 15642 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15643 if (isShiftedInt<16, 16>(Value)) 15644 Result = DAG.getTargetConstant(Value, dl, TCVT); 15645 break; 15646 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15647 if (isUInt<16>(Value)) 15648 Result = DAG.getTargetConstant(Value, dl, TCVT); 15649 break; 15650 case 'M': // "M" is a constant that is greater than 31. 15651 if (Value > 31) 15652 Result = DAG.getTargetConstant(Value, dl, TCVT); 15653 break; 15654 case 'N': // "N" is a positive constant that is an exact power of two. 15655 if (Value > 0 && isPowerOf2_64(Value)) 15656 Result = DAG.getTargetConstant(Value, dl, TCVT); 15657 break; 15658 case 'O': // "O" is the constant zero. 15659 if (Value == 0) 15660 Result = DAG.getTargetConstant(Value, dl, TCVT); 15661 break; 15662 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15663 if (isInt<16>(-Value)) 15664 Result = DAG.getTargetConstant(Value, dl, TCVT); 15665 break; 15666 } 15667 break; 15668 } 15669 } 15670 15671 if (Result.getNode()) { 15672 Ops.push_back(Result); 15673 return; 15674 } 15675 15676 // Handle standard constraint letters. 15677 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15678 } 15679 15680 // isLegalAddressingMode - Return true if the addressing mode represented 15681 // by AM is legal for this target, for a load/store of the specified type. 15682 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15683 const AddrMode &AM, Type *Ty, 15684 unsigned AS, 15685 Instruction *I) const { 15686 // Vector type r+i form is supported since power9 as DQ form. We don't check 15687 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15688 // imm form is preferred and the offset can be adjusted to use imm form later 15689 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15690 // max offset to check legal addressing mode, we should be a little aggressive 15691 // to contain other offsets for that LSRUse. 15692 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15693 return false; 15694 15695 // PPC allows a sign-extended 16-bit immediate field. 15696 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15697 return false; 15698 15699 // No global is ever allowed as a base. 15700 if (AM.BaseGV) 15701 return false; 15702 15703 // PPC only support r+r, 15704 switch (AM.Scale) { 15705 case 0: // "r+i" or just "i", depending on HasBaseReg. 15706 break; 15707 case 1: 15708 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15709 return false; 15710 // Otherwise we have r+r or r+i. 15711 break; 15712 case 2: 15713 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15714 return false; 15715 // Allow 2*r as r+r. 15716 break; 15717 default: 15718 // No other scales are supported. 15719 return false; 15720 } 15721 15722 return true; 15723 } 15724 15725 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15726 SelectionDAG &DAG) const { 15727 MachineFunction &MF = DAG.getMachineFunction(); 15728 MachineFrameInfo &MFI = MF.getFrameInfo(); 15729 MFI.setReturnAddressIsTaken(true); 15730 15731 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15732 return SDValue(); 15733 15734 SDLoc dl(Op); 15735 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15736 15737 // Make sure the function does not optimize away the store of the RA to 15738 // the stack. 15739 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15740 FuncInfo->setLRStoreRequired(); 15741 bool isPPC64 = Subtarget.isPPC64(); 15742 auto PtrVT = getPointerTy(MF.getDataLayout()); 15743 15744 if (Depth > 0) { 15745 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15746 SDValue Offset = 15747 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15748 isPPC64 ? MVT::i64 : MVT::i32); 15749 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15750 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15751 MachinePointerInfo()); 15752 } 15753 15754 // Just load the return address off the stack. 15755 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15756 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15757 MachinePointerInfo()); 15758 } 15759 15760 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15761 SelectionDAG &DAG) const { 15762 SDLoc dl(Op); 15763 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15764 15765 MachineFunction &MF = DAG.getMachineFunction(); 15766 MachineFrameInfo &MFI = MF.getFrameInfo(); 15767 MFI.setFrameAddressIsTaken(true); 15768 15769 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15770 bool isPPC64 = PtrVT == MVT::i64; 15771 15772 // Naked functions never have a frame pointer, and so we use r1. For all 15773 // other functions, this decision must be delayed until during PEI. 15774 unsigned FrameReg; 15775 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15776 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15777 else 15778 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15779 15780 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15781 PtrVT); 15782 while (Depth--) 15783 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15784 FrameAddr, MachinePointerInfo()); 15785 return FrameAddr; 15786 } 15787 15788 // FIXME? Maybe this could be a TableGen attribute on some registers and 15789 // this table could be generated automatically from RegInfo. 15790 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15791 const MachineFunction &MF) const { 15792 bool isPPC64 = Subtarget.isPPC64(); 15793 15794 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15795 if (!is64Bit && VT != LLT::scalar(32)) 15796 report_fatal_error("Invalid register global variable type"); 15797 15798 Register Reg = StringSwitch<Register>(RegName) 15799 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15800 .Case("r2", isPPC64 ? Register() : PPC::R2) 15801 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15802 .Default(Register()); 15803 15804 if (Reg) 15805 return Reg; 15806 report_fatal_error("Invalid register name global variable"); 15807 } 15808 15809 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15810 // 32-bit SVR4 ABI access everything as got-indirect. 15811 if (Subtarget.is32BitELFABI()) 15812 return true; 15813 15814 // AIX accesses everything indirectly through the TOC, which is similar to 15815 // the GOT. 15816 if (Subtarget.isAIXABI()) 15817 return true; 15818 15819 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15820 // If it is small or large code model, module locals are accessed 15821 // indirectly by loading their address from .toc/.got. 15822 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15823 return true; 15824 15825 // JumpTable and BlockAddress are accessed as got-indirect. 15826 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15827 return true; 15828 15829 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15830 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15831 15832 return false; 15833 } 15834 15835 bool 15836 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15837 // The PowerPC target isn't yet aware of offsets. 15838 return false; 15839 } 15840 15841 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15842 const CallInst &I, 15843 MachineFunction &MF, 15844 unsigned Intrinsic) const { 15845 switch (Intrinsic) { 15846 case Intrinsic::ppc_altivec_lvx: 15847 case Intrinsic::ppc_altivec_lvxl: 15848 case Intrinsic::ppc_altivec_lvebx: 15849 case Intrinsic::ppc_altivec_lvehx: 15850 case Intrinsic::ppc_altivec_lvewx: 15851 case Intrinsic::ppc_vsx_lxvd2x: 15852 case Intrinsic::ppc_vsx_lxvw4x: { 15853 EVT VT; 15854 switch (Intrinsic) { 15855 case Intrinsic::ppc_altivec_lvebx: 15856 VT = MVT::i8; 15857 break; 15858 case Intrinsic::ppc_altivec_lvehx: 15859 VT = MVT::i16; 15860 break; 15861 case Intrinsic::ppc_altivec_lvewx: 15862 VT = MVT::i32; 15863 break; 15864 case Intrinsic::ppc_vsx_lxvd2x: 15865 VT = MVT::v2f64; 15866 break; 15867 default: 15868 VT = MVT::v4i32; 15869 break; 15870 } 15871 15872 Info.opc = ISD::INTRINSIC_W_CHAIN; 15873 Info.memVT = VT; 15874 Info.ptrVal = I.getArgOperand(0); 15875 Info.offset = -VT.getStoreSize()+1; 15876 Info.size = 2*VT.getStoreSize()-1; 15877 Info.align = Align(1); 15878 Info.flags = MachineMemOperand::MOLoad; 15879 return true; 15880 } 15881 case Intrinsic::ppc_altivec_stvx: 15882 case Intrinsic::ppc_altivec_stvxl: 15883 case Intrinsic::ppc_altivec_stvebx: 15884 case Intrinsic::ppc_altivec_stvehx: 15885 case Intrinsic::ppc_altivec_stvewx: 15886 case Intrinsic::ppc_vsx_stxvd2x: 15887 case Intrinsic::ppc_vsx_stxvw4x: { 15888 EVT VT; 15889 switch (Intrinsic) { 15890 case Intrinsic::ppc_altivec_stvebx: 15891 VT = MVT::i8; 15892 break; 15893 case Intrinsic::ppc_altivec_stvehx: 15894 VT = MVT::i16; 15895 break; 15896 case Intrinsic::ppc_altivec_stvewx: 15897 VT = MVT::i32; 15898 break; 15899 case Intrinsic::ppc_vsx_stxvd2x: 15900 VT = MVT::v2f64; 15901 break; 15902 default: 15903 VT = MVT::v4i32; 15904 break; 15905 } 15906 15907 Info.opc = ISD::INTRINSIC_VOID; 15908 Info.memVT = VT; 15909 Info.ptrVal = I.getArgOperand(1); 15910 Info.offset = -VT.getStoreSize()+1; 15911 Info.size = 2*VT.getStoreSize()-1; 15912 Info.align = Align(1); 15913 Info.flags = MachineMemOperand::MOStore; 15914 return true; 15915 } 15916 default: 15917 break; 15918 } 15919 15920 return false; 15921 } 15922 15923 /// It returns EVT::Other if the type should be determined using generic 15924 /// target-independent logic. 15925 EVT PPCTargetLowering::getOptimalMemOpType( 15926 const MemOp &Op, const AttributeList &FuncAttributes) const { 15927 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15928 // We should use Altivec/VSX loads and stores when available. For unaligned 15929 // addresses, unaligned VSX loads are only fast starting with the P8. 15930 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15931 (Op.isAligned(Align(16)) || 15932 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15933 return MVT::v4i32; 15934 } 15935 15936 if (Subtarget.isPPC64()) { 15937 return MVT::i64; 15938 } 15939 15940 return MVT::i32; 15941 } 15942 15943 /// Returns true if it is beneficial to convert a load of a constant 15944 /// to just the constant itself. 15945 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15946 Type *Ty) const { 15947 assert(Ty->isIntegerTy()); 15948 15949 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15950 return !(BitSize == 0 || BitSize > 64); 15951 } 15952 15953 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15954 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15955 return false; 15956 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15957 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15958 return NumBits1 == 64 && NumBits2 == 32; 15959 } 15960 15961 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15962 if (!VT1.isInteger() || !VT2.isInteger()) 15963 return false; 15964 unsigned NumBits1 = VT1.getSizeInBits(); 15965 unsigned NumBits2 = VT2.getSizeInBits(); 15966 return NumBits1 == 64 && NumBits2 == 32; 15967 } 15968 15969 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15970 // Generally speaking, zexts are not free, but they are free when they can be 15971 // folded with other operations. 15972 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15973 EVT MemVT = LD->getMemoryVT(); 15974 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15975 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15976 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15977 LD->getExtensionType() == ISD::ZEXTLOAD)) 15978 return true; 15979 } 15980 15981 // FIXME: Add other cases... 15982 // - 32-bit shifts with a zext to i64 15983 // - zext after ctlz, bswap, etc. 15984 // - zext after and by a constant mask 15985 15986 return TargetLowering::isZExtFree(Val, VT2); 15987 } 15988 15989 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15990 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15991 "invalid fpext types"); 15992 // Extending to float128 is not free. 15993 if (DestVT == MVT::f128) 15994 return false; 15995 return true; 15996 } 15997 15998 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15999 return isInt<16>(Imm) || isUInt<16>(Imm); 16000 } 16001 16002 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16003 return isInt<16>(Imm) || isUInt<16>(Imm); 16004 } 16005 16006 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 16007 unsigned, 16008 unsigned, 16009 MachineMemOperand::Flags, 16010 bool *Fast) const { 16011 if (DisablePPCUnaligned) 16012 return false; 16013 16014 // PowerPC supports unaligned memory access for simple non-vector types. 16015 // Although accessing unaligned addresses is not as efficient as accessing 16016 // aligned addresses, it is generally more efficient than manual expansion, 16017 // and generally only traps for software emulation when crossing page 16018 // boundaries. 16019 16020 if (!VT.isSimple()) 16021 return false; 16022 16023 if (VT.isFloatingPoint() && !VT.isVector() && 16024 !Subtarget.allowsUnalignedFPAccess()) 16025 return false; 16026 16027 if (VT.getSimpleVT().isVector()) { 16028 if (Subtarget.hasVSX()) { 16029 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16030 VT != MVT::v4f32 && VT != MVT::v4i32) 16031 return false; 16032 } else { 16033 return false; 16034 } 16035 } 16036 16037 if (VT == MVT::ppcf128) 16038 return false; 16039 16040 if (Fast) 16041 *Fast = true; 16042 16043 return true; 16044 } 16045 16046 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16047 EVT VT) const { 16048 return isFMAFasterThanFMulAndFAdd( 16049 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16050 } 16051 16052 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16053 Type *Ty) const { 16054 switch (Ty->getScalarType()->getTypeID()) { 16055 case Type::FloatTyID: 16056 case Type::DoubleTyID: 16057 return true; 16058 case Type::FP128TyID: 16059 return Subtarget.hasP9Vector(); 16060 default: 16061 return false; 16062 } 16063 } 16064 16065 // FIXME: add more patterns which are not profitable to hoist. 16066 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16067 if (!I->hasOneUse()) 16068 return true; 16069 16070 Instruction *User = I->user_back(); 16071 assert(User && "A single use instruction with no uses."); 16072 16073 switch (I->getOpcode()) { 16074 case Instruction::FMul: { 16075 // Don't break FMA, PowerPC prefers FMA. 16076 if (User->getOpcode() != Instruction::FSub && 16077 User->getOpcode() != Instruction::FAdd) 16078 return true; 16079 16080 const TargetOptions &Options = getTargetMachine().Options; 16081 const Function *F = I->getFunction(); 16082 const DataLayout &DL = F->getParent()->getDataLayout(); 16083 Type *Ty = User->getOperand(0)->getType(); 16084 16085 return !( 16086 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16087 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16088 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16089 } 16090 case Instruction::Load: { 16091 // Don't break "store (load float*)" pattern, this pattern will be combined 16092 // to "store (load int32)" in later InstCombine pass. See function 16093 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16094 // cycles than loading a 32 bit integer. 16095 LoadInst *LI = cast<LoadInst>(I); 16096 // For the loads that combineLoadToOperationType does nothing, like 16097 // ordered load, it should be profitable to hoist them. 16098 // For swifterror load, it can only be used for pointer to pointer type, so 16099 // later type check should get rid of this case. 16100 if (!LI->isUnordered()) 16101 return true; 16102 16103 if (User->getOpcode() != Instruction::Store) 16104 return true; 16105 16106 if (I->getType()->getTypeID() != Type::FloatTyID) 16107 return true; 16108 16109 return false; 16110 } 16111 default: 16112 return true; 16113 } 16114 return true; 16115 } 16116 16117 const MCPhysReg * 16118 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16119 // LR is a callee-save register, but we must treat it as clobbered by any call 16120 // site. Hence we include LR in the scratch registers, which are in turn added 16121 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16122 // to CTR, which is used by any indirect call. 16123 static const MCPhysReg ScratchRegs[] = { 16124 PPC::X12, PPC::LR8, PPC::CTR8, 0 16125 }; 16126 16127 return ScratchRegs; 16128 } 16129 16130 Register PPCTargetLowering::getExceptionPointerRegister( 16131 const Constant *PersonalityFn) const { 16132 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16133 } 16134 16135 Register PPCTargetLowering::getExceptionSelectorRegister( 16136 const Constant *PersonalityFn) const { 16137 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16138 } 16139 16140 bool 16141 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16142 EVT VT , unsigned DefinedValues) const { 16143 if (VT == MVT::v2i64) 16144 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16145 16146 if (Subtarget.hasVSX()) 16147 return true; 16148 16149 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16150 } 16151 16152 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16153 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16154 return TargetLowering::getSchedulingPreference(N); 16155 16156 return Sched::ILP; 16157 } 16158 16159 // Create a fast isel object. 16160 FastISel * 16161 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16162 const TargetLibraryInfo *LibInfo) const { 16163 return PPC::createFastISel(FuncInfo, LibInfo); 16164 } 16165 16166 // 'Inverted' means the FMA opcode after negating one multiplicand. 16167 // For example, (fma -a b c) = (fnmsub a b c) 16168 static unsigned invertFMAOpcode(unsigned Opc) { 16169 switch (Opc) { 16170 default: 16171 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16172 case ISD::FMA: 16173 return PPCISD::FNMSUB; 16174 case PPCISD::FNMSUB: 16175 return ISD::FMA; 16176 } 16177 } 16178 16179 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16180 bool LegalOps, bool OptForSize, 16181 NegatibleCost &Cost, 16182 unsigned Depth) const { 16183 if (Depth > SelectionDAG::MaxRecursionDepth) 16184 return SDValue(); 16185 16186 unsigned Opc = Op.getOpcode(); 16187 EVT VT = Op.getValueType(); 16188 SDNodeFlags Flags = Op.getNode()->getFlags(); 16189 16190 switch (Opc) { 16191 case PPCISD::FNMSUB: 16192 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16193 break; 16194 16195 const TargetOptions &Options = getTargetMachine().Options; 16196 SDValue N0 = Op.getOperand(0); 16197 SDValue N1 = Op.getOperand(1); 16198 SDValue N2 = Op.getOperand(2); 16199 SDLoc Loc(Op); 16200 16201 NegatibleCost N2Cost = NegatibleCost::Expensive; 16202 SDValue NegN2 = 16203 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16204 16205 if (!NegN2) 16206 return SDValue(); 16207 16208 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16209 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16210 // These transformations may change sign of zeroes. For example, 16211 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16212 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16213 // Try and choose the cheaper one to negate. 16214 NegatibleCost N0Cost = NegatibleCost::Expensive; 16215 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16216 N0Cost, Depth + 1); 16217 16218 NegatibleCost N1Cost = NegatibleCost::Expensive; 16219 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16220 N1Cost, Depth + 1); 16221 16222 if (NegN0 && N0Cost <= N1Cost) { 16223 Cost = std::min(N0Cost, N2Cost); 16224 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16225 } else if (NegN1) { 16226 Cost = std::min(N1Cost, N2Cost); 16227 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16228 } 16229 } 16230 16231 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16232 if (isOperationLegal(ISD::FMA, VT)) { 16233 Cost = N2Cost; 16234 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16235 } 16236 16237 break; 16238 } 16239 16240 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16241 Cost, Depth); 16242 } 16243 16244 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16245 bool PPCTargetLowering::useLoadStackGuardNode() const { 16246 if (!Subtarget.isTargetLinux()) 16247 return TargetLowering::useLoadStackGuardNode(); 16248 return true; 16249 } 16250 16251 // Override to disable global variable loading on Linux. 16252 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16253 if (!Subtarget.isTargetLinux()) 16254 return TargetLowering::insertSSPDeclarations(M); 16255 } 16256 16257 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16258 bool ForCodeSize) const { 16259 if (!VT.isSimple() || !Subtarget.hasVSX()) 16260 return false; 16261 16262 switch(VT.getSimpleVT().SimpleTy) { 16263 default: 16264 // For FP types that are currently not supported by PPC backend, return 16265 // false. Examples: f16, f80. 16266 return false; 16267 case MVT::f32: 16268 case MVT::f64: 16269 if (Subtarget.hasPrefixInstrs()) { 16270 // With prefixed instructions, we can materialize anything that can be 16271 // represented with a 32-bit immediate, not just positive zero. 16272 APFloat APFloatOfImm = Imm; 16273 return convertToNonDenormSingle(APFloatOfImm); 16274 } 16275 LLVM_FALLTHROUGH; 16276 case MVT::ppcf128: 16277 return Imm.isPosZero(); 16278 } 16279 } 16280 16281 // For vector shift operation op, fold 16282 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16283 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16284 SelectionDAG &DAG) { 16285 SDValue N0 = N->getOperand(0); 16286 SDValue N1 = N->getOperand(1); 16287 EVT VT = N0.getValueType(); 16288 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16289 unsigned Opcode = N->getOpcode(); 16290 unsigned TargetOpcode; 16291 16292 switch (Opcode) { 16293 default: 16294 llvm_unreachable("Unexpected shift operation"); 16295 case ISD::SHL: 16296 TargetOpcode = PPCISD::SHL; 16297 break; 16298 case ISD::SRL: 16299 TargetOpcode = PPCISD::SRL; 16300 break; 16301 case ISD::SRA: 16302 TargetOpcode = PPCISD::SRA; 16303 break; 16304 } 16305 16306 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16307 N1->getOpcode() == ISD::AND) 16308 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16309 if (Mask->getZExtValue() == OpSizeInBits - 1) 16310 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16311 16312 return SDValue(); 16313 } 16314 16315 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16316 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16317 return Value; 16318 16319 SDValue N0 = N->getOperand(0); 16320 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16321 if (!Subtarget.isISA3_0() || 16322 N0.getOpcode() != ISD::SIGN_EXTEND || 16323 N0.getOperand(0).getValueType() != MVT::i32 || 16324 CN1 == nullptr || N->getValueType(0) != MVT::i64) 16325 return SDValue(); 16326 16327 // We can't save an operation here if the value is already extended, and 16328 // the existing shift is easier to combine. 16329 SDValue ExtsSrc = N0.getOperand(0); 16330 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16331 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16332 return SDValue(); 16333 16334 SDLoc DL(N0); 16335 SDValue ShiftBy = SDValue(CN1, 0); 16336 // We want the shift amount to be i32 on the extswli, but the shift could 16337 // have an i64. 16338 if (ShiftBy.getValueType() == MVT::i64) 16339 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16340 16341 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16342 ShiftBy); 16343 } 16344 16345 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16346 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16347 return Value; 16348 16349 return SDValue(); 16350 } 16351 16352 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16353 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16354 return Value; 16355 16356 return SDValue(); 16357 } 16358 16359 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16360 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16361 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16362 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16363 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16364 const PPCSubtarget &Subtarget) { 16365 if (!Subtarget.isPPC64()) 16366 return SDValue(); 16367 16368 SDValue LHS = N->getOperand(0); 16369 SDValue RHS = N->getOperand(1); 16370 16371 auto isZextOfCompareWithConstant = [](SDValue Op) { 16372 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16373 Op.getValueType() != MVT::i64) 16374 return false; 16375 16376 SDValue Cmp = Op.getOperand(0); 16377 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16378 Cmp.getOperand(0).getValueType() != MVT::i64) 16379 return false; 16380 16381 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16382 int64_t NegConstant = 0 - Constant->getSExtValue(); 16383 // Due to the limitations of the addi instruction, 16384 // -C is required to be [-32768, 32767]. 16385 return isInt<16>(NegConstant); 16386 } 16387 16388 return false; 16389 }; 16390 16391 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16392 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16393 16394 // If there is a pattern, canonicalize a zext operand to the RHS. 16395 if (LHSHasPattern && !RHSHasPattern) 16396 std::swap(LHS, RHS); 16397 else if (!LHSHasPattern && !RHSHasPattern) 16398 return SDValue(); 16399 16400 SDLoc DL(N); 16401 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16402 SDValue Cmp = RHS.getOperand(0); 16403 SDValue Z = Cmp.getOperand(0); 16404 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16405 16406 assert(Constant && "Constant Should not be a null pointer."); 16407 int64_t NegConstant = 0 - Constant->getSExtValue(); 16408 16409 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16410 default: break; 16411 case ISD::SETNE: { 16412 // when C == 0 16413 // --> addze X, (addic Z, -1).carry 16414 // / 16415 // add X, (zext(setne Z, C))-- 16416 // \ when -32768 <= -C <= 32767 && C != 0 16417 // --> addze X, (addic (addi Z, -C), -1).carry 16418 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16419 DAG.getConstant(NegConstant, DL, MVT::i64)); 16420 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16421 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16422 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16423 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16424 SDValue(Addc.getNode(), 1)); 16425 } 16426 case ISD::SETEQ: { 16427 // when C == 0 16428 // --> addze X, (subfic Z, 0).carry 16429 // / 16430 // add X, (zext(sete Z, C))-- 16431 // \ when -32768 <= -C <= 32767 && C != 0 16432 // --> addze X, (subfic (addi Z, -C), 0).carry 16433 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16434 DAG.getConstant(NegConstant, DL, MVT::i64)); 16435 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16436 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16437 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16438 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16439 SDValue(Subc.getNode(), 1)); 16440 } 16441 } 16442 16443 return SDValue(); 16444 } 16445 16446 // Transform 16447 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16448 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16449 // In this case both C1 and C2 must be known constants. 16450 // C1+C2 must fit into a 34 bit signed integer. 16451 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16452 const PPCSubtarget &Subtarget) { 16453 if (!Subtarget.isUsingPCRelativeCalls()) 16454 return SDValue(); 16455 16456 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16457 // If we find that node try to cast the Global Address and the Constant. 16458 SDValue LHS = N->getOperand(0); 16459 SDValue RHS = N->getOperand(1); 16460 16461 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16462 std::swap(LHS, RHS); 16463 16464 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16465 return SDValue(); 16466 16467 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16468 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16469 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16470 16471 // Check that both casts succeeded. 16472 if (!GSDN || !ConstNode) 16473 return SDValue(); 16474 16475 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16476 SDLoc DL(GSDN); 16477 16478 // The signed int offset needs to fit in 34 bits. 16479 if (!isInt<34>(NewOffset)) 16480 return SDValue(); 16481 16482 // The new global address is a copy of the old global address except 16483 // that it has the updated Offset. 16484 SDValue GA = 16485 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16486 NewOffset, GSDN->getTargetFlags()); 16487 SDValue MatPCRel = 16488 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16489 return MatPCRel; 16490 } 16491 16492 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16493 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16494 return Value; 16495 16496 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16497 return Value; 16498 16499 return SDValue(); 16500 } 16501 16502 // Detect TRUNCATE operations on bitcasts of float128 values. 16503 // What we are looking for here is the situtation where we extract a subset 16504 // of bits from a 128 bit float. 16505 // This can be of two forms: 16506 // 1) BITCAST of f128 feeding TRUNCATE 16507 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16508 // The reason this is required is because we do not have a legal i128 type 16509 // and so we want to prevent having to store the f128 and then reload part 16510 // of it. 16511 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16512 DAGCombinerInfo &DCI) const { 16513 // If we are using CRBits then try that first. 16514 if (Subtarget.useCRBits()) { 16515 // Check if CRBits did anything and return that if it did. 16516 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16517 return CRTruncValue; 16518 } 16519 16520 SDLoc dl(N); 16521 SDValue Op0 = N->getOperand(0); 16522 16523 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16524 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16525 EVT VT = N->getValueType(0); 16526 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16527 return SDValue(); 16528 SDValue Sub = Op0.getOperand(0); 16529 if (Sub.getOpcode() == ISD::SUB) { 16530 SDValue SubOp0 = Sub.getOperand(0); 16531 SDValue SubOp1 = Sub.getOperand(1); 16532 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16533 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16534 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16535 SubOp1.getOperand(0), 16536 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16537 } 16538 } 16539 } 16540 16541 // Looking for a truncate of i128 to i64. 16542 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16543 return SDValue(); 16544 16545 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16546 16547 // SRL feeding TRUNCATE. 16548 if (Op0.getOpcode() == ISD::SRL) { 16549 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16550 // The right shift has to be by 64 bits. 16551 if (!ConstNode || ConstNode->getZExtValue() != 64) 16552 return SDValue(); 16553 16554 // Switch the element number to extract. 16555 EltToExtract = EltToExtract ? 0 : 1; 16556 // Update Op0 past the SRL. 16557 Op0 = Op0.getOperand(0); 16558 } 16559 16560 // BITCAST feeding a TRUNCATE possibly via SRL. 16561 if (Op0.getOpcode() == ISD::BITCAST && 16562 Op0.getValueType() == MVT::i128 && 16563 Op0.getOperand(0).getValueType() == MVT::f128) { 16564 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16565 return DCI.DAG.getNode( 16566 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16567 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16568 } 16569 return SDValue(); 16570 } 16571 16572 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16573 SelectionDAG &DAG = DCI.DAG; 16574 16575 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16576 if (!ConstOpOrElement) 16577 return SDValue(); 16578 16579 // An imul is usually smaller than the alternative sequence for legal type. 16580 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16581 isOperationLegal(ISD::MUL, N->getValueType(0))) 16582 return SDValue(); 16583 16584 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16585 switch (this->Subtarget.getCPUDirective()) { 16586 default: 16587 // TODO: enhance the condition for subtarget before pwr8 16588 return false; 16589 case PPC::DIR_PWR8: 16590 // type mul add shl 16591 // scalar 4 1 1 16592 // vector 7 2 2 16593 return true; 16594 case PPC::DIR_PWR9: 16595 case PPC::DIR_PWR10: 16596 case PPC::DIR_PWR_FUTURE: 16597 // type mul add shl 16598 // scalar 5 2 2 16599 // vector 7 2 2 16600 16601 // The cycle RATIO of related operations are showed as a table above. 16602 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16603 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16604 // are 4, it is always profitable; but for 3 instrs patterns 16605 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16606 // So we should only do it for vector type. 16607 return IsAddOne && IsNeg ? VT.isVector() : true; 16608 } 16609 }; 16610 16611 EVT VT = N->getValueType(0); 16612 SDLoc DL(N); 16613 16614 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16615 bool IsNeg = MulAmt.isNegative(); 16616 APInt MulAmtAbs = MulAmt.abs(); 16617 16618 if ((MulAmtAbs - 1).isPowerOf2()) { 16619 // (mul x, 2^N + 1) => (add (shl x, N), x) 16620 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16621 16622 if (!IsProfitable(IsNeg, true, VT)) 16623 return SDValue(); 16624 16625 SDValue Op0 = N->getOperand(0); 16626 SDValue Op1 = 16627 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16628 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16629 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16630 16631 if (!IsNeg) 16632 return Res; 16633 16634 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16635 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16636 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16637 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16638 16639 if (!IsProfitable(IsNeg, false, VT)) 16640 return SDValue(); 16641 16642 SDValue Op0 = N->getOperand(0); 16643 SDValue Op1 = 16644 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16645 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16646 16647 if (!IsNeg) 16648 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16649 else 16650 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16651 16652 } else { 16653 return SDValue(); 16654 } 16655 } 16656 16657 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16658 // in combiner since we need to check SD flags and other subtarget features. 16659 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16660 DAGCombinerInfo &DCI) const { 16661 SDValue N0 = N->getOperand(0); 16662 SDValue N1 = N->getOperand(1); 16663 SDValue N2 = N->getOperand(2); 16664 SDNodeFlags Flags = N->getFlags(); 16665 EVT VT = N->getValueType(0); 16666 SelectionDAG &DAG = DCI.DAG; 16667 const TargetOptions &Options = getTargetMachine().Options; 16668 unsigned Opc = N->getOpcode(); 16669 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16670 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16671 SDLoc Loc(N); 16672 16673 if (!isOperationLegal(ISD::FMA, VT)) 16674 return SDValue(); 16675 16676 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16677 // since (fnmsub a b c)=-0 while c-ab=+0. 16678 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16679 return SDValue(); 16680 16681 // (fma (fneg a) b c) => (fnmsub a b c) 16682 // (fnmsub (fneg a) b c) => (fma a b c) 16683 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16684 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16685 16686 // (fma a (fneg b) c) => (fnmsub a b c) 16687 // (fnmsub a (fneg b) c) => (fma a b c) 16688 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16689 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16690 16691 return SDValue(); 16692 } 16693 16694 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16695 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16696 if (!Subtarget.is64BitELFABI()) 16697 return false; 16698 16699 // If not a tail call then no need to proceed. 16700 if (!CI->isTailCall()) 16701 return false; 16702 16703 // If sibling calls have been disabled and tail-calls aren't guaranteed 16704 // there is no reason to duplicate. 16705 auto &TM = getTargetMachine(); 16706 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16707 return false; 16708 16709 // Can't tail call a function called indirectly, or if it has variadic args. 16710 const Function *Callee = CI->getCalledFunction(); 16711 if (!Callee || Callee->isVarArg()) 16712 return false; 16713 16714 // Make sure the callee and caller calling conventions are eligible for tco. 16715 const Function *Caller = CI->getParent()->getParent(); 16716 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16717 CI->getCallingConv())) 16718 return false; 16719 16720 // If the function is local then we have a good chance at tail-calling it 16721 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16722 } 16723 16724 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16725 if (!Subtarget.hasVSX()) 16726 return false; 16727 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16728 return true; 16729 return VT == MVT::f32 || VT == MVT::f64 || 16730 VT == MVT::v4f32 || VT == MVT::v2f64; 16731 } 16732 16733 bool PPCTargetLowering:: 16734 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16735 const Value *Mask = AndI.getOperand(1); 16736 // If the mask is suitable for andi. or andis. we should sink the and. 16737 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16738 // Can't handle constants wider than 64-bits. 16739 if (CI->getBitWidth() > 64) 16740 return false; 16741 int64_t ConstVal = CI->getZExtValue(); 16742 return isUInt<16>(ConstVal) || 16743 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16744 } 16745 16746 // For non-constant masks, we can always use the record-form and. 16747 return true; 16748 } 16749 16750 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16751 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16752 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16753 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16754 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16755 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16756 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16757 assert(Subtarget.hasP9Altivec() && 16758 "Only combine this when P9 altivec supported!"); 16759 EVT VT = N->getValueType(0); 16760 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16761 return SDValue(); 16762 16763 SelectionDAG &DAG = DCI.DAG; 16764 SDLoc dl(N); 16765 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16766 // Even for signed integers, if it's known to be positive (as signed 16767 // integer) due to zero-extended inputs. 16768 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16769 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16770 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16771 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16772 (SubOpcd1 == ISD::ZERO_EXTEND || 16773 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16774 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16775 N->getOperand(0)->getOperand(0), 16776 N->getOperand(0)->getOperand(1), 16777 DAG.getTargetConstant(0, dl, MVT::i32)); 16778 } 16779 16780 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16781 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16782 N->getOperand(0).hasOneUse()) { 16783 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16784 N->getOperand(0)->getOperand(0), 16785 N->getOperand(0)->getOperand(1), 16786 DAG.getTargetConstant(1, dl, MVT::i32)); 16787 } 16788 } 16789 16790 return SDValue(); 16791 } 16792 16793 // For type v4i32/v8ii16/v16i8, transform 16794 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16795 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16796 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16797 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16798 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16799 DAGCombinerInfo &DCI) const { 16800 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16801 assert(Subtarget.hasP9Altivec() && 16802 "Only combine this when P9 altivec supported!"); 16803 16804 SelectionDAG &DAG = DCI.DAG; 16805 SDLoc dl(N); 16806 SDValue Cond = N->getOperand(0); 16807 SDValue TrueOpnd = N->getOperand(1); 16808 SDValue FalseOpnd = N->getOperand(2); 16809 EVT VT = N->getOperand(1).getValueType(); 16810 16811 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16812 FalseOpnd.getOpcode() != ISD::SUB) 16813 return SDValue(); 16814 16815 // ABSD only available for type v4i32/v8i16/v16i8 16816 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16817 return SDValue(); 16818 16819 // At least to save one more dependent computation 16820 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16821 return SDValue(); 16822 16823 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16824 16825 // Can only handle unsigned comparison here 16826 switch (CC) { 16827 default: 16828 return SDValue(); 16829 case ISD::SETUGT: 16830 case ISD::SETUGE: 16831 break; 16832 case ISD::SETULT: 16833 case ISD::SETULE: 16834 std::swap(TrueOpnd, FalseOpnd); 16835 break; 16836 } 16837 16838 SDValue CmpOpnd1 = Cond.getOperand(0); 16839 SDValue CmpOpnd2 = Cond.getOperand(1); 16840 16841 // SETCC CmpOpnd1 CmpOpnd2 cond 16842 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16843 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16844 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16845 TrueOpnd.getOperand(1) == CmpOpnd2 && 16846 FalseOpnd.getOperand(0) == CmpOpnd2 && 16847 FalseOpnd.getOperand(1) == CmpOpnd1) { 16848 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16849 CmpOpnd1, CmpOpnd2, 16850 DAG.getTargetConstant(0, dl, MVT::i32)); 16851 } 16852 16853 return SDValue(); 16854 } 16855