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 if (Subtarget.isAIXABI() && 7664 (VA.getLocVT().isVector() || VA.getValVT().isVector())) 7665 report_fatal_error("Returning vector types not yet supported on AIX."); 7666 7667 switch (VA.getLocInfo()) { 7668 default: llvm_unreachable("Unknown loc info!"); 7669 case CCValAssign::Full: break; 7670 case CCValAssign::AExt: 7671 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7672 break; 7673 case CCValAssign::ZExt: 7674 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7675 break; 7676 case CCValAssign::SExt: 7677 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7678 break; 7679 } 7680 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7681 bool isLittleEndian = Subtarget.isLittleEndian(); 7682 // Legalize ret f64 -> ret 2 x i32. 7683 SDValue SVal = 7684 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7685 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7686 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7687 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7688 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7689 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7690 Flag = Chain.getValue(1); 7691 VA = RVLocs[++i]; // skip ahead to next loc 7692 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7693 } else 7694 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7695 Flag = Chain.getValue(1); 7696 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7697 } 7698 7699 RetOps[0] = Chain; // Update chain. 7700 7701 // Add the flag if we have it. 7702 if (Flag.getNode()) 7703 RetOps.push_back(Flag); 7704 7705 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7706 } 7707 7708 SDValue 7709 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7710 SelectionDAG &DAG) const { 7711 SDLoc dl(Op); 7712 7713 // Get the correct type for integers. 7714 EVT IntVT = Op.getValueType(); 7715 7716 // Get the inputs. 7717 SDValue Chain = Op.getOperand(0); 7718 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7719 // Build a DYNAREAOFFSET node. 7720 SDValue Ops[2] = {Chain, FPSIdx}; 7721 SDVTList VTs = DAG.getVTList(IntVT); 7722 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7723 } 7724 7725 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7726 SelectionDAG &DAG) const { 7727 // When we pop the dynamic allocation we need to restore the SP link. 7728 SDLoc dl(Op); 7729 7730 // Get the correct type for pointers. 7731 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7732 7733 // Construct the stack pointer operand. 7734 bool isPPC64 = Subtarget.isPPC64(); 7735 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7736 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7737 7738 // Get the operands for the STACKRESTORE. 7739 SDValue Chain = Op.getOperand(0); 7740 SDValue SaveSP = Op.getOperand(1); 7741 7742 // Load the old link SP. 7743 SDValue LoadLinkSP = 7744 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7745 7746 // Restore the stack pointer. 7747 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7748 7749 // Store the old link SP. 7750 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7751 } 7752 7753 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7754 MachineFunction &MF = DAG.getMachineFunction(); 7755 bool isPPC64 = Subtarget.isPPC64(); 7756 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7757 7758 // Get current frame pointer save index. The users of this index will be 7759 // primarily DYNALLOC instructions. 7760 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7761 int RASI = FI->getReturnAddrSaveIndex(); 7762 7763 // If the frame pointer save index hasn't been defined yet. 7764 if (!RASI) { 7765 // Find out what the fix offset of the frame pointer save area. 7766 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7767 // Allocate the frame index for frame pointer save area. 7768 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7769 // Save the result. 7770 FI->setReturnAddrSaveIndex(RASI); 7771 } 7772 return DAG.getFrameIndex(RASI, PtrVT); 7773 } 7774 7775 SDValue 7776 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7777 MachineFunction &MF = DAG.getMachineFunction(); 7778 bool isPPC64 = Subtarget.isPPC64(); 7779 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7780 7781 // Get current frame pointer save index. The users of this index will be 7782 // primarily DYNALLOC instructions. 7783 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7784 int FPSI = FI->getFramePointerSaveIndex(); 7785 7786 // If the frame pointer save index hasn't been defined yet. 7787 if (!FPSI) { 7788 // Find out what the fix offset of the frame pointer save area. 7789 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7790 // Allocate the frame index for frame pointer save area. 7791 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7792 // Save the result. 7793 FI->setFramePointerSaveIndex(FPSI); 7794 } 7795 return DAG.getFrameIndex(FPSI, PtrVT); 7796 } 7797 7798 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7799 SelectionDAG &DAG) const { 7800 MachineFunction &MF = DAG.getMachineFunction(); 7801 // Get the inputs. 7802 SDValue Chain = Op.getOperand(0); 7803 SDValue Size = Op.getOperand(1); 7804 SDLoc dl(Op); 7805 7806 // Get the correct type for pointers. 7807 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7808 // Negate the size. 7809 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7810 DAG.getConstant(0, dl, PtrVT), Size); 7811 // Construct a node for the frame pointer save index. 7812 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7813 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7814 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7815 if (hasInlineStackProbe(MF)) 7816 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7817 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7818 } 7819 7820 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7821 SelectionDAG &DAG) const { 7822 MachineFunction &MF = DAG.getMachineFunction(); 7823 7824 bool isPPC64 = Subtarget.isPPC64(); 7825 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7826 7827 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7828 return DAG.getFrameIndex(FI, PtrVT); 7829 } 7830 7831 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7832 SelectionDAG &DAG) const { 7833 SDLoc DL(Op); 7834 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7835 DAG.getVTList(MVT::i32, MVT::Other), 7836 Op.getOperand(0), Op.getOperand(1)); 7837 } 7838 7839 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7840 SelectionDAG &DAG) const { 7841 SDLoc DL(Op); 7842 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7843 Op.getOperand(0), Op.getOperand(1)); 7844 } 7845 7846 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7847 if (Op.getValueType().isVector()) 7848 return LowerVectorLoad(Op, DAG); 7849 7850 assert(Op.getValueType() == MVT::i1 && 7851 "Custom lowering only for i1 loads"); 7852 7853 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7854 7855 SDLoc dl(Op); 7856 LoadSDNode *LD = cast<LoadSDNode>(Op); 7857 7858 SDValue Chain = LD->getChain(); 7859 SDValue BasePtr = LD->getBasePtr(); 7860 MachineMemOperand *MMO = LD->getMemOperand(); 7861 7862 SDValue NewLD = 7863 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7864 BasePtr, MVT::i8, MMO); 7865 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7866 7867 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7868 return DAG.getMergeValues(Ops, dl); 7869 } 7870 7871 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7872 if (Op.getOperand(1).getValueType().isVector()) 7873 return LowerVectorStore(Op, DAG); 7874 7875 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7876 "Custom lowering only for i1 stores"); 7877 7878 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7879 7880 SDLoc dl(Op); 7881 StoreSDNode *ST = cast<StoreSDNode>(Op); 7882 7883 SDValue Chain = ST->getChain(); 7884 SDValue BasePtr = ST->getBasePtr(); 7885 SDValue Value = ST->getValue(); 7886 MachineMemOperand *MMO = ST->getMemOperand(); 7887 7888 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7889 Value); 7890 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7891 } 7892 7893 // FIXME: Remove this once the ANDI glue bug is fixed: 7894 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7895 assert(Op.getValueType() == MVT::i1 && 7896 "Custom lowering only for i1 results"); 7897 7898 SDLoc DL(Op); 7899 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7900 } 7901 7902 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7903 SelectionDAG &DAG) const { 7904 7905 // Implements a vector truncate that fits in a vector register as a shuffle. 7906 // We want to legalize vector truncates down to where the source fits in 7907 // a vector register (and target is therefore smaller than vector register 7908 // size). At that point legalization will try to custom lower the sub-legal 7909 // result and get here - where we can contain the truncate as a single target 7910 // operation. 7911 7912 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7913 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7914 // 7915 // We will implement it for big-endian ordering as this (where x denotes 7916 // undefined): 7917 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7918 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7919 // 7920 // The same operation in little-endian ordering will be: 7921 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7922 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7923 7924 EVT TrgVT = Op.getValueType(); 7925 assert(TrgVT.isVector() && "Vector type expected."); 7926 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7927 EVT EltVT = TrgVT.getVectorElementType(); 7928 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7929 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7930 !isPowerOf2_32(EltVT.getSizeInBits())) 7931 return SDValue(); 7932 7933 SDValue N1 = Op.getOperand(0); 7934 EVT SrcVT = N1.getValueType(); 7935 unsigned SrcSize = SrcVT.getSizeInBits(); 7936 if (SrcSize > 256 || 7937 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7938 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7939 return SDValue(); 7940 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7941 return SDValue(); 7942 7943 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7944 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7945 7946 SDLoc DL(Op); 7947 SDValue Op1, Op2; 7948 if (SrcSize == 256) { 7949 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7950 EVT SplitVT = 7951 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7952 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7953 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7954 DAG.getConstant(0, DL, VecIdxTy)); 7955 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7956 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7957 } 7958 else { 7959 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7960 Op2 = DAG.getUNDEF(WideVT); 7961 } 7962 7963 // First list the elements we want to keep. 7964 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7965 SmallVector<int, 16> ShuffV; 7966 if (Subtarget.isLittleEndian()) 7967 for (unsigned i = 0; i < TrgNumElts; ++i) 7968 ShuffV.push_back(i * SizeMult); 7969 else 7970 for (unsigned i = 1; i <= TrgNumElts; ++i) 7971 ShuffV.push_back(i * SizeMult - 1); 7972 7973 // Populate the remaining elements with undefs. 7974 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7975 // ShuffV.push_back(i + WideNumElts); 7976 ShuffV.push_back(WideNumElts + 1); 7977 7978 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7979 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7980 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7981 } 7982 7983 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7984 /// possible. 7985 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7986 // Not FP, or using SPE? Not a fsel. 7987 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7988 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7989 return Op; 7990 7991 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7992 7993 EVT ResVT = Op.getValueType(); 7994 EVT CmpVT = Op.getOperand(0).getValueType(); 7995 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7996 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7997 SDLoc dl(Op); 7998 SDNodeFlags Flags = Op.getNode()->getFlags(); 7999 8000 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 8001 // presence of infinities. 8002 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 8003 switch (CC) { 8004 default: 8005 break; 8006 case ISD::SETOGT: 8007 case ISD::SETGT: 8008 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 8009 case ISD::SETOLT: 8010 case ISD::SETLT: 8011 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8012 } 8013 } 8014 8015 // We might be able to do better than this under some circumstances, but in 8016 // general, fsel-based lowering of select is a finite-math-only optimization. 8017 // For more information, see section F.3 of the 2.06 ISA specification. 8018 // With ISA 3.0 8019 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 8020 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 8021 return Op; 8022 8023 // If the RHS of the comparison is a 0.0, we don't need to do the 8024 // subtraction at all. 8025 SDValue Sel1; 8026 if (isFloatingPointZero(RHS)) 8027 switch (CC) { 8028 default: break; // SETUO etc aren't handled by fsel. 8029 case ISD::SETNE: 8030 std::swap(TV, FV); 8031 LLVM_FALLTHROUGH; 8032 case ISD::SETEQ: 8033 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8034 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8035 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8036 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8037 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8038 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8039 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8040 case ISD::SETULT: 8041 case ISD::SETLT: 8042 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8043 LLVM_FALLTHROUGH; 8044 case ISD::SETOGE: 8045 case ISD::SETGE: 8046 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8047 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8048 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8049 case ISD::SETUGT: 8050 case ISD::SETGT: 8051 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8052 LLVM_FALLTHROUGH; 8053 case ISD::SETOLE: 8054 case ISD::SETLE: 8055 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8056 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8057 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8058 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8059 } 8060 8061 SDValue Cmp; 8062 switch (CC) { 8063 default: break; // SETUO etc aren't handled by fsel. 8064 case ISD::SETNE: 8065 std::swap(TV, FV); 8066 LLVM_FALLTHROUGH; 8067 case ISD::SETEQ: 8068 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8069 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8070 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8071 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8072 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8073 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8074 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8075 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8076 case ISD::SETULT: 8077 case ISD::SETLT: 8078 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8079 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8080 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8081 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8082 case ISD::SETOGE: 8083 case ISD::SETGE: 8084 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8085 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8086 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8087 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8088 case ISD::SETUGT: 8089 case ISD::SETGT: 8090 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8091 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8092 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8093 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8094 case ISD::SETOLE: 8095 case ISD::SETLE: 8096 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8097 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8098 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8099 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8100 } 8101 return Op; 8102 } 8103 8104 static unsigned getPPCStrictOpcode(unsigned Opc) { 8105 switch (Opc) { 8106 default: 8107 llvm_unreachable("No strict version of this opcode!"); 8108 case PPCISD::FCTIDZ: 8109 return PPCISD::STRICT_FCTIDZ; 8110 case PPCISD::FCTIWZ: 8111 return PPCISD::STRICT_FCTIWZ; 8112 case PPCISD::FCTIDUZ: 8113 return PPCISD::STRICT_FCTIDUZ; 8114 case PPCISD::FCTIWUZ: 8115 return PPCISD::STRICT_FCTIWUZ; 8116 case PPCISD::FCFID: 8117 return PPCISD::STRICT_FCFID; 8118 case PPCISD::FCFIDU: 8119 return PPCISD::STRICT_FCFIDU; 8120 case PPCISD::FCFIDS: 8121 return PPCISD::STRICT_FCFIDS; 8122 case PPCISD::FCFIDUS: 8123 return PPCISD::STRICT_FCFIDUS; 8124 } 8125 } 8126 8127 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8128 const PPCSubtarget &Subtarget) { 8129 SDLoc dl(Op); 8130 bool IsStrict = Op->isStrictFPOpcode(); 8131 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8132 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8133 8134 // TODO: Any other flags to propagate? 8135 SDNodeFlags Flags; 8136 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8137 8138 // For strict nodes, source is the second operand. 8139 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8140 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8141 assert(Src.getValueType().isFloatingPoint()); 8142 if (Src.getValueType() == MVT::f32) { 8143 if (IsStrict) { 8144 Src = 8145 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8146 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8147 Chain = Src.getValue(1); 8148 } else 8149 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8150 } 8151 SDValue Conv; 8152 unsigned Opc = ISD::DELETED_NODE; 8153 switch (Op.getSimpleValueType().SimpleTy) { 8154 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8155 case MVT::i32: 8156 Opc = IsSigned ? PPCISD::FCTIWZ 8157 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8158 break; 8159 case MVT::i64: 8160 assert((IsSigned || Subtarget.hasFPCVT()) && 8161 "i64 FP_TO_UINT is supported only with FPCVT"); 8162 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8163 } 8164 if (IsStrict) { 8165 Opc = getPPCStrictOpcode(Opc); 8166 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8167 {Chain, Src}, Flags); 8168 } else { 8169 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8170 } 8171 return Conv; 8172 } 8173 8174 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8175 SelectionDAG &DAG, 8176 const SDLoc &dl) const { 8177 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8178 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8179 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8180 bool IsStrict = Op->isStrictFPOpcode(); 8181 8182 // Convert the FP value to an int value through memory. 8183 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8184 (IsSigned || Subtarget.hasFPCVT()); 8185 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8186 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8187 MachinePointerInfo MPI = 8188 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8189 8190 // Emit a store to the stack slot. 8191 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8192 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8193 if (i32Stack) { 8194 MachineFunction &MF = DAG.getMachineFunction(); 8195 Alignment = Align(4); 8196 MachineMemOperand *MMO = 8197 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8198 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8199 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8200 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8201 } else 8202 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8203 8204 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8205 // add in a bias on big endian. 8206 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8207 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8208 DAG.getConstant(4, dl, FIPtr.getValueType())); 8209 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8210 } 8211 8212 RLI.Chain = Chain; 8213 RLI.Ptr = FIPtr; 8214 RLI.MPI = MPI; 8215 RLI.Alignment = Alignment; 8216 } 8217 8218 /// Custom lowers floating point to integer conversions to use 8219 /// the direct move instructions available in ISA 2.07 to avoid the 8220 /// need for load/store combinations. 8221 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8222 SelectionDAG &DAG, 8223 const SDLoc &dl) const { 8224 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8225 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8226 if (Op->isStrictFPOpcode()) 8227 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8228 else 8229 return Mov; 8230 } 8231 8232 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8233 const SDLoc &dl) const { 8234 bool IsStrict = Op->isStrictFPOpcode(); 8235 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8236 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8237 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8238 EVT SrcVT = Src.getValueType(); 8239 EVT DstVT = Op.getValueType(); 8240 8241 // FP to INT conversions are legal for f128. 8242 if (SrcVT == MVT::f128) 8243 return Op; 8244 8245 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8246 // PPC (the libcall is not available). 8247 if (SrcVT == MVT::ppcf128) { 8248 if (DstVT == MVT::i32) { 8249 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8250 // set other fast-math flags to FP operations in both strict and 8251 // non-strict cases. (FP_TO_SINT, FSUB) 8252 SDNodeFlags Flags; 8253 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8254 8255 if (IsSigned) { 8256 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8257 DAG.getIntPtrConstant(0, dl)); 8258 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8259 DAG.getIntPtrConstant(1, dl)); 8260 8261 // Add the two halves of the long double in round-to-zero mode, and use 8262 // a smaller FP_TO_SINT. 8263 if (IsStrict) { 8264 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8265 DAG.getVTList(MVT::f64, MVT::Other), 8266 {Op.getOperand(0), Lo, Hi}, Flags); 8267 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8268 DAG.getVTList(MVT::i32, MVT::Other), 8269 {Res.getValue(1), Res}, Flags); 8270 } else { 8271 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8272 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8273 } 8274 } else { 8275 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8276 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8277 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8278 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8279 if (IsStrict) { 8280 // Sel = Src < 0x80000000 8281 // FltOfs = select Sel, 0.0, 0x80000000 8282 // IntOfs = select Sel, 0, 0x80000000 8283 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8284 SDValue Chain = Op.getOperand(0); 8285 EVT SetCCVT = 8286 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8287 EVT DstSetCCVT = 8288 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8289 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8290 SDNodeFlags(), Chain, true); 8291 Chain = Sel.getValue(1); 8292 8293 SDValue FltOfs = DAG.getSelect( 8294 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8295 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8296 8297 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8298 DAG.getVTList(SrcVT, MVT::Other), 8299 {Chain, Src, FltOfs}, Flags); 8300 Chain = Val.getValue(1); 8301 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8302 DAG.getVTList(DstVT, MVT::Other), 8303 {Chain, Val}, Flags); 8304 Chain = SInt.getValue(1); 8305 SDValue IntOfs = DAG.getSelect( 8306 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8307 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8308 return DAG.getMergeValues({Result, Chain}, dl); 8309 } else { 8310 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8311 // FIXME: generated code sucks. 8312 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8313 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8314 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8315 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8316 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8317 } 8318 } 8319 } 8320 8321 return SDValue(); 8322 } 8323 8324 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8325 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8326 8327 ReuseLoadInfo RLI; 8328 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8329 8330 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8331 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8332 } 8333 8334 // We're trying to insert a regular store, S, and then a load, L. If the 8335 // incoming value, O, is a load, we might just be able to have our load use the 8336 // address used by O. However, we don't know if anything else will store to 8337 // that address before we can load from it. To prevent this situation, we need 8338 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8339 // the same chain operand as O, we create a token factor from the chain results 8340 // of O and L, and we replace all uses of O's chain result with that token 8341 // factor (see spliceIntoChain below for this last part). 8342 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8343 ReuseLoadInfo &RLI, 8344 SelectionDAG &DAG, 8345 ISD::LoadExtType ET) const { 8346 // Conservatively skip reusing for constrained FP nodes. 8347 if (Op->isStrictFPOpcode()) 8348 return false; 8349 8350 SDLoc dl(Op); 8351 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8352 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8353 if (ET == ISD::NON_EXTLOAD && 8354 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8355 isOperationLegalOrCustom(Op.getOpcode(), 8356 Op.getOperand(0).getValueType())) { 8357 8358 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8359 return true; 8360 } 8361 8362 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8363 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8364 LD->isNonTemporal()) 8365 return false; 8366 if (LD->getMemoryVT() != MemVT) 8367 return false; 8368 8369 RLI.Ptr = LD->getBasePtr(); 8370 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8371 assert(LD->getAddressingMode() == ISD::PRE_INC && 8372 "Non-pre-inc AM on PPC?"); 8373 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8374 LD->getOffset()); 8375 } 8376 8377 RLI.Chain = LD->getChain(); 8378 RLI.MPI = LD->getPointerInfo(); 8379 RLI.IsDereferenceable = LD->isDereferenceable(); 8380 RLI.IsInvariant = LD->isInvariant(); 8381 RLI.Alignment = LD->getAlign(); 8382 RLI.AAInfo = LD->getAAInfo(); 8383 RLI.Ranges = LD->getRanges(); 8384 8385 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8386 return true; 8387 } 8388 8389 // Given the head of the old chain, ResChain, insert a token factor containing 8390 // it and NewResChain, and make users of ResChain now be users of that token 8391 // factor. 8392 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8393 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8394 SDValue NewResChain, 8395 SelectionDAG &DAG) const { 8396 if (!ResChain) 8397 return; 8398 8399 SDLoc dl(NewResChain); 8400 8401 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8402 NewResChain, DAG.getUNDEF(MVT::Other)); 8403 assert(TF.getNode() != NewResChain.getNode() && 8404 "A new TF really is required here"); 8405 8406 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8407 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8408 } 8409 8410 /// Analyze profitability of direct move 8411 /// prefer float load to int load plus direct move 8412 /// when there is no integer use of int load 8413 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8414 SDNode *Origin = Op.getOperand(0).getNode(); 8415 if (Origin->getOpcode() != ISD::LOAD) 8416 return true; 8417 8418 // If there is no LXSIBZX/LXSIHZX, like Power8, 8419 // prefer direct move if the memory size is 1 or 2 bytes. 8420 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8421 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8422 return true; 8423 8424 for (SDNode::use_iterator UI = Origin->use_begin(), 8425 UE = Origin->use_end(); 8426 UI != UE; ++UI) { 8427 8428 // Only look at the users of the loaded value. 8429 if (UI.getUse().get().getResNo() != 0) 8430 continue; 8431 8432 if (UI->getOpcode() != ISD::SINT_TO_FP && 8433 UI->getOpcode() != ISD::UINT_TO_FP && 8434 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8435 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8436 return true; 8437 } 8438 8439 return false; 8440 } 8441 8442 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8443 const PPCSubtarget &Subtarget, 8444 SDValue Chain = SDValue()) { 8445 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8446 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8447 SDLoc dl(Op); 8448 8449 // TODO: Any other flags to propagate? 8450 SDNodeFlags Flags; 8451 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8452 8453 // If we have FCFIDS, then use it when converting to single-precision. 8454 // Otherwise, convert to double-precision and then round. 8455 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8456 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8457 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8458 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8459 if (Op->isStrictFPOpcode()) { 8460 if (!Chain) 8461 Chain = Op.getOperand(0); 8462 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8463 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8464 } else 8465 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8466 } 8467 8468 /// Custom lowers integer to floating point conversions to use 8469 /// the direct move instructions available in ISA 2.07 to avoid the 8470 /// need for load/store combinations. 8471 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8472 SelectionDAG &DAG, 8473 const SDLoc &dl) const { 8474 assert((Op.getValueType() == MVT::f32 || 8475 Op.getValueType() == MVT::f64) && 8476 "Invalid floating point type as target of conversion"); 8477 assert(Subtarget.hasFPCVT() && 8478 "Int to FP conversions with direct moves require FPCVT"); 8479 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8480 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8481 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8482 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8483 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8484 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8485 return convertIntToFP(Op, Mov, DAG, Subtarget); 8486 } 8487 8488 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8489 8490 EVT VecVT = Vec.getValueType(); 8491 assert(VecVT.isVector() && "Expected a vector type."); 8492 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8493 8494 EVT EltVT = VecVT.getVectorElementType(); 8495 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8496 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8497 8498 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8499 SmallVector<SDValue, 16> Ops(NumConcat); 8500 Ops[0] = Vec; 8501 SDValue UndefVec = DAG.getUNDEF(VecVT); 8502 for (unsigned i = 1; i < NumConcat; ++i) 8503 Ops[i] = UndefVec; 8504 8505 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8506 } 8507 8508 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8509 const SDLoc &dl) const { 8510 bool IsStrict = Op->isStrictFPOpcode(); 8511 unsigned Opc = Op.getOpcode(); 8512 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8513 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8514 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8515 "Unexpected conversion type"); 8516 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8517 "Supports conversions to v2f64/v4f32 only."); 8518 8519 // TODO: Any other flags to propagate? 8520 SDNodeFlags Flags; 8521 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8522 8523 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8524 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8525 8526 SDValue Wide = widenVec(DAG, Src, dl); 8527 EVT WideVT = Wide.getValueType(); 8528 unsigned WideNumElts = WideVT.getVectorNumElements(); 8529 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8530 8531 SmallVector<int, 16> ShuffV; 8532 for (unsigned i = 0; i < WideNumElts; ++i) 8533 ShuffV.push_back(i + WideNumElts); 8534 8535 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8536 int SaveElts = FourEltRes ? 4 : 2; 8537 if (Subtarget.isLittleEndian()) 8538 for (int i = 0; i < SaveElts; i++) 8539 ShuffV[i * Stride] = i; 8540 else 8541 for (int i = 1; i <= SaveElts; i++) 8542 ShuffV[i * Stride - 1] = i - 1; 8543 8544 SDValue ShuffleSrc2 = 8545 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8546 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8547 8548 SDValue Extend; 8549 if (SignedConv) { 8550 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8551 EVT ExtVT = Src.getValueType(); 8552 if (Subtarget.hasP9Altivec()) 8553 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8554 IntermediateVT.getVectorNumElements()); 8555 8556 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8557 DAG.getValueType(ExtVT)); 8558 } else 8559 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8560 8561 if (IsStrict) 8562 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8563 {Op.getOperand(0), Extend}, Flags); 8564 8565 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8566 } 8567 8568 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8569 SelectionDAG &DAG) const { 8570 SDLoc dl(Op); 8571 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8572 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8573 bool IsStrict = Op->isStrictFPOpcode(); 8574 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8575 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8576 8577 // TODO: Any other flags to propagate? 8578 SDNodeFlags Flags; 8579 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8580 8581 EVT InVT = Src.getValueType(); 8582 EVT OutVT = Op.getValueType(); 8583 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8584 isOperationCustom(Op.getOpcode(), InVT)) 8585 return LowerINT_TO_FPVector(Op, DAG, dl); 8586 8587 // Conversions to f128 are legal. 8588 if (Op.getValueType() == MVT::f128) 8589 return Op; 8590 8591 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8592 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8593 return SDValue(); 8594 8595 if (Src.getValueType() == MVT::i1) 8596 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8597 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8598 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8599 8600 // If we have direct moves, we can do all the conversion, skip the store/load 8601 // however, without FPCVT we can't do most conversions. 8602 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8603 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8604 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8605 8606 assert((IsSigned || Subtarget.hasFPCVT()) && 8607 "UINT_TO_FP is supported only with FPCVT"); 8608 8609 if (Src.getValueType() == MVT::i64) { 8610 SDValue SINT = Src; 8611 // When converting to single-precision, we actually need to convert 8612 // to double-precision first and then round to single-precision. 8613 // To avoid double-rounding effects during that operation, we have 8614 // to prepare the input operand. Bits that might be truncated when 8615 // converting to double-precision are replaced by a bit that won't 8616 // be lost at this stage, but is below the single-precision rounding 8617 // position. 8618 // 8619 // However, if -enable-unsafe-fp-math is in effect, accept double 8620 // rounding to avoid the extra overhead. 8621 if (Op.getValueType() == MVT::f32 && 8622 !Subtarget.hasFPCVT() && 8623 !DAG.getTarget().Options.UnsafeFPMath) { 8624 8625 // Twiddle input to make sure the low 11 bits are zero. (If this 8626 // is the case, we are guaranteed the value will fit into the 53 bit 8627 // mantissa of an IEEE double-precision value without rounding.) 8628 // If any of those low 11 bits were not zero originally, make sure 8629 // bit 12 (value 2048) is set instead, so that the final rounding 8630 // to single-precision gets the correct result. 8631 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8632 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8633 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8634 Round, DAG.getConstant(2047, dl, MVT::i64)); 8635 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8636 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8637 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8638 8639 // However, we cannot use that value unconditionally: if the magnitude 8640 // of the input value is small, the bit-twiddling we did above might 8641 // end up visibly changing the output. Fortunately, in that case, we 8642 // don't need to twiddle bits since the original input will convert 8643 // exactly to double-precision floating-point already. Therefore, 8644 // construct a conditional to use the original value if the top 11 8645 // bits are all sign-bit copies, and use the rounded value computed 8646 // above otherwise. 8647 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8648 SINT, DAG.getConstant(53, dl, MVT::i32)); 8649 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8650 Cond, DAG.getConstant(1, dl, MVT::i64)); 8651 Cond = DAG.getSetCC( 8652 dl, 8653 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8654 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8655 8656 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8657 } 8658 8659 ReuseLoadInfo RLI; 8660 SDValue Bits; 8661 8662 MachineFunction &MF = DAG.getMachineFunction(); 8663 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8664 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8665 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8666 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8667 } else if (Subtarget.hasLFIWAX() && 8668 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8669 MachineMemOperand *MMO = 8670 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8671 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8672 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8673 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8674 DAG.getVTList(MVT::f64, MVT::Other), 8675 Ops, MVT::i32, MMO); 8676 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8677 } else if (Subtarget.hasFPCVT() && 8678 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8679 MachineMemOperand *MMO = 8680 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8681 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8682 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8683 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8684 DAG.getVTList(MVT::f64, MVT::Other), 8685 Ops, MVT::i32, MMO); 8686 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8687 } else if (((Subtarget.hasLFIWAX() && 8688 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8689 (Subtarget.hasFPCVT() && 8690 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8691 SINT.getOperand(0).getValueType() == MVT::i32) { 8692 MachineFrameInfo &MFI = MF.getFrameInfo(); 8693 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8694 8695 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8696 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8697 8698 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8699 MachinePointerInfo::getFixedStack( 8700 DAG.getMachineFunction(), FrameIdx)); 8701 Chain = Store; 8702 8703 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8704 "Expected an i32 store"); 8705 8706 RLI.Ptr = FIdx; 8707 RLI.Chain = Chain; 8708 RLI.MPI = 8709 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8710 RLI.Alignment = Align(4); 8711 8712 MachineMemOperand *MMO = 8713 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8714 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8715 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8716 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8717 PPCISD::LFIWZX : PPCISD::LFIWAX, 8718 dl, DAG.getVTList(MVT::f64, MVT::Other), 8719 Ops, MVT::i32, MMO); 8720 Chain = Bits.getValue(1); 8721 } else 8722 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8723 8724 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8725 if (IsStrict) 8726 Chain = FP.getValue(1); 8727 8728 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8729 if (IsStrict) 8730 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8731 DAG.getVTList(MVT::f32, MVT::Other), 8732 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8733 else 8734 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8735 DAG.getIntPtrConstant(0, dl)); 8736 } 8737 return FP; 8738 } 8739 8740 assert(Src.getValueType() == MVT::i32 && 8741 "Unhandled INT_TO_FP type in custom expander!"); 8742 // Since we only generate this in 64-bit mode, we can take advantage of 8743 // 64-bit registers. In particular, sign extend the input value into the 8744 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8745 // then lfd it and fcfid it. 8746 MachineFunction &MF = DAG.getMachineFunction(); 8747 MachineFrameInfo &MFI = MF.getFrameInfo(); 8748 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8749 8750 SDValue Ld; 8751 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8752 ReuseLoadInfo RLI; 8753 bool ReusingLoad; 8754 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8755 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8756 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8757 8758 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8759 MachinePointerInfo::getFixedStack( 8760 DAG.getMachineFunction(), FrameIdx)); 8761 Chain = Store; 8762 8763 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8764 "Expected an i32 store"); 8765 8766 RLI.Ptr = FIdx; 8767 RLI.Chain = Chain; 8768 RLI.MPI = 8769 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8770 RLI.Alignment = Align(4); 8771 } 8772 8773 MachineMemOperand *MMO = 8774 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8775 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8776 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8777 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8778 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8779 MVT::i32, MMO); 8780 Chain = Ld.getValue(1); 8781 if (ReusingLoad) 8782 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8783 } else { 8784 assert(Subtarget.isPPC64() && 8785 "i32->FP without LFIWAX supported only on PPC64"); 8786 8787 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8788 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8789 8790 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8791 8792 // STD the extended value into the stack slot. 8793 SDValue Store = DAG.getStore( 8794 Chain, dl, Ext64, FIdx, 8795 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8796 Chain = Store; 8797 8798 // Load the value as a double. 8799 Ld = DAG.getLoad( 8800 MVT::f64, dl, Chain, FIdx, 8801 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8802 Chain = Ld.getValue(1); 8803 } 8804 8805 // FCFID it and return it. 8806 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8807 if (IsStrict) 8808 Chain = FP.getValue(1); 8809 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8810 if (IsStrict) 8811 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8812 DAG.getVTList(MVT::f32, MVT::Other), 8813 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8814 else 8815 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8816 DAG.getIntPtrConstant(0, dl)); 8817 } 8818 return FP; 8819 } 8820 8821 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8822 SelectionDAG &DAG) const { 8823 SDLoc dl(Op); 8824 /* 8825 The rounding mode is in bits 30:31 of FPSR, and has the following 8826 settings: 8827 00 Round to nearest 8828 01 Round to 0 8829 10 Round to +inf 8830 11 Round to -inf 8831 8832 FLT_ROUNDS, on the other hand, expects the following: 8833 -1 Undefined 8834 0 Round to 0 8835 1 Round to nearest 8836 2 Round to +inf 8837 3 Round to -inf 8838 8839 To perform the conversion, we do: 8840 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8841 */ 8842 8843 MachineFunction &MF = DAG.getMachineFunction(); 8844 EVT VT = Op.getValueType(); 8845 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8846 8847 // Save FP Control Word to register 8848 SDValue Chain = Op.getOperand(0); 8849 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8850 Chain = MFFS.getValue(1); 8851 8852 // Save FP register to stack slot 8853 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8854 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8855 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8856 8857 // Load FP Control Word from low 32 bits of stack slot. 8858 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8859 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8860 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8861 Chain = CWD.getValue(1); 8862 8863 // Transform as necessary 8864 SDValue CWD1 = 8865 DAG.getNode(ISD::AND, dl, MVT::i32, 8866 CWD, DAG.getConstant(3, dl, MVT::i32)); 8867 SDValue CWD2 = 8868 DAG.getNode(ISD::SRL, dl, MVT::i32, 8869 DAG.getNode(ISD::AND, dl, MVT::i32, 8870 DAG.getNode(ISD::XOR, dl, MVT::i32, 8871 CWD, DAG.getConstant(3, dl, MVT::i32)), 8872 DAG.getConstant(3, dl, MVT::i32)), 8873 DAG.getConstant(1, dl, MVT::i32)); 8874 8875 SDValue RetVal = 8876 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8877 8878 RetVal = 8879 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8880 dl, VT, RetVal); 8881 8882 return DAG.getMergeValues({RetVal, Chain}, dl); 8883 } 8884 8885 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8886 EVT VT = Op.getValueType(); 8887 unsigned BitWidth = VT.getSizeInBits(); 8888 SDLoc dl(Op); 8889 assert(Op.getNumOperands() == 3 && 8890 VT == Op.getOperand(1).getValueType() && 8891 "Unexpected SHL!"); 8892 8893 // Expand into a bunch of logical ops. Note that these ops 8894 // depend on the PPC behavior for oversized shift amounts. 8895 SDValue Lo = Op.getOperand(0); 8896 SDValue Hi = Op.getOperand(1); 8897 SDValue Amt = Op.getOperand(2); 8898 EVT AmtVT = Amt.getValueType(); 8899 8900 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8901 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8902 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8903 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8904 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8905 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8906 DAG.getConstant(-BitWidth, dl, AmtVT)); 8907 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8908 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8909 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8910 SDValue OutOps[] = { OutLo, OutHi }; 8911 return DAG.getMergeValues(OutOps, dl); 8912 } 8913 8914 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8915 EVT VT = Op.getValueType(); 8916 SDLoc dl(Op); 8917 unsigned BitWidth = VT.getSizeInBits(); 8918 assert(Op.getNumOperands() == 3 && 8919 VT == Op.getOperand(1).getValueType() && 8920 "Unexpected SRL!"); 8921 8922 // Expand into a bunch of logical ops. Note that these ops 8923 // depend on the PPC behavior for oversized shift amounts. 8924 SDValue Lo = Op.getOperand(0); 8925 SDValue Hi = Op.getOperand(1); 8926 SDValue Amt = Op.getOperand(2); 8927 EVT AmtVT = Amt.getValueType(); 8928 8929 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8930 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8931 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8932 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8933 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8934 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8935 DAG.getConstant(-BitWidth, dl, AmtVT)); 8936 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8937 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8938 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8939 SDValue OutOps[] = { OutLo, OutHi }; 8940 return DAG.getMergeValues(OutOps, dl); 8941 } 8942 8943 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8944 SDLoc dl(Op); 8945 EVT VT = Op.getValueType(); 8946 unsigned BitWidth = VT.getSizeInBits(); 8947 assert(Op.getNumOperands() == 3 && 8948 VT == Op.getOperand(1).getValueType() && 8949 "Unexpected SRA!"); 8950 8951 // Expand into a bunch of logical ops, followed by a select_cc. 8952 SDValue Lo = Op.getOperand(0); 8953 SDValue Hi = Op.getOperand(1); 8954 SDValue Amt = Op.getOperand(2); 8955 EVT AmtVT = Amt.getValueType(); 8956 8957 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8958 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8959 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8960 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8961 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8962 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8963 DAG.getConstant(-BitWidth, dl, AmtVT)); 8964 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8965 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8966 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8967 Tmp4, Tmp6, ISD::SETLE); 8968 SDValue OutOps[] = { OutLo, OutHi }; 8969 return DAG.getMergeValues(OutOps, dl); 8970 } 8971 8972 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8973 SelectionDAG &DAG) const { 8974 SDLoc dl(Op); 8975 EVT VT = Op.getValueType(); 8976 unsigned BitWidth = VT.getSizeInBits(); 8977 8978 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8979 SDValue X = Op.getOperand(0); 8980 SDValue Y = Op.getOperand(1); 8981 SDValue Z = Op.getOperand(2); 8982 EVT AmtVT = Z.getValueType(); 8983 8984 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8985 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8986 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8987 // on PowerPC shift by BW being well defined. 8988 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8989 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8990 SDValue SubZ = 8991 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8992 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8993 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8994 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8995 } 8996 8997 //===----------------------------------------------------------------------===// 8998 // Vector related lowering. 8999 // 9000 9001 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 9002 /// element size of SplatSize. Cast the result to VT. 9003 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 9004 SelectionDAG &DAG, const SDLoc &dl) { 9005 static const MVT VTys[] = { // canonical VT to use for each size. 9006 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 9007 }; 9008 9009 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 9010 9011 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 9012 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 9013 SplatSize = 1; 9014 Val = 0xFF; 9015 } 9016 9017 EVT CanonicalVT = VTys[SplatSize-1]; 9018 9019 // Build a canonical splat for this value. 9020 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 9021 } 9022 9023 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 9024 /// specified intrinsic ID. 9025 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 9026 const SDLoc &dl, EVT DestVT = MVT::Other) { 9027 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 9028 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9029 DAG.getConstant(IID, dl, MVT::i32), Op); 9030 } 9031 9032 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 9033 /// specified intrinsic ID. 9034 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 9035 SelectionDAG &DAG, const SDLoc &dl, 9036 EVT DestVT = MVT::Other) { 9037 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 9038 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9039 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 9040 } 9041 9042 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 9043 /// specified intrinsic ID. 9044 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 9045 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 9046 EVT DestVT = MVT::Other) { 9047 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 9048 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9049 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 9050 } 9051 9052 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 9053 /// amount. The result has the specified value type. 9054 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 9055 SelectionDAG &DAG, const SDLoc &dl) { 9056 // Force LHS/RHS to be the right type. 9057 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 9058 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 9059 9060 int Ops[16]; 9061 for (unsigned i = 0; i != 16; ++i) 9062 Ops[i] = i + Amt; 9063 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 9064 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9065 } 9066 9067 /// Do we have an efficient pattern in a .td file for this node? 9068 /// 9069 /// \param V - pointer to the BuildVectorSDNode being matched 9070 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9071 /// 9072 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9073 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9074 /// the opposite is true (expansion is beneficial) are: 9075 /// - The node builds a vector out of integers that are not 32 or 64-bits 9076 /// - The node builds a vector out of constants 9077 /// - The node is a "load-and-splat" 9078 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9079 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9080 bool HasDirectMove, 9081 bool HasP8Vector) { 9082 EVT VecVT = V->getValueType(0); 9083 bool RightType = VecVT == MVT::v2f64 || 9084 (HasP8Vector && VecVT == MVT::v4f32) || 9085 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9086 if (!RightType) 9087 return false; 9088 9089 bool IsSplat = true; 9090 bool IsLoad = false; 9091 SDValue Op0 = V->getOperand(0); 9092 9093 // This function is called in a block that confirms the node is not a constant 9094 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9095 // different constants. 9096 if (V->isConstant()) 9097 return false; 9098 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9099 if (V->getOperand(i).isUndef()) 9100 return false; 9101 // We want to expand nodes that represent load-and-splat even if the 9102 // loaded value is a floating point truncation or conversion to int. 9103 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9104 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9105 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9106 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9107 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9108 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9109 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9110 IsLoad = true; 9111 // If the operands are different or the input is not a load and has more 9112 // uses than just this BV node, then it isn't a splat. 9113 if (V->getOperand(i) != Op0 || 9114 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9115 IsSplat = false; 9116 } 9117 return !(IsSplat && IsLoad); 9118 } 9119 9120 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9121 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9122 9123 SDLoc dl(Op); 9124 SDValue Op0 = Op->getOperand(0); 9125 9126 if ((Op.getValueType() != MVT::f128) || 9127 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9128 (Op0.getOperand(0).getValueType() != MVT::i64) || 9129 (Op0.getOperand(1).getValueType() != MVT::i64)) 9130 return SDValue(); 9131 9132 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9133 Op0.getOperand(1)); 9134 } 9135 9136 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9137 const SDValue *InputLoad = &Op; 9138 if (InputLoad->getOpcode() == ISD::BITCAST) 9139 InputLoad = &InputLoad->getOperand(0); 9140 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9141 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9142 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9143 InputLoad = &InputLoad->getOperand(0); 9144 } 9145 if (InputLoad->getOpcode() != ISD::LOAD) 9146 return nullptr; 9147 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9148 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9149 } 9150 9151 // Convert the argument APFloat to a single precision APFloat if there is no 9152 // loss in information during the conversion to single precision APFloat and the 9153 // resulting number is not a denormal number. Return true if successful. 9154 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9155 APFloat APFloatToConvert = ArgAPFloat; 9156 bool LosesInfo = true; 9157 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9158 &LosesInfo); 9159 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9160 if (Success) 9161 ArgAPFloat = APFloatToConvert; 9162 return Success; 9163 } 9164 9165 // Bitcast the argument APInt to a double and convert it to a single precision 9166 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9167 // argument if there is no loss in information during the conversion from 9168 // double to single precision APFloat and the resulting number is not a denormal 9169 // number. Return true if successful. 9170 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9171 double DpValue = ArgAPInt.bitsToDouble(); 9172 APFloat APFloatDp(DpValue); 9173 bool Success = convertToNonDenormSingle(APFloatDp); 9174 if (Success) 9175 ArgAPInt = APFloatDp.bitcastToAPInt(); 9176 return Success; 9177 } 9178 9179 // If this is a case we can't handle, return null and let the default 9180 // expansion code take care of it. If we CAN select this case, and if it 9181 // selects to a single instruction, return Op. Otherwise, if we can codegen 9182 // this case more efficiently than a constant pool load, lower it to the 9183 // sequence of ops that should be used. 9184 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9185 SelectionDAG &DAG) const { 9186 SDLoc dl(Op); 9187 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9188 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9189 9190 // Check if this is a splat of a constant value. 9191 APInt APSplatBits, APSplatUndef; 9192 unsigned SplatBitSize; 9193 bool HasAnyUndefs; 9194 bool BVNIsConstantSplat = 9195 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9196 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9197 9198 // If it is a splat of a double, check if we can shrink it to a 32 bit 9199 // non-denormal float which when converted back to double gives us the same 9200 // double. This is to exploit the XXSPLTIDP instruction. 9201 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 9202 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 9203 convertToNonDenormSingle(APSplatBits)) { 9204 SDValue SplatNode = DAG.getNode( 9205 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9206 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9207 return DAG.getBitcast(Op.getValueType(), SplatNode); 9208 } 9209 9210 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9211 9212 bool IsPermutedLoad = false; 9213 const SDValue *InputLoad = 9214 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9215 // Handle load-and-splat patterns as we have instructions that will do this 9216 // in one go. 9217 if (InputLoad && DAG.isSplatValue(Op, true)) { 9218 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9219 9220 // We have handling for 4 and 8 byte elements. 9221 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9222 9223 // Checking for a single use of this load, we have to check for vector 9224 // width (128 bits) / ElementSize uses (since each operand of the 9225 // BUILD_VECTOR is a separate use of the value. 9226 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9227 ((Subtarget.hasVSX() && ElementSize == 64) || 9228 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9229 SDValue Ops[] = { 9230 LD->getChain(), // Chain 9231 LD->getBasePtr(), // Ptr 9232 DAG.getValueType(Op.getValueType()) // VT 9233 }; 9234 return 9235 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9236 DAG.getVTList(Op.getValueType(), MVT::Other), 9237 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9238 } 9239 } 9240 9241 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9242 // lowered to VSX instructions under certain conditions. 9243 // Without VSX, there is no pattern more efficient than expanding the node. 9244 if (Subtarget.hasVSX() && 9245 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9246 Subtarget.hasP8Vector())) 9247 return Op; 9248 return SDValue(); 9249 } 9250 9251 uint64_t SplatBits = APSplatBits.getZExtValue(); 9252 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9253 unsigned SplatSize = SplatBitSize / 8; 9254 9255 // First, handle single instruction cases. 9256 9257 // All zeros? 9258 if (SplatBits == 0) { 9259 // Canonicalize all zero vectors to be v4i32. 9260 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9261 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9262 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9263 } 9264 return Op; 9265 } 9266 9267 // We have XXSPLTIW for constant splats four bytes wide. 9268 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9269 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9270 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9271 // turned into a 4-byte splat of 0xABABABAB. 9272 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9273 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 9274 Op.getValueType(), DAG, dl); 9275 9276 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9277 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9278 dl); 9279 9280 // We have XXSPLTIB for constant splats one byte wide. 9281 if (Subtarget.hasP9Vector() && SplatSize == 1) 9282 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9283 dl); 9284 9285 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9286 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9287 (32-SplatBitSize)); 9288 if (SextVal >= -16 && SextVal <= 15) 9289 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9290 dl); 9291 9292 // Two instruction sequences. 9293 9294 // If this value is in the range [-32,30] and is even, use: 9295 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9296 // If this value is in the range [17,31] and is odd, use: 9297 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9298 // If this value is in the range [-31,-17] and is odd, use: 9299 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9300 // Note the last two are three-instruction sequences. 9301 if (SextVal >= -32 && SextVal <= 31) { 9302 // To avoid having these optimizations undone by constant folding, 9303 // we convert to a pseudo that will be expanded later into one of 9304 // the above forms. 9305 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9306 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9307 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9308 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9309 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9310 if (VT == Op.getValueType()) 9311 return RetVal; 9312 else 9313 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9314 } 9315 9316 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9317 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9318 // for fneg/fabs. 9319 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9320 // Make -1 and vspltisw -1: 9321 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9322 9323 // Make the VSLW intrinsic, computing 0x8000_0000. 9324 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9325 OnesV, DAG, dl); 9326 9327 // xor by OnesV to invert it. 9328 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9329 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9330 } 9331 9332 // Check to see if this is a wide variety of vsplti*, binop self cases. 9333 static const signed char SplatCsts[] = { 9334 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9335 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9336 }; 9337 9338 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9339 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9340 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9341 int i = SplatCsts[idx]; 9342 9343 // Figure out what shift amount will be used by altivec if shifted by i in 9344 // this splat size. 9345 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9346 9347 // vsplti + shl self. 9348 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9349 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9350 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9351 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9352 Intrinsic::ppc_altivec_vslw 9353 }; 9354 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9355 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9356 } 9357 9358 // vsplti + srl self. 9359 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9360 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9361 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9362 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9363 Intrinsic::ppc_altivec_vsrw 9364 }; 9365 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9366 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9367 } 9368 9369 // vsplti + sra self. 9370 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9371 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9372 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9373 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9374 Intrinsic::ppc_altivec_vsraw 9375 }; 9376 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9377 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9378 } 9379 9380 // vsplti + rol self. 9381 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9382 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9383 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9384 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9385 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9386 Intrinsic::ppc_altivec_vrlw 9387 }; 9388 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9389 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9390 } 9391 9392 // t = vsplti c, result = vsldoi t, t, 1 9393 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9394 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9395 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9396 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9397 } 9398 // t = vsplti c, result = vsldoi t, t, 2 9399 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9400 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9401 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9402 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9403 } 9404 // t = vsplti c, result = vsldoi t, t, 3 9405 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9406 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9407 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9408 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9409 } 9410 } 9411 9412 return SDValue(); 9413 } 9414 9415 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9416 /// the specified operations to build the shuffle. 9417 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9418 SDValue RHS, SelectionDAG &DAG, 9419 const SDLoc &dl) { 9420 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9421 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9422 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9423 9424 enum { 9425 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9426 OP_VMRGHW, 9427 OP_VMRGLW, 9428 OP_VSPLTISW0, 9429 OP_VSPLTISW1, 9430 OP_VSPLTISW2, 9431 OP_VSPLTISW3, 9432 OP_VSLDOI4, 9433 OP_VSLDOI8, 9434 OP_VSLDOI12 9435 }; 9436 9437 if (OpNum == OP_COPY) { 9438 if (LHSID == (1*9+2)*9+3) return LHS; 9439 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9440 return RHS; 9441 } 9442 9443 SDValue OpLHS, OpRHS; 9444 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9445 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9446 9447 int ShufIdxs[16]; 9448 switch (OpNum) { 9449 default: llvm_unreachable("Unknown i32 permute!"); 9450 case OP_VMRGHW: 9451 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9452 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9453 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9454 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9455 break; 9456 case OP_VMRGLW: 9457 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9458 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9459 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9460 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9461 break; 9462 case OP_VSPLTISW0: 9463 for (unsigned i = 0; i != 16; ++i) 9464 ShufIdxs[i] = (i&3)+0; 9465 break; 9466 case OP_VSPLTISW1: 9467 for (unsigned i = 0; i != 16; ++i) 9468 ShufIdxs[i] = (i&3)+4; 9469 break; 9470 case OP_VSPLTISW2: 9471 for (unsigned i = 0; i != 16; ++i) 9472 ShufIdxs[i] = (i&3)+8; 9473 break; 9474 case OP_VSPLTISW3: 9475 for (unsigned i = 0; i != 16; ++i) 9476 ShufIdxs[i] = (i&3)+12; 9477 break; 9478 case OP_VSLDOI4: 9479 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9480 case OP_VSLDOI8: 9481 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9482 case OP_VSLDOI12: 9483 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9484 } 9485 EVT VT = OpLHS.getValueType(); 9486 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9487 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9488 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9489 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9490 } 9491 9492 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9493 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9494 /// SDValue. 9495 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9496 SelectionDAG &DAG) const { 9497 const unsigned BytesInVector = 16; 9498 bool IsLE = Subtarget.isLittleEndian(); 9499 SDLoc dl(N); 9500 SDValue V1 = N->getOperand(0); 9501 SDValue V2 = N->getOperand(1); 9502 unsigned ShiftElts = 0, InsertAtByte = 0; 9503 bool Swap = false; 9504 9505 // Shifts required to get the byte we want at element 7. 9506 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9507 0, 15, 14, 13, 12, 11, 10, 9}; 9508 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9509 1, 2, 3, 4, 5, 6, 7, 8}; 9510 9511 ArrayRef<int> Mask = N->getMask(); 9512 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9513 9514 // For each mask element, find out if we're just inserting something 9515 // from V2 into V1 or vice versa. 9516 // Possible permutations inserting an element from V2 into V1: 9517 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9518 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9519 // ... 9520 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9521 // Inserting from V1 into V2 will be similar, except mask range will be 9522 // [16,31]. 9523 9524 bool FoundCandidate = false; 9525 // If both vector operands for the shuffle are the same vector, the mask 9526 // will contain only elements from the first one and the second one will be 9527 // undef. 9528 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9529 // Go through the mask of half-words to find an element that's being moved 9530 // from one vector to the other. 9531 for (unsigned i = 0; i < BytesInVector; ++i) { 9532 unsigned CurrentElement = Mask[i]; 9533 // If 2nd operand is undefined, we should only look for element 7 in the 9534 // Mask. 9535 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9536 continue; 9537 9538 bool OtherElementsInOrder = true; 9539 // Examine the other elements in the Mask to see if they're in original 9540 // order. 9541 for (unsigned j = 0; j < BytesInVector; ++j) { 9542 if (j == i) 9543 continue; 9544 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9545 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9546 // in which we always assume we're always picking from the 1st operand. 9547 int MaskOffset = 9548 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9549 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9550 OtherElementsInOrder = false; 9551 break; 9552 } 9553 } 9554 // If other elements are in original order, we record the number of shifts 9555 // we need to get the element we want into element 7. Also record which byte 9556 // in the vector we should insert into. 9557 if (OtherElementsInOrder) { 9558 // If 2nd operand is undefined, we assume no shifts and no swapping. 9559 if (V2.isUndef()) { 9560 ShiftElts = 0; 9561 Swap = false; 9562 } else { 9563 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9564 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9565 : BigEndianShifts[CurrentElement & 0xF]; 9566 Swap = CurrentElement < BytesInVector; 9567 } 9568 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9569 FoundCandidate = true; 9570 break; 9571 } 9572 } 9573 9574 if (!FoundCandidate) 9575 return SDValue(); 9576 9577 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9578 // optionally with VECSHL if shift is required. 9579 if (Swap) 9580 std::swap(V1, V2); 9581 if (V2.isUndef()) 9582 V2 = V1; 9583 if (ShiftElts) { 9584 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9585 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9586 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9587 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9588 } 9589 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9590 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9591 } 9592 9593 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9594 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9595 /// SDValue. 9596 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9597 SelectionDAG &DAG) const { 9598 const unsigned NumHalfWords = 8; 9599 const unsigned BytesInVector = NumHalfWords * 2; 9600 // Check that the shuffle is on half-words. 9601 if (!isNByteElemShuffleMask(N, 2, 1)) 9602 return SDValue(); 9603 9604 bool IsLE = Subtarget.isLittleEndian(); 9605 SDLoc dl(N); 9606 SDValue V1 = N->getOperand(0); 9607 SDValue V2 = N->getOperand(1); 9608 unsigned ShiftElts = 0, InsertAtByte = 0; 9609 bool Swap = false; 9610 9611 // Shifts required to get the half-word we want at element 3. 9612 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9613 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9614 9615 uint32_t Mask = 0; 9616 uint32_t OriginalOrderLow = 0x1234567; 9617 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9618 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9619 // 32-bit space, only need 4-bit nibbles per element. 9620 for (unsigned i = 0; i < NumHalfWords; ++i) { 9621 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9622 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9623 } 9624 9625 // For each mask element, find out if we're just inserting something 9626 // from V2 into V1 or vice versa. Possible permutations inserting an element 9627 // from V2 into V1: 9628 // X, 1, 2, 3, 4, 5, 6, 7 9629 // 0, X, 2, 3, 4, 5, 6, 7 9630 // 0, 1, X, 3, 4, 5, 6, 7 9631 // 0, 1, 2, X, 4, 5, 6, 7 9632 // 0, 1, 2, 3, X, 5, 6, 7 9633 // 0, 1, 2, 3, 4, X, 6, 7 9634 // 0, 1, 2, 3, 4, 5, X, 7 9635 // 0, 1, 2, 3, 4, 5, 6, X 9636 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9637 9638 bool FoundCandidate = false; 9639 // Go through the mask of half-words to find an element that's being moved 9640 // from one vector to the other. 9641 for (unsigned i = 0; i < NumHalfWords; ++i) { 9642 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9643 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9644 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9645 uint32_t TargetOrder = 0x0; 9646 9647 // If both vector operands for the shuffle are the same vector, the mask 9648 // will contain only elements from the first one and the second one will be 9649 // undef. 9650 if (V2.isUndef()) { 9651 ShiftElts = 0; 9652 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9653 TargetOrder = OriginalOrderLow; 9654 Swap = false; 9655 // Skip if not the correct element or mask of other elements don't equal 9656 // to our expected order. 9657 if (MaskOneElt == VINSERTHSrcElem && 9658 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9659 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9660 FoundCandidate = true; 9661 break; 9662 } 9663 } else { // If both operands are defined. 9664 // Target order is [8,15] if the current mask is between [0,7]. 9665 TargetOrder = 9666 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9667 // Skip if mask of other elements don't equal our expected order. 9668 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9669 // We only need the last 3 bits for the number of shifts. 9670 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9671 : BigEndianShifts[MaskOneElt & 0x7]; 9672 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9673 Swap = MaskOneElt < NumHalfWords; 9674 FoundCandidate = true; 9675 break; 9676 } 9677 } 9678 } 9679 9680 if (!FoundCandidate) 9681 return SDValue(); 9682 9683 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9684 // optionally with VECSHL if shift is required. 9685 if (Swap) 9686 std::swap(V1, V2); 9687 if (V2.isUndef()) 9688 V2 = V1; 9689 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9690 if (ShiftElts) { 9691 // Double ShiftElts because we're left shifting on v16i8 type. 9692 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9693 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9694 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9695 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9696 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9697 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9698 } 9699 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9700 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9701 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9702 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9703 } 9704 9705 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9706 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9707 /// return the default SDValue. 9708 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9709 SelectionDAG &DAG) const { 9710 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9711 // to v16i8. Peek through the bitcasts to get the actual operands. 9712 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9713 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9714 9715 auto ShuffleMask = SVN->getMask(); 9716 SDValue VecShuffle(SVN, 0); 9717 SDLoc DL(SVN); 9718 9719 // Check that we have a four byte shuffle. 9720 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9721 return SDValue(); 9722 9723 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9724 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9725 std::swap(LHS, RHS); 9726 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9727 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9728 } 9729 9730 // Ensure that the RHS is a vector of constants. 9731 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9732 if (!BVN) 9733 return SDValue(); 9734 9735 // Check if RHS is a splat of 4-bytes (or smaller). 9736 APInt APSplatValue, APSplatUndef; 9737 unsigned SplatBitSize; 9738 bool HasAnyUndefs; 9739 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9740 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9741 SplatBitSize > 32) 9742 return SDValue(); 9743 9744 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9745 // The instruction splats a constant C into two words of the source vector 9746 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9747 // Thus we check that the shuffle mask is the equivalent of 9748 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9749 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9750 // within each word are consecutive, so we only need to check the first byte. 9751 SDValue Index; 9752 bool IsLE = Subtarget.isLittleEndian(); 9753 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9754 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9755 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9756 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9757 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9758 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9759 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9760 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9761 else 9762 return SDValue(); 9763 9764 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9765 // for XXSPLTI32DX. 9766 unsigned SplatVal = APSplatValue.getZExtValue(); 9767 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9768 SplatVal |= (SplatVal << SplatBitSize); 9769 9770 SDValue SplatNode = DAG.getNode( 9771 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9772 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9773 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9774 } 9775 9776 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9777 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9778 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9779 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9780 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9781 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9782 assert(Op.getValueType() == MVT::v1i128 && 9783 "Only set v1i128 as custom, other type shouldn't reach here!"); 9784 SDLoc dl(Op); 9785 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9786 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9787 unsigned SHLAmt = N1.getConstantOperandVal(0); 9788 if (SHLAmt % 8 == 0) { 9789 SmallVector<int, 16> Mask(16, 0); 9790 std::iota(Mask.begin(), Mask.end(), 0); 9791 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9792 if (SDValue Shuffle = 9793 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9794 DAG.getUNDEF(MVT::v16i8), Mask)) 9795 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9796 } 9797 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9798 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9799 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9800 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9801 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9802 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9803 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9804 } 9805 9806 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9807 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9808 /// return the code it can be lowered into. Worst case, it can always be 9809 /// lowered into a vperm. 9810 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9811 SelectionDAG &DAG) const { 9812 SDLoc dl(Op); 9813 SDValue V1 = Op.getOperand(0); 9814 SDValue V2 = Op.getOperand(1); 9815 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9816 9817 // Any nodes that were combined in the target-independent combiner prior 9818 // to vector legalization will not be sent to the target combine. Try to 9819 // combine it here. 9820 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9821 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9822 return NewShuffle; 9823 Op = NewShuffle; 9824 SVOp = cast<ShuffleVectorSDNode>(Op); 9825 V1 = Op.getOperand(0); 9826 V2 = Op.getOperand(1); 9827 } 9828 EVT VT = Op.getValueType(); 9829 bool isLittleEndian = Subtarget.isLittleEndian(); 9830 9831 unsigned ShiftElts, InsertAtByte; 9832 bool Swap = false; 9833 9834 // If this is a load-and-splat, we can do that with a single instruction 9835 // in some cases. However if the load has multiple uses, we don't want to 9836 // combine it because that will just produce multiple loads. 9837 bool IsPermutedLoad = false; 9838 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9839 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9840 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9841 InputLoad->hasOneUse()) { 9842 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9843 int SplatIdx = 9844 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9845 9846 // The splat index for permuted loads will be in the left half of the vector 9847 // which is strictly wider than the loaded value by 8 bytes. So we need to 9848 // adjust the splat index to point to the correct address in memory. 9849 if (IsPermutedLoad) { 9850 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9851 SplatIdx += IsFourByte ? 2 : 1; 9852 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9853 "Splat of a value outside of the loaded memory"); 9854 } 9855 9856 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9857 // For 4-byte load-and-splat, we need Power9. 9858 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9859 uint64_t Offset = 0; 9860 if (IsFourByte) 9861 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9862 else 9863 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9864 9865 SDValue BasePtr = LD->getBasePtr(); 9866 if (Offset != 0) 9867 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9868 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9869 SDValue Ops[] = { 9870 LD->getChain(), // Chain 9871 BasePtr, // BasePtr 9872 DAG.getValueType(Op.getValueType()) // VT 9873 }; 9874 SDVTList VTL = 9875 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9876 SDValue LdSplt = 9877 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9878 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9879 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9880 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9881 return LdSplt; 9882 } 9883 } 9884 if (Subtarget.hasP9Vector() && 9885 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9886 isLittleEndian)) { 9887 if (Swap) 9888 std::swap(V1, V2); 9889 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9890 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9891 if (ShiftElts) { 9892 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9893 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9894 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9895 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9896 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9897 } 9898 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9899 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9900 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9901 } 9902 9903 if (Subtarget.hasPrefixInstrs()) { 9904 SDValue SplatInsertNode; 9905 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9906 return SplatInsertNode; 9907 } 9908 9909 if (Subtarget.hasP9Altivec()) { 9910 SDValue NewISDNode; 9911 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9912 return NewISDNode; 9913 9914 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9915 return NewISDNode; 9916 } 9917 9918 if (Subtarget.hasVSX() && 9919 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9920 if (Swap) 9921 std::swap(V1, V2); 9922 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9923 SDValue Conv2 = 9924 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9925 9926 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9927 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9928 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9929 } 9930 9931 if (Subtarget.hasVSX() && 9932 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9933 if (Swap) 9934 std::swap(V1, V2); 9935 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9936 SDValue Conv2 = 9937 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9938 9939 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9940 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9941 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9942 } 9943 9944 if (Subtarget.hasP9Vector()) { 9945 if (PPC::isXXBRHShuffleMask(SVOp)) { 9946 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9947 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9948 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9949 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9950 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9951 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9952 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9953 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9954 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9955 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9956 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9957 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9958 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9959 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9960 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9961 } 9962 } 9963 9964 if (Subtarget.hasVSX()) { 9965 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9966 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9967 9968 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9969 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9970 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9971 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9972 } 9973 9974 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9975 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9976 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9977 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9978 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9979 } 9980 } 9981 9982 // Cases that are handled by instructions that take permute immediates 9983 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9984 // selected by the instruction selector. 9985 if (V2.isUndef()) { 9986 if (PPC::isSplatShuffleMask(SVOp, 1) || 9987 PPC::isSplatShuffleMask(SVOp, 2) || 9988 PPC::isSplatShuffleMask(SVOp, 4) || 9989 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9990 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9991 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9992 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9993 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9994 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9995 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9996 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9997 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9998 (Subtarget.hasP8Altivec() && ( 9999 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 10000 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 10001 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 10002 return Op; 10003 } 10004 } 10005 10006 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10007 // and produce a fixed permutation. If any of these match, do not lower to 10008 // VPERM. 10009 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10010 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10011 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10012 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10013 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10014 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10015 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10016 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10017 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10018 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10019 (Subtarget.hasP8Altivec() && ( 10020 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10021 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10022 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10023 return Op; 10024 10025 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10026 // perfect shuffle table to emit an optimal matching sequence. 10027 ArrayRef<int> PermMask = SVOp->getMask(); 10028 10029 unsigned PFIndexes[4]; 10030 bool isFourElementShuffle = true; 10031 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 10032 unsigned EltNo = 8; // Start out undef. 10033 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10034 if (PermMask[i*4+j] < 0) 10035 continue; // Undef, ignore it. 10036 10037 unsigned ByteSource = PermMask[i*4+j]; 10038 if ((ByteSource & 3) != j) { 10039 isFourElementShuffle = false; 10040 break; 10041 } 10042 10043 if (EltNo == 8) { 10044 EltNo = ByteSource/4; 10045 } else if (EltNo != ByteSource/4) { 10046 isFourElementShuffle = false; 10047 break; 10048 } 10049 } 10050 PFIndexes[i] = EltNo; 10051 } 10052 10053 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10054 // perfect shuffle vector to determine if it is cost effective to do this as 10055 // discrete instructions, or whether we should use a vperm. 10056 // For now, we skip this for little endian until such time as we have a 10057 // little-endian perfect shuffle table. 10058 if (isFourElementShuffle && !isLittleEndian) { 10059 // Compute the index in the perfect shuffle table. 10060 unsigned PFTableIndex = 10061 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10062 10063 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10064 unsigned Cost = (PFEntry >> 30); 10065 10066 // Determining when to avoid vperm is tricky. Many things affect the cost 10067 // of vperm, particularly how many times the perm mask needs to be computed. 10068 // For example, if the perm mask can be hoisted out of a loop or is already 10069 // used (perhaps because there are multiple permutes with the same shuffle 10070 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10071 // the loop requires an extra register. 10072 // 10073 // As a compromise, we only emit discrete instructions if the shuffle can be 10074 // generated in 3 or fewer operations. When we have loop information 10075 // available, if this block is within a loop, we should avoid using vperm 10076 // for 3-operation perms and use a constant pool load instead. 10077 if (Cost < 3) 10078 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10079 } 10080 10081 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10082 // vector that will get spilled to the constant pool. 10083 if (V2.isUndef()) V2 = V1; 10084 10085 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10086 // that it is in input element units, not in bytes. Convert now. 10087 10088 // For little endian, the order of the input vectors is reversed, and 10089 // the permutation mask is complemented with respect to 31. This is 10090 // necessary to produce proper semantics with the big-endian-biased vperm 10091 // instruction. 10092 EVT EltVT = V1.getValueType().getVectorElementType(); 10093 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10094 10095 SmallVector<SDValue, 16> ResultMask; 10096 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10097 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10098 10099 for (unsigned j = 0; j != BytesPerElement; ++j) 10100 if (isLittleEndian) 10101 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10102 dl, MVT::i32)); 10103 else 10104 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10105 MVT::i32)); 10106 } 10107 10108 ShufflesHandledWithVPERM++; 10109 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10110 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10111 LLVM_DEBUG(SVOp->dump()); 10112 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10113 LLVM_DEBUG(VPermMask.dump()); 10114 10115 if (isLittleEndian) 10116 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10117 V2, V1, VPermMask); 10118 else 10119 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10120 V1, V2, VPermMask); 10121 } 10122 10123 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10124 /// vector comparison. If it is, return true and fill in Opc/isDot with 10125 /// information about the intrinsic. 10126 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10127 bool &isDot, const PPCSubtarget &Subtarget) { 10128 unsigned IntrinsicID = 10129 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10130 CompareOpc = -1; 10131 isDot = false; 10132 switch (IntrinsicID) { 10133 default: 10134 return false; 10135 // Comparison predicates. 10136 case Intrinsic::ppc_altivec_vcmpbfp_p: 10137 CompareOpc = 966; 10138 isDot = true; 10139 break; 10140 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10141 CompareOpc = 198; 10142 isDot = true; 10143 break; 10144 case Intrinsic::ppc_altivec_vcmpequb_p: 10145 CompareOpc = 6; 10146 isDot = true; 10147 break; 10148 case Intrinsic::ppc_altivec_vcmpequh_p: 10149 CompareOpc = 70; 10150 isDot = true; 10151 break; 10152 case Intrinsic::ppc_altivec_vcmpequw_p: 10153 CompareOpc = 134; 10154 isDot = true; 10155 break; 10156 case Intrinsic::ppc_altivec_vcmpequd_p: 10157 if (Subtarget.hasP8Altivec()) { 10158 CompareOpc = 199; 10159 isDot = true; 10160 } else 10161 return false; 10162 break; 10163 case Intrinsic::ppc_altivec_vcmpneb_p: 10164 case Intrinsic::ppc_altivec_vcmpneh_p: 10165 case Intrinsic::ppc_altivec_vcmpnew_p: 10166 case Intrinsic::ppc_altivec_vcmpnezb_p: 10167 case Intrinsic::ppc_altivec_vcmpnezh_p: 10168 case Intrinsic::ppc_altivec_vcmpnezw_p: 10169 if (Subtarget.hasP9Altivec()) { 10170 switch (IntrinsicID) { 10171 default: 10172 llvm_unreachable("Unknown comparison intrinsic."); 10173 case Intrinsic::ppc_altivec_vcmpneb_p: 10174 CompareOpc = 7; 10175 break; 10176 case Intrinsic::ppc_altivec_vcmpneh_p: 10177 CompareOpc = 71; 10178 break; 10179 case Intrinsic::ppc_altivec_vcmpnew_p: 10180 CompareOpc = 135; 10181 break; 10182 case Intrinsic::ppc_altivec_vcmpnezb_p: 10183 CompareOpc = 263; 10184 break; 10185 case Intrinsic::ppc_altivec_vcmpnezh_p: 10186 CompareOpc = 327; 10187 break; 10188 case Intrinsic::ppc_altivec_vcmpnezw_p: 10189 CompareOpc = 391; 10190 break; 10191 } 10192 isDot = true; 10193 } else 10194 return false; 10195 break; 10196 case Intrinsic::ppc_altivec_vcmpgefp_p: 10197 CompareOpc = 454; 10198 isDot = true; 10199 break; 10200 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10201 CompareOpc = 710; 10202 isDot = true; 10203 break; 10204 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10205 CompareOpc = 774; 10206 isDot = true; 10207 break; 10208 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10209 CompareOpc = 838; 10210 isDot = true; 10211 break; 10212 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10213 CompareOpc = 902; 10214 isDot = true; 10215 break; 10216 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10217 if (Subtarget.hasP8Altivec()) { 10218 CompareOpc = 967; 10219 isDot = true; 10220 } else 10221 return false; 10222 break; 10223 case Intrinsic::ppc_altivec_vcmpgtub_p: 10224 CompareOpc = 518; 10225 isDot = true; 10226 break; 10227 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10228 CompareOpc = 582; 10229 isDot = true; 10230 break; 10231 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10232 CompareOpc = 646; 10233 isDot = true; 10234 break; 10235 case Intrinsic::ppc_altivec_vcmpgtud_p: 10236 if (Subtarget.hasP8Altivec()) { 10237 CompareOpc = 711; 10238 isDot = true; 10239 } else 10240 return false; 10241 break; 10242 10243 case Intrinsic::ppc_altivec_vcmpequq: 10244 case Intrinsic::ppc_altivec_vcmpgtsq: 10245 case Intrinsic::ppc_altivec_vcmpgtuq: 10246 if (!Subtarget.isISA3_1()) 10247 return false; 10248 switch (IntrinsicID) { 10249 default: 10250 llvm_unreachable("Unknown comparison intrinsic."); 10251 case Intrinsic::ppc_altivec_vcmpequq: 10252 CompareOpc = 455; 10253 break; 10254 case Intrinsic::ppc_altivec_vcmpgtsq: 10255 CompareOpc = 903; 10256 break; 10257 case Intrinsic::ppc_altivec_vcmpgtuq: 10258 CompareOpc = 647; 10259 break; 10260 } 10261 break; 10262 10263 // VSX predicate comparisons use the same infrastructure 10264 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10265 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10266 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10267 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10268 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10269 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10270 if (Subtarget.hasVSX()) { 10271 switch (IntrinsicID) { 10272 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10273 CompareOpc = 99; 10274 break; 10275 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10276 CompareOpc = 115; 10277 break; 10278 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10279 CompareOpc = 107; 10280 break; 10281 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10282 CompareOpc = 67; 10283 break; 10284 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10285 CompareOpc = 83; 10286 break; 10287 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10288 CompareOpc = 75; 10289 break; 10290 } 10291 isDot = true; 10292 } else 10293 return false; 10294 break; 10295 10296 // Normal Comparisons. 10297 case Intrinsic::ppc_altivec_vcmpbfp: 10298 CompareOpc = 966; 10299 break; 10300 case Intrinsic::ppc_altivec_vcmpeqfp: 10301 CompareOpc = 198; 10302 break; 10303 case Intrinsic::ppc_altivec_vcmpequb: 10304 CompareOpc = 6; 10305 break; 10306 case Intrinsic::ppc_altivec_vcmpequh: 10307 CompareOpc = 70; 10308 break; 10309 case Intrinsic::ppc_altivec_vcmpequw: 10310 CompareOpc = 134; 10311 break; 10312 case Intrinsic::ppc_altivec_vcmpequd: 10313 if (Subtarget.hasP8Altivec()) 10314 CompareOpc = 199; 10315 else 10316 return false; 10317 break; 10318 case Intrinsic::ppc_altivec_vcmpneb: 10319 case Intrinsic::ppc_altivec_vcmpneh: 10320 case Intrinsic::ppc_altivec_vcmpnew: 10321 case Intrinsic::ppc_altivec_vcmpnezb: 10322 case Intrinsic::ppc_altivec_vcmpnezh: 10323 case Intrinsic::ppc_altivec_vcmpnezw: 10324 if (Subtarget.hasP9Altivec()) 10325 switch (IntrinsicID) { 10326 default: 10327 llvm_unreachable("Unknown comparison intrinsic."); 10328 case Intrinsic::ppc_altivec_vcmpneb: 10329 CompareOpc = 7; 10330 break; 10331 case Intrinsic::ppc_altivec_vcmpneh: 10332 CompareOpc = 71; 10333 break; 10334 case Intrinsic::ppc_altivec_vcmpnew: 10335 CompareOpc = 135; 10336 break; 10337 case Intrinsic::ppc_altivec_vcmpnezb: 10338 CompareOpc = 263; 10339 break; 10340 case Intrinsic::ppc_altivec_vcmpnezh: 10341 CompareOpc = 327; 10342 break; 10343 case Intrinsic::ppc_altivec_vcmpnezw: 10344 CompareOpc = 391; 10345 break; 10346 } 10347 else 10348 return false; 10349 break; 10350 case Intrinsic::ppc_altivec_vcmpgefp: 10351 CompareOpc = 454; 10352 break; 10353 case Intrinsic::ppc_altivec_vcmpgtfp: 10354 CompareOpc = 710; 10355 break; 10356 case Intrinsic::ppc_altivec_vcmpgtsb: 10357 CompareOpc = 774; 10358 break; 10359 case Intrinsic::ppc_altivec_vcmpgtsh: 10360 CompareOpc = 838; 10361 break; 10362 case Intrinsic::ppc_altivec_vcmpgtsw: 10363 CompareOpc = 902; 10364 break; 10365 case Intrinsic::ppc_altivec_vcmpgtsd: 10366 if (Subtarget.hasP8Altivec()) 10367 CompareOpc = 967; 10368 else 10369 return false; 10370 break; 10371 case Intrinsic::ppc_altivec_vcmpgtub: 10372 CompareOpc = 518; 10373 break; 10374 case Intrinsic::ppc_altivec_vcmpgtuh: 10375 CompareOpc = 582; 10376 break; 10377 case Intrinsic::ppc_altivec_vcmpgtuw: 10378 CompareOpc = 646; 10379 break; 10380 case Intrinsic::ppc_altivec_vcmpgtud: 10381 if (Subtarget.hasP8Altivec()) 10382 CompareOpc = 711; 10383 else 10384 return false; 10385 break; 10386 case Intrinsic::ppc_altivec_vcmpequq_p: 10387 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10388 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10389 if (!Subtarget.isISA3_1()) 10390 return false; 10391 switch (IntrinsicID) { 10392 default: 10393 llvm_unreachable("Unknown comparison intrinsic."); 10394 case Intrinsic::ppc_altivec_vcmpequq_p: 10395 CompareOpc = 455; 10396 break; 10397 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10398 CompareOpc = 903; 10399 break; 10400 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10401 CompareOpc = 647; 10402 break; 10403 } 10404 isDot = true; 10405 break; 10406 } 10407 return true; 10408 } 10409 10410 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10411 /// lower, do it, otherwise return null. 10412 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10413 SelectionDAG &DAG) const { 10414 unsigned IntrinsicID = 10415 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10416 10417 SDLoc dl(Op); 10418 10419 if (IntrinsicID == Intrinsic::thread_pointer) { 10420 // Reads the thread pointer register, used for __builtin_thread_pointer. 10421 if (Subtarget.isPPC64()) 10422 return DAG.getRegister(PPC::X13, MVT::i64); 10423 return DAG.getRegister(PPC::R2, MVT::i32); 10424 } 10425 10426 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10427 // opcode number of the comparison. 10428 int CompareOpc; 10429 bool isDot; 10430 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10431 return SDValue(); // Don't custom lower most intrinsics. 10432 10433 // If this is a non-dot comparison, make the VCMP node and we are done. 10434 if (!isDot) { 10435 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10436 Op.getOperand(1), Op.getOperand(2), 10437 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10438 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10439 } 10440 10441 // Create the PPCISD altivec 'dot' comparison node. 10442 SDValue Ops[] = { 10443 Op.getOperand(2), // LHS 10444 Op.getOperand(3), // RHS 10445 DAG.getConstant(CompareOpc, dl, MVT::i32) 10446 }; 10447 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10448 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10449 10450 // Now that we have the comparison, emit a copy from the CR to a GPR. 10451 // This is flagged to the above dot comparison. 10452 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10453 DAG.getRegister(PPC::CR6, MVT::i32), 10454 CompNode.getValue(1)); 10455 10456 // Unpack the result based on how the target uses it. 10457 unsigned BitNo; // Bit # of CR6. 10458 bool InvertBit; // Invert result? 10459 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10460 default: // Can't happen, don't crash on invalid number though. 10461 case 0: // Return the value of the EQ bit of CR6. 10462 BitNo = 0; InvertBit = false; 10463 break; 10464 case 1: // Return the inverted value of the EQ bit of CR6. 10465 BitNo = 0; InvertBit = true; 10466 break; 10467 case 2: // Return the value of the LT bit of CR6. 10468 BitNo = 2; InvertBit = false; 10469 break; 10470 case 3: // Return the inverted value of the LT bit of CR6. 10471 BitNo = 2; InvertBit = true; 10472 break; 10473 } 10474 10475 // Shift the bit into the low position. 10476 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10477 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10478 // Isolate the bit. 10479 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10480 DAG.getConstant(1, dl, MVT::i32)); 10481 10482 // If we are supposed to, toggle the bit. 10483 if (InvertBit) 10484 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10485 DAG.getConstant(1, dl, MVT::i32)); 10486 return Flags; 10487 } 10488 10489 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10490 SelectionDAG &DAG) const { 10491 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10492 // the beginning of the argument list. 10493 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10494 SDLoc DL(Op); 10495 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10496 case Intrinsic::ppc_cfence: { 10497 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10498 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10499 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10500 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10501 Op.getOperand(ArgStart + 1)), 10502 Op.getOperand(0)), 10503 0); 10504 } 10505 default: 10506 break; 10507 } 10508 return SDValue(); 10509 } 10510 10511 // Lower scalar BSWAP64 to xxbrd. 10512 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10513 SDLoc dl(Op); 10514 // MTVSRDD 10515 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10516 Op.getOperand(0)); 10517 // XXBRD 10518 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10519 // MFVSRD 10520 int VectorIndex = 0; 10521 if (Subtarget.isLittleEndian()) 10522 VectorIndex = 1; 10523 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10524 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10525 return Op; 10526 } 10527 10528 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10529 // compared to a value that is atomically loaded (atomic loads zero-extend). 10530 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10531 SelectionDAG &DAG) const { 10532 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10533 "Expecting an atomic compare-and-swap here."); 10534 SDLoc dl(Op); 10535 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10536 EVT MemVT = AtomicNode->getMemoryVT(); 10537 if (MemVT.getSizeInBits() >= 32) 10538 return Op; 10539 10540 SDValue CmpOp = Op.getOperand(2); 10541 // If this is already correctly zero-extended, leave it alone. 10542 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10543 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10544 return Op; 10545 10546 // Clear the high bits of the compare operand. 10547 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10548 SDValue NewCmpOp = 10549 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10550 DAG.getConstant(MaskVal, dl, MVT::i32)); 10551 10552 // Replace the existing compare operand with the properly zero-extended one. 10553 SmallVector<SDValue, 4> Ops; 10554 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10555 Ops.push_back(AtomicNode->getOperand(i)); 10556 Ops[2] = NewCmpOp; 10557 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10558 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10559 auto NodeTy = 10560 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10561 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10562 } 10563 10564 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10565 SelectionDAG &DAG) const { 10566 SDLoc dl(Op); 10567 // Create a stack slot that is 16-byte aligned. 10568 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10569 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10570 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10571 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10572 10573 // Store the input value into Value#0 of the stack slot. 10574 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10575 MachinePointerInfo()); 10576 // Load it out. 10577 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10578 } 10579 10580 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10581 SelectionDAG &DAG) const { 10582 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10583 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10584 10585 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10586 // We have legal lowering for constant indices but not for variable ones. 10587 if (!C) 10588 return SDValue(); 10589 10590 EVT VT = Op.getValueType(); 10591 SDLoc dl(Op); 10592 SDValue V1 = Op.getOperand(0); 10593 SDValue V2 = Op.getOperand(1); 10594 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10595 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10596 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10597 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10598 unsigned InsertAtElement = C->getZExtValue(); 10599 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10600 if (Subtarget.isLittleEndian()) { 10601 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10602 } 10603 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10604 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10605 } 10606 return Op; 10607 } 10608 10609 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10610 SelectionDAG &DAG) const { 10611 SDLoc dl(Op); 10612 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10613 SDValue LoadChain = LN->getChain(); 10614 SDValue BasePtr = LN->getBasePtr(); 10615 EVT VT = Op.getValueType(); 10616 10617 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10618 return Op; 10619 10620 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10621 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10622 // 2 or 4 vsx registers. 10623 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10624 "Type unsupported without MMA"); 10625 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10626 "Type unsupported without paired vector support"); 10627 Align Alignment = LN->getAlign(); 10628 SmallVector<SDValue, 4> Loads; 10629 SmallVector<SDValue, 4> LoadChains; 10630 unsigned NumVecs = VT.getSizeInBits() / 128; 10631 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10632 SDValue Load = 10633 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10634 LN->getPointerInfo().getWithOffset(Idx * 16), 10635 commonAlignment(Alignment, Idx * 16), 10636 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10637 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10638 DAG.getConstant(16, dl, BasePtr.getValueType())); 10639 Loads.push_back(Load); 10640 LoadChains.push_back(Load.getValue(1)); 10641 } 10642 if (Subtarget.isLittleEndian()) { 10643 std::reverse(Loads.begin(), Loads.end()); 10644 std::reverse(LoadChains.begin(), LoadChains.end()); 10645 } 10646 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10647 SDValue Value = 10648 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10649 dl, VT, Loads); 10650 SDValue RetOps[] = {Value, TF}; 10651 return DAG.getMergeValues(RetOps, dl); 10652 } 10653 10654 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10655 SelectionDAG &DAG) const { 10656 SDLoc dl(Op); 10657 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10658 SDValue StoreChain = SN->getChain(); 10659 SDValue BasePtr = SN->getBasePtr(); 10660 SDValue Value = SN->getValue(); 10661 EVT StoreVT = Value.getValueType(); 10662 10663 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10664 return Op; 10665 10666 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10667 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10668 // underlying registers individually. 10669 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10670 "Type unsupported without MMA"); 10671 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10672 "Type unsupported without paired vector support"); 10673 Align Alignment = SN->getAlign(); 10674 SmallVector<SDValue, 4> Stores; 10675 unsigned NumVecs = 2; 10676 if (StoreVT == MVT::v512i1) { 10677 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10678 NumVecs = 4; 10679 } 10680 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10681 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10682 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10683 DAG.getConstant(VecNum, dl, MVT::i64)); 10684 SDValue Store = 10685 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10686 SN->getPointerInfo().getWithOffset(Idx * 16), 10687 commonAlignment(Alignment, Idx * 16), 10688 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10689 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10690 DAG.getConstant(16, dl, BasePtr.getValueType())); 10691 Stores.push_back(Store); 10692 } 10693 SDValue TF = DAG.getTokenFactor(dl, Stores); 10694 return TF; 10695 } 10696 10697 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10698 SDLoc dl(Op); 10699 if (Op.getValueType() == MVT::v4i32) { 10700 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10701 10702 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10703 // +16 as shift amt. 10704 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10705 SDValue RHSSwap = // = vrlw RHS, 16 10706 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10707 10708 // Shrinkify inputs to v8i16. 10709 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10710 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10711 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10712 10713 // Low parts multiplied together, generating 32-bit results (we ignore the 10714 // top parts). 10715 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10716 LHS, RHS, DAG, dl, MVT::v4i32); 10717 10718 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10719 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10720 // Shift the high parts up 16 bits. 10721 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10722 Neg16, DAG, dl); 10723 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10724 } else if (Op.getValueType() == MVT::v16i8) { 10725 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10726 bool isLittleEndian = Subtarget.isLittleEndian(); 10727 10728 // Multiply the even 8-bit parts, producing 16-bit sums. 10729 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10730 LHS, RHS, DAG, dl, MVT::v8i16); 10731 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10732 10733 // Multiply the odd 8-bit parts, producing 16-bit sums. 10734 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10735 LHS, RHS, DAG, dl, MVT::v8i16); 10736 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10737 10738 // Merge the results together. Because vmuleub and vmuloub are 10739 // instructions with a big-endian bias, we must reverse the 10740 // element numbering and reverse the meaning of "odd" and "even" 10741 // when generating little endian code. 10742 int Ops[16]; 10743 for (unsigned i = 0; i != 8; ++i) { 10744 if (isLittleEndian) { 10745 Ops[i*2 ] = 2*i; 10746 Ops[i*2+1] = 2*i+16; 10747 } else { 10748 Ops[i*2 ] = 2*i+1; 10749 Ops[i*2+1] = 2*i+1+16; 10750 } 10751 } 10752 if (isLittleEndian) 10753 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10754 else 10755 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10756 } else { 10757 llvm_unreachable("Unknown mul to lower!"); 10758 } 10759 } 10760 10761 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10762 10763 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10764 10765 EVT VT = Op.getValueType(); 10766 assert(VT.isVector() && 10767 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10768 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10769 VT == MVT::v16i8) && 10770 "Unexpected vector element type!"); 10771 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10772 "Current subtarget doesn't support smax v2i64!"); 10773 10774 // For vector abs, it can be lowered to: 10775 // abs x 10776 // ==> 10777 // y = -x 10778 // smax(x, y) 10779 10780 SDLoc dl(Op); 10781 SDValue X = Op.getOperand(0); 10782 SDValue Zero = DAG.getConstant(0, dl, VT); 10783 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10784 10785 // SMAX patch https://reviews.llvm.org/D47332 10786 // hasn't landed yet, so use intrinsic first here. 10787 // TODO: Should use SMAX directly once SMAX patch landed 10788 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10789 if (VT == MVT::v2i64) 10790 BifID = Intrinsic::ppc_altivec_vmaxsd; 10791 else if (VT == MVT::v8i16) 10792 BifID = Intrinsic::ppc_altivec_vmaxsh; 10793 else if (VT == MVT::v16i8) 10794 BifID = Intrinsic::ppc_altivec_vmaxsb; 10795 10796 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10797 } 10798 10799 // Custom lowering for fpext vf32 to v2f64 10800 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10801 10802 assert(Op.getOpcode() == ISD::FP_EXTEND && 10803 "Should only be called for ISD::FP_EXTEND"); 10804 10805 // FIXME: handle extends from half precision float vectors on P9. 10806 // We only want to custom lower an extend from v2f32 to v2f64. 10807 if (Op.getValueType() != MVT::v2f64 || 10808 Op.getOperand(0).getValueType() != MVT::v2f32) 10809 return SDValue(); 10810 10811 SDLoc dl(Op); 10812 SDValue Op0 = Op.getOperand(0); 10813 10814 switch (Op0.getOpcode()) { 10815 default: 10816 return SDValue(); 10817 case ISD::EXTRACT_SUBVECTOR: { 10818 assert(Op0.getNumOperands() == 2 && 10819 isa<ConstantSDNode>(Op0->getOperand(1)) && 10820 "Node should have 2 operands with second one being a constant!"); 10821 10822 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10823 return SDValue(); 10824 10825 // Custom lower is only done for high or low doubleword. 10826 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10827 if (Idx % 2 != 0) 10828 return SDValue(); 10829 10830 // Since input is v4f32, at this point Idx is either 0 or 2. 10831 // Shift to get the doubleword position we want. 10832 int DWord = Idx >> 1; 10833 10834 // High and low word positions are different on little endian. 10835 if (Subtarget.isLittleEndian()) 10836 DWord ^= 0x1; 10837 10838 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10839 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10840 } 10841 case ISD::FADD: 10842 case ISD::FMUL: 10843 case ISD::FSUB: { 10844 SDValue NewLoad[2]; 10845 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10846 // Ensure both input are loads. 10847 SDValue LdOp = Op0.getOperand(i); 10848 if (LdOp.getOpcode() != ISD::LOAD) 10849 return SDValue(); 10850 // Generate new load node. 10851 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10852 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10853 NewLoad[i] = DAG.getMemIntrinsicNode( 10854 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10855 LD->getMemoryVT(), LD->getMemOperand()); 10856 } 10857 SDValue NewOp = 10858 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10859 NewLoad[1], Op0.getNode()->getFlags()); 10860 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10861 DAG.getConstant(0, dl, MVT::i32)); 10862 } 10863 case ISD::LOAD: { 10864 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10865 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10866 SDValue NewLd = DAG.getMemIntrinsicNode( 10867 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10868 LD->getMemoryVT(), LD->getMemOperand()); 10869 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10870 DAG.getConstant(0, dl, MVT::i32)); 10871 } 10872 } 10873 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10874 } 10875 10876 /// LowerOperation - Provide custom lowering hooks for some operations. 10877 /// 10878 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10879 switch (Op.getOpcode()) { 10880 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10881 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10882 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10883 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10884 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10885 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10886 case ISD::SETCC: return LowerSETCC(Op, DAG); 10887 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10888 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10889 10890 // Variable argument lowering. 10891 case ISD::VASTART: return LowerVASTART(Op, DAG); 10892 case ISD::VAARG: return LowerVAARG(Op, DAG); 10893 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10894 10895 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10896 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10897 case ISD::GET_DYNAMIC_AREA_OFFSET: 10898 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10899 10900 // Exception handling lowering. 10901 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10902 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10903 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10904 10905 case ISD::LOAD: return LowerLOAD(Op, DAG); 10906 case ISD::STORE: return LowerSTORE(Op, DAG); 10907 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10908 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10909 case ISD::STRICT_FP_TO_UINT: 10910 case ISD::STRICT_FP_TO_SINT: 10911 case ISD::FP_TO_UINT: 10912 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10913 case ISD::STRICT_UINT_TO_FP: 10914 case ISD::STRICT_SINT_TO_FP: 10915 case ISD::UINT_TO_FP: 10916 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10917 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10918 10919 // Lower 64-bit shifts. 10920 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10921 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10922 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10923 10924 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10925 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10926 10927 // Vector-related lowering. 10928 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10929 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10930 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10931 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10932 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10933 case ISD::MUL: return LowerMUL(Op, DAG); 10934 case ISD::ABS: return LowerABS(Op, DAG); 10935 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10936 case ISD::ROTL: return LowerROTL(Op, DAG); 10937 10938 // For counter-based loop handling. 10939 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10940 10941 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10942 10943 // Frame & Return address. 10944 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10945 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10946 10947 case ISD::INTRINSIC_VOID: 10948 return LowerINTRINSIC_VOID(Op, DAG); 10949 case ISD::BSWAP: 10950 return LowerBSWAP(Op, DAG); 10951 case ISD::ATOMIC_CMP_SWAP: 10952 return LowerATOMIC_CMP_SWAP(Op, DAG); 10953 } 10954 } 10955 10956 void PPCTargetLowering::LowerOperationWrapper(SDNode *N, 10957 SmallVectorImpl<SDValue> &Results, 10958 SelectionDAG &DAG) const { 10959 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10960 10961 if (!Res.getNode()) 10962 return; 10963 10964 // Take the return value as-is if original node has only one result. 10965 if (N->getNumValues() == 1) { 10966 Results.push_back(Res); 10967 return; 10968 } 10969 10970 // New node should have the same number of results. 10971 assert((N->getNumValues() == Res->getNumValues()) && 10972 "Lowering returned the wrong number of results!"); 10973 10974 for (unsigned i = 0; i < N->getNumValues(); ++i) 10975 Results.push_back(Res.getValue(i)); 10976 } 10977 10978 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10979 SmallVectorImpl<SDValue>&Results, 10980 SelectionDAG &DAG) const { 10981 SDLoc dl(N); 10982 switch (N->getOpcode()) { 10983 default: 10984 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10985 case ISD::READCYCLECOUNTER: { 10986 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10987 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10988 10989 Results.push_back( 10990 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10991 Results.push_back(RTB.getValue(2)); 10992 break; 10993 } 10994 case ISD::INTRINSIC_W_CHAIN: { 10995 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10996 Intrinsic::loop_decrement) 10997 break; 10998 10999 assert(N->getValueType(0) == MVT::i1 && 11000 "Unexpected result type for CTR decrement intrinsic"); 11001 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11002 N->getValueType(0)); 11003 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11004 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11005 N->getOperand(1)); 11006 11007 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11008 Results.push_back(NewInt.getValue(1)); 11009 break; 11010 } 11011 case ISD::VAARG: { 11012 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11013 return; 11014 11015 EVT VT = N->getValueType(0); 11016 11017 if (VT == MVT::i64) { 11018 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11019 11020 Results.push_back(NewNode); 11021 Results.push_back(NewNode.getValue(1)); 11022 } 11023 return; 11024 } 11025 case ISD::STRICT_FP_TO_SINT: 11026 case ISD::STRICT_FP_TO_UINT: 11027 case ISD::FP_TO_SINT: 11028 case ISD::FP_TO_UINT: 11029 // LowerFP_TO_INT() can only handle f32 and f64. 11030 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11031 MVT::ppcf128) 11032 return; 11033 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 11034 return; 11035 case ISD::TRUNCATE: { 11036 if (!N->getValueType(0).isVector()) 11037 return; 11038 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11039 if (Lowered) 11040 Results.push_back(Lowered); 11041 return; 11042 } 11043 case ISD::BITCAST: 11044 // Don't handle bitcast here. 11045 return; 11046 case ISD::FP_EXTEND: 11047 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11048 if (Lowered) 11049 Results.push_back(Lowered); 11050 return; 11051 } 11052 } 11053 11054 //===----------------------------------------------------------------------===// 11055 // Other Lowering Code 11056 //===----------------------------------------------------------------------===// 11057 11058 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 11059 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11060 Function *Func = Intrinsic::getDeclaration(M, Id); 11061 return Builder.CreateCall(Func, {}); 11062 } 11063 11064 // The mappings for emitLeading/TrailingFence is taken from 11065 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11066 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11067 Instruction *Inst, 11068 AtomicOrdering Ord) const { 11069 if (Ord == AtomicOrdering::SequentiallyConsistent) 11070 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11071 if (isReleaseOrStronger(Ord)) 11072 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11073 return nullptr; 11074 } 11075 11076 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11077 Instruction *Inst, 11078 AtomicOrdering Ord) const { 11079 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11080 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11081 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11082 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11083 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11084 return Builder.CreateCall( 11085 Intrinsic::getDeclaration( 11086 Builder.GetInsertBlock()->getParent()->getParent(), 11087 Intrinsic::ppc_cfence, {Inst->getType()}), 11088 {Inst}); 11089 // FIXME: Can use isync for rmw operation. 11090 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11091 } 11092 return nullptr; 11093 } 11094 11095 MachineBasicBlock * 11096 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11097 unsigned AtomicSize, 11098 unsigned BinOpcode, 11099 unsigned CmpOpcode, 11100 unsigned CmpPred) const { 11101 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11102 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11103 11104 auto LoadMnemonic = PPC::LDARX; 11105 auto StoreMnemonic = PPC::STDCX; 11106 switch (AtomicSize) { 11107 default: 11108 llvm_unreachable("Unexpected size of atomic entity"); 11109 case 1: 11110 LoadMnemonic = PPC::LBARX; 11111 StoreMnemonic = PPC::STBCX; 11112 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11113 break; 11114 case 2: 11115 LoadMnemonic = PPC::LHARX; 11116 StoreMnemonic = PPC::STHCX; 11117 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11118 break; 11119 case 4: 11120 LoadMnemonic = PPC::LWARX; 11121 StoreMnemonic = PPC::STWCX; 11122 break; 11123 case 8: 11124 LoadMnemonic = PPC::LDARX; 11125 StoreMnemonic = PPC::STDCX; 11126 break; 11127 } 11128 11129 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11130 MachineFunction *F = BB->getParent(); 11131 MachineFunction::iterator It = ++BB->getIterator(); 11132 11133 Register dest = MI.getOperand(0).getReg(); 11134 Register ptrA = MI.getOperand(1).getReg(); 11135 Register ptrB = MI.getOperand(2).getReg(); 11136 Register incr = MI.getOperand(3).getReg(); 11137 DebugLoc dl = MI.getDebugLoc(); 11138 11139 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11140 MachineBasicBlock *loop2MBB = 11141 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11142 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11143 F->insert(It, loopMBB); 11144 if (CmpOpcode) 11145 F->insert(It, loop2MBB); 11146 F->insert(It, exitMBB); 11147 exitMBB->splice(exitMBB->begin(), BB, 11148 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11149 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11150 11151 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11152 Register TmpReg = (!BinOpcode) ? incr : 11153 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11154 : &PPC::GPRCRegClass); 11155 11156 // thisMBB: 11157 // ... 11158 // fallthrough --> loopMBB 11159 BB->addSuccessor(loopMBB); 11160 11161 // loopMBB: 11162 // l[wd]arx dest, ptr 11163 // add r0, dest, incr 11164 // st[wd]cx. r0, ptr 11165 // bne- loopMBB 11166 // fallthrough --> exitMBB 11167 11168 // For max/min... 11169 // loopMBB: 11170 // l[wd]arx dest, ptr 11171 // cmpl?[wd] incr, dest 11172 // bgt exitMBB 11173 // loop2MBB: 11174 // st[wd]cx. dest, ptr 11175 // bne- loopMBB 11176 // fallthrough --> exitMBB 11177 11178 BB = loopMBB; 11179 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11180 .addReg(ptrA).addReg(ptrB); 11181 if (BinOpcode) 11182 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11183 if (CmpOpcode) { 11184 // Signed comparisons of byte or halfword values must be sign-extended. 11185 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11186 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11187 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11188 ExtReg).addReg(dest); 11189 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11190 .addReg(incr).addReg(ExtReg); 11191 } else 11192 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11193 .addReg(incr).addReg(dest); 11194 11195 BuildMI(BB, dl, TII->get(PPC::BCC)) 11196 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11197 BB->addSuccessor(loop2MBB); 11198 BB->addSuccessor(exitMBB); 11199 BB = loop2MBB; 11200 } 11201 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11202 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11203 BuildMI(BB, dl, TII->get(PPC::BCC)) 11204 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11205 BB->addSuccessor(loopMBB); 11206 BB->addSuccessor(exitMBB); 11207 11208 // exitMBB: 11209 // ... 11210 BB = exitMBB; 11211 return BB; 11212 } 11213 11214 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11215 MachineInstr &MI, MachineBasicBlock *BB, 11216 bool is8bit, // operation 11217 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11218 // If we support part-word atomic mnemonics, just use them 11219 if (Subtarget.hasPartwordAtomics()) 11220 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11221 CmpPred); 11222 11223 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11224 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11225 // In 64 bit mode we have to use 64 bits for addresses, even though the 11226 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11227 // registers without caring whether they're 32 or 64, but here we're 11228 // doing actual arithmetic on the addresses. 11229 bool is64bit = Subtarget.isPPC64(); 11230 bool isLittleEndian = Subtarget.isLittleEndian(); 11231 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11232 11233 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11234 MachineFunction *F = BB->getParent(); 11235 MachineFunction::iterator It = ++BB->getIterator(); 11236 11237 Register dest = MI.getOperand(0).getReg(); 11238 Register ptrA = MI.getOperand(1).getReg(); 11239 Register ptrB = MI.getOperand(2).getReg(); 11240 Register incr = MI.getOperand(3).getReg(); 11241 DebugLoc dl = MI.getDebugLoc(); 11242 11243 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11244 MachineBasicBlock *loop2MBB = 11245 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11246 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11247 F->insert(It, loopMBB); 11248 if (CmpOpcode) 11249 F->insert(It, loop2MBB); 11250 F->insert(It, exitMBB); 11251 exitMBB->splice(exitMBB->begin(), BB, 11252 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11253 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11254 11255 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11256 const TargetRegisterClass *RC = 11257 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11258 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11259 11260 Register PtrReg = RegInfo.createVirtualRegister(RC); 11261 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11262 Register ShiftReg = 11263 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11264 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11265 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11266 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11267 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11268 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11269 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11270 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11271 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11272 Register Ptr1Reg; 11273 Register TmpReg = 11274 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11275 11276 // thisMBB: 11277 // ... 11278 // fallthrough --> loopMBB 11279 BB->addSuccessor(loopMBB); 11280 11281 // The 4-byte load must be aligned, while a char or short may be 11282 // anywhere in the word. Hence all this nasty bookkeeping code. 11283 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11284 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11285 // xori shift, shift1, 24 [16] 11286 // rlwinm ptr, ptr1, 0, 0, 29 11287 // slw incr2, incr, shift 11288 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11289 // slw mask, mask2, shift 11290 // loopMBB: 11291 // lwarx tmpDest, ptr 11292 // add tmp, tmpDest, incr2 11293 // andc tmp2, tmpDest, mask 11294 // and tmp3, tmp, mask 11295 // or tmp4, tmp3, tmp2 11296 // stwcx. tmp4, ptr 11297 // bne- loopMBB 11298 // fallthrough --> exitMBB 11299 // srw dest, tmpDest, shift 11300 if (ptrA != ZeroReg) { 11301 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11302 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11303 .addReg(ptrA) 11304 .addReg(ptrB); 11305 } else { 11306 Ptr1Reg = ptrB; 11307 } 11308 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11309 // mode. 11310 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11311 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11312 .addImm(3) 11313 .addImm(27) 11314 .addImm(is8bit ? 28 : 27); 11315 if (!isLittleEndian) 11316 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11317 .addReg(Shift1Reg) 11318 .addImm(is8bit ? 24 : 16); 11319 if (is64bit) 11320 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11321 .addReg(Ptr1Reg) 11322 .addImm(0) 11323 .addImm(61); 11324 else 11325 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11326 .addReg(Ptr1Reg) 11327 .addImm(0) 11328 .addImm(0) 11329 .addImm(29); 11330 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11331 if (is8bit) 11332 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11333 else { 11334 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11335 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11336 .addReg(Mask3Reg) 11337 .addImm(65535); 11338 } 11339 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11340 .addReg(Mask2Reg) 11341 .addReg(ShiftReg); 11342 11343 BB = loopMBB; 11344 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11345 .addReg(ZeroReg) 11346 .addReg(PtrReg); 11347 if (BinOpcode) 11348 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11349 .addReg(Incr2Reg) 11350 .addReg(TmpDestReg); 11351 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11352 .addReg(TmpDestReg) 11353 .addReg(MaskReg); 11354 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11355 if (CmpOpcode) { 11356 // For unsigned comparisons, we can directly compare the shifted values. 11357 // For signed comparisons we shift and sign extend. 11358 Register SReg = RegInfo.createVirtualRegister(GPRC); 11359 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11360 .addReg(TmpDestReg) 11361 .addReg(MaskReg); 11362 unsigned ValueReg = SReg; 11363 unsigned CmpReg = Incr2Reg; 11364 if (CmpOpcode == PPC::CMPW) { 11365 ValueReg = RegInfo.createVirtualRegister(GPRC); 11366 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11367 .addReg(SReg) 11368 .addReg(ShiftReg); 11369 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11370 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11371 .addReg(ValueReg); 11372 ValueReg = ValueSReg; 11373 CmpReg = incr; 11374 } 11375 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11376 .addReg(CmpReg) 11377 .addReg(ValueReg); 11378 BuildMI(BB, dl, TII->get(PPC::BCC)) 11379 .addImm(CmpPred) 11380 .addReg(PPC::CR0) 11381 .addMBB(exitMBB); 11382 BB->addSuccessor(loop2MBB); 11383 BB->addSuccessor(exitMBB); 11384 BB = loop2MBB; 11385 } 11386 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11387 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11388 .addReg(Tmp4Reg) 11389 .addReg(ZeroReg) 11390 .addReg(PtrReg); 11391 BuildMI(BB, dl, TII->get(PPC::BCC)) 11392 .addImm(PPC::PRED_NE) 11393 .addReg(PPC::CR0) 11394 .addMBB(loopMBB); 11395 BB->addSuccessor(loopMBB); 11396 BB->addSuccessor(exitMBB); 11397 11398 // exitMBB: 11399 // ... 11400 BB = exitMBB; 11401 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11402 .addReg(TmpDestReg) 11403 .addReg(ShiftReg); 11404 return BB; 11405 } 11406 11407 llvm::MachineBasicBlock * 11408 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11409 MachineBasicBlock *MBB) const { 11410 DebugLoc DL = MI.getDebugLoc(); 11411 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11412 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11413 11414 MachineFunction *MF = MBB->getParent(); 11415 MachineRegisterInfo &MRI = MF->getRegInfo(); 11416 11417 const BasicBlock *BB = MBB->getBasicBlock(); 11418 MachineFunction::iterator I = ++MBB->getIterator(); 11419 11420 Register DstReg = MI.getOperand(0).getReg(); 11421 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11422 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11423 Register mainDstReg = MRI.createVirtualRegister(RC); 11424 Register restoreDstReg = MRI.createVirtualRegister(RC); 11425 11426 MVT PVT = getPointerTy(MF->getDataLayout()); 11427 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11428 "Invalid Pointer Size!"); 11429 // For v = setjmp(buf), we generate 11430 // 11431 // thisMBB: 11432 // SjLjSetup mainMBB 11433 // bl mainMBB 11434 // v_restore = 1 11435 // b sinkMBB 11436 // 11437 // mainMBB: 11438 // buf[LabelOffset] = LR 11439 // v_main = 0 11440 // 11441 // sinkMBB: 11442 // v = phi(main, restore) 11443 // 11444 11445 MachineBasicBlock *thisMBB = MBB; 11446 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11447 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11448 MF->insert(I, mainMBB); 11449 MF->insert(I, sinkMBB); 11450 11451 MachineInstrBuilder MIB; 11452 11453 // Transfer the remainder of BB and its successor edges to sinkMBB. 11454 sinkMBB->splice(sinkMBB->begin(), MBB, 11455 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11456 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11457 11458 // Note that the structure of the jmp_buf used here is not compatible 11459 // with that used by libc, and is not designed to be. Specifically, it 11460 // stores only those 'reserved' registers that LLVM does not otherwise 11461 // understand how to spill. Also, by convention, by the time this 11462 // intrinsic is called, Clang has already stored the frame address in the 11463 // first slot of the buffer and stack address in the third. Following the 11464 // X86 target code, we'll store the jump address in the second slot. We also 11465 // need to save the TOC pointer (R2) to handle jumps between shared 11466 // libraries, and that will be stored in the fourth slot. The thread 11467 // identifier (R13) is not affected. 11468 11469 // thisMBB: 11470 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11471 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11472 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11473 11474 // Prepare IP either in reg. 11475 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11476 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11477 Register BufReg = MI.getOperand(1).getReg(); 11478 11479 if (Subtarget.is64BitELFABI()) { 11480 setUsesTOCBasePtr(*MBB->getParent()); 11481 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11482 .addReg(PPC::X2) 11483 .addImm(TOCOffset) 11484 .addReg(BufReg) 11485 .cloneMemRefs(MI); 11486 } 11487 11488 // Naked functions never have a base pointer, and so we use r1. For all 11489 // other functions, this decision must be delayed until during PEI. 11490 unsigned BaseReg; 11491 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11492 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11493 else 11494 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11495 11496 MIB = BuildMI(*thisMBB, MI, DL, 11497 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11498 .addReg(BaseReg) 11499 .addImm(BPOffset) 11500 .addReg(BufReg) 11501 .cloneMemRefs(MI); 11502 11503 // Setup 11504 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11505 MIB.addRegMask(TRI->getNoPreservedMask()); 11506 11507 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11508 11509 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11510 .addMBB(mainMBB); 11511 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11512 11513 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11514 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11515 11516 // mainMBB: 11517 // mainDstReg = 0 11518 MIB = 11519 BuildMI(mainMBB, DL, 11520 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11521 11522 // Store IP 11523 if (Subtarget.isPPC64()) { 11524 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11525 .addReg(LabelReg) 11526 .addImm(LabelOffset) 11527 .addReg(BufReg); 11528 } else { 11529 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11530 .addReg(LabelReg) 11531 .addImm(LabelOffset) 11532 .addReg(BufReg); 11533 } 11534 MIB.cloneMemRefs(MI); 11535 11536 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11537 mainMBB->addSuccessor(sinkMBB); 11538 11539 // sinkMBB: 11540 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11541 TII->get(PPC::PHI), DstReg) 11542 .addReg(mainDstReg).addMBB(mainMBB) 11543 .addReg(restoreDstReg).addMBB(thisMBB); 11544 11545 MI.eraseFromParent(); 11546 return sinkMBB; 11547 } 11548 11549 MachineBasicBlock * 11550 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11551 MachineBasicBlock *MBB) const { 11552 DebugLoc DL = MI.getDebugLoc(); 11553 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11554 11555 MachineFunction *MF = MBB->getParent(); 11556 MachineRegisterInfo &MRI = MF->getRegInfo(); 11557 11558 MVT PVT = getPointerTy(MF->getDataLayout()); 11559 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11560 "Invalid Pointer Size!"); 11561 11562 const TargetRegisterClass *RC = 11563 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11564 Register Tmp = MRI.createVirtualRegister(RC); 11565 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11566 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11567 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11568 unsigned BP = 11569 (PVT == MVT::i64) 11570 ? PPC::X30 11571 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11572 : PPC::R30); 11573 11574 MachineInstrBuilder MIB; 11575 11576 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11577 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11578 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11579 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11580 11581 Register BufReg = MI.getOperand(0).getReg(); 11582 11583 // Reload FP (the jumped-to function may not have had a 11584 // frame pointer, and if so, then its r31 will be restored 11585 // as necessary). 11586 if (PVT == MVT::i64) { 11587 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11588 .addImm(0) 11589 .addReg(BufReg); 11590 } else { 11591 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11592 .addImm(0) 11593 .addReg(BufReg); 11594 } 11595 MIB.cloneMemRefs(MI); 11596 11597 // Reload IP 11598 if (PVT == MVT::i64) { 11599 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11600 .addImm(LabelOffset) 11601 .addReg(BufReg); 11602 } else { 11603 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11604 .addImm(LabelOffset) 11605 .addReg(BufReg); 11606 } 11607 MIB.cloneMemRefs(MI); 11608 11609 // Reload SP 11610 if (PVT == MVT::i64) { 11611 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11612 .addImm(SPOffset) 11613 .addReg(BufReg); 11614 } else { 11615 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11616 .addImm(SPOffset) 11617 .addReg(BufReg); 11618 } 11619 MIB.cloneMemRefs(MI); 11620 11621 // Reload BP 11622 if (PVT == MVT::i64) { 11623 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11624 .addImm(BPOffset) 11625 .addReg(BufReg); 11626 } else { 11627 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11628 .addImm(BPOffset) 11629 .addReg(BufReg); 11630 } 11631 MIB.cloneMemRefs(MI); 11632 11633 // Reload TOC 11634 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11635 setUsesTOCBasePtr(*MBB->getParent()); 11636 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11637 .addImm(TOCOffset) 11638 .addReg(BufReg) 11639 .cloneMemRefs(MI); 11640 } 11641 11642 // Jump 11643 BuildMI(*MBB, MI, DL, 11644 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11645 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11646 11647 MI.eraseFromParent(); 11648 return MBB; 11649 } 11650 11651 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11652 // If the function specifically requests inline stack probes, emit them. 11653 if (MF.getFunction().hasFnAttribute("probe-stack")) 11654 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11655 "inline-asm"; 11656 return false; 11657 } 11658 11659 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11660 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11661 unsigned StackAlign = TFI->getStackAlignment(); 11662 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11663 "Unexpected stack alignment"); 11664 // The default stack probe size is 4096 if the function has no 11665 // stack-probe-size attribute. 11666 unsigned StackProbeSize = 4096; 11667 const Function &Fn = MF.getFunction(); 11668 if (Fn.hasFnAttribute("stack-probe-size")) 11669 Fn.getFnAttribute("stack-probe-size") 11670 .getValueAsString() 11671 .getAsInteger(0, StackProbeSize); 11672 // Round down to the stack alignment. 11673 StackProbeSize &= ~(StackAlign - 1); 11674 return StackProbeSize ? StackProbeSize : StackAlign; 11675 } 11676 11677 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11678 // into three phases. In the first phase, it uses pseudo instruction 11679 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11680 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11681 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11682 // MaxCallFrameSize so that it can calculate correct data area pointer. 11683 MachineBasicBlock * 11684 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11685 MachineBasicBlock *MBB) const { 11686 const bool isPPC64 = Subtarget.isPPC64(); 11687 MachineFunction *MF = MBB->getParent(); 11688 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11689 DebugLoc DL = MI.getDebugLoc(); 11690 const unsigned ProbeSize = getStackProbeSize(*MF); 11691 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11692 MachineRegisterInfo &MRI = MF->getRegInfo(); 11693 // The CFG of probing stack looks as 11694 // +-----+ 11695 // | MBB | 11696 // +--+--+ 11697 // | 11698 // +----v----+ 11699 // +--->+ TestMBB +---+ 11700 // | +----+----+ | 11701 // | | | 11702 // | +-----v----+ | 11703 // +---+ BlockMBB | | 11704 // +----------+ | 11705 // | 11706 // +---------+ | 11707 // | TailMBB +<--+ 11708 // +---------+ 11709 // In MBB, calculate previous frame pointer and final stack pointer. 11710 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11711 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11712 // TailMBB is spliced via \p MI. 11713 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11714 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11715 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11716 11717 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11718 MF->insert(MBBIter, TestMBB); 11719 MF->insert(MBBIter, BlockMBB); 11720 MF->insert(MBBIter, TailMBB); 11721 11722 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11723 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11724 11725 Register DstReg = MI.getOperand(0).getReg(); 11726 Register NegSizeReg = MI.getOperand(1).getReg(); 11727 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11728 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11729 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11730 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11731 11732 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11733 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11734 // NegSize. 11735 unsigned ProbeOpc; 11736 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11737 ProbeOpc = 11738 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11739 else 11740 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11741 // and NegSizeReg will be allocated in the same phyreg to avoid 11742 // redundant copy when NegSizeReg has only one use which is current MI and 11743 // will be replaced by PREPARE_PROBED_ALLOCA then. 11744 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11745 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11746 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11747 .addDef(ActualNegSizeReg) 11748 .addReg(NegSizeReg) 11749 .add(MI.getOperand(2)) 11750 .add(MI.getOperand(3)); 11751 11752 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11753 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11754 FinalStackPtr) 11755 .addReg(SPReg) 11756 .addReg(ActualNegSizeReg); 11757 11758 // Materialize a scratch register for update. 11759 int64_t NegProbeSize = -(int64_t)ProbeSize; 11760 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11761 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11762 if (!isInt<16>(NegProbeSize)) { 11763 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11764 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11765 .addImm(NegProbeSize >> 16); 11766 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11767 ScratchReg) 11768 .addReg(TempReg) 11769 .addImm(NegProbeSize & 0xFFFF); 11770 } else 11771 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11772 .addImm(NegProbeSize); 11773 11774 { 11775 // Probing leading residual part. 11776 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11777 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11778 .addReg(ActualNegSizeReg) 11779 .addReg(ScratchReg); 11780 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11781 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11782 .addReg(Div) 11783 .addReg(ScratchReg); 11784 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11785 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11786 .addReg(Mul) 11787 .addReg(ActualNegSizeReg); 11788 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11789 .addReg(FramePointer) 11790 .addReg(SPReg) 11791 .addReg(NegMod); 11792 } 11793 11794 { 11795 // Remaining part should be multiple of ProbeSize. 11796 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11797 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11798 .addReg(SPReg) 11799 .addReg(FinalStackPtr); 11800 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11801 .addImm(PPC::PRED_EQ) 11802 .addReg(CmpResult) 11803 .addMBB(TailMBB); 11804 TestMBB->addSuccessor(BlockMBB); 11805 TestMBB->addSuccessor(TailMBB); 11806 } 11807 11808 { 11809 // Touch the block. 11810 // |P...|P...|P... 11811 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11812 .addReg(FramePointer) 11813 .addReg(SPReg) 11814 .addReg(ScratchReg); 11815 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11816 BlockMBB->addSuccessor(TestMBB); 11817 } 11818 11819 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11820 // DYNAREAOFFSET pseudo instruction to get the future result. 11821 Register MaxCallFrameSizeReg = 11822 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11823 BuildMI(TailMBB, DL, 11824 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11825 MaxCallFrameSizeReg) 11826 .add(MI.getOperand(2)) 11827 .add(MI.getOperand(3)); 11828 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11829 .addReg(SPReg) 11830 .addReg(MaxCallFrameSizeReg); 11831 11832 // Splice instructions after MI to TailMBB. 11833 TailMBB->splice(TailMBB->end(), MBB, 11834 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11835 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11836 MBB->addSuccessor(TestMBB); 11837 11838 // Delete the pseudo instruction. 11839 MI.eraseFromParent(); 11840 11841 ++NumDynamicAllocaProbed; 11842 return TailMBB; 11843 } 11844 11845 MachineBasicBlock * 11846 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11847 MachineBasicBlock *BB) const { 11848 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11849 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11850 if (Subtarget.is64BitELFABI() && 11851 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11852 !Subtarget.isUsingPCRelativeCalls()) { 11853 // Call lowering should have added an r2 operand to indicate a dependence 11854 // on the TOC base pointer value. It can't however, because there is no 11855 // way to mark the dependence as implicit there, and so the stackmap code 11856 // will confuse it with a regular operand. Instead, add the dependence 11857 // here. 11858 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11859 } 11860 11861 return emitPatchPoint(MI, BB); 11862 } 11863 11864 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11865 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11866 return emitEHSjLjSetJmp(MI, BB); 11867 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11868 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11869 return emitEHSjLjLongJmp(MI, BB); 11870 } 11871 11872 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11873 11874 // To "insert" these instructions we actually have to insert their 11875 // control-flow patterns. 11876 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11877 MachineFunction::iterator It = ++BB->getIterator(); 11878 11879 MachineFunction *F = BB->getParent(); 11880 11881 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11882 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11883 MI.getOpcode() == PPC::SELECT_I8) { 11884 SmallVector<MachineOperand, 2> Cond; 11885 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11886 MI.getOpcode() == PPC::SELECT_CC_I8) 11887 Cond.push_back(MI.getOperand(4)); 11888 else 11889 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11890 Cond.push_back(MI.getOperand(1)); 11891 11892 DebugLoc dl = MI.getDebugLoc(); 11893 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11894 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11895 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11896 MI.getOpcode() == PPC::SELECT_CC_F8 || 11897 MI.getOpcode() == PPC::SELECT_CC_F16 || 11898 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11899 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11900 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11901 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11902 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11903 MI.getOpcode() == PPC::SELECT_CC_SPE || 11904 MI.getOpcode() == PPC::SELECT_F4 || 11905 MI.getOpcode() == PPC::SELECT_F8 || 11906 MI.getOpcode() == PPC::SELECT_F16 || 11907 MI.getOpcode() == PPC::SELECT_SPE || 11908 MI.getOpcode() == PPC::SELECT_SPE4 || 11909 MI.getOpcode() == PPC::SELECT_VRRC || 11910 MI.getOpcode() == PPC::SELECT_VSFRC || 11911 MI.getOpcode() == PPC::SELECT_VSSRC || 11912 MI.getOpcode() == PPC::SELECT_VSRC) { 11913 // The incoming instruction knows the destination vreg to set, the 11914 // condition code register to branch on, the true/false values to 11915 // select between, and a branch opcode to use. 11916 11917 // thisMBB: 11918 // ... 11919 // TrueVal = ... 11920 // cmpTY ccX, r1, r2 11921 // bCC copy1MBB 11922 // fallthrough --> copy0MBB 11923 MachineBasicBlock *thisMBB = BB; 11924 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11925 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11926 DebugLoc dl = MI.getDebugLoc(); 11927 F->insert(It, copy0MBB); 11928 F->insert(It, sinkMBB); 11929 11930 // Transfer the remainder of BB and its successor edges to sinkMBB. 11931 sinkMBB->splice(sinkMBB->begin(), BB, 11932 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11933 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11934 11935 // Next, add the true and fallthrough blocks as its successors. 11936 BB->addSuccessor(copy0MBB); 11937 BB->addSuccessor(sinkMBB); 11938 11939 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11940 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11941 MI.getOpcode() == PPC::SELECT_F16 || 11942 MI.getOpcode() == PPC::SELECT_SPE4 || 11943 MI.getOpcode() == PPC::SELECT_SPE || 11944 MI.getOpcode() == PPC::SELECT_VRRC || 11945 MI.getOpcode() == PPC::SELECT_VSFRC || 11946 MI.getOpcode() == PPC::SELECT_VSSRC || 11947 MI.getOpcode() == PPC::SELECT_VSRC) { 11948 BuildMI(BB, dl, TII->get(PPC::BC)) 11949 .addReg(MI.getOperand(1).getReg()) 11950 .addMBB(sinkMBB); 11951 } else { 11952 unsigned SelectPred = MI.getOperand(4).getImm(); 11953 BuildMI(BB, dl, TII->get(PPC::BCC)) 11954 .addImm(SelectPred) 11955 .addReg(MI.getOperand(1).getReg()) 11956 .addMBB(sinkMBB); 11957 } 11958 11959 // copy0MBB: 11960 // %FalseValue = ... 11961 // # fallthrough to sinkMBB 11962 BB = copy0MBB; 11963 11964 // Update machine-CFG edges 11965 BB->addSuccessor(sinkMBB); 11966 11967 // sinkMBB: 11968 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11969 // ... 11970 BB = sinkMBB; 11971 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11972 .addReg(MI.getOperand(3).getReg()) 11973 .addMBB(copy0MBB) 11974 .addReg(MI.getOperand(2).getReg()) 11975 .addMBB(thisMBB); 11976 } else if (MI.getOpcode() == PPC::ReadTB) { 11977 // To read the 64-bit time-base register on a 32-bit target, we read the 11978 // two halves. Should the counter have wrapped while it was being read, we 11979 // need to try again. 11980 // ... 11981 // readLoop: 11982 // mfspr Rx,TBU # load from TBU 11983 // mfspr Ry,TB # load from TB 11984 // mfspr Rz,TBU # load from TBU 11985 // cmpw crX,Rx,Rz # check if 'old'='new' 11986 // bne readLoop # branch if they're not equal 11987 // ... 11988 11989 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11990 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11991 DebugLoc dl = MI.getDebugLoc(); 11992 F->insert(It, readMBB); 11993 F->insert(It, sinkMBB); 11994 11995 // Transfer the remainder of BB and its successor edges to sinkMBB. 11996 sinkMBB->splice(sinkMBB->begin(), BB, 11997 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11998 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11999 12000 BB->addSuccessor(readMBB); 12001 BB = readMBB; 12002 12003 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12004 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12005 Register LoReg = MI.getOperand(0).getReg(); 12006 Register HiReg = MI.getOperand(1).getReg(); 12007 12008 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12009 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12010 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12011 12012 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12013 12014 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12015 .addReg(HiReg) 12016 .addReg(ReadAgainReg); 12017 BuildMI(BB, dl, TII->get(PPC::BCC)) 12018 .addImm(PPC::PRED_NE) 12019 .addReg(CmpReg) 12020 .addMBB(readMBB); 12021 12022 BB->addSuccessor(readMBB); 12023 BB->addSuccessor(sinkMBB); 12024 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12025 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12026 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12027 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12028 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12029 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12030 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12031 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12032 12033 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12034 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12035 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12036 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12037 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12038 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12039 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12040 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12041 12042 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12043 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12044 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12045 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12046 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12047 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12048 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12049 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12050 12051 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12052 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12053 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12054 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12055 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12056 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12057 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12058 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12059 12060 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12061 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12062 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12063 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12064 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12065 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12066 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12067 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12068 12069 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12070 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12071 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12072 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12073 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12074 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12075 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12076 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12077 12078 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12079 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12080 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12081 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12082 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12083 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12084 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12085 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12086 12087 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12088 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12089 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12090 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12091 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12092 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12093 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12094 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12095 12096 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12097 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12098 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12099 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12100 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12101 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12102 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12103 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12104 12105 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12106 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12107 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12108 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12109 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12110 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12111 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12112 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12113 12114 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12115 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12116 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12117 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12118 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12119 BB = EmitAtomicBinary(MI, BB, 4, 0); 12120 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12121 BB = EmitAtomicBinary(MI, BB, 8, 0); 12122 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12123 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12124 (Subtarget.hasPartwordAtomics() && 12125 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12126 (Subtarget.hasPartwordAtomics() && 12127 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12128 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12129 12130 auto LoadMnemonic = PPC::LDARX; 12131 auto StoreMnemonic = PPC::STDCX; 12132 switch (MI.getOpcode()) { 12133 default: 12134 llvm_unreachable("Compare and swap of unknown size"); 12135 case PPC::ATOMIC_CMP_SWAP_I8: 12136 LoadMnemonic = PPC::LBARX; 12137 StoreMnemonic = PPC::STBCX; 12138 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12139 break; 12140 case PPC::ATOMIC_CMP_SWAP_I16: 12141 LoadMnemonic = PPC::LHARX; 12142 StoreMnemonic = PPC::STHCX; 12143 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12144 break; 12145 case PPC::ATOMIC_CMP_SWAP_I32: 12146 LoadMnemonic = PPC::LWARX; 12147 StoreMnemonic = PPC::STWCX; 12148 break; 12149 case PPC::ATOMIC_CMP_SWAP_I64: 12150 LoadMnemonic = PPC::LDARX; 12151 StoreMnemonic = PPC::STDCX; 12152 break; 12153 } 12154 Register dest = MI.getOperand(0).getReg(); 12155 Register ptrA = MI.getOperand(1).getReg(); 12156 Register ptrB = MI.getOperand(2).getReg(); 12157 Register oldval = MI.getOperand(3).getReg(); 12158 Register newval = MI.getOperand(4).getReg(); 12159 DebugLoc dl = MI.getDebugLoc(); 12160 12161 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12162 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12163 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12164 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12165 F->insert(It, loop1MBB); 12166 F->insert(It, loop2MBB); 12167 F->insert(It, midMBB); 12168 F->insert(It, exitMBB); 12169 exitMBB->splice(exitMBB->begin(), BB, 12170 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12171 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12172 12173 // thisMBB: 12174 // ... 12175 // fallthrough --> loopMBB 12176 BB->addSuccessor(loop1MBB); 12177 12178 // loop1MBB: 12179 // l[bhwd]arx dest, ptr 12180 // cmp[wd] dest, oldval 12181 // bne- midMBB 12182 // loop2MBB: 12183 // st[bhwd]cx. newval, ptr 12184 // bne- loopMBB 12185 // b exitBB 12186 // midMBB: 12187 // st[bhwd]cx. dest, ptr 12188 // exitBB: 12189 BB = loop1MBB; 12190 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12191 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12192 .addReg(oldval) 12193 .addReg(dest); 12194 BuildMI(BB, dl, TII->get(PPC::BCC)) 12195 .addImm(PPC::PRED_NE) 12196 .addReg(PPC::CR0) 12197 .addMBB(midMBB); 12198 BB->addSuccessor(loop2MBB); 12199 BB->addSuccessor(midMBB); 12200 12201 BB = loop2MBB; 12202 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12203 .addReg(newval) 12204 .addReg(ptrA) 12205 .addReg(ptrB); 12206 BuildMI(BB, dl, TII->get(PPC::BCC)) 12207 .addImm(PPC::PRED_NE) 12208 .addReg(PPC::CR0) 12209 .addMBB(loop1MBB); 12210 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12211 BB->addSuccessor(loop1MBB); 12212 BB->addSuccessor(exitMBB); 12213 12214 BB = midMBB; 12215 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12216 .addReg(dest) 12217 .addReg(ptrA) 12218 .addReg(ptrB); 12219 BB->addSuccessor(exitMBB); 12220 12221 // exitMBB: 12222 // ... 12223 BB = exitMBB; 12224 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12225 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12226 // We must use 64-bit registers for addresses when targeting 64-bit, 12227 // since we're actually doing arithmetic on them. Other registers 12228 // can be 32-bit. 12229 bool is64bit = Subtarget.isPPC64(); 12230 bool isLittleEndian = Subtarget.isLittleEndian(); 12231 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12232 12233 Register dest = MI.getOperand(0).getReg(); 12234 Register ptrA = MI.getOperand(1).getReg(); 12235 Register ptrB = MI.getOperand(2).getReg(); 12236 Register oldval = MI.getOperand(3).getReg(); 12237 Register newval = MI.getOperand(4).getReg(); 12238 DebugLoc dl = MI.getDebugLoc(); 12239 12240 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12241 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12242 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12243 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12244 F->insert(It, loop1MBB); 12245 F->insert(It, loop2MBB); 12246 F->insert(It, midMBB); 12247 F->insert(It, exitMBB); 12248 exitMBB->splice(exitMBB->begin(), BB, 12249 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12250 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12251 12252 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12253 const TargetRegisterClass *RC = 12254 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12255 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12256 12257 Register PtrReg = RegInfo.createVirtualRegister(RC); 12258 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12259 Register ShiftReg = 12260 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12261 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12262 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12263 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12264 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12265 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12266 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12267 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12268 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12269 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12270 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12271 Register Ptr1Reg; 12272 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12273 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12274 // thisMBB: 12275 // ... 12276 // fallthrough --> loopMBB 12277 BB->addSuccessor(loop1MBB); 12278 12279 // The 4-byte load must be aligned, while a char or short may be 12280 // anywhere in the word. Hence all this nasty bookkeeping code. 12281 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12282 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12283 // xori shift, shift1, 24 [16] 12284 // rlwinm ptr, ptr1, 0, 0, 29 12285 // slw newval2, newval, shift 12286 // slw oldval2, oldval,shift 12287 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12288 // slw mask, mask2, shift 12289 // and newval3, newval2, mask 12290 // and oldval3, oldval2, mask 12291 // loop1MBB: 12292 // lwarx tmpDest, ptr 12293 // and tmp, tmpDest, mask 12294 // cmpw tmp, oldval3 12295 // bne- midMBB 12296 // loop2MBB: 12297 // andc tmp2, tmpDest, mask 12298 // or tmp4, tmp2, newval3 12299 // stwcx. tmp4, ptr 12300 // bne- loop1MBB 12301 // b exitBB 12302 // midMBB: 12303 // stwcx. tmpDest, ptr 12304 // exitBB: 12305 // srw dest, tmpDest, shift 12306 if (ptrA != ZeroReg) { 12307 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12308 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12309 .addReg(ptrA) 12310 .addReg(ptrB); 12311 } else { 12312 Ptr1Reg = ptrB; 12313 } 12314 12315 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12316 // mode. 12317 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12318 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12319 .addImm(3) 12320 .addImm(27) 12321 .addImm(is8bit ? 28 : 27); 12322 if (!isLittleEndian) 12323 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12324 .addReg(Shift1Reg) 12325 .addImm(is8bit ? 24 : 16); 12326 if (is64bit) 12327 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12328 .addReg(Ptr1Reg) 12329 .addImm(0) 12330 .addImm(61); 12331 else 12332 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12333 .addReg(Ptr1Reg) 12334 .addImm(0) 12335 .addImm(0) 12336 .addImm(29); 12337 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12338 .addReg(newval) 12339 .addReg(ShiftReg); 12340 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12341 .addReg(oldval) 12342 .addReg(ShiftReg); 12343 if (is8bit) 12344 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12345 else { 12346 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12347 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12348 .addReg(Mask3Reg) 12349 .addImm(65535); 12350 } 12351 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12352 .addReg(Mask2Reg) 12353 .addReg(ShiftReg); 12354 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12355 .addReg(NewVal2Reg) 12356 .addReg(MaskReg); 12357 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12358 .addReg(OldVal2Reg) 12359 .addReg(MaskReg); 12360 12361 BB = loop1MBB; 12362 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12363 .addReg(ZeroReg) 12364 .addReg(PtrReg); 12365 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12366 .addReg(TmpDestReg) 12367 .addReg(MaskReg); 12368 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12369 .addReg(TmpReg) 12370 .addReg(OldVal3Reg); 12371 BuildMI(BB, dl, TII->get(PPC::BCC)) 12372 .addImm(PPC::PRED_NE) 12373 .addReg(PPC::CR0) 12374 .addMBB(midMBB); 12375 BB->addSuccessor(loop2MBB); 12376 BB->addSuccessor(midMBB); 12377 12378 BB = loop2MBB; 12379 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12380 .addReg(TmpDestReg) 12381 .addReg(MaskReg); 12382 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12383 .addReg(Tmp2Reg) 12384 .addReg(NewVal3Reg); 12385 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12386 .addReg(Tmp4Reg) 12387 .addReg(ZeroReg) 12388 .addReg(PtrReg); 12389 BuildMI(BB, dl, TII->get(PPC::BCC)) 12390 .addImm(PPC::PRED_NE) 12391 .addReg(PPC::CR0) 12392 .addMBB(loop1MBB); 12393 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12394 BB->addSuccessor(loop1MBB); 12395 BB->addSuccessor(exitMBB); 12396 12397 BB = midMBB; 12398 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12399 .addReg(TmpDestReg) 12400 .addReg(ZeroReg) 12401 .addReg(PtrReg); 12402 BB->addSuccessor(exitMBB); 12403 12404 // exitMBB: 12405 // ... 12406 BB = exitMBB; 12407 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12408 .addReg(TmpReg) 12409 .addReg(ShiftReg); 12410 } else if (MI.getOpcode() == PPC::FADDrtz) { 12411 // This pseudo performs an FADD with rounding mode temporarily forced 12412 // to round-to-zero. We emit this via custom inserter since the FPSCR 12413 // is not modeled at the SelectionDAG level. 12414 Register Dest = MI.getOperand(0).getReg(); 12415 Register Src1 = MI.getOperand(1).getReg(); 12416 Register Src2 = MI.getOperand(2).getReg(); 12417 DebugLoc dl = MI.getDebugLoc(); 12418 12419 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12420 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12421 12422 // Save FPSCR value. 12423 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12424 12425 // Set rounding mode to round-to-zero. 12426 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12427 .addImm(31) 12428 .addReg(PPC::RM, RegState::ImplicitDefine); 12429 12430 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12431 .addImm(30) 12432 .addReg(PPC::RM, RegState::ImplicitDefine); 12433 12434 // Perform addition. 12435 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12436 .addReg(Src1) 12437 .addReg(Src2); 12438 if (MI.getFlag(MachineInstr::NoFPExcept)) 12439 MIB.setMIFlag(MachineInstr::NoFPExcept); 12440 12441 // Restore FPSCR value. 12442 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12443 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12444 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12445 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12446 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12447 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12448 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12449 ? PPC::ANDI8_rec 12450 : PPC::ANDI_rec; 12451 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12452 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12453 12454 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12455 Register Dest = RegInfo.createVirtualRegister( 12456 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12457 12458 DebugLoc Dl = MI.getDebugLoc(); 12459 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12460 .addReg(MI.getOperand(1).getReg()) 12461 .addImm(1); 12462 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12463 MI.getOperand(0).getReg()) 12464 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12465 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12466 DebugLoc Dl = MI.getDebugLoc(); 12467 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12468 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12469 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12470 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12471 MI.getOperand(0).getReg()) 12472 .addReg(CRReg); 12473 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12474 DebugLoc Dl = MI.getDebugLoc(); 12475 unsigned Imm = MI.getOperand(1).getImm(); 12476 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12477 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12478 MI.getOperand(0).getReg()) 12479 .addReg(PPC::CR0EQ); 12480 } else if (MI.getOpcode() == PPC::SETRNDi) { 12481 DebugLoc dl = MI.getDebugLoc(); 12482 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12483 12484 // Save FPSCR value. 12485 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12486 12487 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12488 // the following settings: 12489 // 00 Round to nearest 12490 // 01 Round to 0 12491 // 10 Round to +inf 12492 // 11 Round to -inf 12493 12494 // When the operand is immediate, using the two least significant bits of 12495 // the immediate to set the bits 62:63 of FPSCR. 12496 unsigned Mode = MI.getOperand(1).getImm(); 12497 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12498 .addImm(31) 12499 .addReg(PPC::RM, RegState::ImplicitDefine); 12500 12501 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12502 .addImm(30) 12503 .addReg(PPC::RM, RegState::ImplicitDefine); 12504 } else if (MI.getOpcode() == PPC::SETRND) { 12505 DebugLoc dl = MI.getDebugLoc(); 12506 12507 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12508 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12509 // If the target doesn't have DirectMove, we should use stack to do the 12510 // conversion, because the target doesn't have the instructions like mtvsrd 12511 // or mfvsrd to do this conversion directly. 12512 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12513 if (Subtarget.hasDirectMove()) { 12514 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12515 .addReg(SrcReg); 12516 } else { 12517 // Use stack to do the register copy. 12518 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12519 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12520 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12521 if (RC == &PPC::F8RCRegClass) { 12522 // Copy register from F8RCRegClass to G8RCRegclass. 12523 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12524 "Unsupported RegClass."); 12525 12526 StoreOp = PPC::STFD; 12527 LoadOp = PPC::LD; 12528 } else { 12529 // Copy register from G8RCRegClass to F8RCRegclass. 12530 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12531 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12532 "Unsupported RegClass."); 12533 } 12534 12535 MachineFrameInfo &MFI = F->getFrameInfo(); 12536 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12537 12538 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12539 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12540 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12541 MFI.getObjectAlign(FrameIdx)); 12542 12543 // Store the SrcReg into the stack. 12544 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12545 .addReg(SrcReg) 12546 .addImm(0) 12547 .addFrameIndex(FrameIdx) 12548 .addMemOperand(MMOStore); 12549 12550 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12551 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12552 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12553 MFI.getObjectAlign(FrameIdx)); 12554 12555 // Load from the stack where SrcReg is stored, and save to DestReg, 12556 // so we have done the RegClass conversion from RegClass::SrcReg to 12557 // RegClass::DestReg. 12558 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12559 .addImm(0) 12560 .addFrameIndex(FrameIdx) 12561 .addMemOperand(MMOLoad); 12562 } 12563 }; 12564 12565 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12566 12567 // Save FPSCR value. 12568 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12569 12570 // When the operand is gprc register, use two least significant bits of the 12571 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12572 // 12573 // copy OldFPSCRTmpReg, OldFPSCRReg 12574 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12575 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12576 // copy NewFPSCRReg, NewFPSCRTmpReg 12577 // mtfsf 255, NewFPSCRReg 12578 MachineOperand SrcOp = MI.getOperand(1); 12579 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12580 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12581 12582 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12583 12584 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12585 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12586 12587 // The first operand of INSERT_SUBREG should be a register which has 12588 // subregisters, we only care about its RegClass, so we should use an 12589 // IMPLICIT_DEF register. 12590 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12591 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12592 .addReg(ImDefReg) 12593 .add(SrcOp) 12594 .addImm(1); 12595 12596 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12597 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12598 .addReg(OldFPSCRTmpReg) 12599 .addReg(ExtSrcReg) 12600 .addImm(0) 12601 .addImm(62); 12602 12603 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12604 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12605 12606 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12607 // bits of FPSCR. 12608 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12609 .addImm(255) 12610 .addReg(NewFPSCRReg) 12611 .addImm(0) 12612 .addImm(0); 12613 } else if (MI.getOpcode() == PPC::SETFLM) { 12614 DebugLoc Dl = MI.getDebugLoc(); 12615 12616 // Result of setflm is previous FPSCR content, so we need to save it first. 12617 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12618 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12619 12620 // Put bits in 32:63 to FPSCR. 12621 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12622 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12623 .addImm(255) 12624 .addReg(NewFPSCRReg) 12625 .addImm(0) 12626 .addImm(0); 12627 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12628 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12629 return emitProbedAlloca(MI, BB); 12630 } else { 12631 llvm_unreachable("Unexpected instr type to insert"); 12632 } 12633 12634 MI.eraseFromParent(); // The pseudo instruction is gone now. 12635 return BB; 12636 } 12637 12638 //===----------------------------------------------------------------------===// 12639 // Target Optimization Hooks 12640 //===----------------------------------------------------------------------===// 12641 12642 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12643 // For the estimates, convergence is quadratic, so we essentially double the 12644 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12645 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12646 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12647 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12648 if (VT.getScalarType() == MVT::f64) 12649 RefinementSteps++; 12650 return RefinementSteps; 12651 } 12652 12653 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12654 int Enabled, int &RefinementSteps, 12655 bool &UseOneConstNR, 12656 bool Reciprocal) const { 12657 EVT VT = Operand.getValueType(); 12658 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12659 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12660 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12661 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12662 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12663 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12664 12665 // The Newton-Raphson computation with a single constant does not provide 12666 // enough accuracy on some CPUs. 12667 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12668 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12669 } 12670 return SDValue(); 12671 } 12672 12673 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12674 int Enabled, 12675 int &RefinementSteps) const { 12676 EVT VT = Operand.getValueType(); 12677 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12678 (VT == MVT::f64 && Subtarget.hasFRE()) || 12679 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12680 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12681 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12682 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12683 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12684 } 12685 return SDValue(); 12686 } 12687 12688 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12689 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12690 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12691 // enabled for division), this functionality is redundant with the default 12692 // combiner logic (once the division -> reciprocal/multiply transformation 12693 // has taken place). As a result, this matters more for older cores than for 12694 // newer ones. 12695 12696 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12697 // reciprocal if there are two or more FDIVs (for embedded cores with only 12698 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12699 switch (Subtarget.getCPUDirective()) { 12700 default: 12701 return 3; 12702 case PPC::DIR_440: 12703 case PPC::DIR_A2: 12704 case PPC::DIR_E500: 12705 case PPC::DIR_E500mc: 12706 case PPC::DIR_E5500: 12707 return 2; 12708 } 12709 } 12710 12711 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12712 // collapsed, and so we need to look through chains of them. 12713 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12714 int64_t& Offset, SelectionDAG &DAG) { 12715 if (DAG.isBaseWithConstantOffset(Loc)) { 12716 Base = Loc.getOperand(0); 12717 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12718 12719 // The base might itself be a base plus an offset, and if so, accumulate 12720 // that as well. 12721 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12722 } 12723 } 12724 12725 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12726 unsigned Bytes, int Dist, 12727 SelectionDAG &DAG) { 12728 if (VT.getSizeInBits() / 8 != Bytes) 12729 return false; 12730 12731 SDValue BaseLoc = Base->getBasePtr(); 12732 if (Loc.getOpcode() == ISD::FrameIndex) { 12733 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12734 return false; 12735 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12736 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12737 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12738 int FS = MFI.getObjectSize(FI); 12739 int BFS = MFI.getObjectSize(BFI); 12740 if (FS != BFS || FS != (int)Bytes) return false; 12741 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12742 } 12743 12744 SDValue Base1 = Loc, Base2 = BaseLoc; 12745 int64_t Offset1 = 0, Offset2 = 0; 12746 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12747 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12748 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12749 return true; 12750 12751 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12752 const GlobalValue *GV1 = nullptr; 12753 const GlobalValue *GV2 = nullptr; 12754 Offset1 = 0; 12755 Offset2 = 0; 12756 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12757 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12758 if (isGA1 && isGA2 && GV1 == GV2) 12759 return Offset1 == (Offset2 + Dist*Bytes); 12760 return false; 12761 } 12762 12763 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12764 // not enforce equality of the chain operands. 12765 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12766 unsigned Bytes, int Dist, 12767 SelectionDAG &DAG) { 12768 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12769 EVT VT = LS->getMemoryVT(); 12770 SDValue Loc = LS->getBasePtr(); 12771 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12772 } 12773 12774 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12775 EVT VT; 12776 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12777 default: return false; 12778 case Intrinsic::ppc_altivec_lvx: 12779 case Intrinsic::ppc_altivec_lvxl: 12780 case Intrinsic::ppc_vsx_lxvw4x: 12781 case Intrinsic::ppc_vsx_lxvw4x_be: 12782 VT = MVT::v4i32; 12783 break; 12784 case Intrinsic::ppc_vsx_lxvd2x: 12785 case Intrinsic::ppc_vsx_lxvd2x_be: 12786 VT = MVT::v2f64; 12787 break; 12788 case Intrinsic::ppc_altivec_lvebx: 12789 VT = MVT::i8; 12790 break; 12791 case Intrinsic::ppc_altivec_lvehx: 12792 VT = MVT::i16; 12793 break; 12794 case Intrinsic::ppc_altivec_lvewx: 12795 VT = MVT::i32; 12796 break; 12797 } 12798 12799 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12800 } 12801 12802 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12803 EVT VT; 12804 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12805 default: return false; 12806 case Intrinsic::ppc_altivec_stvx: 12807 case Intrinsic::ppc_altivec_stvxl: 12808 case Intrinsic::ppc_vsx_stxvw4x: 12809 VT = MVT::v4i32; 12810 break; 12811 case Intrinsic::ppc_vsx_stxvd2x: 12812 VT = MVT::v2f64; 12813 break; 12814 case Intrinsic::ppc_vsx_stxvw4x_be: 12815 VT = MVT::v4i32; 12816 break; 12817 case Intrinsic::ppc_vsx_stxvd2x_be: 12818 VT = MVT::v2f64; 12819 break; 12820 case Intrinsic::ppc_altivec_stvebx: 12821 VT = MVT::i8; 12822 break; 12823 case Intrinsic::ppc_altivec_stvehx: 12824 VT = MVT::i16; 12825 break; 12826 case Intrinsic::ppc_altivec_stvewx: 12827 VT = MVT::i32; 12828 break; 12829 } 12830 12831 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12832 } 12833 12834 return false; 12835 } 12836 12837 // Return true is there is a nearyby consecutive load to the one provided 12838 // (regardless of alignment). We search up and down the chain, looking though 12839 // token factors and other loads (but nothing else). As a result, a true result 12840 // indicates that it is safe to create a new consecutive load adjacent to the 12841 // load provided. 12842 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12843 SDValue Chain = LD->getChain(); 12844 EVT VT = LD->getMemoryVT(); 12845 12846 SmallSet<SDNode *, 16> LoadRoots; 12847 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12848 SmallSet<SDNode *, 16> Visited; 12849 12850 // First, search up the chain, branching to follow all token-factor operands. 12851 // If we find a consecutive load, then we're done, otherwise, record all 12852 // nodes just above the top-level loads and token factors. 12853 while (!Queue.empty()) { 12854 SDNode *ChainNext = Queue.pop_back_val(); 12855 if (!Visited.insert(ChainNext).second) 12856 continue; 12857 12858 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12859 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12860 return true; 12861 12862 if (!Visited.count(ChainLD->getChain().getNode())) 12863 Queue.push_back(ChainLD->getChain().getNode()); 12864 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12865 for (const SDUse &O : ChainNext->ops()) 12866 if (!Visited.count(O.getNode())) 12867 Queue.push_back(O.getNode()); 12868 } else 12869 LoadRoots.insert(ChainNext); 12870 } 12871 12872 // Second, search down the chain, starting from the top-level nodes recorded 12873 // in the first phase. These top-level nodes are the nodes just above all 12874 // loads and token factors. Starting with their uses, recursively look though 12875 // all loads (just the chain uses) and token factors to find a consecutive 12876 // load. 12877 Visited.clear(); 12878 Queue.clear(); 12879 12880 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12881 IE = LoadRoots.end(); I != IE; ++I) { 12882 Queue.push_back(*I); 12883 12884 while (!Queue.empty()) { 12885 SDNode *LoadRoot = Queue.pop_back_val(); 12886 if (!Visited.insert(LoadRoot).second) 12887 continue; 12888 12889 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12890 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12891 return true; 12892 12893 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12894 UE = LoadRoot->use_end(); UI != UE; ++UI) 12895 if (((isa<MemSDNode>(*UI) && 12896 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12897 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12898 Queue.push_back(*UI); 12899 } 12900 } 12901 12902 return false; 12903 } 12904 12905 /// This function is called when we have proved that a SETCC node can be replaced 12906 /// by subtraction (and other supporting instructions) so that the result of 12907 /// comparison is kept in a GPR instead of CR. This function is purely for 12908 /// codegen purposes and has some flags to guide the codegen process. 12909 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12910 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12911 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12912 12913 // Zero extend the operands to the largest legal integer. Originally, they 12914 // must be of a strictly smaller size. 12915 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12916 DAG.getConstant(Size, DL, MVT::i32)); 12917 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12918 DAG.getConstant(Size, DL, MVT::i32)); 12919 12920 // Swap if needed. Depends on the condition code. 12921 if (Swap) 12922 std::swap(Op0, Op1); 12923 12924 // Subtract extended integers. 12925 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12926 12927 // Move the sign bit to the least significant position and zero out the rest. 12928 // Now the least significant bit carries the result of original comparison. 12929 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12930 DAG.getConstant(Size - 1, DL, MVT::i32)); 12931 auto Final = Shifted; 12932 12933 // Complement the result if needed. Based on the condition code. 12934 if (Complement) 12935 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12936 DAG.getConstant(1, DL, MVT::i64)); 12937 12938 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12939 } 12940 12941 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12942 DAGCombinerInfo &DCI) const { 12943 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12944 12945 SelectionDAG &DAG = DCI.DAG; 12946 SDLoc DL(N); 12947 12948 // Size of integers being compared has a critical role in the following 12949 // analysis, so we prefer to do this when all types are legal. 12950 if (!DCI.isAfterLegalizeDAG()) 12951 return SDValue(); 12952 12953 // If all users of SETCC extend its value to a legal integer type 12954 // then we replace SETCC with a subtraction 12955 for (SDNode::use_iterator UI = N->use_begin(), 12956 UE = N->use_end(); UI != UE; ++UI) { 12957 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12958 return SDValue(); 12959 } 12960 12961 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12962 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12963 12964 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12965 12966 if (OpSize < Size) { 12967 switch (CC) { 12968 default: break; 12969 case ISD::SETULT: 12970 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12971 case ISD::SETULE: 12972 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12973 case ISD::SETUGT: 12974 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12975 case ISD::SETUGE: 12976 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12977 } 12978 } 12979 12980 return SDValue(); 12981 } 12982 12983 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12984 DAGCombinerInfo &DCI) const { 12985 SelectionDAG &DAG = DCI.DAG; 12986 SDLoc dl(N); 12987 12988 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12989 // If we're tracking CR bits, we need to be careful that we don't have: 12990 // trunc(binary-ops(zext(x), zext(y))) 12991 // or 12992 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12993 // such that we're unnecessarily moving things into GPRs when it would be 12994 // better to keep them in CR bits. 12995 12996 // Note that trunc here can be an actual i1 trunc, or can be the effective 12997 // truncation that comes from a setcc or select_cc. 12998 if (N->getOpcode() == ISD::TRUNCATE && 12999 N->getValueType(0) != MVT::i1) 13000 return SDValue(); 13001 13002 if (N->getOperand(0).getValueType() != MVT::i32 && 13003 N->getOperand(0).getValueType() != MVT::i64) 13004 return SDValue(); 13005 13006 if (N->getOpcode() == ISD::SETCC || 13007 N->getOpcode() == ISD::SELECT_CC) { 13008 // If we're looking at a comparison, then we need to make sure that the 13009 // high bits (all except for the first) don't matter the result. 13010 ISD::CondCode CC = 13011 cast<CondCodeSDNode>(N->getOperand( 13012 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13013 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13014 13015 if (ISD::isSignedIntSetCC(CC)) { 13016 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13017 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13018 return SDValue(); 13019 } else if (ISD::isUnsignedIntSetCC(CC)) { 13020 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13021 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13022 !DAG.MaskedValueIsZero(N->getOperand(1), 13023 APInt::getHighBitsSet(OpBits, OpBits-1))) 13024 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13025 : SDValue()); 13026 } else { 13027 // This is neither a signed nor an unsigned comparison, just make sure 13028 // that the high bits are equal. 13029 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13030 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13031 13032 // We don't really care about what is known about the first bit (if 13033 // anything), so clear it in all masks prior to comparing them. 13034 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 13035 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 13036 13037 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 13038 return SDValue(); 13039 } 13040 } 13041 13042 // We now know that the higher-order bits are irrelevant, we just need to 13043 // make sure that all of the intermediate operations are bit operations, and 13044 // all inputs are extensions. 13045 if (N->getOperand(0).getOpcode() != ISD::AND && 13046 N->getOperand(0).getOpcode() != ISD::OR && 13047 N->getOperand(0).getOpcode() != ISD::XOR && 13048 N->getOperand(0).getOpcode() != ISD::SELECT && 13049 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13050 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13051 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13052 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13053 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13054 return SDValue(); 13055 13056 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13057 N->getOperand(1).getOpcode() != ISD::AND && 13058 N->getOperand(1).getOpcode() != ISD::OR && 13059 N->getOperand(1).getOpcode() != ISD::XOR && 13060 N->getOperand(1).getOpcode() != ISD::SELECT && 13061 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13062 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13063 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13064 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13065 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13066 return SDValue(); 13067 13068 SmallVector<SDValue, 4> Inputs; 13069 SmallVector<SDValue, 8> BinOps, PromOps; 13070 SmallPtrSet<SDNode *, 16> Visited; 13071 13072 for (unsigned i = 0; i < 2; ++i) { 13073 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13074 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13075 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13076 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13077 isa<ConstantSDNode>(N->getOperand(i))) 13078 Inputs.push_back(N->getOperand(i)); 13079 else 13080 BinOps.push_back(N->getOperand(i)); 13081 13082 if (N->getOpcode() == ISD::TRUNCATE) 13083 break; 13084 } 13085 13086 // Visit all inputs, collect all binary operations (and, or, xor and 13087 // select) that are all fed by extensions. 13088 while (!BinOps.empty()) { 13089 SDValue BinOp = BinOps.back(); 13090 BinOps.pop_back(); 13091 13092 if (!Visited.insert(BinOp.getNode()).second) 13093 continue; 13094 13095 PromOps.push_back(BinOp); 13096 13097 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13098 // The condition of the select is not promoted. 13099 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13100 continue; 13101 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13102 continue; 13103 13104 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13105 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13106 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13107 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13108 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13109 Inputs.push_back(BinOp.getOperand(i)); 13110 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13111 BinOp.getOperand(i).getOpcode() == ISD::OR || 13112 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13113 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13114 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13115 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13116 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13117 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13118 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13119 BinOps.push_back(BinOp.getOperand(i)); 13120 } else { 13121 // We have an input that is not an extension or another binary 13122 // operation; we'll abort this transformation. 13123 return SDValue(); 13124 } 13125 } 13126 } 13127 13128 // Make sure that this is a self-contained cluster of operations (which 13129 // is not quite the same thing as saying that everything has only one 13130 // use). 13131 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13132 if (isa<ConstantSDNode>(Inputs[i])) 13133 continue; 13134 13135 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13136 UE = Inputs[i].getNode()->use_end(); 13137 UI != UE; ++UI) { 13138 SDNode *User = *UI; 13139 if (User != N && !Visited.count(User)) 13140 return SDValue(); 13141 13142 // Make sure that we're not going to promote the non-output-value 13143 // operand(s) or SELECT or SELECT_CC. 13144 // FIXME: Although we could sometimes handle this, and it does occur in 13145 // practice that one of the condition inputs to the select is also one of 13146 // the outputs, we currently can't deal with this. 13147 if (User->getOpcode() == ISD::SELECT) { 13148 if (User->getOperand(0) == Inputs[i]) 13149 return SDValue(); 13150 } else if (User->getOpcode() == ISD::SELECT_CC) { 13151 if (User->getOperand(0) == Inputs[i] || 13152 User->getOperand(1) == Inputs[i]) 13153 return SDValue(); 13154 } 13155 } 13156 } 13157 13158 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13159 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13160 UE = PromOps[i].getNode()->use_end(); 13161 UI != UE; ++UI) { 13162 SDNode *User = *UI; 13163 if (User != N && !Visited.count(User)) 13164 return SDValue(); 13165 13166 // Make sure that we're not going to promote the non-output-value 13167 // operand(s) or SELECT or SELECT_CC. 13168 // FIXME: Although we could sometimes handle this, and it does occur in 13169 // practice that one of the condition inputs to the select is also one of 13170 // the outputs, we currently can't deal with this. 13171 if (User->getOpcode() == ISD::SELECT) { 13172 if (User->getOperand(0) == PromOps[i]) 13173 return SDValue(); 13174 } else if (User->getOpcode() == ISD::SELECT_CC) { 13175 if (User->getOperand(0) == PromOps[i] || 13176 User->getOperand(1) == PromOps[i]) 13177 return SDValue(); 13178 } 13179 } 13180 } 13181 13182 // Replace all inputs with the extension operand. 13183 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13184 // Constants may have users outside the cluster of to-be-promoted nodes, 13185 // and so we need to replace those as we do the promotions. 13186 if (isa<ConstantSDNode>(Inputs[i])) 13187 continue; 13188 else 13189 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13190 } 13191 13192 std::list<HandleSDNode> PromOpHandles; 13193 for (auto &PromOp : PromOps) 13194 PromOpHandles.emplace_back(PromOp); 13195 13196 // Replace all operations (these are all the same, but have a different 13197 // (i1) return type). DAG.getNode will validate that the types of 13198 // a binary operator match, so go through the list in reverse so that 13199 // we've likely promoted both operands first. Any intermediate truncations or 13200 // extensions disappear. 13201 while (!PromOpHandles.empty()) { 13202 SDValue PromOp = PromOpHandles.back().getValue(); 13203 PromOpHandles.pop_back(); 13204 13205 if (PromOp.getOpcode() == ISD::TRUNCATE || 13206 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13207 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13208 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13209 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13210 PromOp.getOperand(0).getValueType() != MVT::i1) { 13211 // The operand is not yet ready (see comment below). 13212 PromOpHandles.emplace_front(PromOp); 13213 continue; 13214 } 13215 13216 SDValue RepValue = PromOp.getOperand(0); 13217 if (isa<ConstantSDNode>(RepValue)) 13218 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13219 13220 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13221 continue; 13222 } 13223 13224 unsigned C; 13225 switch (PromOp.getOpcode()) { 13226 default: C = 0; break; 13227 case ISD::SELECT: C = 1; break; 13228 case ISD::SELECT_CC: C = 2; break; 13229 } 13230 13231 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13232 PromOp.getOperand(C).getValueType() != MVT::i1) || 13233 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13234 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13235 // The to-be-promoted operands of this node have not yet been 13236 // promoted (this should be rare because we're going through the 13237 // list backward, but if one of the operands has several users in 13238 // this cluster of to-be-promoted nodes, it is possible). 13239 PromOpHandles.emplace_front(PromOp); 13240 continue; 13241 } 13242 13243 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13244 PromOp.getNode()->op_end()); 13245 13246 // If there are any constant inputs, make sure they're replaced now. 13247 for (unsigned i = 0; i < 2; ++i) 13248 if (isa<ConstantSDNode>(Ops[C+i])) 13249 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13250 13251 DAG.ReplaceAllUsesOfValueWith(PromOp, 13252 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13253 } 13254 13255 // Now we're left with the initial truncation itself. 13256 if (N->getOpcode() == ISD::TRUNCATE) 13257 return N->getOperand(0); 13258 13259 // Otherwise, this is a comparison. The operands to be compared have just 13260 // changed type (to i1), but everything else is the same. 13261 return SDValue(N, 0); 13262 } 13263 13264 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13265 DAGCombinerInfo &DCI) const { 13266 SelectionDAG &DAG = DCI.DAG; 13267 SDLoc dl(N); 13268 13269 // If we're tracking CR bits, we need to be careful that we don't have: 13270 // zext(binary-ops(trunc(x), trunc(y))) 13271 // or 13272 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13273 // such that we're unnecessarily moving things into CR bits that can more 13274 // efficiently stay in GPRs. Note that if we're not certain that the high 13275 // bits are set as required by the final extension, we still may need to do 13276 // some masking to get the proper behavior. 13277 13278 // This same functionality is important on PPC64 when dealing with 13279 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13280 // the return values of functions. Because it is so similar, it is handled 13281 // here as well. 13282 13283 if (N->getValueType(0) != MVT::i32 && 13284 N->getValueType(0) != MVT::i64) 13285 return SDValue(); 13286 13287 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13288 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13289 return SDValue(); 13290 13291 if (N->getOperand(0).getOpcode() != ISD::AND && 13292 N->getOperand(0).getOpcode() != ISD::OR && 13293 N->getOperand(0).getOpcode() != ISD::XOR && 13294 N->getOperand(0).getOpcode() != ISD::SELECT && 13295 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13296 return SDValue(); 13297 13298 SmallVector<SDValue, 4> Inputs; 13299 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13300 SmallPtrSet<SDNode *, 16> Visited; 13301 13302 // Visit all inputs, collect all binary operations (and, or, xor and 13303 // select) that are all fed by truncations. 13304 while (!BinOps.empty()) { 13305 SDValue BinOp = BinOps.back(); 13306 BinOps.pop_back(); 13307 13308 if (!Visited.insert(BinOp.getNode()).second) 13309 continue; 13310 13311 PromOps.push_back(BinOp); 13312 13313 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13314 // The condition of the select is not promoted. 13315 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13316 continue; 13317 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13318 continue; 13319 13320 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13321 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13322 Inputs.push_back(BinOp.getOperand(i)); 13323 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13324 BinOp.getOperand(i).getOpcode() == ISD::OR || 13325 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13326 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13327 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13328 BinOps.push_back(BinOp.getOperand(i)); 13329 } else { 13330 // We have an input that is not a truncation or another binary 13331 // operation; we'll abort this transformation. 13332 return SDValue(); 13333 } 13334 } 13335 } 13336 13337 // The operands of a select that must be truncated when the select is 13338 // promoted because the operand is actually part of the to-be-promoted set. 13339 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13340 13341 // Make sure that this is a self-contained cluster of operations (which 13342 // is not quite the same thing as saying that everything has only one 13343 // use). 13344 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13345 if (isa<ConstantSDNode>(Inputs[i])) 13346 continue; 13347 13348 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13349 UE = Inputs[i].getNode()->use_end(); 13350 UI != UE; ++UI) { 13351 SDNode *User = *UI; 13352 if (User != N && !Visited.count(User)) 13353 return SDValue(); 13354 13355 // If we're going to promote the non-output-value operand(s) or SELECT or 13356 // SELECT_CC, record them for truncation. 13357 if (User->getOpcode() == ISD::SELECT) { 13358 if (User->getOperand(0) == Inputs[i]) 13359 SelectTruncOp[0].insert(std::make_pair(User, 13360 User->getOperand(0).getValueType())); 13361 } else if (User->getOpcode() == ISD::SELECT_CC) { 13362 if (User->getOperand(0) == Inputs[i]) 13363 SelectTruncOp[0].insert(std::make_pair(User, 13364 User->getOperand(0).getValueType())); 13365 if (User->getOperand(1) == Inputs[i]) 13366 SelectTruncOp[1].insert(std::make_pair(User, 13367 User->getOperand(1).getValueType())); 13368 } 13369 } 13370 } 13371 13372 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13373 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13374 UE = PromOps[i].getNode()->use_end(); 13375 UI != UE; ++UI) { 13376 SDNode *User = *UI; 13377 if (User != N && !Visited.count(User)) 13378 return SDValue(); 13379 13380 // If we're going to promote the non-output-value operand(s) or SELECT or 13381 // SELECT_CC, record them for truncation. 13382 if (User->getOpcode() == ISD::SELECT) { 13383 if (User->getOperand(0) == PromOps[i]) 13384 SelectTruncOp[0].insert(std::make_pair(User, 13385 User->getOperand(0).getValueType())); 13386 } else if (User->getOpcode() == ISD::SELECT_CC) { 13387 if (User->getOperand(0) == PromOps[i]) 13388 SelectTruncOp[0].insert(std::make_pair(User, 13389 User->getOperand(0).getValueType())); 13390 if (User->getOperand(1) == PromOps[i]) 13391 SelectTruncOp[1].insert(std::make_pair(User, 13392 User->getOperand(1).getValueType())); 13393 } 13394 } 13395 } 13396 13397 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13398 bool ReallyNeedsExt = false; 13399 if (N->getOpcode() != ISD::ANY_EXTEND) { 13400 // If all of the inputs are not already sign/zero extended, then 13401 // we'll still need to do that at the end. 13402 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13403 if (isa<ConstantSDNode>(Inputs[i])) 13404 continue; 13405 13406 unsigned OpBits = 13407 Inputs[i].getOperand(0).getValueSizeInBits(); 13408 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13409 13410 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13411 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13412 APInt::getHighBitsSet(OpBits, 13413 OpBits-PromBits))) || 13414 (N->getOpcode() == ISD::SIGN_EXTEND && 13415 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13416 (OpBits-(PromBits-1)))) { 13417 ReallyNeedsExt = true; 13418 break; 13419 } 13420 } 13421 } 13422 13423 // Replace all inputs, either with the truncation operand, or a 13424 // truncation or extension to the final output type. 13425 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13426 // Constant inputs need to be replaced with the to-be-promoted nodes that 13427 // use them because they might have users outside of the cluster of 13428 // promoted nodes. 13429 if (isa<ConstantSDNode>(Inputs[i])) 13430 continue; 13431 13432 SDValue InSrc = Inputs[i].getOperand(0); 13433 if (Inputs[i].getValueType() == N->getValueType(0)) 13434 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13435 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13436 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13437 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13438 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13439 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13440 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13441 else 13442 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13443 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13444 } 13445 13446 std::list<HandleSDNode> PromOpHandles; 13447 for (auto &PromOp : PromOps) 13448 PromOpHandles.emplace_back(PromOp); 13449 13450 // Replace all operations (these are all the same, but have a different 13451 // (promoted) return type). DAG.getNode will validate that the types of 13452 // a binary operator match, so go through the list in reverse so that 13453 // we've likely promoted both operands first. 13454 while (!PromOpHandles.empty()) { 13455 SDValue PromOp = PromOpHandles.back().getValue(); 13456 PromOpHandles.pop_back(); 13457 13458 unsigned C; 13459 switch (PromOp.getOpcode()) { 13460 default: C = 0; break; 13461 case ISD::SELECT: C = 1; break; 13462 case ISD::SELECT_CC: C = 2; break; 13463 } 13464 13465 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13466 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13467 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13468 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13469 // The to-be-promoted operands of this node have not yet been 13470 // promoted (this should be rare because we're going through the 13471 // list backward, but if one of the operands has several users in 13472 // this cluster of to-be-promoted nodes, it is possible). 13473 PromOpHandles.emplace_front(PromOp); 13474 continue; 13475 } 13476 13477 // For SELECT and SELECT_CC nodes, we do a similar check for any 13478 // to-be-promoted comparison inputs. 13479 if (PromOp.getOpcode() == ISD::SELECT || 13480 PromOp.getOpcode() == ISD::SELECT_CC) { 13481 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13482 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13483 (SelectTruncOp[1].count(PromOp.getNode()) && 13484 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13485 PromOpHandles.emplace_front(PromOp); 13486 continue; 13487 } 13488 } 13489 13490 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13491 PromOp.getNode()->op_end()); 13492 13493 // If this node has constant inputs, then they'll need to be promoted here. 13494 for (unsigned i = 0; i < 2; ++i) { 13495 if (!isa<ConstantSDNode>(Ops[C+i])) 13496 continue; 13497 if (Ops[C+i].getValueType() == N->getValueType(0)) 13498 continue; 13499 13500 if (N->getOpcode() == ISD::SIGN_EXTEND) 13501 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13502 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13503 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13504 else 13505 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13506 } 13507 13508 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13509 // truncate them again to the original value type. 13510 if (PromOp.getOpcode() == ISD::SELECT || 13511 PromOp.getOpcode() == ISD::SELECT_CC) { 13512 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13513 if (SI0 != SelectTruncOp[0].end()) 13514 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13515 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13516 if (SI1 != SelectTruncOp[1].end()) 13517 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13518 } 13519 13520 DAG.ReplaceAllUsesOfValueWith(PromOp, 13521 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13522 } 13523 13524 // Now we're left with the initial extension itself. 13525 if (!ReallyNeedsExt) 13526 return N->getOperand(0); 13527 13528 // To zero extend, just mask off everything except for the first bit (in the 13529 // i1 case). 13530 if (N->getOpcode() == ISD::ZERO_EXTEND) 13531 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13532 DAG.getConstant(APInt::getLowBitsSet( 13533 N->getValueSizeInBits(0), PromBits), 13534 dl, N->getValueType(0))); 13535 13536 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13537 "Invalid extension type"); 13538 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13539 SDValue ShiftCst = 13540 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13541 return DAG.getNode( 13542 ISD::SRA, dl, N->getValueType(0), 13543 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13544 ShiftCst); 13545 } 13546 13547 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13548 DAGCombinerInfo &DCI) const { 13549 assert(N->getOpcode() == ISD::SETCC && 13550 "Should be called with a SETCC node"); 13551 13552 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13553 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13554 SDValue LHS = N->getOperand(0); 13555 SDValue RHS = N->getOperand(1); 13556 13557 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13558 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13559 LHS.hasOneUse()) 13560 std::swap(LHS, RHS); 13561 13562 // x == 0-y --> x+y == 0 13563 // x != 0-y --> x+y != 0 13564 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13565 RHS.hasOneUse()) { 13566 SDLoc DL(N); 13567 SelectionDAG &DAG = DCI.DAG; 13568 EVT VT = N->getValueType(0); 13569 EVT OpVT = LHS.getValueType(); 13570 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13571 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13572 } 13573 } 13574 13575 return DAGCombineTruncBoolExt(N, DCI); 13576 } 13577 13578 // Is this an extending load from an f32 to an f64? 13579 static bool isFPExtLoad(SDValue Op) { 13580 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13581 return LD->getExtensionType() == ISD::EXTLOAD && 13582 Op.getValueType() == MVT::f64; 13583 return false; 13584 } 13585 13586 /// Reduces the number of fp-to-int conversion when building a vector. 13587 /// 13588 /// If this vector is built out of floating to integer conversions, 13589 /// transform it to a vector built out of floating point values followed by a 13590 /// single floating to integer conversion of the vector. 13591 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13592 /// becomes (fptosi (build_vector ($A, $B, ...))) 13593 SDValue PPCTargetLowering:: 13594 combineElementTruncationToVectorTruncation(SDNode *N, 13595 DAGCombinerInfo &DCI) const { 13596 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13597 "Should be called with a BUILD_VECTOR node"); 13598 13599 SelectionDAG &DAG = DCI.DAG; 13600 SDLoc dl(N); 13601 13602 SDValue FirstInput = N->getOperand(0); 13603 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13604 "The input operand must be an fp-to-int conversion."); 13605 13606 // This combine happens after legalization so the fp_to_[su]i nodes are 13607 // already converted to PPCSISD nodes. 13608 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13609 if (FirstConversion == PPCISD::FCTIDZ || 13610 FirstConversion == PPCISD::FCTIDUZ || 13611 FirstConversion == PPCISD::FCTIWZ || 13612 FirstConversion == PPCISD::FCTIWUZ) { 13613 bool IsSplat = true; 13614 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13615 FirstConversion == PPCISD::FCTIWUZ; 13616 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13617 SmallVector<SDValue, 4> Ops; 13618 EVT TargetVT = N->getValueType(0); 13619 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13620 SDValue NextOp = N->getOperand(i); 13621 if (NextOp.getOpcode() != PPCISD::MFVSR) 13622 return SDValue(); 13623 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13624 if (NextConversion != FirstConversion) 13625 return SDValue(); 13626 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13627 // This is not valid if the input was originally double precision. It is 13628 // also not profitable to do unless this is an extending load in which 13629 // case doing this combine will allow us to combine consecutive loads. 13630 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13631 return SDValue(); 13632 if (N->getOperand(i) != FirstInput) 13633 IsSplat = false; 13634 } 13635 13636 // If this is a splat, we leave it as-is since there will be only a single 13637 // fp-to-int conversion followed by a splat of the integer. This is better 13638 // for 32-bit and smaller ints and neutral for 64-bit ints. 13639 if (IsSplat) 13640 return SDValue(); 13641 13642 // Now that we know we have the right type of node, get its operands 13643 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13644 SDValue In = N->getOperand(i).getOperand(0); 13645 if (Is32Bit) { 13646 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13647 // here, we know that all inputs are extending loads so this is safe). 13648 if (In.isUndef()) 13649 Ops.push_back(DAG.getUNDEF(SrcVT)); 13650 else { 13651 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13652 MVT::f32, In.getOperand(0), 13653 DAG.getIntPtrConstant(1, dl)); 13654 Ops.push_back(Trunc); 13655 } 13656 } else 13657 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13658 } 13659 13660 unsigned Opcode; 13661 if (FirstConversion == PPCISD::FCTIDZ || 13662 FirstConversion == PPCISD::FCTIWZ) 13663 Opcode = ISD::FP_TO_SINT; 13664 else 13665 Opcode = ISD::FP_TO_UINT; 13666 13667 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13668 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13669 return DAG.getNode(Opcode, dl, TargetVT, BV); 13670 } 13671 return SDValue(); 13672 } 13673 13674 /// Reduce the number of loads when building a vector. 13675 /// 13676 /// Building a vector out of multiple loads can be converted to a load 13677 /// of the vector type if the loads are consecutive. If the loads are 13678 /// consecutive but in descending order, a shuffle is added at the end 13679 /// to reorder the vector. 13680 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13681 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13682 "Should be called with a BUILD_VECTOR node"); 13683 13684 SDLoc dl(N); 13685 13686 // Return early for non byte-sized type, as they can't be consecutive. 13687 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13688 return SDValue(); 13689 13690 bool InputsAreConsecutiveLoads = true; 13691 bool InputsAreReverseConsecutive = true; 13692 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13693 SDValue FirstInput = N->getOperand(0); 13694 bool IsRoundOfExtLoad = false; 13695 13696 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13697 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13698 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13699 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13700 } 13701 // Not a build vector of (possibly fp_rounded) loads. 13702 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13703 N->getNumOperands() == 1) 13704 return SDValue(); 13705 13706 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13707 // If any inputs are fp_round(extload), they all must be. 13708 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13709 return SDValue(); 13710 13711 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13712 N->getOperand(i); 13713 if (NextInput.getOpcode() != ISD::LOAD) 13714 return SDValue(); 13715 13716 SDValue PreviousInput = 13717 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13718 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13719 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13720 13721 // If any inputs are fp_round(extload), they all must be. 13722 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13723 return SDValue(); 13724 13725 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13726 InputsAreConsecutiveLoads = false; 13727 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13728 InputsAreReverseConsecutive = false; 13729 13730 // Exit early if the loads are neither consecutive nor reverse consecutive. 13731 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13732 return SDValue(); 13733 } 13734 13735 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13736 "The loads cannot be both consecutive and reverse consecutive."); 13737 13738 SDValue FirstLoadOp = 13739 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13740 SDValue LastLoadOp = 13741 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13742 N->getOperand(N->getNumOperands()-1); 13743 13744 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13745 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13746 if (InputsAreConsecutiveLoads) { 13747 assert(LD1 && "Input needs to be a LoadSDNode."); 13748 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13749 LD1->getBasePtr(), LD1->getPointerInfo(), 13750 LD1->getAlignment()); 13751 } 13752 if (InputsAreReverseConsecutive) { 13753 assert(LDL && "Input needs to be a LoadSDNode."); 13754 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13755 LDL->getBasePtr(), LDL->getPointerInfo(), 13756 LDL->getAlignment()); 13757 SmallVector<int, 16> Ops; 13758 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13759 Ops.push_back(i); 13760 13761 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13762 DAG.getUNDEF(N->getValueType(0)), Ops); 13763 } 13764 return SDValue(); 13765 } 13766 13767 // This function adds the required vector_shuffle needed to get 13768 // the elements of the vector extract in the correct position 13769 // as specified by the CorrectElems encoding. 13770 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13771 SDValue Input, uint64_t Elems, 13772 uint64_t CorrectElems) { 13773 SDLoc dl(N); 13774 13775 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13776 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13777 13778 // Knowing the element indices being extracted from the original 13779 // vector and the order in which they're being inserted, just put 13780 // them at element indices required for the instruction. 13781 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13782 if (DAG.getDataLayout().isLittleEndian()) 13783 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13784 else 13785 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13786 CorrectElems = CorrectElems >> 8; 13787 Elems = Elems >> 8; 13788 } 13789 13790 SDValue Shuffle = 13791 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13792 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13793 13794 EVT VT = N->getValueType(0); 13795 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13796 13797 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13798 Input.getValueType().getVectorElementType(), 13799 VT.getVectorNumElements()); 13800 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13801 DAG.getValueType(ExtVT)); 13802 } 13803 13804 // Look for build vector patterns where input operands come from sign 13805 // extended vector_extract elements of specific indices. If the correct indices 13806 // aren't used, add a vector shuffle to fix up the indices and create 13807 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13808 // during instruction selection. 13809 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13810 // This array encodes the indices that the vector sign extend instructions 13811 // extract from when extending from one type to another for both BE and LE. 13812 // The right nibble of each byte corresponds to the LE incides. 13813 // and the left nibble of each byte corresponds to the BE incides. 13814 // For example: 0x3074B8FC byte->word 13815 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13816 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13817 // For example: 0x000070F8 byte->double word 13818 // For LE: the allowed indices are: 0x0,0x8 13819 // For BE: the allowed indices are: 0x7,0xF 13820 uint64_t TargetElems[] = { 13821 0x3074B8FC, // b->w 13822 0x000070F8, // b->d 13823 0x10325476, // h->w 13824 0x00003074, // h->d 13825 0x00001032, // w->d 13826 }; 13827 13828 uint64_t Elems = 0; 13829 int Index; 13830 SDValue Input; 13831 13832 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13833 if (!Op) 13834 return false; 13835 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13836 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13837 return false; 13838 13839 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13840 // of the right width. 13841 SDValue Extract = Op.getOperand(0); 13842 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13843 Extract = Extract.getOperand(0); 13844 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13845 return false; 13846 13847 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13848 if (!ExtOp) 13849 return false; 13850 13851 Index = ExtOp->getZExtValue(); 13852 if (Input && Input != Extract.getOperand(0)) 13853 return false; 13854 13855 if (!Input) 13856 Input = Extract.getOperand(0); 13857 13858 Elems = Elems << 8; 13859 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13860 Elems |= Index; 13861 13862 return true; 13863 }; 13864 13865 // If the build vector operands aren't sign extended vector extracts, 13866 // of the same input vector, then return. 13867 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13868 if (!isSExtOfVecExtract(N->getOperand(i))) { 13869 return SDValue(); 13870 } 13871 } 13872 13873 // If the vector extract indicies are not correct, add the appropriate 13874 // vector_shuffle. 13875 int TgtElemArrayIdx; 13876 int InputSize = Input.getValueType().getScalarSizeInBits(); 13877 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13878 if (InputSize + OutputSize == 40) 13879 TgtElemArrayIdx = 0; 13880 else if (InputSize + OutputSize == 72) 13881 TgtElemArrayIdx = 1; 13882 else if (InputSize + OutputSize == 48) 13883 TgtElemArrayIdx = 2; 13884 else if (InputSize + OutputSize == 80) 13885 TgtElemArrayIdx = 3; 13886 else if (InputSize + OutputSize == 96) 13887 TgtElemArrayIdx = 4; 13888 else 13889 return SDValue(); 13890 13891 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13892 CorrectElems = DAG.getDataLayout().isLittleEndian() 13893 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13894 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13895 if (Elems != CorrectElems) { 13896 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13897 } 13898 13899 // Regular lowering will catch cases where a shuffle is not needed. 13900 return SDValue(); 13901 } 13902 13903 // Look for the pattern of a load from a narrow width to i128, feeding 13904 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13905 // (LXVRZX). This node represents a zero extending load that will be matched 13906 // to the Load VSX Vector Rightmost instructions. 13907 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13908 SDLoc DL(N); 13909 13910 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13911 if (N->getValueType(0) != MVT::v1i128) 13912 return SDValue(); 13913 13914 SDValue Operand = N->getOperand(0); 13915 // Proceed with the transformation if the operand to the BUILD_VECTOR 13916 // is a load instruction. 13917 if (Operand.getOpcode() != ISD::LOAD) 13918 return SDValue(); 13919 13920 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13921 EVT MemoryType = LD->getMemoryVT(); 13922 13923 // This transformation is only valid if the we are loading either a byte, 13924 // halfword, word, or doubleword. 13925 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13926 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13927 13928 // Ensure that the load from the narrow width is being zero extended to i128. 13929 if (!ValidLDType || 13930 (LD->getExtensionType() != ISD::ZEXTLOAD && 13931 LD->getExtensionType() != ISD::EXTLOAD)) 13932 return SDValue(); 13933 13934 SDValue LoadOps[] = { 13935 LD->getChain(), LD->getBasePtr(), 13936 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13937 13938 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13939 DAG.getVTList(MVT::v1i128, MVT::Other), 13940 LoadOps, MemoryType, LD->getMemOperand()); 13941 } 13942 13943 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13944 DAGCombinerInfo &DCI) const { 13945 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13946 "Should be called with a BUILD_VECTOR node"); 13947 13948 SelectionDAG &DAG = DCI.DAG; 13949 SDLoc dl(N); 13950 13951 if (!Subtarget.hasVSX()) 13952 return SDValue(); 13953 13954 // The target independent DAG combiner will leave a build_vector of 13955 // float-to-int conversions intact. We can generate MUCH better code for 13956 // a float-to-int conversion of a vector of floats. 13957 SDValue FirstInput = N->getOperand(0); 13958 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13959 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13960 if (Reduced) 13961 return Reduced; 13962 } 13963 13964 // If we're building a vector out of consecutive loads, just load that 13965 // vector type. 13966 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13967 if (Reduced) 13968 return Reduced; 13969 13970 // If we're building a vector out of extended elements from another vector 13971 // we have P9 vector integer extend instructions. The code assumes legal 13972 // input types (i.e. it can't handle things like v4i16) so do not run before 13973 // legalization. 13974 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13975 Reduced = combineBVOfVecSExt(N, DAG); 13976 if (Reduced) 13977 return Reduced; 13978 } 13979 13980 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13981 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13982 // is a load from <valid narrow width> to i128. 13983 if (Subtarget.isISA3_1()) { 13984 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13985 if (BVOfZLoad) 13986 return BVOfZLoad; 13987 } 13988 13989 if (N->getValueType(0) != MVT::v2f64) 13990 return SDValue(); 13991 13992 // Looking for: 13993 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13994 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13995 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13996 return SDValue(); 13997 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13998 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13999 return SDValue(); 14000 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14001 return SDValue(); 14002 14003 SDValue Ext1 = FirstInput.getOperand(0); 14004 SDValue Ext2 = N->getOperand(1).getOperand(0); 14005 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14006 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14007 return SDValue(); 14008 14009 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14010 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14011 if (!Ext1Op || !Ext2Op) 14012 return SDValue(); 14013 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14014 Ext1.getOperand(0) != Ext2.getOperand(0)) 14015 return SDValue(); 14016 14017 int FirstElem = Ext1Op->getZExtValue(); 14018 int SecondElem = Ext2Op->getZExtValue(); 14019 int SubvecIdx; 14020 if (FirstElem == 0 && SecondElem == 1) 14021 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14022 else if (FirstElem == 2 && SecondElem == 3) 14023 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14024 else 14025 return SDValue(); 14026 14027 SDValue SrcVec = Ext1.getOperand(0); 14028 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14029 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14030 return DAG.getNode(NodeType, dl, MVT::v2f64, 14031 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14032 } 14033 14034 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14035 DAGCombinerInfo &DCI) const { 14036 assert((N->getOpcode() == ISD::SINT_TO_FP || 14037 N->getOpcode() == ISD::UINT_TO_FP) && 14038 "Need an int -> FP conversion node here"); 14039 14040 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14041 return SDValue(); 14042 14043 SelectionDAG &DAG = DCI.DAG; 14044 SDLoc dl(N); 14045 SDValue Op(N, 0); 14046 14047 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14048 // from the hardware. 14049 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14050 return SDValue(); 14051 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14052 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14053 return SDValue(); 14054 14055 SDValue FirstOperand(Op.getOperand(0)); 14056 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14057 (FirstOperand.getValueType() == MVT::i8 || 14058 FirstOperand.getValueType() == MVT::i16); 14059 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14060 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14061 bool DstDouble = Op.getValueType() == MVT::f64; 14062 unsigned ConvOp = Signed ? 14063 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14064 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14065 SDValue WidthConst = 14066 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14067 dl, false); 14068 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14069 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14070 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14071 DAG.getVTList(MVT::f64, MVT::Other), 14072 Ops, MVT::i8, LDN->getMemOperand()); 14073 14074 // For signed conversion, we need to sign-extend the value in the VSR 14075 if (Signed) { 14076 SDValue ExtOps[] = { Ld, WidthConst }; 14077 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14078 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14079 } else 14080 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14081 } 14082 14083 14084 // For i32 intermediate values, unfortunately, the conversion functions 14085 // leave the upper 32 bits of the value are undefined. Within the set of 14086 // scalar instructions, we have no method for zero- or sign-extending the 14087 // value. Thus, we cannot handle i32 intermediate values here. 14088 if (Op.getOperand(0).getValueType() == MVT::i32) 14089 return SDValue(); 14090 14091 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14092 "UINT_TO_FP is supported only with FPCVT"); 14093 14094 // If we have FCFIDS, then use it when converting to single-precision. 14095 // Otherwise, convert to double-precision and then round. 14096 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14097 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14098 : PPCISD::FCFIDS) 14099 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14100 : PPCISD::FCFID); 14101 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14102 ? MVT::f32 14103 : MVT::f64; 14104 14105 // If we're converting from a float, to an int, and back to a float again, 14106 // then we don't need the store/load pair at all. 14107 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14108 Subtarget.hasFPCVT()) || 14109 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14110 SDValue Src = Op.getOperand(0).getOperand(0); 14111 if (Src.getValueType() == MVT::f32) { 14112 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14113 DCI.AddToWorklist(Src.getNode()); 14114 } else if (Src.getValueType() != MVT::f64) { 14115 // Make sure that we don't pick up a ppc_fp128 source value. 14116 return SDValue(); 14117 } 14118 14119 unsigned FCTOp = 14120 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14121 PPCISD::FCTIDUZ; 14122 14123 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14124 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14125 14126 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14127 FP = DAG.getNode(ISD::FP_ROUND, dl, 14128 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14129 DCI.AddToWorklist(FP.getNode()); 14130 } 14131 14132 return FP; 14133 } 14134 14135 return SDValue(); 14136 } 14137 14138 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14139 // builtins) into loads with swaps. 14140 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14141 DAGCombinerInfo &DCI) const { 14142 SelectionDAG &DAG = DCI.DAG; 14143 SDLoc dl(N); 14144 SDValue Chain; 14145 SDValue Base; 14146 MachineMemOperand *MMO; 14147 14148 switch (N->getOpcode()) { 14149 default: 14150 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14151 case ISD::LOAD: { 14152 LoadSDNode *LD = cast<LoadSDNode>(N); 14153 Chain = LD->getChain(); 14154 Base = LD->getBasePtr(); 14155 MMO = LD->getMemOperand(); 14156 // If the MMO suggests this isn't a load of a full vector, leave 14157 // things alone. For a built-in, we have to make the change for 14158 // correctness, so if there is a size problem that will be a bug. 14159 if (MMO->getSize() < 16) 14160 return SDValue(); 14161 break; 14162 } 14163 case ISD::INTRINSIC_W_CHAIN: { 14164 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14165 Chain = Intrin->getChain(); 14166 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14167 // us what we want. Get operand 2 instead. 14168 Base = Intrin->getOperand(2); 14169 MMO = Intrin->getMemOperand(); 14170 break; 14171 } 14172 } 14173 14174 MVT VecTy = N->getValueType(0).getSimpleVT(); 14175 14176 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14177 // aligned and the type is a vector with elements up to 4 bytes 14178 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14179 VecTy.getScalarSizeInBits() <= 32) { 14180 return SDValue(); 14181 } 14182 14183 SDValue LoadOps[] = { Chain, Base }; 14184 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14185 DAG.getVTList(MVT::v2f64, MVT::Other), 14186 LoadOps, MVT::v2f64, MMO); 14187 14188 DCI.AddToWorklist(Load.getNode()); 14189 Chain = Load.getValue(1); 14190 SDValue Swap = DAG.getNode( 14191 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14192 DCI.AddToWorklist(Swap.getNode()); 14193 14194 // Add a bitcast if the resulting load type doesn't match v2f64. 14195 if (VecTy != MVT::v2f64) { 14196 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14197 DCI.AddToWorklist(N.getNode()); 14198 // Package {bitcast value, swap's chain} to match Load's shape. 14199 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14200 N, Swap.getValue(1)); 14201 } 14202 14203 return Swap; 14204 } 14205 14206 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14207 // builtins) into stores with swaps. 14208 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14209 DAGCombinerInfo &DCI) const { 14210 SelectionDAG &DAG = DCI.DAG; 14211 SDLoc dl(N); 14212 SDValue Chain; 14213 SDValue Base; 14214 unsigned SrcOpnd; 14215 MachineMemOperand *MMO; 14216 14217 switch (N->getOpcode()) { 14218 default: 14219 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14220 case ISD::STORE: { 14221 StoreSDNode *ST = cast<StoreSDNode>(N); 14222 Chain = ST->getChain(); 14223 Base = ST->getBasePtr(); 14224 MMO = ST->getMemOperand(); 14225 SrcOpnd = 1; 14226 // If the MMO suggests this isn't a store of a full vector, leave 14227 // things alone. For a built-in, we have to make the change for 14228 // correctness, so if there is a size problem that will be a bug. 14229 if (MMO->getSize() < 16) 14230 return SDValue(); 14231 break; 14232 } 14233 case ISD::INTRINSIC_VOID: { 14234 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14235 Chain = Intrin->getChain(); 14236 // Intrin->getBasePtr() oddly does not get what we want. 14237 Base = Intrin->getOperand(3); 14238 MMO = Intrin->getMemOperand(); 14239 SrcOpnd = 2; 14240 break; 14241 } 14242 } 14243 14244 SDValue Src = N->getOperand(SrcOpnd); 14245 MVT VecTy = Src.getValueType().getSimpleVT(); 14246 14247 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14248 // aligned and the type is a vector with elements up to 4 bytes 14249 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14250 VecTy.getScalarSizeInBits() <= 32) { 14251 return SDValue(); 14252 } 14253 14254 // All stores are done as v2f64 and possible bit cast. 14255 if (VecTy != MVT::v2f64) { 14256 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14257 DCI.AddToWorklist(Src.getNode()); 14258 } 14259 14260 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14261 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14262 DCI.AddToWorklist(Swap.getNode()); 14263 Chain = Swap.getValue(1); 14264 SDValue StoreOps[] = { Chain, Swap, Base }; 14265 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14266 DAG.getVTList(MVT::Other), 14267 StoreOps, VecTy, MMO); 14268 DCI.AddToWorklist(Store.getNode()); 14269 return Store; 14270 } 14271 14272 // Handle DAG combine for STORE (FP_TO_INT F). 14273 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14274 DAGCombinerInfo &DCI) const { 14275 14276 SelectionDAG &DAG = DCI.DAG; 14277 SDLoc dl(N); 14278 unsigned Opcode = N->getOperand(1).getOpcode(); 14279 14280 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14281 && "Not a FP_TO_INT Instruction!"); 14282 14283 SDValue Val = N->getOperand(1).getOperand(0); 14284 EVT Op1VT = N->getOperand(1).getValueType(); 14285 EVT ResVT = Val.getValueType(); 14286 14287 if (!isTypeLegal(ResVT)) 14288 return SDValue(); 14289 14290 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14291 bool ValidTypeForStoreFltAsInt = 14292 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14293 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14294 14295 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14296 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14297 return SDValue(); 14298 14299 // Extend f32 values to f64 14300 if (ResVT.getScalarSizeInBits() == 32) { 14301 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14302 DCI.AddToWorklist(Val.getNode()); 14303 } 14304 14305 // Set signed or unsigned conversion opcode. 14306 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14307 PPCISD::FP_TO_SINT_IN_VSR : 14308 PPCISD::FP_TO_UINT_IN_VSR; 14309 14310 Val = DAG.getNode(ConvOpcode, 14311 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14312 DCI.AddToWorklist(Val.getNode()); 14313 14314 // Set number of bytes being converted. 14315 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14316 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14317 DAG.getIntPtrConstant(ByteSize, dl, false), 14318 DAG.getValueType(Op1VT) }; 14319 14320 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14321 DAG.getVTList(MVT::Other), Ops, 14322 cast<StoreSDNode>(N)->getMemoryVT(), 14323 cast<StoreSDNode>(N)->getMemOperand()); 14324 14325 DCI.AddToWorklist(Val.getNode()); 14326 return Val; 14327 } 14328 14329 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14330 // Check that the source of the element keeps flipping 14331 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14332 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14333 for (int i = 1, e = Mask.size(); i < e; i++) { 14334 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14335 return false; 14336 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14337 return false; 14338 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14339 } 14340 return true; 14341 } 14342 14343 static bool isSplatBV(SDValue Op) { 14344 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14345 return false; 14346 SDValue FirstOp; 14347 14348 // Find first non-undef input. 14349 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14350 FirstOp = Op.getOperand(i); 14351 if (!FirstOp.isUndef()) 14352 break; 14353 } 14354 14355 // All inputs are undef or the same as the first non-undef input. 14356 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14357 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14358 return false; 14359 return true; 14360 } 14361 14362 static SDValue isScalarToVec(SDValue Op) { 14363 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14364 return Op; 14365 if (Op.getOpcode() != ISD::BITCAST) 14366 return SDValue(); 14367 Op = Op.getOperand(0); 14368 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14369 return Op; 14370 return SDValue(); 14371 } 14372 14373 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14374 int LHSMaxIdx, int RHSMinIdx, 14375 int RHSMaxIdx, int HalfVec) { 14376 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14377 int Idx = ShuffV[i]; 14378 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14379 ShuffV[i] += HalfVec; 14380 } 14381 return; 14382 } 14383 14384 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14385 // the original is: 14386 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14387 // In such a case, just change the shuffle mask to extract the element 14388 // from the permuted index. 14389 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14390 SDLoc dl(OrigSToV); 14391 EVT VT = OrigSToV.getValueType(); 14392 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14393 "Expecting a SCALAR_TO_VECTOR here"); 14394 SDValue Input = OrigSToV.getOperand(0); 14395 14396 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14397 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14398 SDValue OrigVector = Input.getOperand(0); 14399 14400 // Can't handle non-const element indices or different vector types 14401 // for the input to the extract and the output of the scalar_to_vector. 14402 if (Idx && VT == OrigVector.getValueType()) { 14403 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14404 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14405 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14406 } 14407 } 14408 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14409 OrigSToV.getOperand(0)); 14410 } 14411 14412 // On little endian subtargets, combine shuffles such as: 14413 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14414 // into: 14415 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14416 // because the latter can be matched to a single instruction merge. 14417 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14418 // to put the value into element zero. Adjust the shuffle mask so that the 14419 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14420 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14421 SelectionDAG &DAG) const { 14422 SDValue LHS = SVN->getOperand(0); 14423 SDValue RHS = SVN->getOperand(1); 14424 auto Mask = SVN->getMask(); 14425 int NumElts = LHS.getValueType().getVectorNumElements(); 14426 SDValue Res(SVN, 0); 14427 SDLoc dl(SVN); 14428 14429 // None of these combines are useful on big endian systems since the ISA 14430 // already has a big endian bias. 14431 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14432 return Res; 14433 14434 // If this is not a shuffle of a shuffle and the first element comes from 14435 // the second vector, canonicalize to the commuted form. This will make it 14436 // more likely to match one of the single instruction patterns. 14437 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14438 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14439 std::swap(LHS, RHS); 14440 Res = DAG.getCommutedVectorShuffle(*SVN); 14441 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14442 } 14443 14444 // Adjust the shuffle mask if either input vector comes from a 14445 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14446 // form (to prevent the need for a swap). 14447 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14448 SDValue SToVLHS = isScalarToVec(LHS); 14449 SDValue SToVRHS = isScalarToVec(RHS); 14450 if (SToVLHS || SToVRHS) { 14451 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14452 : SToVRHS.getValueType().getVectorNumElements(); 14453 int NumEltsOut = ShuffV.size(); 14454 14455 // Initially assume that neither input is permuted. These will be adjusted 14456 // accordingly if either input is. 14457 int LHSMaxIdx = -1; 14458 int RHSMinIdx = -1; 14459 int RHSMaxIdx = -1; 14460 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14461 14462 // Get the permuted scalar to vector nodes for the source(s) that come from 14463 // ISD::SCALAR_TO_VECTOR. 14464 if (SToVLHS) { 14465 // Set up the values for the shuffle vector fixup. 14466 LHSMaxIdx = NumEltsOut / NumEltsIn; 14467 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14468 if (SToVLHS.getValueType() != LHS.getValueType()) 14469 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14470 LHS = SToVLHS; 14471 } 14472 if (SToVRHS) { 14473 RHSMinIdx = NumEltsOut; 14474 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14475 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14476 if (SToVRHS.getValueType() != RHS.getValueType()) 14477 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14478 RHS = SToVRHS; 14479 } 14480 14481 // Fix up the shuffle mask to reflect where the desired element actually is. 14482 // The minimum and maximum indices that correspond to element zero for both 14483 // the LHS and RHS are computed and will control which shuffle mask entries 14484 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14485 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14486 // HalfVec to refer to the corresponding element in the permuted vector. 14487 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14488 HalfVec); 14489 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14490 14491 // We may have simplified away the shuffle. We won't be able to do anything 14492 // further with it here. 14493 if (!isa<ShuffleVectorSDNode>(Res)) 14494 return Res; 14495 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14496 } 14497 14498 // The common case after we commuted the shuffle is that the RHS is a splat 14499 // and we have elements coming in from the splat at indices that are not 14500 // conducive to using a merge. 14501 // Example: 14502 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14503 if (!isSplatBV(RHS)) 14504 return Res; 14505 14506 // We are looking for a mask such that all even elements are from 14507 // one vector and all odd elements from the other. 14508 if (!isAlternatingShuffMask(Mask, NumElts)) 14509 return Res; 14510 14511 // Adjust the mask so we are pulling in the same index from the splat 14512 // as the index from the interesting vector in consecutive elements. 14513 // Example (even elements from first vector): 14514 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14515 if (Mask[0] < NumElts) 14516 for (int i = 1, e = Mask.size(); i < e; i += 2) 14517 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14518 // Example (odd elements from first vector): 14519 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14520 else 14521 for (int i = 0, e = Mask.size(); i < e; i += 2) 14522 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14523 14524 // If the RHS has undefs, we need to remove them since we may have created 14525 // a shuffle that adds those instead of the splat value. 14526 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14527 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14528 14529 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14530 return Res; 14531 } 14532 14533 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14534 LSBaseSDNode *LSBase, 14535 DAGCombinerInfo &DCI) const { 14536 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14537 "Not a reverse memop pattern!"); 14538 14539 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14540 auto Mask = SVN->getMask(); 14541 int i = 0; 14542 auto I = Mask.rbegin(); 14543 auto E = Mask.rend(); 14544 14545 for (; I != E; ++I) { 14546 if (*I != i) 14547 return false; 14548 i++; 14549 } 14550 return true; 14551 }; 14552 14553 SelectionDAG &DAG = DCI.DAG; 14554 EVT VT = SVN->getValueType(0); 14555 14556 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14557 return SDValue(); 14558 14559 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14560 // See comment in PPCVSXSwapRemoval.cpp. 14561 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14562 if (!Subtarget.hasP9Vector()) 14563 return SDValue(); 14564 14565 if(!IsElementReverse(SVN)) 14566 return SDValue(); 14567 14568 if (LSBase->getOpcode() == ISD::LOAD) { 14569 SDLoc dl(SVN); 14570 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14571 return DAG.getMemIntrinsicNode( 14572 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14573 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14574 } 14575 14576 if (LSBase->getOpcode() == ISD::STORE) { 14577 SDLoc dl(LSBase); 14578 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14579 LSBase->getBasePtr()}; 14580 return DAG.getMemIntrinsicNode( 14581 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14582 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14583 } 14584 14585 llvm_unreachable("Expected a load or store node here"); 14586 } 14587 14588 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14589 DAGCombinerInfo &DCI) const { 14590 SelectionDAG &DAG = DCI.DAG; 14591 SDLoc dl(N); 14592 switch (N->getOpcode()) { 14593 default: break; 14594 case ISD::ADD: 14595 return combineADD(N, DCI); 14596 case ISD::SHL: 14597 return combineSHL(N, DCI); 14598 case ISD::SRA: 14599 return combineSRA(N, DCI); 14600 case ISD::SRL: 14601 return combineSRL(N, DCI); 14602 case ISD::MUL: 14603 return combineMUL(N, DCI); 14604 case ISD::FMA: 14605 case PPCISD::FNMSUB: 14606 return combineFMALike(N, DCI); 14607 case PPCISD::SHL: 14608 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14609 return N->getOperand(0); 14610 break; 14611 case PPCISD::SRL: 14612 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14613 return N->getOperand(0); 14614 break; 14615 case PPCISD::SRA: 14616 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14617 if (C->isNullValue() || // 0 >>s V -> 0. 14618 C->isAllOnesValue()) // -1 >>s V -> -1. 14619 return N->getOperand(0); 14620 } 14621 break; 14622 case ISD::SIGN_EXTEND: 14623 case ISD::ZERO_EXTEND: 14624 case ISD::ANY_EXTEND: 14625 return DAGCombineExtBoolTrunc(N, DCI); 14626 case ISD::TRUNCATE: 14627 return combineTRUNCATE(N, DCI); 14628 case ISD::SETCC: 14629 if (SDValue CSCC = combineSetCC(N, DCI)) 14630 return CSCC; 14631 LLVM_FALLTHROUGH; 14632 case ISD::SELECT_CC: 14633 return DAGCombineTruncBoolExt(N, DCI); 14634 case ISD::SINT_TO_FP: 14635 case ISD::UINT_TO_FP: 14636 return combineFPToIntToFP(N, DCI); 14637 case ISD::VECTOR_SHUFFLE: 14638 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14639 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14640 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14641 } 14642 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14643 case ISD::STORE: { 14644 14645 EVT Op1VT = N->getOperand(1).getValueType(); 14646 unsigned Opcode = N->getOperand(1).getOpcode(); 14647 14648 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14649 SDValue Val= combineStoreFPToInt(N, DCI); 14650 if (Val) 14651 return Val; 14652 } 14653 14654 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14655 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14656 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14657 if (Val) 14658 return Val; 14659 } 14660 14661 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14662 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14663 N->getOperand(1).getNode()->hasOneUse() && 14664 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14665 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14666 14667 // STBRX can only handle simple types and it makes no sense to store less 14668 // two bytes in byte-reversed order. 14669 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14670 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14671 break; 14672 14673 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14674 // Do an any-extend to 32-bits if this is a half-word input. 14675 if (BSwapOp.getValueType() == MVT::i16) 14676 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14677 14678 // If the type of BSWAP operand is wider than stored memory width 14679 // it need to be shifted to the right side before STBRX. 14680 if (Op1VT.bitsGT(mVT)) { 14681 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14682 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14683 DAG.getConstant(Shift, dl, MVT::i32)); 14684 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14685 if (Op1VT == MVT::i64) 14686 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14687 } 14688 14689 SDValue Ops[] = { 14690 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14691 }; 14692 return 14693 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14694 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14695 cast<StoreSDNode>(N)->getMemOperand()); 14696 } 14697 14698 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14699 // So it can increase the chance of CSE constant construction. 14700 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14701 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14702 // Need to sign-extended to 64-bits to handle negative values. 14703 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14704 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14705 MemVT.getSizeInBits()); 14706 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14707 14708 // DAG.getTruncStore() can't be used here because it doesn't accept 14709 // the general (base + offset) addressing mode. 14710 // So we use UpdateNodeOperands and setTruncatingStore instead. 14711 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14712 N->getOperand(3)); 14713 cast<StoreSDNode>(N)->setTruncatingStore(true); 14714 return SDValue(N, 0); 14715 } 14716 14717 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14718 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14719 if (Op1VT.isSimple()) { 14720 MVT StoreVT = Op1VT.getSimpleVT(); 14721 if (Subtarget.needsSwapsForVSXMemOps() && 14722 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14723 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14724 return expandVSXStoreForLE(N, DCI); 14725 } 14726 break; 14727 } 14728 case ISD::LOAD: { 14729 LoadSDNode *LD = cast<LoadSDNode>(N); 14730 EVT VT = LD->getValueType(0); 14731 14732 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14733 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14734 if (VT.isSimple()) { 14735 MVT LoadVT = VT.getSimpleVT(); 14736 if (Subtarget.needsSwapsForVSXMemOps() && 14737 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14738 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14739 return expandVSXLoadForLE(N, DCI); 14740 } 14741 14742 // We sometimes end up with a 64-bit integer load, from which we extract 14743 // two single-precision floating-point numbers. This happens with 14744 // std::complex<float>, and other similar structures, because of the way we 14745 // canonicalize structure copies. However, if we lack direct moves, 14746 // then the final bitcasts from the extracted integer values to the 14747 // floating-point numbers turn into store/load pairs. Even with direct moves, 14748 // just loading the two floating-point numbers is likely better. 14749 auto ReplaceTwoFloatLoad = [&]() { 14750 if (VT != MVT::i64) 14751 return false; 14752 14753 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14754 LD->isVolatile()) 14755 return false; 14756 14757 // We're looking for a sequence like this: 14758 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14759 // t16: i64 = srl t13, Constant:i32<32> 14760 // t17: i32 = truncate t16 14761 // t18: f32 = bitcast t17 14762 // t19: i32 = truncate t13 14763 // t20: f32 = bitcast t19 14764 14765 if (!LD->hasNUsesOfValue(2, 0)) 14766 return false; 14767 14768 auto UI = LD->use_begin(); 14769 while (UI.getUse().getResNo() != 0) ++UI; 14770 SDNode *Trunc = *UI++; 14771 while (UI.getUse().getResNo() != 0) ++UI; 14772 SDNode *RightShift = *UI; 14773 if (Trunc->getOpcode() != ISD::TRUNCATE) 14774 std::swap(Trunc, RightShift); 14775 14776 if (Trunc->getOpcode() != ISD::TRUNCATE || 14777 Trunc->getValueType(0) != MVT::i32 || 14778 !Trunc->hasOneUse()) 14779 return false; 14780 if (RightShift->getOpcode() != ISD::SRL || 14781 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14782 RightShift->getConstantOperandVal(1) != 32 || 14783 !RightShift->hasOneUse()) 14784 return false; 14785 14786 SDNode *Trunc2 = *RightShift->use_begin(); 14787 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14788 Trunc2->getValueType(0) != MVT::i32 || 14789 !Trunc2->hasOneUse()) 14790 return false; 14791 14792 SDNode *Bitcast = *Trunc->use_begin(); 14793 SDNode *Bitcast2 = *Trunc2->use_begin(); 14794 14795 if (Bitcast->getOpcode() != ISD::BITCAST || 14796 Bitcast->getValueType(0) != MVT::f32) 14797 return false; 14798 if (Bitcast2->getOpcode() != ISD::BITCAST || 14799 Bitcast2->getValueType(0) != MVT::f32) 14800 return false; 14801 14802 if (Subtarget.isLittleEndian()) 14803 std::swap(Bitcast, Bitcast2); 14804 14805 // Bitcast has the second float (in memory-layout order) and Bitcast2 14806 // has the first one. 14807 14808 SDValue BasePtr = LD->getBasePtr(); 14809 if (LD->isIndexed()) { 14810 assert(LD->getAddressingMode() == ISD::PRE_INC && 14811 "Non-pre-inc AM on PPC?"); 14812 BasePtr = 14813 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14814 LD->getOffset()); 14815 } 14816 14817 auto MMOFlags = 14818 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14819 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14820 LD->getPointerInfo(), LD->getAlignment(), 14821 MMOFlags, LD->getAAInfo()); 14822 SDValue AddPtr = 14823 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14824 BasePtr, DAG.getIntPtrConstant(4, dl)); 14825 SDValue FloatLoad2 = DAG.getLoad( 14826 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14827 LD->getPointerInfo().getWithOffset(4), 14828 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14829 14830 if (LD->isIndexed()) { 14831 // Note that DAGCombine should re-form any pre-increment load(s) from 14832 // what is produced here if that makes sense. 14833 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14834 } 14835 14836 DCI.CombineTo(Bitcast2, FloatLoad); 14837 DCI.CombineTo(Bitcast, FloatLoad2); 14838 14839 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14840 SDValue(FloatLoad2.getNode(), 1)); 14841 return true; 14842 }; 14843 14844 if (ReplaceTwoFloatLoad()) 14845 return SDValue(N, 0); 14846 14847 EVT MemVT = LD->getMemoryVT(); 14848 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14849 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14850 if (LD->isUnindexed() && VT.isVector() && 14851 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14852 // P8 and later hardware should just use LOAD. 14853 !Subtarget.hasP8Vector() && 14854 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14855 VT == MVT::v4f32))) && 14856 LD->getAlign() < ABIAlignment) { 14857 // This is a type-legal unaligned Altivec load. 14858 SDValue Chain = LD->getChain(); 14859 SDValue Ptr = LD->getBasePtr(); 14860 bool isLittleEndian = Subtarget.isLittleEndian(); 14861 14862 // This implements the loading of unaligned vectors as described in 14863 // the venerable Apple Velocity Engine overview. Specifically: 14864 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14865 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14866 // 14867 // The general idea is to expand a sequence of one or more unaligned 14868 // loads into an alignment-based permutation-control instruction (lvsl 14869 // or lvsr), a series of regular vector loads (which always truncate 14870 // their input address to an aligned address), and a series of 14871 // permutations. The results of these permutations are the requested 14872 // loaded values. The trick is that the last "extra" load is not taken 14873 // from the address you might suspect (sizeof(vector) bytes after the 14874 // last requested load), but rather sizeof(vector) - 1 bytes after the 14875 // last requested vector. The point of this is to avoid a page fault if 14876 // the base address happened to be aligned. This works because if the 14877 // base address is aligned, then adding less than a full vector length 14878 // will cause the last vector in the sequence to be (re)loaded. 14879 // Otherwise, the next vector will be fetched as you might suspect was 14880 // necessary. 14881 14882 // We might be able to reuse the permutation generation from 14883 // a different base address offset from this one by an aligned amount. 14884 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14885 // optimization later. 14886 Intrinsic::ID Intr, IntrLD, IntrPerm; 14887 MVT PermCntlTy, PermTy, LDTy; 14888 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14889 : Intrinsic::ppc_altivec_lvsl; 14890 IntrLD = Intrinsic::ppc_altivec_lvx; 14891 IntrPerm = Intrinsic::ppc_altivec_vperm; 14892 PermCntlTy = MVT::v16i8; 14893 PermTy = MVT::v4i32; 14894 LDTy = MVT::v4i32; 14895 14896 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14897 14898 // Create the new MMO for the new base load. It is like the original MMO, 14899 // but represents an area in memory almost twice the vector size centered 14900 // on the original address. If the address is unaligned, we might start 14901 // reading up to (sizeof(vector)-1) bytes below the address of the 14902 // original unaligned load. 14903 MachineFunction &MF = DAG.getMachineFunction(); 14904 MachineMemOperand *BaseMMO = 14905 MF.getMachineMemOperand(LD->getMemOperand(), 14906 -(long)MemVT.getStoreSize()+1, 14907 2*MemVT.getStoreSize()-1); 14908 14909 // Create the new base load. 14910 SDValue LDXIntID = 14911 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14912 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14913 SDValue BaseLoad = 14914 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14915 DAG.getVTList(PermTy, MVT::Other), 14916 BaseLoadOps, LDTy, BaseMMO); 14917 14918 // Note that the value of IncOffset (which is provided to the next 14919 // load's pointer info offset value, and thus used to calculate the 14920 // alignment), and the value of IncValue (which is actually used to 14921 // increment the pointer value) are different! This is because we 14922 // require the next load to appear to be aligned, even though it 14923 // is actually offset from the base pointer by a lesser amount. 14924 int IncOffset = VT.getSizeInBits() / 8; 14925 int IncValue = IncOffset; 14926 14927 // Walk (both up and down) the chain looking for another load at the real 14928 // (aligned) offset (the alignment of the other load does not matter in 14929 // this case). If found, then do not use the offset reduction trick, as 14930 // that will prevent the loads from being later combined (as they would 14931 // otherwise be duplicates). 14932 if (!findConsecutiveLoad(LD, DAG)) 14933 --IncValue; 14934 14935 SDValue Increment = 14936 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14937 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14938 14939 MachineMemOperand *ExtraMMO = 14940 MF.getMachineMemOperand(LD->getMemOperand(), 14941 1, 2*MemVT.getStoreSize()-1); 14942 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14943 SDValue ExtraLoad = 14944 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14945 DAG.getVTList(PermTy, MVT::Other), 14946 ExtraLoadOps, LDTy, ExtraMMO); 14947 14948 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14949 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14950 14951 // Because vperm has a big-endian bias, we must reverse the order 14952 // of the input vectors and complement the permute control vector 14953 // when generating little endian code. We have already handled the 14954 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14955 // and ExtraLoad here. 14956 SDValue Perm; 14957 if (isLittleEndian) 14958 Perm = BuildIntrinsicOp(IntrPerm, 14959 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14960 else 14961 Perm = BuildIntrinsicOp(IntrPerm, 14962 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14963 14964 if (VT != PermTy) 14965 Perm = Subtarget.hasAltivec() 14966 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14967 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14968 DAG.getTargetConstant(1, dl, MVT::i64)); 14969 // second argument is 1 because this rounding 14970 // is always exact. 14971 14972 // The output of the permutation is our loaded result, the TokenFactor is 14973 // our new chain. 14974 DCI.CombineTo(N, Perm, TF); 14975 return SDValue(N, 0); 14976 } 14977 } 14978 break; 14979 case ISD::INTRINSIC_WO_CHAIN: { 14980 bool isLittleEndian = Subtarget.isLittleEndian(); 14981 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14982 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14983 : Intrinsic::ppc_altivec_lvsl); 14984 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14985 SDValue Add = N->getOperand(1); 14986 14987 int Bits = 4 /* 16 byte alignment */; 14988 14989 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14990 APInt::getAllOnesValue(Bits /* alignment */) 14991 .zext(Add.getScalarValueSizeInBits()))) { 14992 SDNode *BasePtr = Add->getOperand(0).getNode(); 14993 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14994 UE = BasePtr->use_end(); 14995 UI != UE; ++UI) { 14996 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14997 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14998 IID) { 14999 // We've found another LVSL/LVSR, and this address is an aligned 15000 // multiple of that one. The results will be the same, so use the 15001 // one we've just found instead. 15002 15003 return SDValue(*UI, 0); 15004 } 15005 } 15006 } 15007 15008 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15009 SDNode *BasePtr = Add->getOperand(0).getNode(); 15010 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15011 UE = BasePtr->use_end(); UI != UE; ++UI) { 15012 if (UI->getOpcode() == ISD::ADD && 15013 isa<ConstantSDNode>(UI->getOperand(1)) && 15014 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15015 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 15016 (1ULL << Bits) == 0) { 15017 SDNode *OtherAdd = *UI; 15018 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 15019 VE = OtherAdd->use_end(); VI != VE; ++VI) { 15020 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15021 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 15022 return SDValue(*VI, 0); 15023 } 15024 } 15025 } 15026 } 15027 } 15028 } 15029 15030 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15031 // Expose the vabsduw/h/b opportunity for down stream 15032 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15033 (IID == Intrinsic::ppc_altivec_vmaxsw || 15034 IID == Intrinsic::ppc_altivec_vmaxsh || 15035 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15036 SDValue V1 = N->getOperand(1); 15037 SDValue V2 = N->getOperand(2); 15038 if ((V1.getSimpleValueType() == MVT::v4i32 || 15039 V1.getSimpleValueType() == MVT::v8i16 || 15040 V1.getSimpleValueType() == MVT::v16i8) && 15041 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15042 // (0-a, a) 15043 if (V1.getOpcode() == ISD::SUB && 15044 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15045 V1.getOperand(1) == V2) { 15046 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15047 } 15048 // (a, 0-a) 15049 if (V2.getOpcode() == ISD::SUB && 15050 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15051 V2.getOperand(1) == V1) { 15052 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15053 } 15054 // (x-y, y-x) 15055 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15056 V1.getOperand(0) == V2.getOperand(1) && 15057 V1.getOperand(1) == V2.getOperand(0)) { 15058 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15059 } 15060 } 15061 } 15062 } 15063 15064 break; 15065 case ISD::INTRINSIC_W_CHAIN: 15066 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15067 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15068 if (Subtarget.needsSwapsForVSXMemOps()) { 15069 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15070 default: 15071 break; 15072 case Intrinsic::ppc_vsx_lxvw4x: 15073 case Intrinsic::ppc_vsx_lxvd2x: 15074 return expandVSXLoadForLE(N, DCI); 15075 } 15076 } 15077 break; 15078 case ISD::INTRINSIC_VOID: 15079 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15080 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15081 if (Subtarget.needsSwapsForVSXMemOps()) { 15082 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15083 default: 15084 break; 15085 case Intrinsic::ppc_vsx_stxvw4x: 15086 case Intrinsic::ppc_vsx_stxvd2x: 15087 return expandVSXStoreForLE(N, DCI); 15088 } 15089 } 15090 break; 15091 case ISD::BSWAP: 15092 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15093 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 15094 N->getOperand(0).hasOneUse() && 15095 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15096 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 15097 N->getValueType(0) == MVT::i64))) { 15098 SDValue Load = N->getOperand(0); 15099 LoadSDNode *LD = cast<LoadSDNode>(Load); 15100 // Create the byte-swapping load. 15101 SDValue Ops[] = { 15102 LD->getChain(), // Chain 15103 LD->getBasePtr(), // Ptr 15104 DAG.getValueType(N->getValueType(0)) // VT 15105 }; 15106 SDValue BSLoad = 15107 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15108 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15109 MVT::i64 : MVT::i32, MVT::Other), 15110 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15111 15112 // If this is an i16 load, insert the truncate. 15113 SDValue ResVal = BSLoad; 15114 if (N->getValueType(0) == MVT::i16) 15115 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15116 15117 // First, combine the bswap away. This makes the value produced by the 15118 // load dead. 15119 DCI.CombineTo(N, ResVal); 15120 15121 // Next, combine the load away, we give it a bogus result value but a real 15122 // chain result. The result value is dead because the bswap is dead. 15123 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15124 15125 // Return N so it doesn't get rechecked! 15126 return SDValue(N, 0); 15127 } 15128 break; 15129 case PPCISD::VCMP: 15130 // If a VCMPo node already exists with exactly the same operands as this 15131 // node, use its result instead of this node (VCMPo computes both a CR6 and 15132 // a normal output). 15133 // 15134 if (!N->getOperand(0).hasOneUse() && 15135 !N->getOperand(1).hasOneUse() && 15136 !N->getOperand(2).hasOneUse()) { 15137 15138 // Scan all of the users of the LHS, looking for VCMPo's that match. 15139 SDNode *VCMPoNode = nullptr; 15140 15141 SDNode *LHSN = N->getOperand(0).getNode(); 15142 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15143 UI != E; ++UI) 15144 if (UI->getOpcode() == PPCISD::VCMPo && 15145 UI->getOperand(1) == N->getOperand(1) && 15146 UI->getOperand(2) == N->getOperand(2) && 15147 UI->getOperand(0) == N->getOperand(0)) { 15148 VCMPoNode = *UI; 15149 break; 15150 } 15151 15152 // If there is no VCMPo node, or if the flag value has a single use, don't 15153 // transform this. 15154 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 15155 break; 15156 15157 // Look at the (necessarily single) use of the flag value. If it has a 15158 // chain, this transformation is more complex. Note that multiple things 15159 // could use the value result, which we should ignore. 15160 SDNode *FlagUser = nullptr; 15161 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 15162 FlagUser == nullptr; ++UI) { 15163 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 15164 SDNode *User = *UI; 15165 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15166 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 15167 FlagUser = User; 15168 break; 15169 } 15170 } 15171 } 15172 15173 // If the user is a MFOCRF instruction, we know this is safe. 15174 // Otherwise we give up for right now. 15175 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15176 return SDValue(VCMPoNode, 0); 15177 } 15178 break; 15179 case ISD::BRCOND: { 15180 SDValue Cond = N->getOperand(1); 15181 SDValue Target = N->getOperand(2); 15182 15183 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15184 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15185 Intrinsic::loop_decrement) { 15186 15187 // We now need to make the intrinsic dead (it cannot be instruction 15188 // selected). 15189 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15190 assert(Cond.getNode()->hasOneUse() && 15191 "Counter decrement has more than one use"); 15192 15193 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15194 N->getOperand(0), Target); 15195 } 15196 } 15197 break; 15198 case ISD::BR_CC: { 15199 // If this is a branch on an altivec predicate comparison, lower this so 15200 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15201 // lowering is done pre-legalize, because the legalizer lowers the predicate 15202 // compare down to code that is difficult to reassemble. 15203 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15204 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15205 15206 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15207 // value. If so, pass-through the AND to get to the intrinsic. 15208 if (LHS.getOpcode() == ISD::AND && 15209 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15210 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15211 Intrinsic::loop_decrement && 15212 isa<ConstantSDNode>(LHS.getOperand(1)) && 15213 !isNullConstant(LHS.getOperand(1))) 15214 LHS = LHS.getOperand(0); 15215 15216 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15217 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15218 Intrinsic::loop_decrement && 15219 isa<ConstantSDNode>(RHS)) { 15220 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15221 "Counter decrement comparison is not EQ or NE"); 15222 15223 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15224 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15225 (CC == ISD::SETNE && !Val); 15226 15227 // We now need to make the intrinsic dead (it cannot be instruction 15228 // selected). 15229 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15230 assert(LHS.getNode()->hasOneUse() && 15231 "Counter decrement has more than one use"); 15232 15233 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15234 N->getOperand(0), N->getOperand(4)); 15235 } 15236 15237 int CompareOpc; 15238 bool isDot; 15239 15240 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15241 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15242 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15243 assert(isDot && "Can't compare against a vector result!"); 15244 15245 // If this is a comparison against something other than 0/1, then we know 15246 // that the condition is never/always true. 15247 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15248 if (Val != 0 && Val != 1) { 15249 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15250 return N->getOperand(0); 15251 // Always !=, turn it into an unconditional branch. 15252 return DAG.getNode(ISD::BR, dl, MVT::Other, 15253 N->getOperand(0), N->getOperand(4)); 15254 } 15255 15256 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15257 15258 // Create the PPCISD altivec 'dot' comparison node. 15259 SDValue Ops[] = { 15260 LHS.getOperand(2), // LHS of compare 15261 LHS.getOperand(3), // RHS of compare 15262 DAG.getConstant(CompareOpc, dl, MVT::i32) 15263 }; 15264 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15265 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15266 15267 // Unpack the result based on how the target uses it. 15268 PPC::Predicate CompOpc; 15269 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15270 default: // Can't happen, don't crash on invalid number though. 15271 case 0: // Branch on the value of the EQ bit of CR6. 15272 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15273 break; 15274 case 1: // Branch on the inverted value of the EQ bit of CR6. 15275 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15276 break; 15277 case 2: // Branch on the value of the LT bit of CR6. 15278 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15279 break; 15280 case 3: // Branch on the inverted value of the LT bit of CR6. 15281 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15282 break; 15283 } 15284 15285 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15286 DAG.getConstant(CompOpc, dl, MVT::i32), 15287 DAG.getRegister(PPC::CR6, MVT::i32), 15288 N->getOperand(4), CompNode.getValue(1)); 15289 } 15290 break; 15291 } 15292 case ISD::BUILD_VECTOR: 15293 return DAGCombineBuildVector(N, DCI); 15294 case ISD::ABS: 15295 return combineABS(N, DCI); 15296 case ISD::VSELECT: 15297 return combineVSelect(N, DCI); 15298 } 15299 15300 return SDValue(); 15301 } 15302 15303 SDValue 15304 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15305 SelectionDAG &DAG, 15306 SmallVectorImpl<SDNode *> &Created) const { 15307 // fold (sdiv X, pow2) 15308 EVT VT = N->getValueType(0); 15309 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15310 return SDValue(); 15311 if ((VT != MVT::i32 && VT != MVT::i64) || 15312 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15313 return SDValue(); 15314 15315 SDLoc DL(N); 15316 SDValue N0 = N->getOperand(0); 15317 15318 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15319 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15320 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15321 15322 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15323 Created.push_back(Op.getNode()); 15324 15325 if (IsNegPow2) { 15326 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15327 Created.push_back(Op.getNode()); 15328 } 15329 15330 return Op; 15331 } 15332 15333 //===----------------------------------------------------------------------===// 15334 // Inline Assembly Support 15335 //===----------------------------------------------------------------------===// 15336 15337 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15338 KnownBits &Known, 15339 const APInt &DemandedElts, 15340 const SelectionDAG &DAG, 15341 unsigned Depth) const { 15342 Known.resetAll(); 15343 switch (Op.getOpcode()) { 15344 default: break; 15345 case PPCISD::LBRX: { 15346 // lhbrx is known to have the top bits cleared out. 15347 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15348 Known.Zero = 0xFFFF0000; 15349 break; 15350 } 15351 case ISD::INTRINSIC_WO_CHAIN: { 15352 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15353 default: break; 15354 case Intrinsic::ppc_altivec_vcmpbfp_p: 15355 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15356 case Intrinsic::ppc_altivec_vcmpequb_p: 15357 case Intrinsic::ppc_altivec_vcmpequh_p: 15358 case Intrinsic::ppc_altivec_vcmpequw_p: 15359 case Intrinsic::ppc_altivec_vcmpequd_p: 15360 case Intrinsic::ppc_altivec_vcmpequq_p: 15361 case Intrinsic::ppc_altivec_vcmpgefp_p: 15362 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15363 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15364 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15365 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15366 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15367 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15368 case Intrinsic::ppc_altivec_vcmpgtub_p: 15369 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15370 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15371 case Intrinsic::ppc_altivec_vcmpgtud_p: 15372 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15373 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15374 break; 15375 } 15376 } 15377 } 15378 } 15379 15380 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15381 switch (Subtarget.getCPUDirective()) { 15382 default: break; 15383 case PPC::DIR_970: 15384 case PPC::DIR_PWR4: 15385 case PPC::DIR_PWR5: 15386 case PPC::DIR_PWR5X: 15387 case PPC::DIR_PWR6: 15388 case PPC::DIR_PWR6X: 15389 case PPC::DIR_PWR7: 15390 case PPC::DIR_PWR8: 15391 case PPC::DIR_PWR9: 15392 case PPC::DIR_PWR10: 15393 case PPC::DIR_PWR_FUTURE: { 15394 if (!ML) 15395 break; 15396 15397 if (!DisableInnermostLoopAlign32) { 15398 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15399 // so that we can decrease cache misses and branch-prediction misses. 15400 // Actual alignment of the loop will depend on the hotness check and other 15401 // logic in alignBlocks. 15402 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15403 return Align(32); 15404 } 15405 15406 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15407 15408 // For small loops (between 5 and 8 instructions), align to a 32-byte 15409 // boundary so that the entire loop fits in one instruction-cache line. 15410 uint64_t LoopSize = 0; 15411 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15412 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15413 LoopSize += TII->getInstSizeInBytes(*J); 15414 if (LoopSize > 32) 15415 break; 15416 } 15417 15418 if (LoopSize > 16 && LoopSize <= 32) 15419 return Align(32); 15420 15421 break; 15422 } 15423 } 15424 15425 return TargetLowering::getPrefLoopAlignment(ML); 15426 } 15427 15428 /// getConstraintType - Given a constraint, return the type of 15429 /// constraint it is for this target. 15430 PPCTargetLowering::ConstraintType 15431 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15432 if (Constraint.size() == 1) { 15433 switch (Constraint[0]) { 15434 default: break; 15435 case 'b': 15436 case 'r': 15437 case 'f': 15438 case 'd': 15439 case 'v': 15440 case 'y': 15441 return C_RegisterClass; 15442 case 'Z': 15443 // FIXME: While Z does indicate a memory constraint, it specifically 15444 // indicates an r+r address (used in conjunction with the 'y' modifier 15445 // in the replacement string). Currently, we're forcing the base 15446 // register to be r0 in the asm printer (which is interpreted as zero) 15447 // and forming the complete address in the second register. This is 15448 // suboptimal. 15449 return C_Memory; 15450 } 15451 } else if (Constraint == "wc") { // individual CR bits. 15452 return C_RegisterClass; 15453 } else if (Constraint == "wa" || Constraint == "wd" || 15454 Constraint == "wf" || Constraint == "ws" || 15455 Constraint == "wi" || Constraint == "ww") { 15456 return C_RegisterClass; // VSX registers. 15457 } 15458 return TargetLowering::getConstraintType(Constraint); 15459 } 15460 15461 /// Examine constraint type and operand type and determine a weight value. 15462 /// This object must already have been set up with the operand type 15463 /// and the current alternative constraint selected. 15464 TargetLowering::ConstraintWeight 15465 PPCTargetLowering::getSingleConstraintMatchWeight( 15466 AsmOperandInfo &info, const char *constraint) const { 15467 ConstraintWeight weight = CW_Invalid; 15468 Value *CallOperandVal = info.CallOperandVal; 15469 // If we don't have a value, we can't do a match, 15470 // but allow it at the lowest weight. 15471 if (!CallOperandVal) 15472 return CW_Default; 15473 Type *type = CallOperandVal->getType(); 15474 15475 // Look at the constraint type. 15476 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15477 return CW_Register; // an individual CR bit. 15478 else if ((StringRef(constraint) == "wa" || 15479 StringRef(constraint) == "wd" || 15480 StringRef(constraint) == "wf") && 15481 type->isVectorTy()) 15482 return CW_Register; 15483 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15484 return CW_Register; // just hold 64-bit integers data. 15485 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15486 return CW_Register; 15487 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15488 return CW_Register; 15489 15490 switch (*constraint) { 15491 default: 15492 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15493 break; 15494 case 'b': 15495 if (type->isIntegerTy()) 15496 weight = CW_Register; 15497 break; 15498 case 'f': 15499 if (type->isFloatTy()) 15500 weight = CW_Register; 15501 break; 15502 case 'd': 15503 if (type->isDoubleTy()) 15504 weight = CW_Register; 15505 break; 15506 case 'v': 15507 if (type->isVectorTy()) 15508 weight = CW_Register; 15509 break; 15510 case 'y': 15511 weight = CW_Register; 15512 break; 15513 case 'Z': 15514 weight = CW_Memory; 15515 break; 15516 } 15517 return weight; 15518 } 15519 15520 std::pair<unsigned, const TargetRegisterClass *> 15521 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15522 StringRef Constraint, 15523 MVT VT) const { 15524 if (Constraint.size() == 1) { 15525 // GCC RS6000 Constraint Letters 15526 switch (Constraint[0]) { 15527 case 'b': // R1-R31 15528 if (VT == MVT::i64 && Subtarget.isPPC64()) 15529 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15530 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15531 case 'r': // R0-R31 15532 if (VT == MVT::i64 && Subtarget.isPPC64()) 15533 return std::make_pair(0U, &PPC::G8RCRegClass); 15534 return std::make_pair(0U, &PPC::GPRCRegClass); 15535 // 'd' and 'f' constraints are both defined to be "the floating point 15536 // registers", where one is for 32-bit and the other for 64-bit. We don't 15537 // really care overly much here so just give them all the same reg classes. 15538 case 'd': 15539 case 'f': 15540 if (Subtarget.hasSPE()) { 15541 if (VT == MVT::f32 || VT == MVT::i32) 15542 return std::make_pair(0U, &PPC::GPRCRegClass); 15543 if (VT == MVT::f64 || VT == MVT::i64) 15544 return std::make_pair(0U, &PPC::SPERCRegClass); 15545 } else { 15546 if (VT == MVT::f32 || VT == MVT::i32) 15547 return std::make_pair(0U, &PPC::F4RCRegClass); 15548 if (VT == MVT::f64 || VT == MVT::i64) 15549 return std::make_pair(0U, &PPC::F8RCRegClass); 15550 } 15551 break; 15552 case 'v': 15553 if (Subtarget.hasAltivec()) 15554 return std::make_pair(0U, &PPC::VRRCRegClass); 15555 break; 15556 case 'y': // crrc 15557 return std::make_pair(0U, &PPC::CRRCRegClass); 15558 } 15559 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15560 // An individual CR bit. 15561 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15562 } else if ((Constraint == "wa" || Constraint == "wd" || 15563 Constraint == "wf" || Constraint == "wi") && 15564 Subtarget.hasVSX()) { 15565 return std::make_pair(0U, &PPC::VSRCRegClass); 15566 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15567 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15568 return std::make_pair(0U, &PPC::VSSRCRegClass); 15569 else 15570 return std::make_pair(0U, &PPC::VSFRCRegClass); 15571 } 15572 15573 // If we name a VSX register, we can't defer to the base class because it 15574 // will not recognize the correct register (their names will be VSL{0-31} 15575 // and V{0-31} so they won't match). So we match them here. 15576 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15577 int VSNum = atoi(Constraint.data() + 3); 15578 assert(VSNum >= 0 && VSNum <= 63 && 15579 "Attempted to access a vsr out of range"); 15580 if (VSNum < 32) 15581 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15582 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15583 } 15584 std::pair<unsigned, const TargetRegisterClass *> R = 15585 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15586 15587 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15588 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15589 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15590 // register. 15591 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15592 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15593 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15594 PPC::GPRCRegClass.contains(R.first)) 15595 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15596 PPC::sub_32, &PPC::G8RCRegClass), 15597 &PPC::G8RCRegClass); 15598 15599 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15600 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15601 R.first = PPC::CR0; 15602 R.second = &PPC::CRRCRegClass; 15603 } 15604 15605 return R; 15606 } 15607 15608 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15609 /// vector. If it is invalid, don't add anything to Ops. 15610 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15611 std::string &Constraint, 15612 std::vector<SDValue>&Ops, 15613 SelectionDAG &DAG) const { 15614 SDValue Result; 15615 15616 // Only support length 1 constraints. 15617 if (Constraint.length() > 1) return; 15618 15619 char Letter = Constraint[0]; 15620 switch (Letter) { 15621 default: break; 15622 case 'I': 15623 case 'J': 15624 case 'K': 15625 case 'L': 15626 case 'M': 15627 case 'N': 15628 case 'O': 15629 case 'P': { 15630 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15631 if (!CST) return; // Must be an immediate to match. 15632 SDLoc dl(Op); 15633 int64_t Value = CST->getSExtValue(); 15634 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15635 // numbers are printed as such. 15636 switch (Letter) { 15637 default: llvm_unreachable("Unknown constraint letter!"); 15638 case 'I': // "I" is a signed 16-bit constant. 15639 if (isInt<16>(Value)) 15640 Result = DAG.getTargetConstant(Value, dl, TCVT); 15641 break; 15642 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15643 if (isShiftedUInt<16, 16>(Value)) 15644 Result = DAG.getTargetConstant(Value, dl, TCVT); 15645 break; 15646 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15647 if (isShiftedInt<16, 16>(Value)) 15648 Result = DAG.getTargetConstant(Value, dl, TCVT); 15649 break; 15650 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15651 if (isUInt<16>(Value)) 15652 Result = DAG.getTargetConstant(Value, dl, TCVT); 15653 break; 15654 case 'M': // "M" is a constant that is greater than 31. 15655 if (Value > 31) 15656 Result = DAG.getTargetConstant(Value, dl, TCVT); 15657 break; 15658 case 'N': // "N" is a positive constant that is an exact power of two. 15659 if (Value > 0 && isPowerOf2_64(Value)) 15660 Result = DAG.getTargetConstant(Value, dl, TCVT); 15661 break; 15662 case 'O': // "O" is the constant zero. 15663 if (Value == 0) 15664 Result = DAG.getTargetConstant(Value, dl, TCVT); 15665 break; 15666 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15667 if (isInt<16>(-Value)) 15668 Result = DAG.getTargetConstant(Value, dl, TCVT); 15669 break; 15670 } 15671 break; 15672 } 15673 } 15674 15675 if (Result.getNode()) { 15676 Ops.push_back(Result); 15677 return; 15678 } 15679 15680 // Handle standard constraint letters. 15681 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15682 } 15683 15684 // isLegalAddressingMode - Return true if the addressing mode represented 15685 // by AM is legal for this target, for a load/store of the specified type. 15686 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15687 const AddrMode &AM, Type *Ty, 15688 unsigned AS, 15689 Instruction *I) const { 15690 // Vector type r+i form is supported since power9 as DQ form. We don't check 15691 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15692 // imm form is preferred and the offset can be adjusted to use imm form later 15693 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15694 // max offset to check legal addressing mode, we should be a little aggressive 15695 // to contain other offsets for that LSRUse. 15696 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15697 return false; 15698 15699 // PPC allows a sign-extended 16-bit immediate field. 15700 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15701 return false; 15702 15703 // No global is ever allowed as a base. 15704 if (AM.BaseGV) 15705 return false; 15706 15707 // PPC only support r+r, 15708 switch (AM.Scale) { 15709 case 0: // "r+i" or just "i", depending on HasBaseReg. 15710 break; 15711 case 1: 15712 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15713 return false; 15714 // Otherwise we have r+r or r+i. 15715 break; 15716 case 2: 15717 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15718 return false; 15719 // Allow 2*r as r+r. 15720 break; 15721 default: 15722 // No other scales are supported. 15723 return false; 15724 } 15725 15726 return true; 15727 } 15728 15729 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15730 SelectionDAG &DAG) const { 15731 MachineFunction &MF = DAG.getMachineFunction(); 15732 MachineFrameInfo &MFI = MF.getFrameInfo(); 15733 MFI.setReturnAddressIsTaken(true); 15734 15735 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15736 return SDValue(); 15737 15738 SDLoc dl(Op); 15739 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15740 15741 // Make sure the function does not optimize away the store of the RA to 15742 // the stack. 15743 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15744 FuncInfo->setLRStoreRequired(); 15745 bool isPPC64 = Subtarget.isPPC64(); 15746 auto PtrVT = getPointerTy(MF.getDataLayout()); 15747 15748 if (Depth > 0) { 15749 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15750 SDValue Offset = 15751 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15752 isPPC64 ? MVT::i64 : MVT::i32); 15753 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15754 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15755 MachinePointerInfo()); 15756 } 15757 15758 // Just load the return address off the stack. 15759 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15760 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15761 MachinePointerInfo()); 15762 } 15763 15764 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15765 SelectionDAG &DAG) const { 15766 SDLoc dl(Op); 15767 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15768 15769 MachineFunction &MF = DAG.getMachineFunction(); 15770 MachineFrameInfo &MFI = MF.getFrameInfo(); 15771 MFI.setFrameAddressIsTaken(true); 15772 15773 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15774 bool isPPC64 = PtrVT == MVT::i64; 15775 15776 // Naked functions never have a frame pointer, and so we use r1. For all 15777 // other functions, this decision must be delayed until during PEI. 15778 unsigned FrameReg; 15779 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15780 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15781 else 15782 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15783 15784 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15785 PtrVT); 15786 while (Depth--) 15787 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15788 FrameAddr, MachinePointerInfo()); 15789 return FrameAddr; 15790 } 15791 15792 // FIXME? Maybe this could be a TableGen attribute on some registers and 15793 // this table could be generated automatically from RegInfo. 15794 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15795 const MachineFunction &MF) const { 15796 bool isPPC64 = Subtarget.isPPC64(); 15797 15798 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15799 if (!is64Bit && VT != LLT::scalar(32)) 15800 report_fatal_error("Invalid register global variable type"); 15801 15802 Register Reg = StringSwitch<Register>(RegName) 15803 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15804 .Case("r2", isPPC64 ? Register() : PPC::R2) 15805 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15806 .Default(Register()); 15807 15808 if (Reg) 15809 return Reg; 15810 report_fatal_error("Invalid register name global variable"); 15811 } 15812 15813 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15814 // 32-bit SVR4 ABI access everything as got-indirect. 15815 if (Subtarget.is32BitELFABI()) 15816 return true; 15817 15818 // AIX accesses everything indirectly through the TOC, which is similar to 15819 // the GOT. 15820 if (Subtarget.isAIXABI()) 15821 return true; 15822 15823 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15824 // If it is small or large code model, module locals are accessed 15825 // indirectly by loading their address from .toc/.got. 15826 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15827 return true; 15828 15829 // JumpTable and BlockAddress are accessed as got-indirect. 15830 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15831 return true; 15832 15833 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15834 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15835 15836 return false; 15837 } 15838 15839 bool 15840 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15841 // The PowerPC target isn't yet aware of offsets. 15842 return false; 15843 } 15844 15845 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15846 const CallInst &I, 15847 MachineFunction &MF, 15848 unsigned Intrinsic) const { 15849 switch (Intrinsic) { 15850 case Intrinsic::ppc_altivec_lvx: 15851 case Intrinsic::ppc_altivec_lvxl: 15852 case Intrinsic::ppc_altivec_lvebx: 15853 case Intrinsic::ppc_altivec_lvehx: 15854 case Intrinsic::ppc_altivec_lvewx: 15855 case Intrinsic::ppc_vsx_lxvd2x: 15856 case Intrinsic::ppc_vsx_lxvw4x: { 15857 EVT VT; 15858 switch (Intrinsic) { 15859 case Intrinsic::ppc_altivec_lvebx: 15860 VT = MVT::i8; 15861 break; 15862 case Intrinsic::ppc_altivec_lvehx: 15863 VT = MVT::i16; 15864 break; 15865 case Intrinsic::ppc_altivec_lvewx: 15866 VT = MVT::i32; 15867 break; 15868 case Intrinsic::ppc_vsx_lxvd2x: 15869 VT = MVT::v2f64; 15870 break; 15871 default: 15872 VT = MVT::v4i32; 15873 break; 15874 } 15875 15876 Info.opc = ISD::INTRINSIC_W_CHAIN; 15877 Info.memVT = VT; 15878 Info.ptrVal = I.getArgOperand(0); 15879 Info.offset = -VT.getStoreSize()+1; 15880 Info.size = 2*VT.getStoreSize()-1; 15881 Info.align = Align(1); 15882 Info.flags = MachineMemOperand::MOLoad; 15883 return true; 15884 } 15885 case Intrinsic::ppc_altivec_stvx: 15886 case Intrinsic::ppc_altivec_stvxl: 15887 case Intrinsic::ppc_altivec_stvebx: 15888 case Intrinsic::ppc_altivec_stvehx: 15889 case Intrinsic::ppc_altivec_stvewx: 15890 case Intrinsic::ppc_vsx_stxvd2x: 15891 case Intrinsic::ppc_vsx_stxvw4x: { 15892 EVT VT; 15893 switch (Intrinsic) { 15894 case Intrinsic::ppc_altivec_stvebx: 15895 VT = MVT::i8; 15896 break; 15897 case Intrinsic::ppc_altivec_stvehx: 15898 VT = MVT::i16; 15899 break; 15900 case Intrinsic::ppc_altivec_stvewx: 15901 VT = MVT::i32; 15902 break; 15903 case Intrinsic::ppc_vsx_stxvd2x: 15904 VT = MVT::v2f64; 15905 break; 15906 default: 15907 VT = MVT::v4i32; 15908 break; 15909 } 15910 15911 Info.opc = ISD::INTRINSIC_VOID; 15912 Info.memVT = VT; 15913 Info.ptrVal = I.getArgOperand(1); 15914 Info.offset = -VT.getStoreSize()+1; 15915 Info.size = 2*VT.getStoreSize()-1; 15916 Info.align = Align(1); 15917 Info.flags = MachineMemOperand::MOStore; 15918 return true; 15919 } 15920 default: 15921 break; 15922 } 15923 15924 return false; 15925 } 15926 15927 /// It returns EVT::Other if the type should be determined using generic 15928 /// target-independent logic. 15929 EVT PPCTargetLowering::getOptimalMemOpType( 15930 const MemOp &Op, const AttributeList &FuncAttributes) const { 15931 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15932 // We should use Altivec/VSX loads and stores when available. For unaligned 15933 // addresses, unaligned VSX loads are only fast starting with the P8. 15934 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15935 (Op.isAligned(Align(16)) || 15936 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15937 return MVT::v4i32; 15938 } 15939 15940 if (Subtarget.isPPC64()) { 15941 return MVT::i64; 15942 } 15943 15944 return MVT::i32; 15945 } 15946 15947 /// Returns true if it is beneficial to convert a load of a constant 15948 /// to just the constant itself. 15949 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15950 Type *Ty) const { 15951 assert(Ty->isIntegerTy()); 15952 15953 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15954 return !(BitSize == 0 || BitSize > 64); 15955 } 15956 15957 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15958 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15959 return false; 15960 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15961 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15962 return NumBits1 == 64 && NumBits2 == 32; 15963 } 15964 15965 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15966 if (!VT1.isInteger() || !VT2.isInteger()) 15967 return false; 15968 unsigned NumBits1 = VT1.getSizeInBits(); 15969 unsigned NumBits2 = VT2.getSizeInBits(); 15970 return NumBits1 == 64 && NumBits2 == 32; 15971 } 15972 15973 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15974 // Generally speaking, zexts are not free, but they are free when they can be 15975 // folded with other operations. 15976 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15977 EVT MemVT = LD->getMemoryVT(); 15978 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15979 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15980 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15981 LD->getExtensionType() == ISD::ZEXTLOAD)) 15982 return true; 15983 } 15984 15985 // FIXME: Add other cases... 15986 // - 32-bit shifts with a zext to i64 15987 // - zext after ctlz, bswap, etc. 15988 // - zext after and by a constant mask 15989 15990 return TargetLowering::isZExtFree(Val, VT2); 15991 } 15992 15993 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15994 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15995 "invalid fpext types"); 15996 // Extending to float128 is not free. 15997 if (DestVT == MVT::f128) 15998 return false; 15999 return true; 16000 } 16001 16002 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16003 return isInt<16>(Imm) || isUInt<16>(Imm); 16004 } 16005 16006 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16007 return isInt<16>(Imm) || isUInt<16>(Imm); 16008 } 16009 16010 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 16011 unsigned, 16012 unsigned, 16013 MachineMemOperand::Flags, 16014 bool *Fast) const { 16015 if (DisablePPCUnaligned) 16016 return false; 16017 16018 // PowerPC supports unaligned memory access for simple non-vector types. 16019 // Although accessing unaligned addresses is not as efficient as accessing 16020 // aligned addresses, it is generally more efficient than manual expansion, 16021 // and generally only traps for software emulation when crossing page 16022 // boundaries. 16023 16024 if (!VT.isSimple()) 16025 return false; 16026 16027 if (VT.isFloatingPoint() && !VT.isVector() && 16028 !Subtarget.allowsUnalignedFPAccess()) 16029 return false; 16030 16031 if (VT.getSimpleVT().isVector()) { 16032 if (Subtarget.hasVSX()) { 16033 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16034 VT != MVT::v4f32 && VT != MVT::v4i32) 16035 return false; 16036 } else { 16037 return false; 16038 } 16039 } 16040 16041 if (VT == MVT::ppcf128) 16042 return false; 16043 16044 if (Fast) 16045 *Fast = true; 16046 16047 return true; 16048 } 16049 16050 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16051 EVT VT) const { 16052 return isFMAFasterThanFMulAndFAdd( 16053 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16054 } 16055 16056 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16057 Type *Ty) const { 16058 switch (Ty->getScalarType()->getTypeID()) { 16059 case Type::FloatTyID: 16060 case Type::DoubleTyID: 16061 return true; 16062 case Type::FP128TyID: 16063 return Subtarget.hasP9Vector(); 16064 default: 16065 return false; 16066 } 16067 } 16068 16069 // FIXME: add more patterns which are not profitable to hoist. 16070 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16071 if (!I->hasOneUse()) 16072 return true; 16073 16074 Instruction *User = I->user_back(); 16075 assert(User && "A single use instruction with no uses."); 16076 16077 switch (I->getOpcode()) { 16078 case Instruction::FMul: { 16079 // Don't break FMA, PowerPC prefers FMA. 16080 if (User->getOpcode() != Instruction::FSub && 16081 User->getOpcode() != Instruction::FAdd) 16082 return true; 16083 16084 const TargetOptions &Options = getTargetMachine().Options; 16085 const Function *F = I->getFunction(); 16086 const DataLayout &DL = F->getParent()->getDataLayout(); 16087 Type *Ty = User->getOperand(0)->getType(); 16088 16089 return !( 16090 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16091 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16092 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16093 } 16094 case Instruction::Load: { 16095 // Don't break "store (load float*)" pattern, this pattern will be combined 16096 // to "store (load int32)" in later InstCombine pass. See function 16097 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16098 // cycles than loading a 32 bit integer. 16099 LoadInst *LI = cast<LoadInst>(I); 16100 // For the loads that combineLoadToOperationType does nothing, like 16101 // ordered load, it should be profitable to hoist them. 16102 // For swifterror load, it can only be used for pointer to pointer type, so 16103 // later type check should get rid of this case. 16104 if (!LI->isUnordered()) 16105 return true; 16106 16107 if (User->getOpcode() != Instruction::Store) 16108 return true; 16109 16110 if (I->getType()->getTypeID() != Type::FloatTyID) 16111 return true; 16112 16113 return false; 16114 } 16115 default: 16116 return true; 16117 } 16118 return true; 16119 } 16120 16121 const MCPhysReg * 16122 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16123 // LR is a callee-save register, but we must treat it as clobbered by any call 16124 // site. Hence we include LR in the scratch registers, which are in turn added 16125 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16126 // to CTR, which is used by any indirect call. 16127 static const MCPhysReg ScratchRegs[] = { 16128 PPC::X12, PPC::LR8, PPC::CTR8, 0 16129 }; 16130 16131 return ScratchRegs; 16132 } 16133 16134 Register PPCTargetLowering::getExceptionPointerRegister( 16135 const Constant *PersonalityFn) const { 16136 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16137 } 16138 16139 Register PPCTargetLowering::getExceptionSelectorRegister( 16140 const Constant *PersonalityFn) const { 16141 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16142 } 16143 16144 bool 16145 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16146 EVT VT , unsigned DefinedValues) const { 16147 if (VT == MVT::v2i64) 16148 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16149 16150 if (Subtarget.hasVSX()) 16151 return true; 16152 16153 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16154 } 16155 16156 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16157 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16158 return TargetLowering::getSchedulingPreference(N); 16159 16160 return Sched::ILP; 16161 } 16162 16163 // Create a fast isel object. 16164 FastISel * 16165 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16166 const TargetLibraryInfo *LibInfo) const { 16167 return PPC::createFastISel(FuncInfo, LibInfo); 16168 } 16169 16170 // 'Inverted' means the FMA opcode after negating one multiplicand. 16171 // For example, (fma -a b c) = (fnmsub a b c) 16172 static unsigned invertFMAOpcode(unsigned Opc) { 16173 switch (Opc) { 16174 default: 16175 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16176 case ISD::FMA: 16177 return PPCISD::FNMSUB; 16178 case PPCISD::FNMSUB: 16179 return ISD::FMA; 16180 } 16181 } 16182 16183 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16184 bool LegalOps, bool OptForSize, 16185 NegatibleCost &Cost, 16186 unsigned Depth) const { 16187 if (Depth > SelectionDAG::MaxRecursionDepth) 16188 return SDValue(); 16189 16190 unsigned Opc = Op.getOpcode(); 16191 EVT VT = Op.getValueType(); 16192 SDNodeFlags Flags = Op.getNode()->getFlags(); 16193 16194 switch (Opc) { 16195 case PPCISD::FNMSUB: 16196 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16197 break; 16198 16199 const TargetOptions &Options = getTargetMachine().Options; 16200 SDValue N0 = Op.getOperand(0); 16201 SDValue N1 = Op.getOperand(1); 16202 SDValue N2 = Op.getOperand(2); 16203 SDLoc Loc(Op); 16204 16205 NegatibleCost N2Cost = NegatibleCost::Expensive; 16206 SDValue NegN2 = 16207 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16208 16209 if (!NegN2) 16210 return SDValue(); 16211 16212 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16213 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16214 // These transformations may change sign of zeroes. For example, 16215 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16216 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16217 // Try and choose the cheaper one to negate. 16218 NegatibleCost N0Cost = NegatibleCost::Expensive; 16219 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16220 N0Cost, Depth + 1); 16221 16222 NegatibleCost N1Cost = NegatibleCost::Expensive; 16223 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16224 N1Cost, Depth + 1); 16225 16226 if (NegN0 && N0Cost <= N1Cost) { 16227 Cost = std::min(N0Cost, N2Cost); 16228 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16229 } else if (NegN1) { 16230 Cost = std::min(N1Cost, N2Cost); 16231 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16232 } 16233 } 16234 16235 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16236 if (isOperationLegal(ISD::FMA, VT)) { 16237 Cost = N2Cost; 16238 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16239 } 16240 16241 break; 16242 } 16243 16244 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16245 Cost, Depth); 16246 } 16247 16248 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16249 bool PPCTargetLowering::useLoadStackGuardNode() const { 16250 if (!Subtarget.isTargetLinux()) 16251 return TargetLowering::useLoadStackGuardNode(); 16252 return true; 16253 } 16254 16255 // Override to disable global variable loading on Linux. 16256 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16257 if (!Subtarget.isTargetLinux()) 16258 return TargetLowering::insertSSPDeclarations(M); 16259 } 16260 16261 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16262 bool ForCodeSize) const { 16263 if (!VT.isSimple() || !Subtarget.hasVSX()) 16264 return false; 16265 16266 switch(VT.getSimpleVT().SimpleTy) { 16267 default: 16268 // For FP types that are currently not supported by PPC backend, return 16269 // false. Examples: f16, f80. 16270 return false; 16271 case MVT::f32: 16272 case MVT::f64: 16273 if (Subtarget.hasPrefixInstrs()) { 16274 // With prefixed instructions, we can materialize anything that can be 16275 // represented with a 32-bit immediate, not just positive zero. 16276 APFloat APFloatOfImm = Imm; 16277 return convertToNonDenormSingle(APFloatOfImm); 16278 } 16279 LLVM_FALLTHROUGH; 16280 case MVT::ppcf128: 16281 return Imm.isPosZero(); 16282 } 16283 } 16284 16285 // For vector shift operation op, fold 16286 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16287 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16288 SelectionDAG &DAG) { 16289 SDValue N0 = N->getOperand(0); 16290 SDValue N1 = N->getOperand(1); 16291 EVT VT = N0.getValueType(); 16292 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16293 unsigned Opcode = N->getOpcode(); 16294 unsigned TargetOpcode; 16295 16296 switch (Opcode) { 16297 default: 16298 llvm_unreachable("Unexpected shift operation"); 16299 case ISD::SHL: 16300 TargetOpcode = PPCISD::SHL; 16301 break; 16302 case ISD::SRL: 16303 TargetOpcode = PPCISD::SRL; 16304 break; 16305 case ISD::SRA: 16306 TargetOpcode = PPCISD::SRA; 16307 break; 16308 } 16309 16310 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16311 N1->getOpcode() == ISD::AND) 16312 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16313 if (Mask->getZExtValue() == OpSizeInBits - 1) 16314 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16315 16316 return SDValue(); 16317 } 16318 16319 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16320 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16321 return Value; 16322 16323 SDValue N0 = N->getOperand(0); 16324 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16325 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16326 N0.getOpcode() != ISD::SIGN_EXTEND || 16327 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16328 N->getValueType(0) != MVT::i64) 16329 return SDValue(); 16330 16331 // We can't save an operation here if the value is already extended, and 16332 // the existing shift is easier to combine. 16333 SDValue ExtsSrc = N0.getOperand(0); 16334 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16335 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16336 return SDValue(); 16337 16338 SDLoc DL(N0); 16339 SDValue ShiftBy = SDValue(CN1, 0); 16340 // We want the shift amount to be i32 on the extswli, but the shift could 16341 // have an i64. 16342 if (ShiftBy.getValueType() == MVT::i64) 16343 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16344 16345 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16346 ShiftBy); 16347 } 16348 16349 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16350 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16351 return Value; 16352 16353 return SDValue(); 16354 } 16355 16356 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16357 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16358 return Value; 16359 16360 return SDValue(); 16361 } 16362 16363 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16364 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16365 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16366 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16367 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16368 const PPCSubtarget &Subtarget) { 16369 if (!Subtarget.isPPC64()) 16370 return SDValue(); 16371 16372 SDValue LHS = N->getOperand(0); 16373 SDValue RHS = N->getOperand(1); 16374 16375 auto isZextOfCompareWithConstant = [](SDValue Op) { 16376 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16377 Op.getValueType() != MVT::i64) 16378 return false; 16379 16380 SDValue Cmp = Op.getOperand(0); 16381 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16382 Cmp.getOperand(0).getValueType() != MVT::i64) 16383 return false; 16384 16385 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16386 int64_t NegConstant = 0 - Constant->getSExtValue(); 16387 // Due to the limitations of the addi instruction, 16388 // -C is required to be [-32768, 32767]. 16389 return isInt<16>(NegConstant); 16390 } 16391 16392 return false; 16393 }; 16394 16395 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16396 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16397 16398 // If there is a pattern, canonicalize a zext operand to the RHS. 16399 if (LHSHasPattern && !RHSHasPattern) 16400 std::swap(LHS, RHS); 16401 else if (!LHSHasPattern && !RHSHasPattern) 16402 return SDValue(); 16403 16404 SDLoc DL(N); 16405 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16406 SDValue Cmp = RHS.getOperand(0); 16407 SDValue Z = Cmp.getOperand(0); 16408 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16409 16410 assert(Constant && "Constant Should not be a null pointer."); 16411 int64_t NegConstant = 0 - Constant->getSExtValue(); 16412 16413 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16414 default: break; 16415 case ISD::SETNE: { 16416 // when C == 0 16417 // --> addze X, (addic Z, -1).carry 16418 // / 16419 // add X, (zext(setne Z, C))-- 16420 // \ when -32768 <= -C <= 32767 && C != 0 16421 // --> addze X, (addic (addi Z, -C), -1).carry 16422 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16423 DAG.getConstant(NegConstant, DL, MVT::i64)); 16424 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16425 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16426 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16427 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16428 SDValue(Addc.getNode(), 1)); 16429 } 16430 case ISD::SETEQ: { 16431 // when C == 0 16432 // --> addze X, (subfic Z, 0).carry 16433 // / 16434 // add X, (zext(sete Z, C))-- 16435 // \ when -32768 <= -C <= 32767 && C != 0 16436 // --> addze X, (subfic (addi Z, -C), 0).carry 16437 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16438 DAG.getConstant(NegConstant, DL, MVT::i64)); 16439 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16440 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16441 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16442 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16443 SDValue(Subc.getNode(), 1)); 16444 } 16445 } 16446 16447 return SDValue(); 16448 } 16449 16450 // Transform 16451 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16452 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16453 // In this case both C1 and C2 must be known constants. 16454 // C1+C2 must fit into a 34 bit signed integer. 16455 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16456 const PPCSubtarget &Subtarget) { 16457 if (!Subtarget.isUsingPCRelativeCalls()) 16458 return SDValue(); 16459 16460 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16461 // If we find that node try to cast the Global Address and the Constant. 16462 SDValue LHS = N->getOperand(0); 16463 SDValue RHS = N->getOperand(1); 16464 16465 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16466 std::swap(LHS, RHS); 16467 16468 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16469 return SDValue(); 16470 16471 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16472 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16473 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16474 16475 // Check that both casts succeeded. 16476 if (!GSDN || !ConstNode) 16477 return SDValue(); 16478 16479 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16480 SDLoc DL(GSDN); 16481 16482 // The signed int offset needs to fit in 34 bits. 16483 if (!isInt<34>(NewOffset)) 16484 return SDValue(); 16485 16486 // The new global address is a copy of the old global address except 16487 // that it has the updated Offset. 16488 SDValue GA = 16489 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16490 NewOffset, GSDN->getTargetFlags()); 16491 SDValue MatPCRel = 16492 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16493 return MatPCRel; 16494 } 16495 16496 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16497 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16498 return Value; 16499 16500 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16501 return Value; 16502 16503 return SDValue(); 16504 } 16505 16506 // Detect TRUNCATE operations on bitcasts of float128 values. 16507 // What we are looking for here is the situtation where we extract a subset 16508 // of bits from a 128 bit float. 16509 // This can be of two forms: 16510 // 1) BITCAST of f128 feeding TRUNCATE 16511 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16512 // The reason this is required is because we do not have a legal i128 type 16513 // and so we want to prevent having to store the f128 and then reload part 16514 // of it. 16515 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16516 DAGCombinerInfo &DCI) const { 16517 // If we are using CRBits then try that first. 16518 if (Subtarget.useCRBits()) { 16519 // Check if CRBits did anything and return that if it did. 16520 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16521 return CRTruncValue; 16522 } 16523 16524 SDLoc dl(N); 16525 SDValue Op0 = N->getOperand(0); 16526 16527 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16528 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16529 EVT VT = N->getValueType(0); 16530 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16531 return SDValue(); 16532 SDValue Sub = Op0.getOperand(0); 16533 if (Sub.getOpcode() == ISD::SUB) { 16534 SDValue SubOp0 = Sub.getOperand(0); 16535 SDValue SubOp1 = Sub.getOperand(1); 16536 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16537 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16538 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16539 SubOp1.getOperand(0), 16540 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16541 } 16542 } 16543 } 16544 16545 // Looking for a truncate of i128 to i64. 16546 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16547 return SDValue(); 16548 16549 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16550 16551 // SRL feeding TRUNCATE. 16552 if (Op0.getOpcode() == ISD::SRL) { 16553 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16554 // The right shift has to be by 64 bits. 16555 if (!ConstNode || ConstNode->getZExtValue() != 64) 16556 return SDValue(); 16557 16558 // Switch the element number to extract. 16559 EltToExtract = EltToExtract ? 0 : 1; 16560 // Update Op0 past the SRL. 16561 Op0 = Op0.getOperand(0); 16562 } 16563 16564 // BITCAST feeding a TRUNCATE possibly via SRL. 16565 if (Op0.getOpcode() == ISD::BITCAST && 16566 Op0.getValueType() == MVT::i128 && 16567 Op0.getOperand(0).getValueType() == MVT::f128) { 16568 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16569 return DCI.DAG.getNode( 16570 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16571 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16572 } 16573 return SDValue(); 16574 } 16575 16576 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16577 SelectionDAG &DAG = DCI.DAG; 16578 16579 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16580 if (!ConstOpOrElement) 16581 return SDValue(); 16582 16583 // An imul is usually smaller than the alternative sequence for legal type. 16584 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16585 isOperationLegal(ISD::MUL, N->getValueType(0))) 16586 return SDValue(); 16587 16588 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16589 switch (this->Subtarget.getCPUDirective()) { 16590 default: 16591 // TODO: enhance the condition for subtarget before pwr8 16592 return false; 16593 case PPC::DIR_PWR8: 16594 // type mul add shl 16595 // scalar 4 1 1 16596 // vector 7 2 2 16597 return true; 16598 case PPC::DIR_PWR9: 16599 case PPC::DIR_PWR10: 16600 case PPC::DIR_PWR_FUTURE: 16601 // type mul add shl 16602 // scalar 5 2 2 16603 // vector 7 2 2 16604 16605 // The cycle RATIO of related operations are showed as a table above. 16606 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16607 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16608 // are 4, it is always profitable; but for 3 instrs patterns 16609 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16610 // So we should only do it for vector type. 16611 return IsAddOne && IsNeg ? VT.isVector() : true; 16612 } 16613 }; 16614 16615 EVT VT = N->getValueType(0); 16616 SDLoc DL(N); 16617 16618 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16619 bool IsNeg = MulAmt.isNegative(); 16620 APInt MulAmtAbs = MulAmt.abs(); 16621 16622 if ((MulAmtAbs - 1).isPowerOf2()) { 16623 // (mul x, 2^N + 1) => (add (shl x, N), x) 16624 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16625 16626 if (!IsProfitable(IsNeg, true, VT)) 16627 return SDValue(); 16628 16629 SDValue Op0 = N->getOperand(0); 16630 SDValue Op1 = 16631 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16632 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16633 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16634 16635 if (!IsNeg) 16636 return Res; 16637 16638 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16639 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16640 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16641 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16642 16643 if (!IsProfitable(IsNeg, false, VT)) 16644 return SDValue(); 16645 16646 SDValue Op0 = N->getOperand(0); 16647 SDValue Op1 = 16648 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16649 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16650 16651 if (!IsNeg) 16652 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16653 else 16654 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16655 16656 } else { 16657 return SDValue(); 16658 } 16659 } 16660 16661 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16662 // in combiner since we need to check SD flags and other subtarget features. 16663 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16664 DAGCombinerInfo &DCI) const { 16665 SDValue N0 = N->getOperand(0); 16666 SDValue N1 = N->getOperand(1); 16667 SDValue N2 = N->getOperand(2); 16668 SDNodeFlags Flags = N->getFlags(); 16669 EVT VT = N->getValueType(0); 16670 SelectionDAG &DAG = DCI.DAG; 16671 const TargetOptions &Options = getTargetMachine().Options; 16672 unsigned Opc = N->getOpcode(); 16673 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16674 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16675 SDLoc Loc(N); 16676 16677 if (!isOperationLegal(ISD::FMA, VT)) 16678 return SDValue(); 16679 16680 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16681 // since (fnmsub a b c)=-0 while c-ab=+0. 16682 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16683 return SDValue(); 16684 16685 // (fma (fneg a) b c) => (fnmsub a b c) 16686 // (fnmsub (fneg a) b c) => (fma a b c) 16687 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16688 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16689 16690 // (fma a (fneg b) c) => (fnmsub a b c) 16691 // (fnmsub a (fneg b) c) => (fma a b c) 16692 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16693 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16694 16695 return SDValue(); 16696 } 16697 16698 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16699 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16700 if (!Subtarget.is64BitELFABI()) 16701 return false; 16702 16703 // If not a tail call then no need to proceed. 16704 if (!CI->isTailCall()) 16705 return false; 16706 16707 // If sibling calls have been disabled and tail-calls aren't guaranteed 16708 // there is no reason to duplicate. 16709 auto &TM = getTargetMachine(); 16710 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16711 return false; 16712 16713 // Can't tail call a function called indirectly, or if it has variadic args. 16714 const Function *Callee = CI->getCalledFunction(); 16715 if (!Callee || Callee->isVarArg()) 16716 return false; 16717 16718 // Make sure the callee and caller calling conventions are eligible for tco. 16719 const Function *Caller = CI->getParent()->getParent(); 16720 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16721 CI->getCallingConv())) 16722 return false; 16723 16724 // If the function is local then we have a good chance at tail-calling it 16725 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16726 } 16727 16728 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16729 if (!Subtarget.hasVSX()) 16730 return false; 16731 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16732 return true; 16733 return VT == MVT::f32 || VT == MVT::f64 || 16734 VT == MVT::v4f32 || VT == MVT::v2f64; 16735 } 16736 16737 bool PPCTargetLowering:: 16738 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16739 const Value *Mask = AndI.getOperand(1); 16740 // If the mask is suitable for andi. or andis. we should sink the and. 16741 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16742 // Can't handle constants wider than 64-bits. 16743 if (CI->getBitWidth() > 64) 16744 return false; 16745 int64_t ConstVal = CI->getZExtValue(); 16746 return isUInt<16>(ConstVal) || 16747 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16748 } 16749 16750 // For non-constant masks, we can always use the record-form and. 16751 return true; 16752 } 16753 16754 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16755 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16756 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16757 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16758 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16759 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16760 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16761 assert(Subtarget.hasP9Altivec() && 16762 "Only combine this when P9 altivec supported!"); 16763 EVT VT = N->getValueType(0); 16764 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16765 return SDValue(); 16766 16767 SelectionDAG &DAG = DCI.DAG; 16768 SDLoc dl(N); 16769 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16770 // Even for signed integers, if it's known to be positive (as signed 16771 // integer) due to zero-extended inputs. 16772 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16773 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16774 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16775 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16776 (SubOpcd1 == ISD::ZERO_EXTEND || 16777 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16778 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16779 N->getOperand(0)->getOperand(0), 16780 N->getOperand(0)->getOperand(1), 16781 DAG.getTargetConstant(0, dl, MVT::i32)); 16782 } 16783 16784 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16785 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16786 N->getOperand(0).hasOneUse()) { 16787 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16788 N->getOperand(0)->getOperand(0), 16789 N->getOperand(0)->getOperand(1), 16790 DAG.getTargetConstant(1, dl, MVT::i32)); 16791 } 16792 } 16793 16794 return SDValue(); 16795 } 16796 16797 // For type v4i32/v8ii16/v16i8, transform 16798 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16799 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16800 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16801 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16802 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16803 DAGCombinerInfo &DCI) const { 16804 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16805 assert(Subtarget.hasP9Altivec() && 16806 "Only combine this when P9 altivec supported!"); 16807 16808 SelectionDAG &DAG = DCI.DAG; 16809 SDLoc dl(N); 16810 SDValue Cond = N->getOperand(0); 16811 SDValue TrueOpnd = N->getOperand(1); 16812 SDValue FalseOpnd = N->getOperand(2); 16813 EVT VT = N->getOperand(1).getValueType(); 16814 16815 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16816 FalseOpnd.getOpcode() != ISD::SUB) 16817 return SDValue(); 16818 16819 // ABSD only available for type v4i32/v8i16/v16i8 16820 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16821 return SDValue(); 16822 16823 // At least to save one more dependent computation 16824 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16825 return SDValue(); 16826 16827 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16828 16829 // Can only handle unsigned comparison here 16830 switch (CC) { 16831 default: 16832 return SDValue(); 16833 case ISD::SETUGT: 16834 case ISD::SETUGE: 16835 break; 16836 case ISD::SETULT: 16837 case ISD::SETULE: 16838 std::swap(TrueOpnd, FalseOpnd); 16839 break; 16840 } 16841 16842 SDValue CmpOpnd1 = Cond.getOperand(0); 16843 SDValue CmpOpnd2 = Cond.getOperand(1); 16844 16845 // SETCC CmpOpnd1 CmpOpnd2 cond 16846 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16847 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16848 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16849 TrueOpnd.getOperand(1) == CmpOpnd2 && 16850 FalseOpnd.getOperand(0) == CmpOpnd2 && 16851 FalseOpnd.getOperand(1) == CmpOpnd1) { 16852 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16853 CmpOpnd1, CmpOpnd2, 16854 DAG.getTargetConstant(0, dl, MVT::i32)); 16855 } 16856 16857 return SDValue(); 16858 } 16859