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 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 switch (IntrinsicID) { 10420 case Intrinsic::thread_pointer: 10421 // Reads the thread pointer register, used for __builtin_thread_pointer. 10422 if (Subtarget.isPPC64()) 10423 return DAG.getRegister(PPC::X13, MVT::i64); 10424 return DAG.getRegister(PPC::R2, MVT::i32); 10425 10426 case Intrinsic::ppc_mma_disassemble_acc: 10427 case Intrinsic::ppc_mma_disassemble_pair: { 10428 int NumVecs = 2; 10429 SDValue WideVec = Op.getOperand(1); 10430 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10431 NumVecs = 4; 10432 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10433 } 10434 SmallVector<SDValue, 4> RetOps; 10435 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10436 SDValue Extract = DAG.getNode( 10437 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10438 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10439 : VecNo, 10440 dl, MVT::i64)); 10441 RetOps.push_back(Extract); 10442 } 10443 return DAG.getMergeValues(RetOps, dl); 10444 } 10445 } 10446 10447 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10448 // opcode number of the comparison. 10449 int CompareOpc; 10450 bool isDot; 10451 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10452 return SDValue(); // Don't custom lower most intrinsics. 10453 10454 // If this is a non-dot comparison, make the VCMP node and we are done. 10455 if (!isDot) { 10456 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10457 Op.getOperand(1), Op.getOperand(2), 10458 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10459 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10460 } 10461 10462 // Create the PPCISD altivec 'dot' comparison node. 10463 SDValue Ops[] = { 10464 Op.getOperand(2), // LHS 10465 Op.getOperand(3), // RHS 10466 DAG.getConstant(CompareOpc, dl, MVT::i32) 10467 }; 10468 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10469 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10470 10471 // Now that we have the comparison, emit a copy from the CR to a GPR. 10472 // This is flagged to the above dot comparison. 10473 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10474 DAG.getRegister(PPC::CR6, MVT::i32), 10475 CompNode.getValue(1)); 10476 10477 // Unpack the result based on how the target uses it. 10478 unsigned BitNo; // Bit # of CR6. 10479 bool InvertBit; // Invert result? 10480 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10481 default: // Can't happen, don't crash on invalid number though. 10482 case 0: // Return the value of the EQ bit of CR6. 10483 BitNo = 0; InvertBit = false; 10484 break; 10485 case 1: // Return the inverted value of the EQ bit of CR6. 10486 BitNo = 0; InvertBit = true; 10487 break; 10488 case 2: // Return the value of the LT bit of CR6. 10489 BitNo = 2; InvertBit = false; 10490 break; 10491 case 3: // Return the inverted value of the LT bit of CR6. 10492 BitNo = 2; InvertBit = true; 10493 break; 10494 } 10495 10496 // Shift the bit into the low position. 10497 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10498 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10499 // Isolate the bit. 10500 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10501 DAG.getConstant(1, dl, MVT::i32)); 10502 10503 // If we are supposed to, toggle the bit. 10504 if (InvertBit) 10505 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10506 DAG.getConstant(1, dl, MVT::i32)); 10507 return Flags; 10508 } 10509 10510 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10511 SelectionDAG &DAG) const { 10512 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10513 // the beginning of the argument list. 10514 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10515 SDLoc DL(Op); 10516 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10517 case Intrinsic::ppc_cfence: { 10518 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10519 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10520 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10521 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10522 Op.getOperand(ArgStart + 1)), 10523 Op.getOperand(0)), 10524 0); 10525 } 10526 default: 10527 break; 10528 } 10529 return SDValue(); 10530 } 10531 10532 // Lower scalar BSWAP64 to xxbrd. 10533 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10534 SDLoc dl(Op); 10535 // MTVSRDD 10536 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10537 Op.getOperand(0)); 10538 // XXBRD 10539 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10540 // MFVSRD 10541 int VectorIndex = 0; 10542 if (Subtarget.isLittleEndian()) 10543 VectorIndex = 1; 10544 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10545 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10546 return Op; 10547 } 10548 10549 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10550 // compared to a value that is atomically loaded (atomic loads zero-extend). 10551 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10552 SelectionDAG &DAG) const { 10553 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10554 "Expecting an atomic compare-and-swap here."); 10555 SDLoc dl(Op); 10556 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10557 EVT MemVT = AtomicNode->getMemoryVT(); 10558 if (MemVT.getSizeInBits() >= 32) 10559 return Op; 10560 10561 SDValue CmpOp = Op.getOperand(2); 10562 // If this is already correctly zero-extended, leave it alone. 10563 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10564 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10565 return Op; 10566 10567 // Clear the high bits of the compare operand. 10568 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10569 SDValue NewCmpOp = 10570 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10571 DAG.getConstant(MaskVal, dl, MVT::i32)); 10572 10573 // Replace the existing compare operand with the properly zero-extended one. 10574 SmallVector<SDValue, 4> Ops; 10575 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10576 Ops.push_back(AtomicNode->getOperand(i)); 10577 Ops[2] = NewCmpOp; 10578 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10579 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10580 auto NodeTy = 10581 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10582 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10583 } 10584 10585 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10586 SelectionDAG &DAG) const { 10587 SDLoc dl(Op); 10588 // Create a stack slot that is 16-byte aligned. 10589 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10590 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10591 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10592 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10593 10594 // Store the input value into Value#0 of the stack slot. 10595 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10596 MachinePointerInfo()); 10597 // Load it out. 10598 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10599 } 10600 10601 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10602 SelectionDAG &DAG) const { 10603 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10604 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10605 10606 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10607 // We have legal lowering for constant indices but not for variable ones. 10608 if (!C) 10609 return SDValue(); 10610 10611 EVT VT = Op.getValueType(); 10612 SDLoc dl(Op); 10613 SDValue V1 = Op.getOperand(0); 10614 SDValue V2 = Op.getOperand(1); 10615 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10616 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10617 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10618 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10619 unsigned InsertAtElement = C->getZExtValue(); 10620 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10621 if (Subtarget.isLittleEndian()) { 10622 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10623 } 10624 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10625 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10626 } 10627 return Op; 10628 } 10629 10630 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10631 SelectionDAG &DAG) const { 10632 SDLoc dl(Op); 10633 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10634 SDValue LoadChain = LN->getChain(); 10635 SDValue BasePtr = LN->getBasePtr(); 10636 EVT VT = Op.getValueType(); 10637 10638 if (VT != MVT::v256i1 && VT != MVT::v512i1) 10639 return Op; 10640 10641 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10642 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 10643 // 2 or 4 vsx registers. 10644 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 10645 "Type unsupported without MMA"); 10646 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10647 "Type unsupported without paired vector support"); 10648 Align Alignment = LN->getAlign(); 10649 SmallVector<SDValue, 4> Loads; 10650 SmallVector<SDValue, 4> LoadChains; 10651 unsigned NumVecs = VT.getSizeInBits() / 128; 10652 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10653 SDValue Load = 10654 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 10655 LN->getPointerInfo().getWithOffset(Idx * 16), 10656 commonAlignment(Alignment, Idx * 16), 10657 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10658 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10659 DAG.getConstant(16, dl, BasePtr.getValueType())); 10660 Loads.push_back(Load); 10661 LoadChains.push_back(Load.getValue(1)); 10662 } 10663 if (Subtarget.isLittleEndian()) { 10664 std::reverse(Loads.begin(), Loads.end()); 10665 std::reverse(LoadChains.begin(), LoadChains.end()); 10666 } 10667 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10668 SDValue Value = 10669 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 10670 dl, VT, Loads); 10671 SDValue RetOps[] = {Value, TF}; 10672 return DAG.getMergeValues(RetOps, dl); 10673 } 10674 10675 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10676 SelectionDAG &DAG) const { 10677 SDLoc dl(Op); 10678 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10679 SDValue StoreChain = SN->getChain(); 10680 SDValue BasePtr = SN->getBasePtr(); 10681 SDValue Value = SN->getValue(); 10682 EVT StoreVT = Value.getValueType(); 10683 10684 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 10685 return Op; 10686 10687 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 10688 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 10689 // underlying registers individually. 10690 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 10691 "Type unsupported without MMA"); 10692 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 10693 "Type unsupported without paired vector support"); 10694 Align Alignment = SN->getAlign(); 10695 SmallVector<SDValue, 4> Stores; 10696 unsigned NumVecs = 2; 10697 if (StoreVT == MVT::v512i1) { 10698 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 10699 NumVecs = 4; 10700 } 10701 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 10702 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 10703 SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 10704 DAG.getConstant(VecNum, dl, MVT::i64)); 10705 SDValue Store = 10706 DAG.getStore(StoreChain, dl, Elt, BasePtr, 10707 SN->getPointerInfo().getWithOffset(Idx * 16), 10708 commonAlignment(Alignment, Idx * 16), 10709 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10710 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10711 DAG.getConstant(16, dl, BasePtr.getValueType())); 10712 Stores.push_back(Store); 10713 } 10714 SDValue TF = DAG.getTokenFactor(dl, Stores); 10715 return TF; 10716 } 10717 10718 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10719 SDLoc dl(Op); 10720 if (Op.getValueType() == MVT::v4i32) { 10721 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10722 10723 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10724 // +16 as shift amt. 10725 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10726 SDValue RHSSwap = // = vrlw RHS, 16 10727 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10728 10729 // Shrinkify inputs to v8i16. 10730 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10731 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10732 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10733 10734 // Low parts multiplied together, generating 32-bit results (we ignore the 10735 // top parts). 10736 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10737 LHS, RHS, DAG, dl, MVT::v4i32); 10738 10739 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10740 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10741 // Shift the high parts up 16 bits. 10742 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10743 Neg16, DAG, dl); 10744 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10745 } else if (Op.getValueType() == MVT::v16i8) { 10746 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10747 bool isLittleEndian = Subtarget.isLittleEndian(); 10748 10749 // Multiply the even 8-bit parts, producing 16-bit sums. 10750 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10751 LHS, RHS, DAG, dl, MVT::v8i16); 10752 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10753 10754 // Multiply the odd 8-bit parts, producing 16-bit sums. 10755 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10756 LHS, RHS, DAG, dl, MVT::v8i16); 10757 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10758 10759 // Merge the results together. Because vmuleub and vmuloub are 10760 // instructions with a big-endian bias, we must reverse the 10761 // element numbering and reverse the meaning of "odd" and "even" 10762 // when generating little endian code. 10763 int Ops[16]; 10764 for (unsigned i = 0; i != 8; ++i) { 10765 if (isLittleEndian) { 10766 Ops[i*2 ] = 2*i; 10767 Ops[i*2+1] = 2*i+16; 10768 } else { 10769 Ops[i*2 ] = 2*i+1; 10770 Ops[i*2+1] = 2*i+1+16; 10771 } 10772 } 10773 if (isLittleEndian) 10774 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10775 else 10776 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10777 } else { 10778 llvm_unreachable("Unknown mul to lower!"); 10779 } 10780 } 10781 10782 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10783 10784 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10785 10786 EVT VT = Op.getValueType(); 10787 assert(VT.isVector() && 10788 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10789 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10790 VT == MVT::v16i8) && 10791 "Unexpected vector element type!"); 10792 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10793 "Current subtarget doesn't support smax v2i64!"); 10794 10795 // For vector abs, it can be lowered to: 10796 // abs x 10797 // ==> 10798 // y = -x 10799 // smax(x, y) 10800 10801 SDLoc dl(Op); 10802 SDValue X = Op.getOperand(0); 10803 SDValue Zero = DAG.getConstant(0, dl, VT); 10804 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10805 10806 // SMAX patch https://reviews.llvm.org/D47332 10807 // hasn't landed yet, so use intrinsic first here. 10808 // TODO: Should use SMAX directly once SMAX patch landed 10809 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10810 if (VT == MVT::v2i64) 10811 BifID = Intrinsic::ppc_altivec_vmaxsd; 10812 else if (VT == MVT::v8i16) 10813 BifID = Intrinsic::ppc_altivec_vmaxsh; 10814 else if (VT == MVT::v16i8) 10815 BifID = Intrinsic::ppc_altivec_vmaxsb; 10816 10817 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10818 } 10819 10820 // Custom lowering for fpext vf32 to v2f64 10821 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10822 10823 assert(Op.getOpcode() == ISD::FP_EXTEND && 10824 "Should only be called for ISD::FP_EXTEND"); 10825 10826 // FIXME: handle extends from half precision float vectors on P9. 10827 // We only want to custom lower an extend from v2f32 to v2f64. 10828 if (Op.getValueType() != MVT::v2f64 || 10829 Op.getOperand(0).getValueType() != MVT::v2f32) 10830 return SDValue(); 10831 10832 SDLoc dl(Op); 10833 SDValue Op0 = Op.getOperand(0); 10834 10835 switch (Op0.getOpcode()) { 10836 default: 10837 return SDValue(); 10838 case ISD::EXTRACT_SUBVECTOR: { 10839 assert(Op0.getNumOperands() == 2 && 10840 isa<ConstantSDNode>(Op0->getOperand(1)) && 10841 "Node should have 2 operands with second one being a constant!"); 10842 10843 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10844 return SDValue(); 10845 10846 // Custom lower is only done for high or low doubleword. 10847 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10848 if (Idx % 2 != 0) 10849 return SDValue(); 10850 10851 // Since input is v4f32, at this point Idx is either 0 or 2. 10852 // Shift to get the doubleword position we want. 10853 int DWord = Idx >> 1; 10854 10855 // High and low word positions are different on little endian. 10856 if (Subtarget.isLittleEndian()) 10857 DWord ^= 0x1; 10858 10859 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10860 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10861 } 10862 case ISD::FADD: 10863 case ISD::FMUL: 10864 case ISD::FSUB: { 10865 SDValue NewLoad[2]; 10866 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10867 // Ensure both input are loads. 10868 SDValue LdOp = Op0.getOperand(i); 10869 if (LdOp.getOpcode() != ISD::LOAD) 10870 return SDValue(); 10871 // Generate new load node. 10872 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10873 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10874 NewLoad[i] = DAG.getMemIntrinsicNode( 10875 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10876 LD->getMemoryVT(), LD->getMemOperand()); 10877 } 10878 SDValue NewOp = 10879 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10880 NewLoad[1], Op0.getNode()->getFlags()); 10881 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10882 DAG.getConstant(0, dl, MVT::i32)); 10883 } 10884 case ISD::LOAD: { 10885 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10886 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10887 SDValue NewLd = DAG.getMemIntrinsicNode( 10888 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10889 LD->getMemoryVT(), LD->getMemOperand()); 10890 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10891 DAG.getConstant(0, dl, MVT::i32)); 10892 } 10893 } 10894 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10895 } 10896 10897 /// LowerOperation - Provide custom lowering hooks for some operations. 10898 /// 10899 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10900 switch (Op.getOpcode()) { 10901 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10902 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10903 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10904 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10905 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10906 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10907 case ISD::SETCC: return LowerSETCC(Op, DAG); 10908 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10909 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10910 10911 // Variable argument lowering. 10912 case ISD::VASTART: return LowerVASTART(Op, DAG); 10913 case ISD::VAARG: return LowerVAARG(Op, DAG); 10914 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10915 10916 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10917 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10918 case ISD::GET_DYNAMIC_AREA_OFFSET: 10919 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10920 10921 // Exception handling lowering. 10922 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10923 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10924 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10925 10926 case ISD::LOAD: return LowerLOAD(Op, DAG); 10927 case ISD::STORE: return LowerSTORE(Op, DAG); 10928 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10929 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10930 case ISD::STRICT_FP_TO_UINT: 10931 case ISD::STRICT_FP_TO_SINT: 10932 case ISD::FP_TO_UINT: 10933 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10934 case ISD::STRICT_UINT_TO_FP: 10935 case ISD::STRICT_SINT_TO_FP: 10936 case ISD::UINT_TO_FP: 10937 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10938 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10939 10940 // Lower 64-bit shifts. 10941 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10942 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10943 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10944 10945 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10946 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10947 10948 // Vector-related lowering. 10949 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10950 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10951 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10952 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10953 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10954 case ISD::MUL: return LowerMUL(Op, DAG); 10955 case ISD::ABS: return LowerABS(Op, DAG); 10956 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10957 case ISD::ROTL: return LowerROTL(Op, DAG); 10958 10959 // For counter-based loop handling. 10960 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10961 10962 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10963 10964 // Frame & Return address. 10965 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10966 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10967 10968 case ISD::INTRINSIC_VOID: 10969 return LowerINTRINSIC_VOID(Op, DAG); 10970 case ISD::BSWAP: 10971 return LowerBSWAP(Op, DAG); 10972 case ISD::ATOMIC_CMP_SWAP: 10973 return LowerATOMIC_CMP_SWAP(Op, DAG); 10974 } 10975 } 10976 10977 void PPCTargetLowering::LowerOperationWrapper(SDNode *N, 10978 SmallVectorImpl<SDValue> &Results, 10979 SelectionDAG &DAG) const { 10980 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10981 10982 if (!Res.getNode()) 10983 return; 10984 10985 // Take the return value as-is if original node has only one result. 10986 if (N->getNumValues() == 1) { 10987 Results.push_back(Res); 10988 return; 10989 } 10990 10991 // New node should have the same number of results. 10992 assert((N->getNumValues() == Res->getNumValues()) && 10993 "Lowering returned the wrong number of results!"); 10994 10995 for (unsigned i = 0; i < N->getNumValues(); ++i) 10996 Results.push_back(Res.getValue(i)); 10997 } 10998 10999 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11000 SmallVectorImpl<SDValue>&Results, 11001 SelectionDAG &DAG) const { 11002 SDLoc dl(N); 11003 switch (N->getOpcode()) { 11004 default: 11005 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11006 case ISD::READCYCLECOUNTER: { 11007 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11008 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11009 11010 Results.push_back( 11011 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11012 Results.push_back(RTB.getValue(2)); 11013 break; 11014 } 11015 case ISD::INTRINSIC_W_CHAIN: { 11016 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11017 Intrinsic::loop_decrement) 11018 break; 11019 11020 assert(N->getValueType(0) == MVT::i1 && 11021 "Unexpected result type for CTR decrement intrinsic"); 11022 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11023 N->getValueType(0)); 11024 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11025 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11026 N->getOperand(1)); 11027 11028 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11029 Results.push_back(NewInt.getValue(1)); 11030 break; 11031 } 11032 case ISD::VAARG: { 11033 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11034 return; 11035 11036 EVT VT = N->getValueType(0); 11037 11038 if (VT == MVT::i64) { 11039 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11040 11041 Results.push_back(NewNode); 11042 Results.push_back(NewNode.getValue(1)); 11043 } 11044 return; 11045 } 11046 case ISD::STRICT_FP_TO_SINT: 11047 case ISD::STRICT_FP_TO_UINT: 11048 case ISD::FP_TO_SINT: 11049 case ISD::FP_TO_UINT: 11050 // LowerFP_TO_INT() can only handle f32 and f64. 11051 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11052 MVT::ppcf128) 11053 return; 11054 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 11055 return; 11056 case ISD::TRUNCATE: { 11057 if (!N->getValueType(0).isVector()) 11058 return; 11059 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11060 if (Lowered) 11061 Results.push_back(Lowered); 11062 return; 11063 } 11064 case ISD::FSHL: 11065 case ISD::FSHR: 11066 // Don't handle funnel shifts here. 11067 return; 11068 case ISD::BITCAST: 11069 // Don't handle bitcast here. 11070 return; 11071 case ISD::FP_EXTEND: 11072 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11073 if (Lowered) 11074 Results.push_back(Lowered); 11075 return; 11076 } 11077 } 11078 11079 //===----------------------------------------------------------------------===// 11080 // Other Lowering Code 11081 //===----------------------------------------------------------------------===// 11082 11083 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 11084 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11085 Function *Func = Intrinsic::getDeclaration(M, Id); 11086 return Builder.CreateCall(Func, {}); 11087 } 11088 11089 // The mappings for emitLeading/TrailingFence is taken from 11090 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11091 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11092 Instruction *Inst, 11093 AtomicOrdering Ord) const { 11094 if (Ord == AtomicOrdering::SequentiallyConsistent) 11095 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11096 if (isReleaseOrStronger(Ord)) 11097 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11098 return nullptr; 11099 } 11100 11101 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11102 Instruction *Inst, 11103 AtomicOrdering Ord) const { 11104 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11105 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11106 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11107 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11108 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11109 return Builder.CreateCall( 11110 Intrinsic::getDeclaration( 11111 Builder.GetInsertBlock()->getParent()->getParent(), 11112 Intrinsic::ppc_cfence, {Inst->getType()}), 11113 {Inst}); 11114 // FIXME: Can use isync for rmw operation. 11115 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11116 } 11117 return nullptr; 11118 } 11119 11120 MachineBasicBlock * 11121 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11122 unsigned AtomicSize, 11123 unsigned BinOpcode, 11124 unsigned CmpOpcode, 11125 unsigned CmpPred) const { 11126 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11127 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11128 11129 auto LoadMnemonic = PPC::LDARX; 11130 auto StoreMnemonic = PPC::STDCX; 11131 switch (AtomicSize) { 11132 default: 11133 llvm_unreachable("Unexpected size of atomic entity"); 11134 case 1: 11135 LoadMnemonic = PPC::LBARX; 11136 StoreMnemonic = PPC::STBCX; 11137 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11138 break; 11139 case 2: 11140 LoadMnemonic = PPC::LHARX; 11141 StoreMnemonic = PPC::STHCX; 11142 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11143 break; 11144 case 4: 11145 LoadMnemonic = PPC::LWARX; 11146 StoreMnemonic = PPC::STWCX; 11147 break; 11148 case 8: 11149 LoadMnemonic = PPC::LDARX; 11150 StoreMnemonic = PPC::STDCX; 11151 break; 11152 } 11153 11154 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11155 MachineFunction *F = BB->getParent(); 11156 MachineFunction::iterator It = ++BB->getIterator(); 11157 11158 Register dest = MI.getOperand(0).getReg(); 11159 Register ptrA = MI.getOperand(1).getReg(); 11160 Register ptrB = MI.getOperand(2).getReg(); 11161 Register incr = MI.getOperand(3).getReg(); 11162 DebugLoc dl = MI.getDebugLoc(); 11163 11164 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11165 MachineBasicBlock *loop2MBB = 11166 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11167 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11168 F->insert(It, loopMBB); 11169 if (CmpOpcode) 11170 F->insert(It, loop2MBB); 11171 F->insert(It, exitMBB); 11172 exitMBB->splice(exitMBB->begin(), BB, 11173 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11174 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11175 11176 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11177 Register TmpReg = (!BinOpcode) ? incr : 11178 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11179 : &PPC::GPRCRegClass); 11180 11181 // thisMBB: 11182 // ... 11183 // fallthrough --> loopMBB 11184 BB->addSuccessor(loopMBB); 11185 11186 // loopMBB: 11187 // l[wd]arx dest, ptr 11188 // add r0, dest, incr 11189 // st[wd]cx. r0, ptr 11190 // bne- loopMBB 11191 // fallthrough --> exitMBB 11192 11193 // For max/min... 11194 // loopMBB: 11195 // l[wd]arx dest, ptr 11196 // cmpl?[wd] incr, dest 11197 // bgt exitMBB 11198 // loop2MBB: 11199 // st[wd]cx. dest, ptr 11200 // bne- loopMBB 11201 // fallthrough --> exitMBB 11202 11203 BB = loopMBB; 11204 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11205 .addReg(ptrA).addReg(ptrB); 11206 if (BinOpcode) 11207 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11208 if (CmpOpcode) { 11209 // Signed comparisons of byte or halfword values must be sign-extended. 11210 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11211 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11212 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11213 ExtReg).addReg(dest); 11214 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11215 .addReg(incr).addReg(ExtReg); 11216 } else 11217 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11218 .addReg(incr).addReg(dest); 11219 11220 BuildMI(BB, dl, TII->get(PPC::BCC)) 11221 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11222 BB->addSuccessor(loop2MBB); 11223 BB->addSuccessor(exitMBB); 11224 BB = loop2MBB; 11225 } 11226 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11227 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11228 BuildMI(BB, dl, TII->get(PPC::BCC)) 11229 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11230 BB->addSuccessor(loopMBB); 11231 BB->addSuccessor(exitMBB); 11232 11233 // exitMBB: 11234 // ... 11235 BB = exitMBB; 11236 return BB; 11237 } 11238 11239 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11240 MachineInstr &MI, MachineBasicBlock *BB, 11241 bool is8bit, // operation 11242 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11243 // If we support part-word atomic mnemonics, just use them 11244 if (Subtarget.hasPartwordAtomics()) 11245 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11246 CmpPred); 11247 11248 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11249 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11250 // In 64 bit mode we have to use 64 bits for addresses, even though the 11251 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11252 // registers without caring whether they're 32 or 64, but here we're 11253 // doing actual arithmetic on the addresses. 11254 bool is64bit = Subtarget.isPPC64(); 11255 bool isLittleEndian = Subtarget.isLittleEndian(); 11256 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11257 11258 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11259 MachineFunction *F = BB->getParent(); 11260 MachineFunction::iterator It = ++BB->getIterator(); 11261 11262 Register dest = MI.getOperand(0).getReg(); 11263 Register ptrA = MI.getOperand(1).getReg(); 11264 Register ptrB = MI.getOperand(2).getReg(); 11265 Register incr = MI.getOperand(3).getReg(); 11266 DebugLoc dl = MI.getDebugLoc(); 11267 11268 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11269 MachineBasicBlock *loop2MBB = 11270 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11271 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11272 F->insert(It, loopMBB); 11273 if (CmpOpcode) 11274 F->insert(It, loop2MBB); 11275 F->insert(It, exitMBB); 11276 exitMBB->splice(exitMBB->begin(), BB, 11277 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11278 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11279 11280 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11281 const TargetRegisterClass *RC = 11282 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11283 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11284 11285 Register PtrReg = RegInfo.createVirtualRegister(RC); 11286 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11287 Register ShiftReg = 11288 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11289 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11290 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11291 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11292 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11293 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11294 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11295 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11296 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11297 Register Ptr1Reg; 11298 Register TmpReg = 11299 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11300 11301 // thisMBB: 11302 // ... 11303 // fallthrough --> loopMBB 11304 BB->addSuccessor(loopMBB); 11305 11306 // The 4-byte load must be aligned, while a char or short may be 11307 // anywhere in the word. Hence all this nasty bookkeeping code. 11308 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11309 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11310 // xori shift, shift1, 24 [16] 11311 // rlwinm ptr, ptr1, 0, 0, 29 11312 // slw incr2, incr, shift 11313 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11314 // slw mask, mask2, shift 11315 // loopMBB: 11316 // lwarx tmpDest, ptr 11317 // add tmp, tmpDest, incr2 11318 // andc tmp2, tmpDest, mask 11319 // and tmp3, tmp, mask 11320 // or tmp4, tmp3, tmp2 11321 // stwcx. tmp4, ptr 11322 // bne- loopMBB 11323 // fallthrough --> exitMBB 11324 // srw dest, tmpDest, shift 11325 if (ptrA != ZeroReg) { 11326 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11327 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11328 .addReg(ptrA) 11329 .addReg(ptrB); 11330 } else { 11331 Ptr1Reg = ptrB; 11332 } 11333 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11334 // mode. 11335 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11336 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11337 .addImm(3) 11338 .addImm(27) 11339 .addImm(is8bit ? 28 : 27); 11340 if (!isLittleEndian) 11341 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11342 .addReg(Shift1Reg) 11343 .addImm(is8bit ? 24 : 16); 11344 if (is64bit) 11345 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11346 .addReg(Ptr1Reg) 11347 .addImm(0) 11348 .addImm(61); 11349 else 11350 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11351 .addReg(Ptr1Reg) 11352 .addImm(0) 11353 .addImm(0) 11354 .addImm(29); 11355 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11356 if (is8bit) 11357 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11358 else { 11359 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11360 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11361 .addReg(Mask3Reg) 11362 .addImm(65535); 11363 } 11364 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11365 .addReg(Mask2Reg) 11366 .addReg(ShiftReg); 11367 11368 BB = loopMBB; 11369 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11370 .addReg(ZeroReg) 11371 .addReg(PtrReg); 11372 if (BinOpcode) 11373 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11374 .addReg(Incr2Reg) 11375 .addReg(TmpDestReg); 11376 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11377 .addReg(TmpDestReg) 11378 .addReg(MaskReg); 11379 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11380 if (CmpOpcode) { 11381 // For unsigned comparisons, we can directly compare the shifted values. 11382 // For signed comparisons we shift and sign extend. 11383 Register SReg = RegInfo.createVirtualRegister(GPRC); 11384 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11385 .addReg(TmpDestReg) 11386 .addReg(MaskReg); 11387 unsigned ValueReg = SReg; 11388 unsigned CmpReg = Incr2Reg; 11389 if (CmpOpcode == PPC::CMPW) { 11390 ValueReg = RegInfo.createVirtualRegister(GPRC); 11391 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11392 .addReg(SReg) 11393 .addReg(ShiftReg); 11394 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11395 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11396 .addReg(ValueReg); 11397 ValueReg = ValueSReg; 11398 CmpReg = incr; 11399 } 11400 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11401 .addReg(CmpReg) 11402 .addReg(ValueReg); 11403 BuildMI(BB, dl, TII->get(PPC::BCC)) 11404 .addImm(CmpPred) 11405 .addReg(PPC::CR0) 11406 .addMBB(exitMBB); 11407 BB->addSuccessor(loop2MBB); 11408 BB->addSuccessor(exitMBB); 11409 BB = loop2MBB; 11410 } 11411 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11412 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11413 .addReg(Tmp4Reg) 11414 .addReg(ZeroReg) 11415 .addReg(PtrReg); 11416 BuildMI(BB, dl, TII->get(PPC::BCC)) 11417 .addImm(PPC::PRED_NE) 11418 .addReg(PPC::CR0) 11419 .addMBB(loopMBB); 11420 BB->addSuccessor(loopMBB); 11421 BB->addSuccessor(exitMBB); 11422 11423 // exitMBB: 11424 // ... 11425 BB = exitMBB; 11426 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11427 .addReg(TmpDestReg) 11428 .addReg(ShiftReg); 11429 return BB; 11430 } 11431 11432 llvm::MachineBasicBlock * 11433 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11434 MachineBasicBlock *MBB) const { 11435 DebugLoc DL = MI.getDebugLoc(); 11436 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11437 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11438 11439 MachineFunction *MF = MBB->getParent(); 11440 MachineRegisterInfo &MRI = MF->getRegInfo(); 11441 11442 const BasicBlock *BB = MBB->getBasicBlock(); 11443 MachineFunction::iterator I = ++MBB->getIterator(); 11444 11445 Register DstReg = MI.getOperand(0).getReg(); 11446 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11447 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11448 Register mainDstReg = MRI.createVirtualRegister(RC); 11449 Register restoreDstReg = MRI.createVirtualRegister(RC); 11450 11451 MVT PVT = getPointerTy(MF->getDataLayout()); 11452 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11453 "Invalid Pointer Size!"); 11454 // For v = setjmp(buf), we generate 11455 // 11456 // thisMBB: 11457 // SjLjSetup mainMBB 11458 // bl mainMBB 11459 // v_restore = 1 11460 // b sinkMBB 11461 // 11462 // mainMBB: 11463 // buf[LabelOffset] = LR 11464 // v_main = 0 11465 // 11466 // sinkMBB: 11467 // v = phi(main, restore) 11468 // 11469 11470 MachineBasicBlock *thisMBB = MBB; 11471 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11472 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11473 MF->insert(I, mainMBB); 11474 MF->insert(I, sinkMBB); 11475 11476 MachineInstrBuilder MIB; 11477 11478 // Transfer the remainder of BB and its successor edges to sinkMBB. 11479 sinkMBB->splice(sinkMBB->begin(), MBB, 11480 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11481 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11482 11483 // Note that the structure of the jmp_buf used here is not compatible 11484 // with that used by libc, and is not designed to be. Specifically, it 11485 // stores only those 'reserved' registers that LLVM does not otherwise 11486 // understand how to spill. Also, by convention, by the time this 11487 // intrinsic is called, Clang has already stored the frame address in the 11488 // first slot of the buffer and stack address in the third. Following the 11489 // X86 target code, we'll store the jump address in the second slot. We also 11490 // need to save the TOC pointer (R2) to handle jumps between shared 11491 // libraries, and that will be stored in the fourth slot. The thread 11492 // identifier (R13) is not affected. 11493 11494 // thisMBB: 11495 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11496 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11497 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11498 11499 // Prepare IP either in reg. 11500 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11501 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11502 Register BufReg = MI.getOperand(1).getReg(); 11503 11504 if (Subtarget.is64BitELFABI()) { 11505 setUsesTOCBasePtr(*MBB->getParent()); 11506 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11507 .addReg(PPC::X2) 11508 .addImm(TOCOffset) 11509 .addReg(BufReg) 11510 .cloneMemRefs(MI); 11511 } 11512 11513 // Naked functions never have a base pointer, and so we use r1. For all 11514 // other functions, this decision must be delayed until during PEI. 11515 unsigned BaseReg; 11516 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11517 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11518 else 11519 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11520 11521 MIB = BuildMI(*thisMBB, MI, DL, 11522 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11523 .addReg(BaseReg) 11524 .addImm(BPOffset) 11525 .addReg(BufReg) 11526 .cloneMemRefs(MI); 11527 11528 // Setup 11529 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11530 MIB.addRegMask(TRI->getNoPreservedMask()); 11531 11532 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11533 11534 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11535 .addMBB(mainMBB); 11536 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11537 11538 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11539 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11540 11541 // mainMBB: 11542 // mainDstReg = 0 11543 MIB = 11544 BuildMI(mainMBB, DL, 11545 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11546 11547 // Store IP 11548 if (Subtarget.isPPC64()) { 11549 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11550 .addReg(LabelReg) 11551 .addImm(LabelOffset) 11552 .addReg(BufReg); 11553 } else { 11554 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11555 .addReg(LabelReg) 11556 .addImm(LabelOffset) 11557 .addReg(BufReg); 11558 } 11559 MIB.cloneMemRefs(MI); 11560 11561 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11562 mainMBB->addSuccessor(sinkMBB); 11563 11564 // sinkMBB: 11565 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11566 TII->get(PPC::PHI), DstReg) 11567 .addReg(mainDstReg).addMBB(mainMBB) 11568 .addReg(restoreDstReg).addMBB(thisMBB); 11569 11570 MI.eraseFromParent(); 11571 return sinkMBB; 11572 } 11573 11574 MachineBasicBlock * 11575 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11576 MachineBasicBlock *MBB) const { 11577 DebugLoc DL = MI.getDebugLoc(); 11578 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11579 11580 MachineFunction *MF = MBB->getParent(); 11581 MachineRegisterInfo &MRI = MF->getRegInfo(); 11582 11583 MVT PVT = getPointerTy(MF->getDataLayout()); 11584 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11585 "Invalid Pointer Size!"); 11586 11587 const TargetRegisterClass *RC = 11588 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11589 Register Tmp = MRI.createVirtualRegister(RC); 11590 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11591 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11592 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11593 unsigned BP = 11594 (PVT == MVT::i64) 11595 ? PPC::X30 11596 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11597 : PPC::R30); 11598 11599 MachineInstrBuilder MIB; 11600 11601 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11602 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11603 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11604 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11605 11606 Register BufReg = MI.getOperand(0).getReg(); 11607 11608 // Reload FP (the jumped-to function may not have had a 11609 // frame pointer, and if so, then its r31 will be restored 11610 // as necessary). 11611 if (PVT == MVT::i64) { 11612 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11613 .addImm(0) 11614 .addReg(BufReg); 11615 } else { 11616 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11617 .addImm(0) 11618 .addReg(BufReg); 11619 } 11620 MIB.cloneMemRefs(MI); 11621 11622 // Reload IP 11623 if (PVT == MVT::i64) { 11624 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11625 .addImm(LabelOffset) 11626 .addReg(BufReg); 11627 } else { 11628 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11629 .addImm(LabelOffset) 11630 .addReg(BufReg); 11631 } 11632 MIB.cloneMemRefs(MI); 11633 11634 // Reload SP 11635 if (PVT == MVT::i64) { 11636 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11637 .addImm(SPOffset) 11638 .addReg(BufReg); 11639 } else { 11640 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11641 .addImm(SPOffset) 11642 .addReg(BufReg); 11643 } 11644 MIB.cloneMemRefs(MI); 11645 11646 // Reload BP 11647 if (PVT == MVT::i64) { 11648 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11649 .addImm(BPOffset) 11650 .addReg(BufReg); 11651 } else { 11652 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11653 .addImm(BPOffset) 11654 .addReg(BufReg); 11655 } 11656 MIB.cloneMemRefs(MI); 11657 11658 // Reload TOC 11659 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11660 setUsesTOCBasePtr(*MBB->getParent()); 11661 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11662 .addImm(TOCOffset) 11663 .addReg(BufReg) 11664 .cloneMemRefs(MI); 11665 } 11666 11667 // Jump 11668 BuildMI(*MBB, MI, DL, 11669 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11670 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11671 11672 MI.eraseFromParent(); 11673 return MBB; 11674 } 11675 11676 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11677 // If the function specifically requests inline stack probes, emit them. 11678 if (MF.getFunction().hasFnAttribute("probe-stack")) 11679 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11680 "inline-asm"; 11681 return false; 11682 } 11683 11684 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11685 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11686 unsigned StackAlign = TFI->getStackAlignment(); 11687 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11688 "Unexpected stack alignment"); 11689 // The default stack probe size is 4096 if the function has no 11690 // stack-probe-size attribute. 11691 unsigned StackProbeSize = 4096; 11692 const Function &Fn = MF.getFunction(); 11693 if (Fn.hasFnAttribute("stack-probe-size")) 11694 Fn.getFnAttribute("stack-probe-size") 11695 .getValueAsString() 11696 .getAsInteger(0, StackProbeSize); 11697 // Round down to the stack alignment. 11698 StackProbeSize &= ~(StackAlign - 1); 11699 return StackProbeSize ? StackProbeSize : StackAlign; 11700 } 11701 11702 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11703 // into three phases. In the first phase, it uses pseudo instruction 11704 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11705 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11706 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11707 // MaxCallFrameSize so that it can calculate correct data area pointer. 11708 MachineBasicBlock * 11709 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11710 MachineBasicBlock *MBB) const { 11711 const bool isPPC64 = Subtarget.isPPC64(); 11712 MachineFunction *MF = MBB->getParent(); 11713 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11714 DebugLoc DL = MI.getDebugLoc(); 11715 const unsigned ProbeSize = getStackProbeSize(*MF); 11716 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11717 MachineRegisterInfo &MRI = MF->getRegInfo(); 11718 // The CFG of probing stack looks as 11719 // +-----+ 11720 // | MBB | 11721 // +--+--+ 11722 // | 11723 // +----v----+ 11724 // +--->+ TestMBB +---+ 11725 // | +----+----+ | 11726 // | | | 11727 // | +-----v----+ | 11728 // +---+ BlockMBB | | 11729 // +----------+ | 11730 // | 11731 // +---------+ | 11732 // | TailMBB +<--+ 11733 // +---------+ 11734 // In MBB, calculate previous frame pointer and final stack pointer. 11735 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11736 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11737 // TailMBB is spliced via \p MI. 11738 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11739 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11740 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11741 11742 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11743 MF->insert(MBBIter, TestMBB); 11744 MF->insert(MBBIter, BlockMBB); 11745 MF->insert(MBBIter, TailMBB); 11746 11747 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11748 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11749 11750 Register DstReg = MI.getOperand(0).getReg(); 11751 Register NegSizeReg = MI.getOperand(1).getReg(); 11752 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11753 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11754 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11755 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11756 11757 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11758 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11759 // NegSize. 11760 unsigned ProbeOpc; 11761 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11762 ProbeOpc = 11763 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11764 else 11765 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11766 // and NegSizeReg will be allocated in the same phyreg to avoid 11767 // redundant copy when NegSizeReg has only one use which is current MI and 11768 // will be replaced by PREPARE_PROBED_ALLOCA then. 11769 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11770 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11771 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11772 .addDef(ActualNegSizeReg) 11773 .addReg(NegSizeReg) 11774 .add(MI.getOperand(2)) 11775 .add(MI.getOperand(3)); 11776 11777 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11778 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11779 FinalStackPtr) 11780 .addReg(SPReg) 11781 .addReg(ActualNegSizeReg); 11782 11783 // Materialize a scratch register for update. 11784 int64_t NegProbeSize = -(int64_t)ProbeSize; 11785 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11786 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11787 if (!isInt<16>(NegProbeSize)) { 11788 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11789 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11790 .addImm(NegProbeSize >> 16); 11791 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11792 ScratchReg) 11793 .addReg(TempReg) 11794 .addImm(NegProbeSize & 0xFFFF); 11795 } else 11796 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11797 .addImm(NegProbeSize); 11798 11799 { 11800 // Probing leading residual part. 11801 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11802 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11803 .addReg(ActualNegSizeReg) 11804 .addReg(ScratchReg); 11805 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11806 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11807 .addReg(Div) 11808 .addReg(ScratchReg); 11809 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11810 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11811 .addReg(Mul) 11812 .addReg(ActualNegSizeReg); 11813 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11814 .addReg(FramePointer) 11815 .addReg(SPReg) 11816 .addReg(NegMod); 11817 } 11818 11819 { 11820 // Remaining part should be multiple of ProbeSize. 11821 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11822 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11823 .addReg(SPReg) 11824 .addReg(FinalStackPtr); 11825 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11826 .addImm(PPC::PRED_EQ) 11827 .addReg(CmpResult) 11828 .addMBB(TailMBB); 11829 TestMBB->addSuccessor(BlockMBB); 11830 TestMBB->addSuccessor(TailMBB); 11831 } 11832 11833 { 11834 // Touch the block. 11835 // |P...|P...|P... 11836 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11837 .addReg(FramePointer) 11838 .addReg(SPReg) 11839 .addReg(ScratchReg); 11840 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11841 BlockMBB->addSuccessor(TestMBB); 11842 } 11843 11844 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11845 // DYNAREAOFFSET pseudo instruction to get the future result. 11846 Register MaxCallFrameSizeReg = 11847 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11848 BuildMI(TailMBB, DL, 11849 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11850 MaxCallFrameSizeReg) 11851 .add(MI.getOperand(2)) 11852 .add(MI.getOperand(3)); 11853 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11854 .addReg(SPReg) 11855 .addReg(MaxCallFrameSizeReg); 11856 11857 // Splice instructions after MI to TailMBB. 11858 TailMBB->splice(TailMBB->end(), MBB, 11859 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11860 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11861 MBB->addSuccessor(TestMBB); 11862 11863 // Delete the pseudo instruction. 11864 MI.eraseFromParent(); 11865 11866 ++NumDynamicAllocaProbed; 11867 return TailMBB; 11868 } 11869 11870 MachineBasicBlock * 11871 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11872 MachineBasicBlock *BB) const { 11873 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11874 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11875 if (Subtarget.is64BitELFABI() && 11876 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11877 !Subtarget.isUsingPCRelativeCalls()) { 11878 // Call lowering should have added an r2 operand to indicate a dependence 11879 // on the TOC base pointer value. It can't however, because there is no 11880 // way to mark the dependence as implicit there, and so the stackmap code 11881 // will confuse it with a regular operand. Instead, add the dependence 11882 // here. 11883 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11884 } 11885 11886 return emitPatchPoint(MI, BB); 11887 } 11888 11889 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11890 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11891 return emitEHSjLjSetJmp(MI, BB); 11892 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11893 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11894 return emitEHSjLjLongJmp(MI, BB); 11895 } 11896 11897 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11898 11899 // To "insert" these instructions we actually have to insert their 11900 // control-flow patterns. 11901 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11902 MachineFunction::iterator It = ++BB->getIterator(); 11903 11904 MachineFunction *F = BB->getParent(); 11905 11906 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11907 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11908 MI.getOpcode() == PPC::SELECT_I8) { 11909 SmallVector<MachineOperand, 2> Cond; 11910 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11911 MI.getOpcode() == PPC::SELECT_CC_I8) 11912 Cond.push_back(MI.getOperand(4)); 11913 else 11914 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11915 Cond.push_back(MI.getOperand(1)); 11916 11917 DebugLoc dl = MI.getDebugLoc(); 11918 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11919 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11920 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11921 MI.getOpcode() == PPC::SELECT_CC_F8 || 11922 MI.getOpcode() == PPC::SELECT_CC_F16 || 11923 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11924 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11925 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11926 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11927 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11928 MI.getOpcode() == PPC::SELECT_CC_SPE || 11929 MI.getOpcode() == PPC::SELECT_F4 || 11930 MI.getOpcode() == PPC::SELECT_F8 || 11931 MI.getOpcode() == PPC::SELECT_F16 || 11932 MI.getOpcode() == PPC::SELECT_SPE || 11933 MI.getOpcode() == PPC::SELECT_SPE4 || 11934 MI.getOpcode() == PPC::SELECT_VRRC || 11935 MI.getOpcode() == PPC::SELECT_VSFRC || 11936 MI.getOpcode() == PPC::SELECT_VSSRC || 11937 MI.getOpcode() == PPC::SELECT_VSRC) { 11938 // The incoming instruction knows the destination vreg to set, the 11939 // condition code register to branch on, the true/false values to 11940 // select between, and a branch opcode to use. 11941 11942 // thisMBB: 11943 // ... 11944 // TrueVal = ... 11945 // cmpTY ccX, r1, r2 11946 // bCC copy1MBB 11947 // fallthrough --> copy0MBB 11948 MachineBasicBlock *thisMBB = BB; 11949 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11950 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11951 DebugLoc dl = MI.getDebugLoc(); 11952 F->insert(It, copy0MBB); 11953 F->insert(It, sinkMBB); 11954 11955 // Transfer the remainder of BB and its successor edges to sinkMBB. 11956 sinkMBB->splice(sinkMBB->begin(), BB, 11957 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11958 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11959 11960 // Next, add the true and fallthrough blocks as its successors. 11961 BB->addSuccessor(copy0MBB); 11962 BB->addSuccessor(sinkMBB); 11963 11964 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11965 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11966 MI.getOpcode() == PPC::SELECT_F16 || 11967 MI.getOpcode() == PPC::SELECT_SPE4 || 11968 MI.getOpcode() == PPC::SELECT_SPE || 11969 MI.getOpcode() == PPC::SELECT_VRRC || 11970 MI.getOpcode() == PPC::SELECT_VSFRC || 11971 MI.getOpcode() == PPC::SELECT_VSSRC || 11972 MI.getOpcode() == PPC::SELECT_VSRC) { 11973 BuildMI(BB, dl, TII->get(PPC::BC)) 11974 .addReg(MI.getOperand(1).getReg()) 11975 .addMBB(sinkMBB); 11976 } else { 11977 unsigned SelectPred = MI.getOperand(4).getImm(); 11978 BuildMI(BB, dl, TII->get(PPC::BCC)) 11979 .addImm(SelectPred) 11980 .addReg(MI.getOperand(1).getReg()) 11981 .addMBB(sinkMBB); 11982 } 11983 11984 // copy0MBB: 11985 // %FalseValue = ... 11986 // # fallthrough to sinkMBB 11987 BB = copy0MBB; 11988 11989 // Update machine-CFG edges 11990 BB->addSuccessor(sinkMBB); 11991 11992 // sinkMBB: 11993 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11994 // ... 11995 BB = sinkMBB; 11996 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11997 .addReg(MI.getOperand(3).getReg()) 11998 .addMBB(copy0MBB) 11999 .addReg(MI.getOperand(2).getReg()) 12000 .addMBB(thisMBB); 12001 } else if (MI.getOpcode() == PPC::ReadTB) { 12002 // To read the 64-bit time-base register on a 32-bit target, we read the 12003 // two halves. Should the counter have wrapped while it was being read, we 12004 // need to try again. 12005 // ... 12006 // readLoop: 12007 // mfspr Rx,TBU # load from TBU 12008 // mfspr Ry,TB # load from TB 12009 // mfspr Rz,TBU # load from TBU 12010 // cmpw crX,Rx,Rz # check if 'old'='new' 12011 // bne readLoop # branch if they're not equal 12012 // ... 12013 12014 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 12015 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12016 DebugLoc dl = MI.getDebugLoc(); 12017 F->insert(It, readMBB); 12018 F->insert(It, sinkMBB); 12019 12020 // Transfer the remainder of BB and its successor edges to sinkMBB. 12021 sinkMBB->splice(sinkMBB->begin(), BB, 12022 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12023 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12024 12025 BB->addSuccessor(readMBB); 12026 BB = readMBB; 12027 12028 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12029 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12030 Register LoReg = MI.getOperand(0).getReg(); 12031 Register HiReg = MI.getOperand(1).getReg(); 12032 12033 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12034 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12035 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12036 12037 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12038 12039 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12040 .addReg(HiReg) 12041 .addReg(ReadAgainReg); 12042 BuildMI(BB, dl, TII->get(PPC::BCC)) 12043 .addImm(PPC::PRED_NE) 12044 .addReg(CmpReg) 12045 .addMBB(readMBB); 12046 12047 BB->addSuccessor(readMBB); 12048 BB->addSuccessor(sinkMBB); 12049 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12050 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12051 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12052 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12053 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12054 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12055 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12056 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12057 12058 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12059 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12060 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12061 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12062 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12063 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12064 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12065 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12066 12067 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12068 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12069 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12070 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12071 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12072 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12073 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12074 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12075 12076 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12077 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12078 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12079 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12080 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12081 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12082 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12083 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12084 12085 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12086 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12087 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12088 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12089 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12090 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12091 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12092 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12093 12094 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12095 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12096 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12097 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12098 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12099 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12100 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12101 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12102 12103 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12104 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 12105 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12106 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 12107 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12108 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 12109 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12110 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 12111 12112 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12113 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 12114 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12115 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 12116 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12117 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 12118 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12119 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 12120 12121 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12122 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 12123 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12124 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 12125 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12126 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 12127 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12128 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 12129 12130 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12131 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 12132 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12133 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 12134 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12135 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12136 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12137 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12138 12139 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12140 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12141 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12142 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12143 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12144 BB = EmitAtomicBinary(MI, BB, 4, 0); 12145 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12146 BB = EmitAtomicBinary(MI, BB, 8, 0); 12147 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12148 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12149 (Subtarget.hasPartwordAtomics() && 12150 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12151 (Subtarget.hasPartwordAtomics() && 12152 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12153 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12154 12155 auto LoadMnemonic = PPC::LDARX; 12156 auto StoreMnemonic = PPC::STDCX; 12157 switch (MI.getOpcode()) { 12158 default: 12159 llvm_unreachable("Compare and swap of unknown size"); 12160 case PPC::ATOMIC_CMP_SWAP_I8: 12161 LoadMnemonic = PPC::LBARX; 12162 StoreMnemonic = PPC::STBCX; 12163 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12164 break; 12165 case PPC::ATOMIC_CMP_SWAP_I16: 12166 LoadMnemonic = PPC::LHARX; 12167 StoreMnemonic = PPC::STHCX; 12168 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12169 break; 12170 case PPC::ATOMIC_CMP_SWAP_I32: 12171 LoadMnemonic = PPC::LWARX; 12172 StoreMnemonic = PPC::STWCX; 12173 break; 12174 case PPC::ATOMIC_CMP_SWAP_I64: 12175 LoadMnemonic = PPC::LDARX; 12176 StoreMnemonic = PPC::STDCX; 12177 break; 12178 } 12179 Register dest = MI.getOperand(0).getReg(); 12180 Register ptrA = MI.getOperand(1).getReg(); 12181 Register ptrB = MI.getOperand(2).getReg(); 12182 Register oldval = MI.getOperand(3).getReg(); 12183 Register newval = MI.getOperand(4).getReg(); 12184 DebugLoc dl = MI.getDebugLoc(); 12185 12186 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12187 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12188 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12189 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12190 F->insert(It, loop1MBB); 12191 F->insert(It, loop2MBB); 12192 F->insert(It, midMBB); 12193 F->insert(It, exitMBB); 12194 exitMBB->splice(exitMBB->begin(), BB, 12195 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12196 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12197 12198 // thisMBB: 12199 // ... 12200 // fallthrough --> loopMBB 12201 BB->addSuccessor(loop1MBB); 12202 12203 // loop1MBB: 12204 // l[bhwd]arx dest, ptr 12205 // cmp[wd] dest, oldval 12206 // bne- midMBB 12207 // loop2MBB: 12208 // st[bhwd]cx. newval, ptr 12209 // bne- loopMBB 12210 // b exitBB 12211 // midMBB: 12212 // st[bhwd]cx. dest, ptr 12213 // exitBB: 12214 BB = loop1MBB; 12215 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12216 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12217 .addReg(oldval) 12218 .addReg(dest); 12219 BuildMI(BB, dl, TII->get(PPC::BCC)) 12220 .addImm(PPC::PRED_NE) 12221 .addReg(PPC::CR0) 12222 .addMBB(midMBB); 12223 BB->addSuccessor(loop2MBB); 12224 BB->addSuccessor(midMBB); 12225 12226 BB = loop2MBB; 12227 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12228 .addReg(newval) 12229 .addReg(ptrA) 12230 .addReg(ptrB); 12231 BuildMI(BB, dl, TII->get(PPC::BCC)) 12232 .addImm(PPC::PRED_NE) 12233 .addReg(PPC::CR0) 12234 .addMBB(loop1MBB); 12235 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12236 BB->addSuccessor(loop1MBB); 12237 BB->addSuccessor(exitMBB); 12238 12239 BB = midMBB; 12240 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12241 .addReg(dest) 12242 .addReg(ptrA) 12243 .addReg(ptrB); 12244 BB->addSuccessor(exitMBB); 12245 12246 // exitMBB: 12247 // ... 12248 BB = exitMBB; 12249 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12250 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12251 // We must use 64-bit registers for addresses when targeting 64-bit, 12252 // since we're actually doing arithmetic on them. Other registers 12253 // can be 32-bit. 12254 bool is64bit = Subtarget.isPPC64(); 12255 bool isLittleEndian = Subtarget.isLittleEndian(); 12256 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12257 12258 Register dest = MI.getOperand(0).getReg(); 12259 Register ptrA = MI.getOperand(1).getReg(); 12260 Register ptrB = MI.getOperand(2).getReg(); 12261 Register oldval = MI.getOperand(3).getReg(); 12262 Register newval = MI.getOperand(4).getReg(); 12263 DebugLoc dl = MI.getDebugLoc(); 12264 12265 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12266 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12267 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12268 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12269 F->insert(It, loop1MBB); 12270 F->insert(It, loop2MBB); 12271 F->insert(It, midMBB); 12272 F->insert(It, exitMBB); 12273 exitMBB->splice(exitMBB->begin(), BB, 12274 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12275 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12276 12277 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12278 const TargetRegisterClass *RC = 12279 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12280 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12281 12282 Register PtrReg = RegInfo.createVirtualRegister(RC); 12283 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12284 Register ShiftReg = 12285 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12286 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12287 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12288 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12289 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12290 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12291 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12292 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12293 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12294 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12295 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12296 Register Ptr1Reg; 12297 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12298 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12299 // thisMBB: 12300 // ... 12301 // fallthrough --> loopMBB 12302 BB->addSuccessor(loop1MBB); 12303 12304 // The 4-byte load must be aligned, while a char or short may be 12305 // anywhere in the word. Hence all this nasty bookkeeping code. 12306 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12307 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12308 // xori shift, shift1, 24 [16] 12309 // rlwinm ptr, ptr1, 0, 0, 29 12310 // slw newval2, newval, shift 12311 // slw oldval2, oldval,shift 12312 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12313 // slw mask, mask2, shift 12314 // and newval3, newval2, mask 12315 // and oldval3, oldval2, mask 12316 // loop1MBB: 12317 // lwarx tmpDest, ptr 12318 // and tmp, tmpDest, mask 12319 // cmpw tmp, oldval3 12320 // bne- midMBB 12321 // loop2MBB: 12322 // andc tmp2, tmpDest, mask 12323 // or tmp4, tmp2, newval3 12324 // stwcx. tmp4, ptr 12325 // bne- loop1MBB 12326 // b exitBB 12327 // midMBB: 12328 // stwcx. tmpDest, ptr 12329 // exitBB: 12330 // srw dest, tmpDest, shift 12331 if (ptrA != ZeroReg) { 12332 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12333 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12334 .addReg(ptrA) 12335 .addReg(ptrB); 12336 } else { 12337 Ptr1Reg = ptrB; 12338 } 12339 12340 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12341 // mode. 12342 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12343 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12344 .addImm(3) 12345 .addImm(27) 12346 .addImm(is8bit ? 28 : 27); 12347 if (!isLittleEndian) 12348 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12349 .addReg(Shift1Reg) 12350 .addImm(is8bit ? 24 : 16); 12351 if (is64bit) 12352 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12353 .addReg(Ptr1Reg) 12354 .addImm(0) 12355 .addImm(61); 12356 else 12357 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12358 .addReg(Ptr1Reg) 12359 .addImm(0) 12360 .addImm(0) 12361 .addImm(29); 12362 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12363 .addReg(newval) 12364 .addReg(ShiftReg); 12365 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12366 .addReg(oldval) 12367 .addReg(ShiftReg); 12368 if (is8bit) 12369 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12370 else { 12371 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12372 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12373 .addReg(Mask3Reg) 12374 .addImm(65535); 12375 } 12376 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12377 .addReg(Mask2Reg) 12378 .addReg(ShiftReg); 12379 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12380 .addReg(NewVal2Reg) 12381 .addReg(MaskReg); 12382 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12383 .addReg(OldVal2Reg) 12384 .addReg(MaskReg); 12385 12386 BB = loop1MBB; 12387 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12388 .addReg(ZeroReg) 12389 .addReg(PtrReg); 12390 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12391 .addReg(TmpDestReg) 12392 .addReg(MaskReg); 12393 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12394 .addReg(TmpReg) 12395 .addReg(OldVal3Reg); 12396 BuildMI(BB, dl, TII->get(PPC::BCC)) 12397 .addImm(PPC::PRED_NE) 12398 .addReg(PPC::CR0) 12399 .addMBB(midMBB); 12400 BB->addSuccessor(loop2MBB); 12401 BB->addSuccessor(midMBB); 12402 12403 BB = loop2MBB; 12404 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12405 .addReg(TmpDestReg) 12406 .addReg(MaskReg); 12407 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12408 .addReg(Tmp2Reg) 12409 .addReg(NewVal3Reg); 12410 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12411 .addReg(Tmp4Reg) 12412 .addReg(ZeroReg) 12413 .addReg(PtrReg); 12414 BuildMI(BB, dl, TII->get(PPC::BCC)) 12415 .addImm(PPC::PRED_NE) 12416 .addReg(PPC::CR0) 12417 .addMBB(loop1MBB); 12418 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12419 BB->addSuccessor(loop1MBB); 12420 BB->addSuccessor(exitMBB); 12421 12422 BB = midMBB; 12423 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12424 .addReg(TmpDestReg) 12425 .addReg(ZeroReg) 12426 .addReg(PtrReg); 12427 BB->addSuccessor(exitMBB); 12428 12429 // exitMBB: 12430 // ... 12431 BB = exitMBB; 12432 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12433 .addReg(TmpReg) 12434 .addReg(ShiftReg); 12435 } else if (MI.getOpcode() == PPC::FADDrtz) { 12436 // This pseudo performs an FADD with rounding mode temporarily forced 12437 // to round-to-zero. We emit this via custom inserter since the FPSCR 12438 // is not modeled at the SelectionDAG level. 12439 Register Dest = MI.getOperand(0).getReg(); 12440 Register Src1 = MI.getOperand(1).getReg(); 12441 Register Src2 = MI.getOperand(2).getReg(); 12442 DebugLoc dl = MI.getDebugLoc(); 12443 12444 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12445 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12446 12447 // Save FPSCR value. 12448 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12449 12450 // Set rounding mode to round-to-zero. 12451 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12452 .addImm(31) 12453 .addReg(PPC::RM, RegState::ImplicitDefine); 12454 12455 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12456 .addImm(30) 12457 .addReg(PPC::RM, RegState::ImplicitDefine); 12458 12459 // Perform addition. 12460 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12461 .addReg(Src1) 12462 .addReg(Src2); 12463 if (MI.getFlag(MachineInstr::NoFPExcept)) 12464 MIB.setMIFlag(MachineInstr::NoFPExcept); 12465 12466 // Restore FPSCR value. 12467 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12468 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12469 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12470 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12471 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12472 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12473 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12474 ? PPC::ANDI8_rec 12475 : PPC::ANDI_rec; 12476 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12477 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12478 12479 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12480 Register Dest = RegInfo.createVirtualRegister( 12481 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12482 12483 DebugLoc Dl = MI.getDebugLoc(); 12484 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12485 .addReg(MI.getOperand(1).getReg()) 12486 .addImm(1); 12487 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12488 MI.getOperand(0).getReg()) 12489 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12490 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12491 DebugLoc Dl = MI.getDebugLoc(); 12492 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12493 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12494 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12495 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12496 MI.getOperand(0).getReg()) 12497 .addReg(CRReg); 12498 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12499 DebugLoc Dl = MI.getDebugLoc(); 12500 unsigned Imm = MI.getOperand(1).getImm(); 12501 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12502 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12503 MI.getOperand(0).getReg()) 12504 .addReg(PPC::CR0EQ); 12505 } else if (MI.getOpcode() == PPC::SETRNDi) { 12506 DebugLoc dl = MI.getDebugLoc(); 12507 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12508 12509 // Save FPSCR value. 12510 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12511 12512 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12513 // the following settings: 12514 // 00 Round to nearest 12515 // 01 Round to 0 12516 // 10 Round to +inf 12517 // 11 Round to -inf 12518 12519 // When the operand is immediate, using the two least significant bits of 12520 // the immediate to set the bits 62:63 of FPSCR. 12521 unsigned Mode = MI.getOperand(1).getImm(); 12522 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12523 .addImm(31) 12524 .addReg(PPC::RM, RegState::ImplicitDefine); 12525 12526 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12527 .addImm(30) 12528 .addReg(PPC::RM, RegState::ImplicitDefine); 12529 } else if (MI.getOpcode() == PPC::SETRND) { 12530 DebugLoc dl = MI.getDebugLoc(); 12531 12532 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12533 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12534 // If the target doesn't have DirectMove, we should use stack to do the 12535 // conversion, because the target doesn't have the instructions like mtvsrd 12536 // or mfvsrd to do this conversion directly. 12537 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12538 if (Subtarget.hasDirectMove()) { 12539 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12540 .addReg(SrcReg); 12541 } else { 12542 // Use stack to do the register copy. 12543 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12544 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12545 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12546 if (RC == &PPC::F8RCRegClass) { 12547 // Copy register from F8RCRegClass to G8RCRegclass. 12548 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12549 "Unsupported RegClass."); 12550 12551 StoreOp = PPC::STFD; 12552 LoadOp = PPC::LD; 12553 } else { 12554 // Copy register from G8RCRegClass to F8RCRegclass. 12555 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12556 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12557 "Unsupported RegClass."); 12558 } 12559 12560 MachineFrameInfo &MFI = F->getFrameInfo(); 12561 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12562 12563 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12564 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12565 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12566 MFI.getObjectAlign(FrameIdx)); 12567 12568 // Store the SrcReg into the stack. 12569 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12570 .addReg(SrcReg) 12571 .addImm(0) 12572 .addFrameIndex(FrameIdx) 12573 .addMemOperand(MMOStore); 12574 12575 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12576 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12577 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12578 MFI.getObjectAlign(FrameIdx)); 12579 12580 // Load from the stack where SrcReg is stored, and save to DestReg, 12581 // so we have done the RegClass conversion from RegClass::SrcReg to 12582 // RegClass::DestReg. 12583 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12584 .addImm(0) 12585 .addFrameIndex(FrameIdx) 12586 .addMemOperand(MMOLoad); 12587 } 12588 }; 12589 12590 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12591 12592 // Save FPSCR value. 12593 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12594 12595 // When the operand is gprc register, use two least significant bits of the 12596 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12597 // 12598 // copy OldFPSCRTmpReg, OldFPSCRReg 12599 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12600 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12601 // copy NewFPSCRReg, NewFPSCRTmpReg 12602 // mtfsf 255, NewFPSCRReg 12603 MachineOperand SrcOp = MI.getOperand(1); 12604 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12605 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12606 12607 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12608 12609 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12610 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12611 12612 // The first operand of INSERT_SUBREG should be a register which has 12613 // subregisters, we only care about its RegClass, so we should use an 12614 // IMPLICIT_DEF register. 12615 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12616 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12617 .addReg(ImDefReg) 12618 .add(SrcOp) 12619 .addImm(1); 12620 12621 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12622 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12623 .addReg(OldFPSCRTmpReg) 12624 .addReg(ExtSrcReg) 12625 .addImm(0) 12626 .addImm(62); 12627 12628 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12629 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12630 12631 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12632 // bits of FPSCR. 12633 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12634 .addImm(255) 12635 .addReg(NewFPSCRReg) 12636 .addImm(0) 12637 .addImm(0); 12638 } else if (MI.getOpcode() == PPC::SETFLM) { 12639 DebugLoc Dl = MI.getDebugLoc(); 12640 12641 // Result of setflm is previous FPSCR content, so we need to save it first. 12642 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12643 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12644 12645 // Put bits in 32:63 to FPSCR. 12646 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12647 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12648 .addImm(255) 12649 .addReg(NewFPSCRReg) 12650 .addImm(0) 12651 .addImm(0); 12652 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12653 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12654 return emitProbedAlloca(MI, BB); 12655 } else { 12656 llvm_unreachable("Unexpected instr type to insert"); 12657 } 12658 12659 MI.eraseFromParent(); // The pseudo instruction is gone now. 12660 return BB; 12661 } 12662 12663 //===----------------------------------------------------------------------===// 12664 // Target Optimization Hooks 12665 //===----------------------------------------------------------------------===// 12666 12667 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12668 // For the estimates, convergence is quadratic, so we essentially double the 12669 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12670 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12671 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12672 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12673 if (VT.getScalarType() == MVT::f64) 12674 RefinementSteps++; 12675 return RefinementSteps; 12676 } 12677 12678 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12679 int Enabled, int &RefinementSteps, 12680 bool &UseOneConstNR, 12681 bool Reciprocal) const { 12682 EVT VT = Operand.getValueType(); 12683 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12684 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12685 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12686 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12687 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12688 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12689 12690 // The Newton-Raphson computation with a single constant does not provide 12691 // enough accuracy on some CPUs. 12692 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12693 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12694 } 12695 return SDValue(); 12696 } 12697 12698 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12699 int Enabled, 12700 int &RefinementSteps) const { 12701 EVT VT = Operand.getValueType(); 12702 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12703 (VT == MVT::f64 && Subtarget.hasFRE()) || 12704 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12705 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12706 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12707 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12708 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12709 } 12710 return SDValue(); 12711 } 12712 12713 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12714 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12715 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12716 // enabled for division), this functionality is redundant with the default 12717 // combiner logic (once the division -> reciprocal/multiply transformation 12718 // has taken place). As a result, this matters more for older cores than for 12719 // newer ones. 12720 12721 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12722 // reciprocal if there are two or more FDIVs (for embedded cores with only 12723 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12724 switch (Subtarget.getCPUDirective()) { 12725 default: 12726 return 3; 12727 case PPC::DIR_440: 12728 case PPC::DIR_A2: 12729 case PPC::DIR_E500: 12730 case PPC::DIR_E500mc: 12731 case PPC::DIR_E5500: 12732 return 2; 12733 } 12734 } 12735 12736 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12737 // collapsed, and so we need to look through chains of them. 12738 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12739 int64_t& Offset, SelectionDAG &DAG) { 12740 if (DAG.isBaseWithConstantOffset(Loc)) { 12741 Base = Loc.getOperand(0); 12742 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12743 12744 // The base might itself be a base plus an offset, and if so, accumulate 12745 // that as well. 12746 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12747 } 12748 } 12749 12750 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12751 unsigned Bytes, int Dist, 12752 SelectionDAG &DAG) { 12753 if (VT.getSizeInBits() / 8 != Bytes) 12754 return false; 12755 12756 SDValue BaseLoc = Base->getBasePtr(); 12757 if (Loc.getOpcode() == ISD::FrameIndex) { 12758 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12759 return false; 12760 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12761 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12762 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12763 int FS = MFI.getObjectSize(FI); 12764 int BFS = MFI.getObjectSize(BFI); 12765 if (FS != BFS || FS != (int)Bytes) return false; 12766 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12767 } 12768 12769 SDValue Base1 = Loc, Base2 = BaseLoc; 12770 int64_t Offset1 = 0, Offset2 = 0; 12771 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12772 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12773 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12774 return true; 12775 12776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12777 const GlobalValue *GV1 = nullptr; 12778 const GlobalValue *GV2 = nullptr; 12779 Offset1 = 0; 12780 Offset2 = 0; 12781 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12782 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12783 if (isGA1 && isGA2 && GV1 == GV2) 12784 return Offset1 == (Offset2 + Dist*Bytes); 12785 return false; 12786 } 12787 12788 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12789 // not enforce equality of the chain operands. 12790 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12791 unsigned Bytes, int Dist, 12792 SelectionDAG &DAG) { 12793 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12794 EVT VT = LS->getMemoryVT(); 12795 SDValue Loc = LS->getBasePtr(); 12796 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12797 } 12798 12799 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12800 EVT VT; 12801 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12802 default: return false; 12803 case Intrinsic::ppc_altivec_lvx: 12804 case Intrinsic::ppc_altivec_lvxl: 12805 case Intrinsic::ppc_vsx_lxvw4x: 12806 case Intrinsic::ppc_vsx_lxvw4x_be: 12807 VT = MVT::v4i32; 12808 break; 12809 case Intrinsic::ppc_vsx_lxvd2x: 12810 case Intrinsic::ppc_vsx_lxvd2x_be: 12811 VT = MVT::v2f64; 12812 break; 12813 case Intrinsic::ppc_altivec_lvebx: 12814 VT = MVT::i8; 12815 break; 12816 case Intrinsic::ppc_altivec_lvehx: 12817 VT = MVT::i16; 12818 break; 12819 case Intrinsic::ppc_altivec_lvewx: 12820 VT = MVT::i32; 12821 break; 12822 } 12823 12824 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12825 } 12826 12827 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12828 EVT VT; 12829 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12830 default: return false; 12831 case Intrinsic::ppc_altivec_stvx: 12832 case Intrinsic::ppc_altivec_stvxl: 12833 case Intrinsic::ppc_vsx_stxvw4x: 12834 VT = MVT::v4i32; 12835 break; 12836 case Intrinsic::ppc_vsx_stxvd2x: 12837 VT = MVT::v2f64; 12838 break; 12839 case Intrinsic::ppc_vsx_stxvw4x_be: 12840 VT = MVT::v4i32; 12841 break; 12842 case Intrinsic::ppc_vsx_stxvd2x_be: 12843 VT = MVT::v2f64; 12844 break; 12845 case Intrinsic::ppc_altivec_stvebx: 12846 VT = MVT::i8; 12847 break; 12848 case Intrinsic::ppc_altivec_stvehx: 12849 VT = MVT::i16; 12850 break; 12851 case Intrinsic::ppc_altivec_stvewx: 12852 VT = MVT::i32; 12853 break; 12854 } 12855 12856 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12857 } 12858 12859 return false; 12860 } 12861 12862 // Return true is there is a nearyby consecutive load to the one provided 12863 // (regardless of alignment). We search up and down the chain, looking though 12864 // token factors and other loads (but nothing else). As a result, a true result 12865 // indicates that it is safe to create a new consecutive load adjacent to the 12866 // load provided. 12867 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12868 SDValue Chain = LD->getChain(); 12869 EVT VT = LD->getMemoryVT(); 12870 12871 SmallSet<SDNode *, 16> LoadRoots; 12872 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12873 SmallSet<SDNode *, 16> Visited; 12874 12875 // First, search up the chain, branching to follow all token-factor operands. 12876 // If we find a consecutive load, then we're done, otherwise, record all 12877 // nodes just above the top-level loads and token factors. 12878 while (!Queue.empty()) { 12879 SDNode *ChainNext = Queue.pop_back_val(); 12880 if (!Visited.insert(ChainNext).second) 12881 continue; 12882 12883 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12884 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12885 return true; 12886 12887 if (!Visited.count(ChainLD->getChain().getNode())) 12888 Queue.push_back(ChainLD->getChain().getNode()); 12889 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12890 for (const SDUse &O : ChainNext->ops()) 12891 if (!Visited.count(O.getNode())) 12892 Queue.push_back(O.getNode()); 12893 } else 12894 LoadRoots.insert(ChainNext); 12895 } 12896 12897 // Second, search down the chain, starting from the top-level nodes recorded 12898 // in the first phase. These top-level nodes are the nodes just above all 12899 // loads and token factors. Starting with their uses, recursively look though 12900 // all loads (just the chain uses) and token factors to find a consecutive 12901 // load. 12902 Visited.clear(); 12903 Queue.clear(); 12904 12905 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12906 IE = LoadRoots.end(); I != IE; ++I) { 12907 Queue.push_back(*I); 12908 12909 while (!Queue.empty()) { 12910 SDNode *LoadRoot = Queue.pop_back_val(); 12911 if (!Visited.insert(LoadRoot).second) 12912 continue; 12913 12914 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12915 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12916 return true; 12917 12918 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12919 UE = LoadRoot->use_end(); UI != UE; ++UI) 12920 if (((isa<MemSDNode>(*UI) && 12921 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12922 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12923 Queue.push_back(*UI); 12924 } 12925 } 12926 12927 return false; 12928 } 12929 12930 /// This function is called when we have proved that a SETCC node can be replaced 12931 /// by subtraction (and other supporting instructions) so that the result of 12932 /// comparison is kept in a GPR instead of CR. This function is purely for 12933 /// codegen purposes and has some flags to guide the codegen process. 12934 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12935 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12936 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12937 12938 // Zero extend the operands to the largest legal integer. Originally, they 12939 // must be of a strictly smaller size. 12940 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12941 DAG.getConstant(Size, DL, MVT::i32)); 12942 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12943 DAG.getConstant(Size, DL, MVT::i32)); 12944 12945 // Swap if needed. Depends on the condition code. 12946 if (Swap) 12947 std::swap(Op0, Op1); 12948 12949 // Subtract extended integers. 12950 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12951 12952 // Move the sign bit to the least significant position and zero out the rest. 12953 // Now the least significant bit carries the result of original comparison. 12954 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12955 DAG.getConstant(Size - 1, DL, MVT::i32)); 12956 auto Final = Shifted; 12957 12958 // Complement the result if needed. Based on the condition code. 12959 if (Complement) 12960 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12961 DAG.getConstant(1, DL, MVT::i64)); 12962 12963 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12964 } 12965 12966 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12967 DAGCombinerInfo &DCI) const { 12968 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12969 12970 SelectionDAG &DAG = DCI.DAG; 12971 SDLoc DL(N); 12972 12973 // Size of integers being compared has a critical role in the following 12974 // analysis, so we prefer to do this when all types are legal. 12975 if (!DCI.isAfterLegalizeDAG()) 12976 return SDValue(); 12977 12978 // If all users of SETCC extend its value to a legal integer type 12979 // then we replace SETCC with a subtraction 12980 for (SDNode::use_iterator UI = N->use_begin(), 12981 UE = N->use_end(); UI != UE; ++UI) { 12982 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12983 return SDValue(); 12984 } 12985 12986 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12987 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12988 12989 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12990 12991 if (OpSize < Size) { 12992 switch (CC) { 12993 default: break; 12994 case ISD::SETULT: 12995 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12996 case ISD::SETULE: 12997 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12998 case ISD::SETUGT: 12999 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13000 case ISD::SETUGE: 13001 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13002 } 13003 } 13004 13005 return SDValue(); 13006 } 13007 13008 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13009 DAGCombinerInfo &DCI) const { 13010 SelectionDAG &DAG = DCI.DAG; 13011 SDLoc dl(N); 13012 13013 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13014 // If we're tracking CR bits, we need to be careful that we don't have: 13015 // trunc(binary-ops(zext(x), zext(y))) 13016 // or 13017 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13018 // such that we're unnecessarily moving things into GPRs when it would be 13019 // better to keep them in CR bits. 13020 13021 // Note that trunc here can be an actual i1 trunc, or can be the effective 13022 // truncation that comes from a setcc or select_cc. 13023 if (N->getOpcode() == ISD::TRUNCATE && 13024 N->getValueType(0) != MVT::i1) 13025 return SDValue(); 13026 13027 if (N->getOperand(0).getValueType() != MVT::i32 && 13028 N->getOperand(0).getValueType() != MVT::i64) 13029 return SDValue(); 13030 13031 if (N->getOpcode() == ISD::SETCC || 13032 N->getOpcode() == ISD::SELECT_CC) { 13033 // If we're looking at a comparison, then we need to make sure that the 13034 // high bits (all except for the first) don't matter the result. 13035 ISD::CondCode CC = 13036 cast<CondCodeSDNode>(N->getOperand( 13037 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13038 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13039 13040 if (ISD::isSignedIntSetCC(CC)) { 13041 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13042 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13043 return SDValue(); 13044 } else if (ISD::isUnsignedIntSetCC(CC)) { 13045 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13046 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13047 !DAG.MaskedValueIsZero(N->getOperand(1), 13048 APInt::getHighBitsSet(OpBits, OpBits-1))) 13049 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13050 : SDValue()); 13051 } else { 13052 // This is neither a signed nor an unsigned comparison, just make sure 13053 // that the high bits are equal. 13054 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13055 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13056 13057 // We don't really care about what is known about the first bit (if 13058 // anything), so clear it in all masks prior to comparing them. 13059 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 13060 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 13061 13062 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 13063 return SDValue(); 13064 } 13065 } 13066 13067 // We now know that the higher-order bits are irrelevant, we just need to 13068 // make sure that all of the intermediate operations are bit operations, and 13069 // all inputs are extensions. 13070 if (N->getOperand(0).getOpcode() != ISD::AND && 13071 N->getOperand(0).getOpcode() != ISD::OR && 13072 N->getOperand(0).getOpcode() != ISD::XOR && 13073 N->getOperand(0).getOpcode() != ISD::SELECT && 13074 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13075 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13076 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13077 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13078 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13079 return SDValue(); 13080 13081 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13082 N->getOperand(1).getOpcode() != ISD::AND && 13083 N->getOperand(1).getOpcode() != ISD::OR && 13084 N->getOperand(1).getOpcode() != ISD::XOR && 13085 N->getOperand(1).getOpcode() != ISD::SELECT && 13086 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13087 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13088 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13089 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13090 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13091 return SDValue(); 13092 13093 SmallVector<SDValue, 4> Inputs; 13094 SmallVector<SDValue, 8> BinOps, PromOps; 13095 SmallPtrSet<SDNode *, 16> Visited; 13096 13097 for (unsigned i = 0; i < 2; ++i) { 13098 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13099 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13100 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13101 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13102 isa<ConstantSDNode>(N->getOperand(i))) 13103 Inputs.push_back(N->getOperand(i)); 13104 else 13105 BinOps.push_back(N->getOperand(i)); 13106 13107 if (N->getOpcode() == ISD::TRUNCATE) 13108 break; 13109 } 13110 13111 // Visit all inputs, collect all binary operations (and, or, xor and 13112 // select) that are all fed by extensions. 13113 while (!BinOps.empty()) { 13114 SDValue BinOp = BinOps.back(); 13115 BinOps.pop_back(); 13116 13117 if (!Visited.insert(BinOp.getNode()).second) 13118 continue; 13119 13120 PromOps.push_back(BinOp); 13121 13122 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13123 // The condition of the select is not promoted. 13124 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13125 continue; 13126 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13127 continue; 13128 13129 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13130 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13131 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13132 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13133 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13134 Inputs.push_back(BinOp.getOperand(i)); 13135 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13136 BinOp.getOperand(i).getOpcode() == ISD::OR || 13137 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13138 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13139 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13140 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13141 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13142 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13143 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13144 BinOps.push_back(BinOp.getOperand(i)); 13145 } else { 13146 // We have an input that is not an extension or another binary 13147 // operation; we'll abort this transformation. 13148 return SDValue(); 13149 } 13150 } 13151 } 13152 13153 // Make sure that this is a self-contained cluster of operations (which 13154 // is not quite the same thing as saying that everything has only one 13155 // use). 13156 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13157 if (isa<ConstantSDNode>(Inputs[i])) 13158 continue; 13159 13160 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13161 UE = Inputs[i].getNode()->use_end(); 13162 UI != UE; ++UI) { 13163 SDNode *User = *UI; 13164 if (User != N && !Visited.count(User)) 13165 return SDValue(); 13166 13167 // Make sure that we're not going to promote the non-output-value 13168 // operand(s) or SELECT or SELECT_CC. 13169 // FIXME: Although we could sometimes handle this, and it does occur in 13170 // practice that one of the condition inputs to the select is also one of 13171 // the outputs, we currently can't deal with this. 13172 if (User->getOpcode() == ISD::SELECT) { 13173 if (User->getOperand(0) == Inputs[i]) 13174 return SDValue(); 13175 } else if (User->getOpcode() == ISD::SELECT_CC) { 13176 if (User->getOperand(0) == Inputs[i] || 13177 User->getOperand(1) == Inputs[i]) 13178 return SDValue(); 13179 } 13180 } 13181 } 13182 13183 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13184 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13185 UE = PromOps[i].getNode()->use_end(); 13186 UI != UE; ++UI) { 13187 SDNode *User = *UI; 13188 if (User != N && !Visited.count(User)) 13189 return SDValue(); 13190 13191 // Make sure that we're not going to promote the non-output-value 13192 // operand(s) or SELECT or SELECT_CC. 13193 // FIXME: Although we could sometimes handle this, and it does occur in 13194 // practice that one of the condition inputs to the select is also one of 13195 // the outputs, we currently can't deal with this. 13196 if (User->getOpcode() == ISD::SELECT) { 13197 if (User->getOperand(0) == PromOps[i]) 13198 return SDValue(); 13199 } else if (User->getOpcode() == ISD::SELECT_CC) { 13200 if (User->getOperand(0) == PromOps[i] || 13201 User->getOperand(1) == PromOps[i]) 13202 return SDValue(); 13203 } 13204 } 13205 } 13206 13207 // Replace all inputs with the extension operand. 13208 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13209 // Constants may have users outside the cluster of to-be-promoted nodes, 13210 // and so we need to replace those as we do the promotions. 13211 if (isa<ConstantSDNode>(Inputs[i])) 13212 continue; 13213 else 13214 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13215 } 13216 13217 std::list<HandleSDNode> PromOpHandles; 13218 for (auto &PromOp : PromOps) 13219 PromOpHandles.emplace_back(PromOp); 13220 13221 // Replace all operations (these are all the same, but have a different 13222 // (i1) return type). DAG.getNode will validate that the types of 13223 // a binary operator match, so go through the list in reverse so that 13224 // we've likely promoted both operands first. Any intermediate truncations or 13225 // extensions disappear. 13226 while (!PromOpHandles.empty()) { 13227 SDValue PromOp = PromOpHandles.back().getValue(); 13228 PromOpHandles.pop_back(); 13229 13230 if (PromOp.getOpcode() == ISD::TRUNCATE || 13231 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13232 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13233 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13234 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13235 PromOp.getOperand(0).getValueType() != MVT::i1) { 13236 // The operand is not yet ready (see comment below). 13237 PromOpHandles.emplace_front(PromOp); 13238 continue; 13239 } 13240 13241 SDValue RepValue = PromOp.getOperand(0); 13242 if (isa<ConstantSDNode>(RepValue)) 13243 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13244 13245 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13246 continue; 13247 } 13248 13249 unsigned C; 13250 switch (PromOp.getOpcode()) { 13251 default: C = 0; break; 13252 case ISD::SELECT: C = 1; break; 13253 case ISD::SELECT_CC: C = 2; break; 13254 } 13255 13256 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13257 PromOp.getOperand(C).getValueType() != MVT::i1) || 13258 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13259 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13260 // The to-be-promoted operands of this node have not yet been 13261 // promoted (this should be rare because we're going through the 13262 // list backward, but if one of the operands has several users in 13263 // this cluster of to-be-promoted nodes, it is possible). 13264 PromOpHandles.emplace_front(PromOp); 13265 continue; 13266 } 13267 13268 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13269 PromOp.getNode()->op_end()); 13270 13271 // If there are any constant inputs, make sure they're replaced now. 13272 for (unsigned i = 0; i < 2; ++i) 13273 if (isa<ConstantSDNode>(Ops[C+i])) 13274 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13275 13276 DAG.ReplaceAllUsesOfValueWith(PromOp, 13277 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13278 } 13279 13280 // Now we're left with the initial truncation itself. 13281 if (N->getOpcode() == ISD::TRUNCATE) 13282 return N->getOperand(0); 13283 13284 // Otherwise, this is a comparison. The operands to be compared have just 13285 // changed type (to i1), but everything else is the same. 13286 return SDValue(N, 0); 13287 } 13288 13289 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13290 DAGCombinerInfo &DCI) const { 13291 SelectionDAG &DAG = DCI.DAG; 13292 SDLoc dl(N); 13293 13294 // If we're tracking CR bits, we need to be careful that we don't have: 13295 // zext(binary-ops(trunc(x), trunc(y))) 13296 // or 13297 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13298 // such that we're unnecessarily moving things into CR bits that can more 13299 // efficiently stay in GPRs. Note that if we're not certain that the high 13300 // bits are set as required by the final extension, we still may need to do 13301 // some masking to get the proper behavior. 13302 13303 // This same functionality is important on PPC64 when dealing with 13304 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13305 // the return values of functions. Because it is so similar, it is handled 13306 // here as well. 13307 13308 if (N->getValueType(0) != MVT::i32 && 13309 N->getValueType(0) != MVT::i64) 13310 return SDValue(); 13311 13312 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13313 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13314 return SDValue(); 13315 13316 if (N->getOperand(0).getOpcode() != ISD::AND && 13317 N->getOperand(0).getOpcode() != ISD::OR && 13318 N->getOperand(0).getOpcode() != ISD::XOR && 13319 N->getOperand(0).getOpcode() != ISD::SELECT && 13320 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13321 return SDValue(); 13322 13323 SmallVector<SDValue, 4> Inputs; 13324 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13325 SmallPtrSet<SDNode *, 16> Visited; 13326 13327 // Visit all inputs, collect all binary operations (and, or, xor and 13328 // select) that are all fed by truncations. 13329 while (!BinOps.empty()) { 13330 SDValue BinOp = BinOps.back(); 13331 BinOps.pop_back(); 13332 13333 if (!Visited.insert(BinOp.getNode()).second) 13334 continue; 13335 13336 PromOps.push_back(BinOp); 13337 13338 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13339 // The condition of the select is not promoted. 13340 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13341 continue; 13342 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13343 continue; 13344 13345 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13346 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13347 Inputs.push_back(BinOp.getOperand(i)); 13348 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13349 BinOp.getOperand(i).getOpcode() == ISD::OR || 13350 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13351 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13352 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13353 BinOps.push_back(BinOp.getOperand(i)); 13354 } else { 13355 // We have an input that is not a truncation or another binary 13356 // operation; we'll abort this transformation. 13357 return SDValue(); 13358 } 13359 } 13360 } 13361 13362 // The operands of a select that must be truncated when the select is 13363 // promoted because the operand is actually part of the to-be-promoted set. 13364 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13365 13366 // Make sure that this is a self-contained cluster of operations (which 13367 // is not quite the same thing as saying that everything has only one 13368 // use). 13369 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13370 if (isa<ConstantSDNode>(Inputs[i])) 13371 continue; 13372 13373 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13374 UE = Inputs[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) == Inputs[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) == Inputs[i]) 13388 SelectTruncOp[0].insert(std::make_pair(User, 13389 User->getOperand(0).getValueType())); 13390 if (User->getOperand(1) == Inputs[i]) 13391 SelectTruncOp[1].insert(std::make_pair(User, 13392 User->getOperand(1).getValueType())); 13393 } 13394 } 13395 } 13396 13397 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13398 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13399 UE = PromOps[i].getNode()->use_end(); 13400 UI != UE; ++UI) { 13401 SDNode *User = *UI; 13402 if (User != N && !Visited.count(User)) 13403 return SDValue(); 13404 13405 // If we're going to promote the non-output-value operand(s) or SELECT or 13406 // SELECT_CC, record them for truncation. 13407 if (User->getOpcode() == ISD::SELECT) { 13408 if (User->getOperand(0) == PromOps[i]) 13409 SelectTruncOp[0].insert(std::make_pair(User, 13410 User->getOperand(0).getValueType())); 13411 } else if (User->getOpcode() == ISD::SELECT_CC) { 13412 if (User->getOperand(0) == PromOps[i]) 13413 SelectTruncOp[0].insert(std::make_pair(User, 13414 User->getOperand(0).getValueType())); 13415 if (User->getOperand(1) == PromOps[i]) 13416 SelectTruncOp[1].insert(std::make_pair(User, 13417 User->getOperand(1).getValueType())); 13418 } 13419 } 13420 } 13421 13422 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13423 bool ReallyNeedsExt = false; 13424 if (N->getOpcode() != ISD::ANY_EXTEND) { 13425 // If all of the inputs are not already sign/zero extended, then 13426 // we'll still need to do that at the end. 13427 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13428 if (isa<ConstantSDNode>(Inputs[i])) 13429 continue; 13430 13431 unsigned OpBits = 13432 Inputs[i].getOperand(0).getValueSizeInBits(); 13433 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13434 13435 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13436 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13437 APInt::getHighBitsSet(OpBits, 13438 OpBits-PromBits))) || 13439 (N->getOpcode() == ISD::SIGN_EXTEND && 13440 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13441 (OpBits-(PromBits-1)))) { 13442 ReallyNeedsExt = true; 13443 break; 13444 } 13445 } 13446 } 13447 13448 // Replace all inputs, either with the truncation operand, or a 13449 // truncation or extension to the final output type. 13450 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13451 // Constant inputs need to be replaced with the to-be-promoted nodes that 13452 // use them because they might have users outside of the cluster of 13453 // promoted nodes. 13454 if (isa<ConstantSDNode>(Inputs[i])) 13455 continue; 13456 13457 SDValue InSrc = Inputs[i].getOperand(0); 13458 if (Inputs[i].getValueType() == N->getValueType(0)) 13459 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13460 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13461 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13462 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13463 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13464 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13465 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13466 else 13467 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13468 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13469 } 13470 13471 std::list<HandleSDNode> PromOpHandles; 13472 for (auto &PromOp : PromOps) 13473 PromOpHandles.emplace_back(PromOp); 13474 13475 // Replace all operations (these are all the same, but have a different 13476 // (promoted) return type). DAG.getNode will validate that the types of 13477 // a binary operator match, so go through the list in reverse so that 13478 // we've likely promoted both operands first. 13479 while (!PromOpHandles.empty()) { 13480 SDValue PromOp = PromOpHandles.back().getValue(); 13481 PromOpHandles.pop_back(); 13482 13483 unsigned C; 13484 switch (PromOp.getOpcode()) { 13485 default: C = 0; break; 13486 case ISD::SELECT: C = 1; break; 13487 case ISD::SELECT_CC: C = 2; break; 13488 } 13489 13490 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13491 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13492 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13493 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13494 // The to-be-promoted operands of this node have not yet been 13495 // promoted (this should be rare because we're going through the 13496 // list backward, but if one of the operands has several users in 13497 // this cluster of to-be-promoted nodes, it is possible). 13498 PromOpHandles.emplace_front(PromOp); 13499 continue; 13500 } 13501 13502 // For SELECT and SELECT_CC nodes, we do a similar check for any 13503 // to-be-promoted comparison inputs. 13504 if (PromOp.getOpcode() == ISD::SELECT || 13505 PromOp.getOpcode() == ISD::SELECT_CC) { 13506 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13507 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13508 (SelectTruncOp[1].count(PromOp.getNode()) && 13509 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13510 PromOpHandles.emplace_front(PromOp); 13511 continue; 13512 } 13513 } 13514 13515 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13516 PromOp.getNode()->op_end()); 13517 13518 // If this node has constant inputs, then they'll need to be promoted here. 13519 for (unsigned i = 0; i < 2; ++i) { 13520 if (!isa<ConstantSDNode>(Ops[C+i])) 13521 continue; 13522 if (Ops[C+i].getValueType() == N->getValueType(0)) 13523 continue; 13524 13525 if (N->getOpcode() == ISD::SIGN_EXTEND) 13526 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13527 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13528 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13529 else 13530 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13531 } 13532 13533 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13534 // truncate them again to the original value type. 13535 if (PromOp.getOpcode() == ISD::SELECT || 13536 PromOp.getOpcode() == ISD::SELECT_CC) { 13537 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13538 if (SI0 != SelectTruncOp[0].end()) 13539 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13540 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13541 if (SI1 != SelectTruncOp[1].end()) 13542 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13543 } 13544 13545 DAG.ReplaceAllUsesOfValueWith(PromOp, 13546 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13547 } 13548 13549 // Now we're left with the initial extension itself. 13550 if (!ReallyNeedsExt) 13551 return N->getOperand(0); 13552 13553 // To zero extend, just mask off everything except for the first bit (in the 13554 // i1 case). 13555 if (N->getOpcode() == ISD::ZERO_EXTEND) 13556 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13557 DAG.getConstant(APInt::getLowBitsSet( 13558 N->getValueSizeInBits(0), PromBits), 13559 dl, N->getValueType(0))); 13560 13561 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13562 "Invalid extension type"); 13563 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13564 SDValue ShiftCst = 13565 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13566 return DAG.getNode( 13567 ISD::SRA, dl, N->getValueType(0), 13568 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13569 ShiftCst); 13570 } 13571 13572 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13573 DAGCombinerInfo &DCI) const { 13574 assert(N->getOpcode() == ISD::SETCC && 13575 "Should be called with a SETCC node"); 13576 13577 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13578 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13579 SDValue LHS = N->getOperand(0); 13580 SDValue RHS = N->getOperand(1); 13581 13582 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13583 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13584 LHS.hasOneUse()) 13585 std::swap(LHS, RHS); 13586 13587 // x == 0-y --> x+y == 0 13588 // x != 0-y --> x+y != 0 13589 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13590 RHS.hasOneUse()) { 13591 SDLoc DL(N); 13592 SelectionDAG &DAG = DCI.DAG; 13593 EVT VT = N->getValueType(0); 13594 EVT OpVT = LHS.getValueType(); 13595 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13596 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13597 } 13598 } 13599 13600 return DAGCombineTruncBoolExt(N, DCI); 13601 } 13602 13603 // Is this an extending load from an f32 to an f64? 13604 static bool isFPExtLoad(SDValue Op) { 13605 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13606 return LD->getExtensionType() == ISD::EXTLOAD && 13607 Op.getValueType() == MVT::f64; 13608 return false; 13609 } 13610 13611 /// Reduces the number of fp-to-int conversion when building a vector. 13612 /// 13613 /// If this vector is built out of floating to integer conversions, 13614 /// transform it to a vector built out of floating point values followed by a 13615 /// single floating to integer conversion of the vector. 13616 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13617 /// becomes (fptosi (build_vector ($A, $B, ...))) 13618 SDValue PPCTargetLowering:: 13619 combineElementTruncationToVectorTruncation(SDNode *N, 13620 DAGCombinerInfo &DCI) const { 13621 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13622 "Should be called with a BUILD_VECTOR node"); 13623 13624 SelectionDAG &DAG = DCI.DAG; 13625 SDLoc dl(N); 13626 13627 SDValue FirstInput = N->getOperand(0); 13628 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13629 "The input operand must be an fp-to-int conversion."); 13630 13631 // This combine happens after legalization so the fp_to_[su]i nodes are 13632 // already converted to PPCSISD nodes. 13633 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13634 if (FirstConversion == PPCISD::FCTIDZ || 13635 FirstConversion == PPCISD::FCTIDUZ || 13636 FirstConversion == PPCISD::FCTIWZ || 13637 FirstConversion == PPCISD::FCTIWUZ) { 13638 bool IsSplat = true; 13639 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13640 FirstConversion == PPCISD::FCTIWUZ; 13641 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13642 SmallVector<SDValue, 4> Ops; 13643 EVT TargetVT = N->getValueType(0); 13644 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13645 SDValue NextOp = N->getOperand(i); 13646 if (NextOp.getOpcode() != PPCISD::MFVSR) 13647 return SDValue(); 13648 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13649 if (NextConversion != FirstConversion) 13650 return SDValue(); 13651 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13652 // This is not valid if the input was originally double precision. It is 13653 // also not profitable to do unless this is an extending load in which 13654 // case doing this combine will allow us to combine consecutive loads. 13655 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13656 return SDValue(); 13657 if (N->getOperand(i) != FirstInput) 13658 IsSplat = false; 13659 } 13660 13661 // If this is a splat, we leave it as-is since there will be only a single 13662 // fp-to-int conversion followed by a splat of the integer. This is better 13663 // for 32-bit and smaller ints and neutral for 64-bit ints. 13664 if (IsSplat) 13665 return SDValue(); 13666 13667 // Now that we know we have the right type of node, get its operands 13668 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13669 SDValue In = N->getOperand(i).getOperand(0); 13670 if (Is32Bit) { 13671 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13672 // here, we know that all inputs are extending loads so this is safe). 13673 if (In.isUndef()) 13674 Ops.push_back(DAG.getUNDEF(SrcVT)); 13675 else { 13676 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13677 MVT::f32, In.getOperand(0), 13678 DAG.getIntPtrConstant(1, dl)); 13679 Ops.push_back(Trunc); 13680 } 13681 } else 13682 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13683 } 13684 13685 unsigned Opcode; 13686 if (FirstConversion == PPCISD::FCTIDZ || 13687 FirstConversion == PPCISD::FCTIWZ) 13688 Opcode = ISD::FP_TO_SINT; 13689 else 13690 Opcode = ISD::FP_TO_UINT; 13691 13692 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13693 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13694 return DAG.getNode(Opcode, dl, TargetVT, BV); 13695 } 13696 return SDValue(); 13697 } 13698 13699 /// Reduce the number of loads when building a vector. 13700 /// 13701 /// Building a vector out of multiple loads can be converted to a load 13702 /// of the vector type if the loads are consecutive. If the loads are 13703 /// consecutive but in descending order, a shuffle is added at the end 13704 /// to reorder the vector. 13705 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13706 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13707 "Should be called with a BUILD_VECTOR node"); 13708 13709 SDLoc dl(N); 13710 13711 // Return early for non byte-sized type, as they can't be consecutive. 13712 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13713 return SDValue(); 13714 13715 bool InputsAreConsecutiveLoads = true; 13716 bool InputsAreReverseConsecutive = true; 13717 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13718 SDValue FirstInput = N->getOperand(0); 13719 bool IsRoundOfExtLoad = false; 13720 13721 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13722 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13723 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13724 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13725 } 13726 // Not a build vector of (possibly fp_rounded) loads. 13727 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13728 N->getNumOperands() == 1) 13729 return SDValue(); 13730 13731 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13732 // If any inputs are fp_round(extload), they all must be. 13733 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13734 return SDValue(); 13735 13736 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13737 N->getOperand(i); 13738 if (NextInput.getOpcode() != ISD::LOAD) 13739 return SDValue(); 13740 13741 SDValue PreviousInput = 13742 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13743 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13744 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13745 13746 // If any inputs are fp_round(extload), they all must be. 13747 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13748 return SDValue(); 13749 13750 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13751 InputsAreConsecutiveLoads = false; 13752 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13753 InputsAreReverseConsecutive = false; 13754 13755 // Exit early if the loads are neither consecutive nor reverse consecutive. 13756 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13757 return SDValue(); 13758 } 13759 13760 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13761 "The loads cannot be both consecutive and reverse consecutive."); 13762 13763 SDValue FirstLoadOp = 13764 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13765 SDValue LastLoadOp = 13766 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13767 N->getOperand(N->getNumOperands()-1); 13768 13769 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13770 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13771 if (InputsAreConsecutiveLoads) { 13772 assert(LD1 && "Input needs to be a LoadSDNode."); 13773 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13774 LD1->getBasePtr(), LD1->getPointerInfo(), 13775 LD1->getAlignment()); 13776 } 13777 if (InputsAreReverseConsecutive) { 13778 assert(LDL && "Input needs to be a LoadSDNode."); 13779 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13780 LDL->getBasePtr(), LDL->getPointerInfo(), 13781 LDL->getAlignment()); 13782 SmallVector<int, 16> Ops; 13783 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13784 Ops.push_back(i); 13785 13786 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13787 DAG.getUNDEF(N->getValueType(0)), Ops); 13788 } 13789 return SDValue(); 13790 } 13791 13792 // This function adds the required vector_shuffle needed to get 13793 // the elements of the vector extract in the correct position 13794 // as specified by the CorrectElems encoding. 13795 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13796 SDValue Input, uint64_t Elems, 13797 uint64_t CorrectElems) { 13798 SDLoc dl(N); 13799 13800 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13801 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13802 13803 // Knowing the element indices being extracted from the original 13804 // vector and the order in which they're being inserted, just put 13805 // them at element indices required for the instruction. 13806 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13807 if (DAG.getDataLayout().isLittleEndian()) 13808 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13809 else 13810 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13811 CorrectElems = CorrectElems >> 8; 13812 Elems = Elems >> 8; 13813 } 13814 13815 SDValue Shuffle = 13816 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13817 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13818 13819 EVT VT = N->getValueType(0); 13820 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13821 13822 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13823 Input.getValueType().getVectorElementType(), 13824 VT.getVectorNumElements()); 13825 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13826 DAG.getValueType(ExtVT)); 13827 } 13828 13829 // Look for build vector patterns where input operands come from sign 13830 // extended vector_extract elements of specific indices. If the correct indices 13831 // aren't used, add a vector shuffle to fix up the indices and create 13832 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13833 // during instruction selection. 13834 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13835 // This array encodes the indices that the vector sign extend instructions 13836 // extract from when extending from one type to another for both BE and LE. 13837 // The right nibble of each byte corresponds to the LE incides. 13838 // and the left nibble of each byte corresponds to the BE incides. 13839 // For example: 0x3074B8FC byte->word 13840 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13841 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13842 // For example: 0x000070F8 byte->double word 13843 // For LE: the allowed indices are: 0x0,0x8 13844 // For BE: the allowed indices are: 0x7,0xF 13845 uint64_t TargetElems[] = { 13846 0x3074B8FC, // b->w 13847 0x000070F8, // b->d 13848 0x10325476, // h->w 13849 0x00003074, // h->d 13850 0x00001032, // w->d 13851 }; 13852 13853 uint64_t Elems = 0; 13854 int Index; 13855 SDValue Input; 13856 13857 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13858 if (!Op) 13859 return false; 13860 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13861 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13862 return false; 13863 13864 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13865 // of the right width. 13866 SDValue Extract = Op.getOperand(0); 13867 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13868 Extract = Extract.getOperand(0); 13869 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13870 return false; 13871 13872 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13873 if (!ExtOp) 13874 return false; 13875 13876 Index = ExtOp->getZExtValue(); 13877 if (Input && Input != Extract.getOperand(0)) 13878 return false; 13879 13880 if (!Input) 13881 Input = Extract.getOperand(0); 13882 13883 Elems = Elems << 8; 13884 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13885 Elems |= Index; 13886 13887 return true; 13888 }; 13889 13890 // If the build vector operands aren't sign extended vector extracts, 13891 // of the same input vector, then return. 13892 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13893 if (!isSExtOfVecExtract(N->getOperand(i))) { 13894 return SDValue(); 13895 } 13896 } 13897 13898 // If the vector extract indicies are not correct, add the appropriate 13899 // vector_shuffle. 13900 int TgtElemArrayIdx; 13901 int InputSize = Input.getValueType().getScalarSizeInBits(); 13902 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13903 if (InputSize + OutputSize == 40) 13904 TgtElemArrayIdx = 0; 13905 else if (InputSize + OutputSize == 72) 13906 TgtElemArrayIdx = 1; 13907 else if (InputSize + OutputSize == 48) 13908 TgtElemArrayIdx = 2; 13909 else if (InputSize + OutputSize == 80) 13910 TgtElemArrayIdx = 3; 13911 else if (InputSize + OutputSize == 96) 13912 TgtElemArrayIdx = 4; 13913 else 13914 return SDValue(); 13915 13916 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13917 CorrectElems = DAG.getDataLayout().isLittleEndian() 13918 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13919 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13920 if (Elems != CorrectElems) { 13921 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13922 } 13923 13924 // Regular lowering will catch cases where a shuffle is not needed. 13925 return SDValue(); 13926 } 13927 13928 // Look for the pattern of a load from a narrow width to i128, feeding 13929 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13930 // (LXVRZX). This node represents a zero extending load that will be matched 13931 // to the Load VSX Vector Rightmost instructions. 13932 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13933 SDLoc DL(N); 13934 13935 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13936 if (N->getValueType(0) != MVT::v1i128) 13937 return SDValue(); 13938 13939 SDValue Operand = N->getOperand(0); 13940 // Proceed with the transformation if the operand to the BUILD_VECTOR 13941 // is a load instruction. 13942 if (Operand.getOpcode() != ISD::LOAD) 13943 return SDValue(); 13944 13945 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13946 EVT MemoryType = LD->getMemoryVT(); 13947 13948 // This transformation is only valid if the we are loading either a byte, 13949 // halfword, word, or doubleword. 13950 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13951 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13952 13953 // Ensure that the load from the narrow width is being zero extended to i128. 13954 if (!ValidLDType || 13955 (LD->getExtensionType() != ISD::ZEXTLOAD && 13956 LD->getExtensionType() != ISD::EXTLOAD)) 13957 return SDValue(); 13958 13959 SDValue LoadOps[] = { 13960 LD->getChain(), LD->getBasePtr(), 13961 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13962 13963 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13964 DAG.getVTList(MVT::v1i128, MVT::Other), 13965 LoadOps, MemoryType, LD->getMemOperand()); 13966 } 13967 13968 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13969 DAGCombinerInfo &DCI) const { 13970 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13971 "Should be called with a BUILD_VECTOR node"); 13972 13973 SelectionDAG &DAG = DCI.DAG; 13974 SDLoc dl(N); 13975 13976 if (!Subtarget.hasVSX()) 13977 return SDValue(); 13978 13979 // The target independent DAG combiner will leave a build_vector of 13980 // float-to-int conversions intact. We can generate MUCH better code for 13981 // a float-to-int conversion of a vector of floats. 13982 SDValue FirstInput = N->getOperand(0); 13983 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13984 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13985 if (Reduced) 13986 return Reduced; 13987 } 13988 13989 // If we're building a vector out of consecutive loads, just load that 13990 // vector type. 13991 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13992 if (Reduced) 13993 return Reduced; 13994 13995 // If we're building a vector out of extended elements from another vector 13996 // we have P9 vector integer extend instructions. The code assumes legal 13997 // input types (i.e. it can't handle things like v4i16) so do not run before 13998 // legalization. 13999 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14000 Reduced = combineBVOfVecSExt(N, DAG); 14001 if (Reduced) 14002 return Reduced; 14003 } 14004 14005 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14006 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14007 // is a load from <valid narrow width> to i128. 14008 if (Subtarget.isISA3_1()) { 14009 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14010 if (BVOfZLoad) 14011 return BVOfZLoad; 14012 } 14013 14014 if (N->getValueType(0) != MVT::v2f64) 14015 return SDValue(); 14016 14017 // Looking for: 14018 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14019 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14020 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14021 return SDValue(); 14022 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14023 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14024 return SDValue(); 14025 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14026 return SDValue(); 14027 14028 SDValue Ext1 = FirstInput.getOperand(0); 14029 SDValue Ext2 = N->getOperand(1).getOperand(0); 14030 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14031 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14032 return SDValue(); 14033 14034 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14035 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14036 if (!Ext1Op || !Ext2Op) 14037 return SDValue(); 14038 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14039 Ext1.getOperand(0) != Ext2.getOperand(0)) 14040 return SDValue(); 14041 14042 int FirstElem = Ext1Op->getZExtValue(); 14043 int SecondElem = Ext2Op->getZExtValue(); 14044 int SubvecIdx; 14045 if (FirstElem == 0 && SecondElem == 1) 14046 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14047 else if (FirstElem == 2 && SecondElem == 3) 14048 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14049 else 14050 return SDValue(); 14051 14052 SDValue SrcVec = Ext1.getOperand(0); 14053 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14054 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14055 return DAG.getNode(NodeType, dl, MVT::v2f64, 14056 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14057 } 14058 14059 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14060 DAGCombinerInfo &DCI) const { 14061 assert((N->getOpcode() == ISD::SINT_TO_FP || 14062 N->getOpcode() == ISD::UINT_TO_FP) && 14063 "Need an int -> FP conversion node here"); 14064 14065 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14066 return SDValue(); 14067 14068 SelectionDAG &DAG = DCI.DAG; 14069 SDLoc dl(N); 14070 SDValue Op(N, 0); 14071 14072 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14073 // from the hardware. 14074 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14075 return SDValue(); 14076 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14077 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14078 return SDValue(); 14079 14080 SDValue FirstOperand(Op.getOperand(0)); 14081 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14082 (FirstOperand.getValueType() == MVT::i8 || 14083 FirstOperand.getValueType() == MVT::i16); 14084 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14085 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14086 bool DstDouble = Op.getValueType() == MVT::f64; 14087 unsigned ConvOp = Signed ? 14088 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14089 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14090 SDValue WidthConst = 14091 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14092 dl, false); 14093 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14094 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14095 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14096 DAG.getVTList(MVT::f64, MVT::Other), 14097 Ops, MVT::i8, LDN->getMemOperand()); 14098 14099 // For signed conversion, we need to sign-extend the value in the VSR 14100 if (Signed) { 14101 SDValue ExtOps[] = { Ld, WidthConst }; 14102 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14103 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14104 } else 14105 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14106 } 14107 14108 14109 // For i32 intermediate values, unfortunately, the conversion functions 14110 // leave the upper 32 bits of the value are undefined. Within the set of 14111 // scalar instructions, we have no method for zero- or sign-extending the 14112 // value. Thus, we cannot handle i32 intermediate values here. 14113 if (Op.getOperand(0).getValueType() == MVT::i32) 14114 return SDValue(); 14115 14116 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14117 "UINT_TO_FP is supported only with FPCVT"); 14118 14119 // If we have FCFIDS, then use it when converting to single-precision. 14120 // Otherwise, convert to double-precision and then round. 14121 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14122 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14123 : PPCISD::FCFIDS) 14124 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14125 : PPCISD::FCFID); 14126 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14127 ? MVT::f32 14128 : MVT::f64; 14129 14130 // If we're converting from a float, to an int, and back to a float again, 14131 // then we don't need the store/load pair at all. 14132 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14133 Subtarget.hasFPCVT()) || 14134 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14135 SDValue Src = Op.getOperand(0).getOperand(0); 14136 if (Src.getValueType() == MVT::f32) { 14137 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14138 DCI.AddToWorklist(Src.getNode()); 14139 } else if (Src.getValueType() != MVT::f64) { 14140 // Make sure that we don't pick up a ppc_fp128 source value. 14141 return SDValue(); 14142 } 14143 14144 unsigned FCTOp = 14145 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14146 PPCISD::FCTIDUZ; 14147 14148 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14149 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14150 14151 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14152 FP = DAG.getNode(ISD::FP_ROUND, dl, 14153 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 14154 DCI.AddToWorklist(FP.getNode()); 14155 } 14156 14157 return FP; 14158 } 14159 14160 return SDValue(); 14161 } 14162 14163 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14164 // builtins) into loads with swaps. 14165 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14166 DAGCombinerInfo &DCI) const { 14167 SelectionDAG &DAG = DCI.DAG; 14168 SDLoc dl(N); 14169 SDValue Chain; 14170 SDValue Base; 14171 MachineMemOperand *MMO; 14172 14173 switch (N->getOpcode()) { 14174 default: 14175 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14176 case ISD::LOAD: { 14177 LoadSDNode *LD = cast<LoadSDNode>(N); 14178 Chain = LD->getChain(); 14179 Base = LD->getBasePtr(); 14180 MMO = LD->getMemOperand(); 14181 // If the MMO suggests this isn't a load of a full vector, leave 14182 // things alone. For a built-in, we have to make the change for 14183 // correctness, so if there is a size problem that will be a bug. 14184 if (MMO->getSize() < 16) 14185 return SDValue(); 14186 break; 14187 } 14188 case ISD::INTRINSIC_W_CHAIN: { 14189 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14190 Chain = Intrin->getChain(); 14191 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14192 // us what we want. Get operand 2 instead. 14193 Base = Intrin->getOperand(2); 14194 MMO = Intrin->getMemOperand(); 14195 break; 14196 } 14197 } 14198 14199 MVT VecTy = N->getValueType(0).getSimpleVT(); 14200 14201 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14202 // aligned and the type is a vector with elements up to 4 bytes 14203 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14204 VecTy.getScalarSizeInBits() <= 32) { 14205 return SDValue(); 14206 } 14207 14208 SDValue LoadOps[] = { Chain, Base }; 14209 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14210 DAG.getVTList(MVT::v2f64, MVT::Other), 14211 LoadOps, MVT::v2f64, MMO); 14212 14213 DCI.AddToWorklist(Load.getNode()); 14214 Chain = Load.getValue(1); 14215 SDValue Swap = DAG.getNode( 14216 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14217 DCI.AddToWorklist(Swap.getNode()); 14218 14219 // Add a bitcast if the resulting load type doesn't match v2f64. 14220 if (VecTy != MVT::v2f64) { 14221 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14222 DCI.AddToWorklist(N.getNode()); 14223 // Package {bitcast value, swap's chain} to match Load's shape. 14224 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14225 N, Swap.getValue(1)); 14226 } 14227 14228 return Swap; 14229 } 14230 14231 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14232 // builtins) into stores with swaps. 14233 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14234 DAGCombinerInfo &DCI) const { 14235 SelectionDAG &DAG = DCI.DAG; 14236 SDLoc dl(N); 14237 SDValue Chain; 14238 SDValue Base; 14239 unsigned SrcOpnd; 14240 MachineMemOperand *MMO; 14241 14242 switch (N->getOpcode()) { 14243 default: 14244 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14245 case ISD::STORE: { 14246 StoreSDNode *ST = cast<StoreSDNode>(N); 14247 Chain = ST->getChain(); 14248 Base = ST->getBasePtr(); 14249 MMO = ST->getMemOperand(); 14250 SrcOpnd = 1; 14251 // If the MMO suggests this isn't a store of a full vector, leave 14252 // things alone. For a built-in, we have to make the change for 14253 // correctness, so if there is a size problem that will be a bug. 14254 if (MMO->getSize() < 16) 14255 return SDValue(); 14256 break; 14257 } 14258 case ISD::INTRINSIC_VOID: { 14259 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14260 Chain = Intrin->getChain(); 14261 // Intrin->getBasePtr() oddly does not get what we want. 14262 Base = Intrin->getOperand(3); 14263 MMO = Intrin->getMemOperand(); 14264 SrcOpnd = 2; 14265 break; 14266 } 14267 } 14268 14269 SDValue Src = N->getOperand(SrcOpnd); 14270 MVT VecTy = Src.getValueType().getSimpleVT(); 14271 14272 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14273 // aligned and the type is a vector with elements up to 4 bytes 14274 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14275 VecTy.getScalarSizeInBits() <= 32) { 14276 return SDValue(); 14277 } 14278 14279 // All stores are done as v2f64 and possible bit cast. 14280 if (VecTy != MVT::v2f64) { 14281 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14282 DCI.AddToWorklist(Src.getNode()); 14283 } 14284 14285 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14286 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14287 DCI.AddToWorklist(Swap.getNode()); 14288 Chain = Swap.getValue(1); 14289 SDValue StoreOps[] = { Chain, Swap, Base }; 14290 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14291 DAG.getVTList(MVT::Other), 14292 StoreOps, VecTy, MMO); 14293 DCI.AddToWorklist(Store.getNode()); 14294 return Store; 14295 } 14296 14297 // Handle DAG combine for STORE (FP_TO_INT F). 14298 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14299 DAGCombinerInfo &DCI) const { 14300 14301 SelectionDAG &DAG = DCI.DAG; 14302 SDLoc dl(N); 14303 unsigned Opcode = N->getOperand(1).getOpcode(); 14304 14305 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14306 && "Not a FP_TO_INT Instruction!"); 14307 14308 SDValue Val = N->getOperand(1).getOperand(0); 14309 EVT Op1VT = N->getOperand(1).getValueType(); 14310 EVT ResVT = Val.getValueType(); 14311 14312 if (!isTypeLegal(ResVT)) 14313 return SDValue(); 14314 14315 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14316 bool ValidTypeForStoreFltAsInt = 14317 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14318 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14319 14320 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14321 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14322 return SDValue(); 14323 14324 // Extend f32 values to f64 14325 if (ResVT.getScalarSizeInBits() == 32) { 14326 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14327 DCI.AddToWorklist(Val.getNode()); 14328 } 14329 14330 // Set signed or unsigned conversion opcode. 14331 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14332 PPCISD::FP_TO_SINT_IN_VSR : 14333 PPCISD::FP_TO_UINT_IN_VSR; 14334 14335 Val = DAG.getNode(ConvOpcode, 14336 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14337 DCI.AddToWorklist(Val.getNode()); 14338 14339 // Set number of bytes being converted. 14340 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14341 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14342 DAG.getIntPtrConstant(ByteSize, dl, false), 14343 DAG.getValueType(Op1VT) }; 14344 14345 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14346 DAG.getVTList(MVT::Other), Ops, 14347 cast<StoreSDNode>(N)->getMemoryVT(), 14348 cast<StoreSDNode>(N)->getMemOperand()); 14349 14350 DCI.AddToWorklist(Val.getNode()); 14351 return Val; 14352 } 14353 14354 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14355 // Check that the source of the element keeps flipping 14356 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14357 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14358 for (int i = 1, e = Mask.size(); i < e; i++) { 14359 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14360 return false; 14361 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14362 return false; 14363 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14364 } 14365 return true; 14366 } 14367 14368 static bool isSplatBV(SDValue Op) { 14369 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14370 return false; 14371 SDValue FirstOp; 14372 14373 // Find first non-undef input. 14374 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14375 FirstOp = Op.getOperand(i); 14376 if (!FirstOp.isUndef()) 14377 break; 14378 } 14379 14380 // All inputs are undef or the same as the first non-undef input. 14381 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14382 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14383 return false; 14384 return true; 14385 } 14386 14387 static SDValue isScalarToVec(SDValue Op) { 14388 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14389 return Op; 14390 if (Op.getOpcode() != ISD::BITCAST) 14391 return SDValue(); 14392 Op = Op.getOperand(0); 14393 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14394 return Op; 14395 return SDValue(); 14396 } 14397 14398 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14399 int LHSMaxIdx, int RHSMinIdx, 14400 int RHSMaxIdx, int HalfVec) { 14401 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14402 int Idx = ShuffV[i]; 14403 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14404 ShuffV[i] += HalfVec; 14405 } 14406 return; 14407 } 14408 14409 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14410 // the original is: 14411 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14412 // In such a case, just change the shuffle mask to extract the element 14413 // from the permuted index. 14414 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14415 SDLoc dl(OrigSToV); 14416 EVT VT = OrigSToV.getValueType(); 14417 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14418 "Expecting a SCALAR_TO_VECTOR here"); 14419 SDValue Input = OrigSToV.getOperand(0); 14420 14421 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14422 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14423 SDValue OrigVector = Input.getOperand(0); 14424 14425 // Can't handle non-const element indices or different vector types 14426 // for the input to the extract and the output of the scalar_to_vector. 14427 if (Idx && VT == OrigVector.getValueType()) { 14428 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14429 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14430 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14431 } 14432 } 14433 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14434 OrigSToV.getOperand(0)); 14435 } 14436 14437 // On little endian subtargets, combine shuffles such as: 14438 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14439 // into: 14440 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14441 // because the latter can be matched to a single instruction merge. 14442 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14443 // to put the value into element zero. Adjust the shuffle mask so that the 14444 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14445 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14446 SelectionDAG &DAG) const { 14447 SDValue LHS = SVN->getOperand(0); 14448 SDValue RHS = SVN->getOperand(1); 14449 auto Mask = SVN->getMask(); 14450 int NumElts = LHS.getValueType().getVectorNumElements(); 14451 SDValue Res(SVN, 0); 14452 SDLoc dl(SVN); 14453 14454 // None of these combines are useful on big endian systems since the ISA 14455 // already has a big endian bias. 14456 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14457 return Res; 14458 14459 // If this is not a shuffle of a shuffle and the first element comes from 14460 // the second vector, canonicalize to the commuted form. This will make it 14461 // more likely to match one of the single instruction patterns. 14462 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14463 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14464 std::swap(LHS, RHS); 14465 Res = DAG.getCommutedVectorShuffle(*SVN); 14466 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14467 } 14468 14469 // Adjust the shuffle mask if either input vector comes from a 14470 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14471 // form (to prevent the need for a swap). 14472 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14473 SDValue SToVLHS = isScalarToVec(LHS); 14474 SDValue SToVRHS = isScalarToVec(RHS); 14475 if (SToVLHS || SToVRHS) { 14476 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14477 : SToVRHS.getValueType().getVectorNumElements(); 14478 int NumEltsOut = ShuffV.size(); 14479 14480 // Initially assume that neither input is permuted. These will be adjusted 14481 // accordingly if either input is. 14482 int LHSMaxIdx = -1; 14483 int RHSMinIdx = -1; 14484 int RHSMaxIdx = -1; 14485 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14486 14487 // Get the permuted scalar to vector nodes for the source(s) that come from 14488 // ISD::SCALAR_TO_VECTOR. 14489 if (SToVLHS) { 14490 // Set up the values for the shuffle vector fixup. 14491 LHSMaxIdx = NumEltsOut / NumEltsIn; 14492 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14493 if (SToVLHS.getValueType() != LHS.getValueType()) 14494 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14495 LHS = SToVLHS; 14496 } 14497 if (SToVRHS) { 14498 RHSMinIdx = NumEltsOut; 14499 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14500 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14501 if (SToVRHS.getValueType() != RHS.getValueType()) 14502 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14503 RHS = SToVRHS; 14504 } 14505 14506 // Fix up the shuffle mask to reflect where the desired element actually is. 14507 // The minimum and maximum indices that correspond to element zero for both 14508 // the LHS and RHS are computed and will control which shuffle mask entries 14509 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14510 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14511 // HalfVec to refer to the corresponding element in the permuted vector. 14512 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14513 HalfVec); 14514 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14515 14516 // We may have simplified away the shuffle. We won't be able to do anything 14517 // further with it here. 14518 if (!isa<ShuffleVectorSDNode>(Res)) 14519 return Res; 14520 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14521 } 14522 14523 // The common case after we commuted the shuffle is that the RHS is a splat 14524 // and we have elements coming in from the splat at indices that are not 14525 // conducive to using a merge. 14526 // Example: 14527 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14528 if (!isSplatBV(RHS)) 14529 return Res; 14530 14531 // We are looking for a mask such that all even elements are from 14532 // one vector and all odd elements from the other. 14533 if (!isAlternatingShuffMask(Mask, NumElts)) 14534 return Res; 14535 14536 // Adjust the mask so we are pulling in the same index from the splat 14537 // as the index from the interesting vector in consecutive elements. 14538 // Example (even elements from first vector): 14539 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14540 if (Mask[0] < NumElts) 14541 for (int i = 1, e = Mask.size(); i < e; i += 2) 14542 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14543 // Example (odd elements from first vector): 14544 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14545 else 14546 for (int i = 0, e = Mask.size(); i < e; i += 2) 14547 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14548 14549 // If the RHS has undefs, we need to remove them since we may have created 14550 // a shuffle that adds those instead of the splat value. 14551 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14552 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14553 14554 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14555 return Res; 14556 } 14557 14558 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14559 LSBaseSDNode *LSBase, 14560 DAGCombinerInfo &DCI) const { 14561 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14562 "Not a reverse memop pattern!"); 14563 14564 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14565 auto Mask = SVN->getMask(); 14566 int i = 0; 14567 auto I = Mask.rbegin(); 14568 auto E = Mask.rend(); 14569 14570 for (; I != E; ++I) { 14571 if (*I != i) 14572 return false; 14573 i++; 14574 } 14575 return true; 14576 }; 14577 14578 SelectionDAG &DAG = DCI.DAG; 14579 EVT VT = SVN->getValueType(0); 14580 14581 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14582 return SDValue(); 14583 14584 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14585 // See comment in PPCVSXSwapRemoval.cpp. 14586 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14587 if (!Subtarget.hasP9Vector()) 14588 return SDValue(); 14589 14590 if(!IsElementReverse(SVN)) 14591 return SDValue(); 14592 14593 if (LSBase->getOpcode() == ISD::LOAD) { 14594 SDLoc dl(SVN); 14595 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14596 return DAG.getMemIntrinsicNode( 14597 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14598 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14599 } 14600 14601 if (LSBase->getOpcode() == ISD::STORE) { 14602 SDLoc dl(LSBase); 14603 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14604 LSBase->getBasePtr()}; 14605 return DAG.getMemIntrinsicNode( 14606 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14607 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14608 } 14609 14610 llvm_unreachable("Expected a load or store node here"); 14611 } 14612 14613 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14614 DAGCombinerInfo &DCI) const { 14615 SelectionDAG &DAG = DCI.DAG; 14616 SDLoc dl(N); 14617 switch (N->getOpcode()) { 14618 default: break; 14619 case ISD::ADD: 14620 return combineADD(N, DCI); 14621 case ISD::SHL: 14622 return combineSHL(N, DCI); 14623 case ISD::SRA: 14624 return combineSRA(N, DCI); 14625 case ISD::SRL: 14626 return combineSRL(N, DCI); 14627 case ISD::MUL: 14628 return combineMUL(N, DCI); 14629 case ISD::FMA: 14630 case PPCISD::FNMSUB: 14631 return combineFMALike(N, DCI); 14632 case PPCISD::SHL: 14633 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14634 return N->getOperand(0); 14635 break; 14636 case PPCISD::SRL: 14637 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14638 return N->getOperand(0); 14639 break; 14640 case PPCISD::SRA: 14641 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14642 if (C->isNullValue() || // 0 >>s V -> 0. 14643 C->isAllOnesValue()) // -1 >>s V -> -1. 14644 return N->getOperand(0); 14645 } 14646 break; 14647 case ISD::SIGN_EXTEND: 14648 case ISD::ZERO_EXTEND: 14649 case ISD::ANY_EXTEND: 14650 return DAGCombineExtBoolTrunc(N, DCI); 14651 case ISD::TRUNCATE: 14652 return combineTRUNCATE(N, DCI); 14653 case ISD::SETCC: 14654 if (SDValue CSCC = combineSetCC(N, DCI)) 14655 return CSCC; 14656 LLVM_FALLTHROUGH; 14657 case ISD::SELECT_CC: 14658 return DAGCombineTruncBoolExt(N, DCI); 14659 case ISD::SINT_TO_FP: 14660 case ISD::UINT_TO_FP: 14661 return combineFPToIntToFP(N, DCI); 14662 case ISD::VECTOR_SHUFFLE: 14663 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14664 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14665 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14666 } 14667 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14668 case ISD::STORE: { 14669 14670 EVT Op1VT = N->getOperand(1).getValueType(); 14671 unsigned Opcode = N->getOperand(1).getOpcode(); 14672 14673 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14674 SDValue Val= combineStoreFPToInt(N, DCI); 14675 if (Val) 14676 return Val; 14677 } 14678 14679 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14680 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14681 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14682 if (Val) 14683 return Val; 14684 } 14685 14686 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14687 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14688 N->getOperand(1).getNode()->hasOneUse() && 14689 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14690 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14691 14692 // STBRX can only handle simple types and it makes no sense to store less 14693 // two bytes in byte-reversed order. 14694 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14695 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14696 break; 14697 14698 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14699 // Do an any-extend to 32-bits if this is a half-word input. 14700 if (BSwapOp.getValueType() == MVT::i16) 14701 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14702 14703 // If the type of BSWAP operand is wider than stored memory width 14704 // it need to be shifted to the right side before STBRX. 14705 if (Op1VT.bitsGT(mVT)) { 14706 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14707 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14708 DAG.getConstant(Shift, dl, MVT::i32)); 14709 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14710 if (Op1VT == MVT::i64) 14711 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14712 } 14713 14714 SDValue Ops[] = { 14715 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14716 }; 14717 return 14718 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14719 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14720 cast<StoreSDNode>(N)->getMemOperand()); 14721 } 14722 14723 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14724 // So it can increase the chance of CSE constant construction. 14725 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14726 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14727 // Need to sign-extended to 64-bits to handle negative values. 14728 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14729 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14730 MemVT.getSizeInBits()); 14731 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14732 14733 // DAG.getTruncStore() can't be used here because it doesn't accept 14734 // the general (base + offset) addressing mode. 14735 // So we use UpdateNodeOperands and setTruncatingStore instead. 14736 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14737 N->getOperand(3)); 14738 cast<StoreSDNode>(N)->setTruncatingStore(true); 14739 return SDValue(N, 0); 14740 } 14741 14742 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14743 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14744 if (Op1VT.isSimple()) { 14745 MVT StoreVT = Op1VT.getSimpleVT(); 14746 if (Subtarget.needsSwapsForVSXMemOps() && 14747 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14748 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14749 return expandVSXStoreForLE(N, DCI); 14750 } 14751 break; 14752 } 14753 case ISD::LOAD: { 14754 LoadSDNode *LD = cast<LoadSDNode>(N); 14755 EVT VT = LD->getValueType(0); 14756 14757 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14758 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14759 if (VT.isSimple()) { 14760 MVT LoadVT = VT.getSimpleVT(); 14761 if (Subtarget.needsSwapsForVSXMemOps() && 14762 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14763 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14764 return expandVSXLoadForLE(N, DCI); 14765 } 14766 14767 // We sometimes end up with a 64-bit integer load, from which we extract 14768 // two single-precision floating-point numbers. This happens with 14769 // std::complex<float>, and other similar structures, because of the way we 14770 // canonicalize structure copies. However, if we lack direct moves, 14771 // then the final bitcasts from the extracted integer values to the 14772 // floating-point numbers turn into store/load pairs. Even with direct moves, 14773 // just loading the two floating-point numbers is likely better. 14774 auto ReplaceTwoFloatLoad = [&]() { 14775 if (VT != MVT::i64) 14776 return false; 14777 14778 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14779 LD->isVolatile()) 14780 return false; 14781 14782 // We're looking for a sequence like this: 14783 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14784 // t16: i64 = srl t13, Constant:i32<32> 14785 // t17: i32 = truncate t16 14786 // t18: f32 = bitcast t17 14787 // t19: i32 = truncate t13 14788 // t20: f32 = bitcast t19 14789 14790 if (!LD->hasNUsesOfValue(2, 0)) 14791 return false; 14792 14793 auto UI = LD->use_begin(); 14794 while (UI.getUse().getResNo() != 0) ++UI; 14795 SDNode *Trunc = *UI++; 14796 while (UI.getUse().getResNo() != 0) ++UI; 14797 SDNode *RightShift = *UI; 14798 if (Trunc->getOpcode() != ISD::TRUNCATE) 14799 std::swap(Trunc, RightShift); 14800 14801 if (Trunc->getOpcode() != ISD::TRUNCATE || 14802 Trunc->getValueType(0) != MVT::i32 || 14803 !Trunc->hasOneUse()) 14804 return false; 14805 if (RightShift->getOpcode() != ISD::SRL || 14806 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14807 RightShift->getConstantOperandVal(1) != 32 || 14808 !RightShift->hasOneUse()) 14809 return false; 14810 14811 SDNode *Trunc2 = *RightShift->use_begin(); 14812 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14813 Trunc2->getValueType(0) != MVT::i32 || 14814 !Trunc2->hasOneUse()) 14815 return false; 14816 14817 SDNode *Bitcast = *Trunc->use_begin(); 14818 SDNode *Bitcast2 = *Trunc2->use_begin(); 14819 14820 if (Bitcast->getOpcode() != ISD::BITCAST || 14821 Bitcast->getValueType(0) != MVT::f32) 14822 return false; 14823 if (Bitcast2->getOpcode() != ISD::BITCAST || 14824 Bitcast2->getValueType(0) != MVT::f32) 14825 return false; 14826 14827 if (Subtarget.isLittleEndian()) 14828 std::swap(Bitcast, Bitcast2); 14829 14830 // Bitcast has the second float (in memory-layout order) and Bitcast2 14831 // has the first one. 14832 14833 SDValue BasePtr = LD->getBasePtr(); 14834 if (LD->isIndexed()) { 14835 assert(LD->getAddressingMode() == ISD::PRE_INC && 14836 "Non-pre-inc AM on PPC?"); 14837 BasePtr = 14838 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14839 LD->getOffset()); 14840 } 14841 14842 auto MMOFlags = 14843 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14844 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14845 LD->getPointerInfo(), LD->getAlignment(), 14846 MMOFlags, LD->getAAInfo()); 14847 SDValue AddPtr = 14848 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14849 BasePtr, DAG.getIntPtrConstant(4, dl)); 14850 SDValue FloatLoad2 = DAG.getLoad( 14851 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14852 LD->getPointerInfo().getWithOffset(4), 14853 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14854 14855 if (LD->isIndexed()) { 14856 // Note that DAGCombine should re-form any pre-increment load(s) from 14857 // what is produced here if that makes sense. 14858 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14859 } 14860 14861 DCI.CombineTo(Bitcast2, FloatLoad); 14862 DCI.CombineTo(Bitcast, FloatLoad2); 14863 14864 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14865 SDValue(FloatLoad2.getNode(), 1)); 14866 return true; 14867 }; 14868 14869 if (ReplaceTwoFloatLoad()) 14870 return SDValue(N, 0); 14871 14872 EVT MemVT = LD->getMemoryVT(); 14873 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14874 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14875 if (LD->isUnindexed() && VT.isVector() && 14876 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14877 // P8 and later hardware should just use LOAD. 14878 !Subtarget.hasP8Vector() && 14879 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14880 VT == MVT::v4f32))) && 14881 LD->getAlign() < ABIAlignment) { 14882 // This is a type-legal unaligned Altivec load. 14883 SDValue Chain = LD->getChain(); 14884 SDValue Ptr = LD->getBasePtr(); 14885 bool isLittleEndian = Subtarget.isLittleEndian(); 14886 14887 // This implements the loading of unaligned vectors as described in 14888 // the venerable Apple Velocity Engine overview. Specifically: 14889 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14890 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14891 // 14892 // The general idea is to expand a sequence of one or more unaligned 14893 // loads into an alignment-based permutation-control instruction (lvsl 14894 // or lvsr), a series of regular vector loads (which always truncate 14895 // their input address to an aligned address), and a series of 14896 // permutations. The results of these permutations are the requested 14897 // loaded values. The trick is that the last "extra" load is not taken 14898 // from the address you might suspect (sizeof(vector) bytes after the 14899 // last requested load), but rather sizeof(vector) - 1 bytes after the 14900 // last requested vector. The point of this is to avoid a page fault if 14901 // the base address happened to be aligned. This works because if the 14902 // base address is aligned, then adding less than a full vector length 14903 // will cause the last vector in the sequence to be (re)loaded. 14904 // Otherwise, the next vector will be fetched as you might suspect was 14905 // necessary. 14906 14907 // We might be able to reuse the permutation generation from 14908 // a different base address offset from this one by an aligned amount. 14909 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14910 // optimization later. 14911 Intrinsic::ID Intr, IntrLD, IntrPerm; 14912 MVT PermCntlTy, PermTy, LDTy; 14913 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14914 : Intrinsic::ppc_altivec_lvsl; 14915 IntrLD = Intrinsic::ppc_altivec_lvx; 14916 IntrPerm = Intrinsic::ppc_altivec_vperm; 14917 PermCntlTy = MVT::v16i8; 14918 PermTy = MVT::v4i32; 14919 LDTy = MVT::v4i32; 14920 14921 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14922 14923 // Create the new MMO for the new base load. It is like the original MMO, 14924 // but represents an area in memory almost twice the vector size centered 14925 // on the original address. If the address is unaligned, we might start 14926 // reading up to (sizeof(vector)-1) bytes below the address of the 14927 // original unaligned load. 14928 MachineFunction &MF = DAG.getMachineFunction(); 14929 MachineMemOperand *BaseMMO = 14930 MF.getMachineMemOperand(LD->getMemOperand(), 14931 -(long)MemVT.getStoreSize()+1, 14932 2*MemVT.getStoreSize()-1); 14933 14934 // Create the new base load. 14935 SDValue LDXIntID = 14936 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14937 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14938 SDValue BaseLoad = 14939 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14940 DAG.getVTList(PermTy, MVT::Other), 14941 BaseLoadOps, LDTy, BaseMMO); 14942 14943 // Note that the value of IncOffset (which is provided to the next 14944 // load's pointer info offset value, and thus used to calculate the 14945 // alignment), and the value of IncValue (which is actually used to 14946 // increment the pointer value) are different! This is because we 14947 // require the next load to appear to be aligned, even though it 14948 // is actually offset from the base pointer by a lesser amount. 14949 int IncOffset = VT.getSizeInBits() / 8; 14950 int IncValue = IncOffset; 14951 14952 // Walk (both up and down) the chain looking for another load at the real 14953 // (aligned) offset (the alignment of the other load does not matter in 14954 // this case). If found, then do not use the offset reduction trick, as 14955 // that will prevent the loads from being later combined (as they would 14956 // otherwise be duplicates). 14957 if (!findConsecutiveLoad(LD, DAG)) 14958 --IncValue; 14959 14960 SDValue Increment = 14961 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14962 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14963 14964 MachineMemOperand *ExtraMMO = 14965 MF.getMachineMemOperand(LD->getMemOperand(), 14966 1, 2*MemVT.getStoreSize()-1); 14967 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14968 SDValue ExtraLoad = 14969 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14970 DAG.getVTList(PermTy, MVT::Other), 14971 ExtraLoadOps, LDTy, ExtraMMO); 14972 14973 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14974 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14975 14976 // Because vperm has a big-endian bias, we must reverse the order 14977 // of the input vectors and complement the permute control vector 14978 // when generating little endian code. We have already handled the 14979 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14980 // and ExtraLoad here. 14981 SDValue Perm; 14982 if (isLittleEndian) 14983 Perm = BuildIntrinsicOp(IntrPerm, 14984 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14985 else 14986 Perm = BuildIntrinsicOp(IntrPerm, 14987 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14988 14989 if (VT != PermTy) 14990 Perm = Subtarget.hasAltivec() 14991 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14992 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14993 DAG.getTargetConstant(1, dl, MVT::i64)); 14994 // second argument is 1 because this rounding 14995 // is always exact. 14996 14997 // The output of the permutation is our loaded result, the TokenFactor is 14998 // our new chain. 14999 DCI.CombineTo(N, Perm, TF); 15000 return SDValue(N, 0); 15001 } 15002 } 15003 break; 15004 case ISD::INTRINSIC_WO_CHAIN: { 15005 bool isLittleEndian = Subtarget.isLittleEndian(); 15006 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15007 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15008 : Intrinsic::ppc_altivec_lvsl); 15009 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15010 SDValue Add = N->getOperand(1); 15011 15012 int Bits = 4 /* 16 byte alignment */; 15013 15014 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15015 APInt::getAllOnesValue(Bits /* alignment */) 15016 .zext(Add.getScalarValueSizeInBits()))) { 15017 SDNode *BasePtr = Add->getOperand(0).getNode(); 15018 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15019 UE = BasePtr->use_end(); 15020 UI != UE; ++UI) { 15021 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15022 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 15023 IID) { 15024 // We've found another LVSL/LVSR, and this address is an aligned 15025 // multiple of that one. The results will be the same, so use the 15026 // one we've just found instead. 15027 15028 return SDValue(*UI, 0); 15029 } 15030 } 15031 } 15032 15033 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15034 SDNode *BasePtr = Add->getOperand(0).getNode(); 15035 for (SDNode::use_iterator UI = BasePtr->use_begin(), 15036 UE = BasePtr->use_end(); UI != UE; ++UI) { 15037 if (UI->getOpcode() == ISD::ADD && 15038 isa<ConstantSDNode>(UI->getOperand(1)) && 15039 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15040 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 15041 (1ULL << Bits) == 0) { 15042 SDNode *OtherAdd = *UI; 15043 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 15044 VE = OtherAdd->use_end(); VI != VE; ++VI) { 15045 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15046 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 15047 return SDValue(*VI, 0); 15048 } 15049 } 15050 } 15051 } 15052 } 15053 } 15054 15055 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15056 // Expose the vabsduw/h/b opportunity for down stream 15057 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15058 (IID == Intrinsic::ppc_altivec_vmaxsw || 15059 IID == Intrinsic::ppc_altivec_vmaxsh || 15060 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15061 SDValue V1 = N->getOperand(1); 15062 SDValue V2 = N->getOperand(2); 15063 if ((V1.getSimpleValueType() == MVT::v4i32 || 15064 V1.getSimpleValueType() == MVT::v8i16 || 15065 V1.getSimpleValueType() == MVT::v16i8) && 15066 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15067 // (0-a, a) 15068 if (V1.getOpcode() == ISD::SUB && 15069 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15070 V1.getOperand(1) == V2) { 15071 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15072 } 15073 // (a, 0-a) 15074 if (V2.getOpcode() == ISD::SUB && 15075 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15076 V2.getOperand(1) == V1) { 15077 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15078 } 15079 // (x-y, y-x) 15080 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15081 V1.getOperand(0) == V2.getOperand(1) && 15082 V1.getOperand(1) == V2.getOperand(0)) { 15083 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15084 } 15085 } 15086 } 15087 } 15088 15089 break; 15090 case ISD::INTRINSIC_W_CHAIN: 15091 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15092 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15093 if (Subtarget.needsSwapsForVSXMemOps()) { 15094 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15095 default: 15096 break; 15097 case Intrinsic::ppc_vsx_lxvw4x: 15098 case Intrinsic::ppc_vsx_lxvd2x: 15099 return expandVSXLoadForLE(N, DCI); 15100 } 15101 } 15102 break; 15103 case ISD::INTRINSIC_VOID: 15104 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15105 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15106 if (Subtarget.needsSwapsForVSXMemOps()) { 15107 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15108 default: 15109 break; 15110 case Intrinsic::ppc_vsx_stxvw4x: 15111 case Intrinsic::ppc_vsx_stxvd2x: 15112 return expandVSXStoreForLE(N, DCI); 15113 } 15114 } 15115 break; 15116 case ISD::BSWAP: 15117 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15118 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 15119 N->getOperand(0).hasOneUse() && 15120 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15121 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 15122 N->getValueType(0) == MVT::i64))) { 15123 SDValue Load = N->getOperand(0); 15124 LoadSDNode *LD = cast<LoadSDNode>(Load); 15125 // Create the byte-swapping load. 15126 SDValue Ops[] = { 15127 LD->getChain(), // Chain 15128 LD->getBasePtr(), // Ptr 15129 DAG.getValueType(N->getValueType(0)) // VT 15130 }; 15131 SDValue BSLoad = 15132 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15133 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15134 MVT::i64 : MVT::i32, MVT::Other), 15135 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15136 15137 // If this is an i16 load, insert the truncate. 15138 SDValue ResVal = BSLoad; 15139 if (N->getValueType(0) == MVT::i16) 15140 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15141 15142 // First, combine the bswap away. This makes the value produced by the 15143 // load dead. 15144 DCI.CombineTo(N, ResVal); 15145 15146 // Next, combine the load away, we give it a bogus result value but a real 15147 // chain result. The result value is dead because the bswap is dead. 15148 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15149 15150 // Return N so it doesn't get rechecked! 15151 return SDValue(N, 0); 15152 } 15153 break; 15154 case PPCISD::VCMP: 15155 // If a VCMPo node already exists with exactly the same operands as this 15156 // node, use its result instead of this node (VCMPo computes both a CR6 and 15157 // a normal output). 15158 // 15159 if (!N->getOperand(0).hasOneUse() && 15160 !N->getOperand(1).hasOneUse() && 15161 !N->getOperand(2).hasOneUse()) { 15162 15163 // Scan all of the users of the LHS, looking for VCMPo's that match. 15164 SDNode *VCMPoNode = nullptr; 15165 15166 SDNode *LHSN = N->getOperand(0).getNode(); 15167 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15168 UI != E; ++UI) 15169 if (UI->getOpcode() == PPCISD::VCMPo && 15170 UI->getOperand(1) == N->getOperand(1) && 15171 UI->getOperand(2) == N->getOperand(2) && 15172 UI->getOperand(0) == N->getOperand(0)) { 15173 VCMPoNode = *UI; 15174 break; 15175 } 15176 15177 // If there is no VCMPo node, or if the flag value has a single use, don't 15178 // transform this. 15179 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 15180 break; 15181 15182 // Look at the (necessarily single) use of the flag value. If it has a 15183 // chain, this transformation is more complex. Note that multiple things 15184 // could use the value result, which we should ignore. 15185 SDNode *FlagUser = nullptr; 15186 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 15187 FlagUser == nullptr; ++UI) { 15188 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 15189 SDNode *User = *UI; 15190 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15191 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 15192 FlagUser = User; 15193 break; 15194 } 15195 } 15196 } 15197 15198 // If the user is a MFOCRF instruction, we know this is safe. 15199 // Otherwise we give up for right now. 15200 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15201 return SDValue(VCMPoNode, 0); 15202 } 15203 break; 15204 case ISD::BRCOND: { 15205 SDValue Cond = N->getOperand(1); 15206 SDValue Target = N->getOperand(2); 15207 15208 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15209 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15210 Intrinsic::loop_decrement) { 15211 15212 // We now need to make the intrinsic dead (it cannot be instruction 15213 // selected). 15214 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15215 assert(Cond.getNode()->hasOneUse() && 15216 "Counter decrement has more than one use"); 15217 15218 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15219 N->getOperand(0), Target); 15220 } 15221 } 15222 break; 15223 case ISD::BR_CC: { 15224 // If this is a branch on an altivec predicate comparison, lower this so 15225 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15226 // lowering is done pre-legalize, because the legalizer lowers the predicate 15227 // compare down to code that is difficult to reassemble. 15228 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15229 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15230 15231 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15232 // value. If so, pass-through the AND to get to the intrinsic. 15233 if (LHS.getOpcode() == ISD::AND && 15234 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15235 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15236 Intrinsic::loop_decrement && 15237 isa<ConstantSDNode>(LHS.getOperand(1)) && 15238 !isNullConstant(LHS.getOperand(1))) 15239 LHS = LHS.getOperand(0); 15240 15241 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15242 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15243 Intrinsic::loop_decrement && 15244 isa<ConstantSDNode>(RHS)) { 15245 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15246 "Counter decrement comparison is not EQ or NE"); 15247 15248 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15249 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15250 (CC == ISD::SETNE && !Val); 15251 15252 // We now need to make the intrinsic dead (it cannot be instruction 15253 // selected). 15254 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15255 assert(LHS.getNode()->hasOneUse() && 15256 "Counter decrement has more than one use"); 15257 15258 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15259 N->getOperand(0), N->getOperand(4)); 15260 } 15261 15262 int CompareOpc; 15263 bool isDot; 15264 15265 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15266 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15267 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15268 assert(isDot && "Can't compare against a vector result!"); 15269 15270 // If this is a comparison against something other than 0/1, then we know 15271 // that the condition is never/always true. 15272 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15273 if (Val != 0 && Val != 1) { 15274 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15275 return N->getOperand(0); 15276 // Always !=, turn it into an unconditional branch. 15277 return DAG.getNode(ISD::BR, dl, MVT::Other, 15278 N->getOperand(0), N->getOperand(4)); 15279 } 15280 15281 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15282 15283 // Create the PPCISD altivec 'dot' comparison node. 15284 SDValue Ops[] = { 15285 LHS.getOperand(2), // LHS of compare 15286 LHS.getOperand(3), // RHS of compare 15287 DAG.getConstant(CompareOpc, dl, MVT::i32) 15288 }; 15289 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15290 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15291 15292 // Unpack the result based on how the target uses it. 15293 PPC::Predicate CompOpc; 15294 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15295 default: // Can't happen, don't crash on invalid number though. 15296 case 0: // Branch on the value of the EQ bit of CR6. 15297 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15298 break; 15299 case 1: // Branch on the inverted value of the EQ bit of CR6. 15300 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15301 break; 15302 case 2: // Branch on the value of the LT bit of CR6. 15303 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15304 break; 15305 case 3: // Branch on the inverted value of the LT bit of CR6. 15306 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15307 break; 15308 } 15309 15310 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15311 DAG.getConstant(CompOpc, dl, MVT::i32), 15312 DAG.getRegister(PPC::CR6, MVT::i32), 15313 N->getOperand(4), CompNode.getValue(1)); 15314 } 15315 break; 15316 } 15317 case ISD::BUILD_VECTOR: 15318 return DAGCombineBuildVector(N, DCI); 15319 case ISD::ABS: 15320 return combineABS(N, DCI); 15321 case ISD::VSELECT: 15322 return combineVSelect(N, DCI); 15323 } 15324 15325 return SDValue(); 15326 } 15327 15328 SDValue 15329 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15330 SelectionDAG &DAG, 15331 SmallVectorImpl<SDNode *> &Created) const { 15332 // fold (sdiv X, pow2) 15333 EVT VT = N->getValueType(0); 15334 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15335 return SDValue(); 15336 if ((VT != MVT::i32 && VT != MVT::i64) || 15337 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15338 return SDValue(); 15339 15340 SDLoc DL(N); 15341 SDValue N0 = N->getOperand(0); 15342 15343 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15344 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15345 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15346 15347 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15348 Created.push_back(Op.getNode()); 15349 15350 if (IsNegPow2) { 15351 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15352 Created.push_back(Op.getNode()); 15353 } 15354 15355 return Op; 15356 } 15357 15358 //===----------------------------------------------------------------------===// 15359 // Inline Assembly Support 15360 //===----------------------------------------------------------------------===// 15361 15362 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15363 KnownBits &Known, 15364 const APInt &DemandedElts, 15365 const SelectionDAG &DAG, 15366 unsigned Depth) const { 15367 Known.resetAll(); 15368 switch (Op.getOpcode()) { 15369 default: break; 15370 case PPCISD::LBRX: { 15371 // lhbrx is known to have the top bits cleared out. 15372 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15373 Known.Zero = 0xFFFF0000; 15374 break; 15375 } 15376 case ISD::INTRINSIC_WO_CHAIN: { 15377 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15378 default: break; 15379 case Intrinsic::ppc_altivec_vcmpbfp_p: 15380 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15381 case Intrinsic::ppc_altivec_vcmpequb_p: 15382 case Intrinsic::ppc_altivec_vcmpequh_p: 15383 case Intrinsic::ppc_altivec_vcmpequw_p: 15384 case Intrinsic::ppc_altivec_vcmpequd_p: 15385 case Intrinsic::ppc_altivec_vcmpequq_p: 15386 case Intrinsic::ppc_altivec_vcmpgefp_p: 15387 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15388 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15389 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15390 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15391 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15392 case Intrinsic::ppc_altivec_vcmpgtsq_p: 15393 case Intrinsic::ppc_altivec_vcmpgtub_p: 15394 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15395 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15396 case Intrinsic::ppc_altivec_vcmpgtud_p: 15397 case Intrinsic::ppc_altivec_vcmpgtuq_p: 15398 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15399 break; 15400 } 15401 } 15402 } 15403 } 15404 15405 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15406 switch (Subtarget.getCPUDirective()) { 15407 default: break; 15408 case PPC::DIR_970: 15409 case PPC::DIR_PWR4: 15410 case PPC::DIR_PWR5: 15411 case PPC::DIR_PWR5X: 15412 case PPC::DIR_PWR6: 15413 case PPC::DIR_PWR6X: 15414 case PPC::DIR_PWR7: 15415 case PPC::DIR_PWR8: 15416 case PPC::DIR_PWR9: 15417 case PPC::DIR_PWR10: 15418 case PPC::DIR_PWR_FUTURE: { 15419 if (!ML) 15420 break; 15421 15422 if (!DisableInnermostLoopAlign32) { 15423 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15424 // so that we can decrease cache misses and branch-prediction misses. 15425 // Actual alignment of the loop will depend on the hotness check and other 15426 // logic in alignBlocks. 15427 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15428 return Align(32); 15429 } 15430 15431 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15432 15433 // For small loops (between 5 and 8 instructions), align to a 32-byte 15434 // boundary so that the entire loop fits in one instruction-cache line. 15435 uint64_t LoopSize = 0; 15436 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15437 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15438 LoopSize += TII->getInstSizeInBytes(*J); 15439 if (LoopSize > 32) 15440 break; 15441 } 15442 15443 if (LoopSize > 16 && LoopSize <= 32) 15444 return Align(32); 15445 15446 break; 15447 } 15448 } 15449 15450 return TargetLowering::getPrefLoopAlignment(ML); 15451 } 15452 15453 /// getConstraintType - Given a constraint, return the type of 15454 /// constraint it is for this target. 15455 PPCTargetLowering::ConstraintType 15456 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15457 if (Constraint.size() == 1) { 15458 switch (Constraint[0]) { 15459 default: break; 15460 case 'b': 15461 case 'r': 15462 case 'f': 15463 case 'd': 15464 case 'v': 15465 case 'y': 15466 return C_RegisterClass; 15467 case 'Z': 15468 // FIXME: While Z does indicate a memory constraint, it specifically 15469 // indicates an r+r address (used in conjunction with the 'y' modifier 15470 // in the replacement string). Currently, we're forcing the base 15471 // register to be r0 in the asm printer (which is interpreted as zero) 15472 // and forming the complete address in the second register. This is 15473 // suboptimal. 15474 return C_Memory; 15475 } 15476 } else if (Constraint == "wc") { // individual CR bits. 15477 return C_RegisterClass; 15478 } else if (Constraint == "wa" || Constraint == "wd" || 15479 Constraint == "wf" || Constraint == "ws" || 15480 Constraint == "wi" || Constraint == "ww") { 15481 return C_RegisterClass; // VSX registers. 15482 } 15483 return TargetLowering::getConstraintType(Constraint); 15484 } 15485 15486 /// Examine constraint type and operand type and determine a weight value. 15487 /// This object must already have been set up with the operand type 15488 /// and the current alternative constraint selected. 15489 TargetLowering::ConstraintWeight 15490 PPCTargetLowering::getSingleConstraintMatchWeight( 15491 AsmOperandInfo &info, const char *constraint) const { 15492 ConstraintWeight weight = CW_Invalid; 15493 Value *CallOperandVal = info.CallOperandVal; 15494 // If we don't have a value, we can't do a match, 15495 // but allow it at the lowest weight. 15496 if (!CallOperandVal) 15497 return CW_Default; 15498 Type *type = CallOperandVal->getType(); 15499 15500 // Look at the constraint type. 15501 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15502 return CW_Register; // an individual CR bit. 15503 else if ((StringRef(constraint) == "wa" || 15504 StringRef(constraint) == "wd" || 15505 StringRef(constraint) == "wf") && 15506 type->isVectorTy()) 15507 return CW_Register; 15508 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15509 return CW_Register; // just hold 64-bit integers data. 15510 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15511 return CW_Register; 15512 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15513 return CW_Register; 15514 15515 switch (*constraint) { 15516 default: 15517 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15518 break; 15519 case 'b': 15520 if (type->isIntegerTy()) 15521 weight = CW_Register; 15522 break; 15523 case 'f': 15524 if (type->isFloatTy()) 15525 weight = CW_Register; 15526 break; 15527 case 'd': 15528 if (type->isDoubleTy()) 15529 weight = CW_Register; 15530 break; 15531 case 'v': 15532 if (type->isVectorTy()) 15533 weight = CW_Register; 15534 break; 15535 case 'y': 15536 weight = CW_Register; 15537 break; 15538 case 'Z': 15539 weight = CW_Memory; 15540 break; 15541 } 15542 return weight; 15543 } 15544 15545 std::pair<unsigned, const TargetRegisterClass *> 15546 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15547 StringRef Constraint, 15548 MVT VT) const { 15549 if (Constraint.size() == 1) { 15550 // GCC RS6000 Constraint Letters 15551 switch (Constraint[0]) { 15552 case 'b': // R1-R31 15553 if (VT == MVT::i64 && Subtarget.isPPC64()) 15554 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15555 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15556 case 'r': // R0-R31 15557 if (VT == MVT::i64 && Subtarget.isPPC64()) 15558 return std::make_pair(0U, &PPC::G8RCRegClass); 15559 return std::make_pair(0U, &PPC::GPRCRegClass); 15560 // 'd' and 'f' constraints are both defined to be "the floating point 15561 // registers", where one is for 32-bit and the other for 64-bit. We don't 15562 // really care overly much here so just give them all the same reg classes. 15563 case 'd': 15564 case 'f': 15565 if (Subtarget.hasSPE()) { 15566 if (VT == MVT::f32 || VT == MVT::i32) 15567 return std::make_pair(0U, &PPC::GPRCRegClass); 15568 if (VT == MVT::f64 || VT == MVT::i64) 15569 return std::make_pair(0U, &PPC::SPERCRegClass); 15570 } else { 15571 if (VT == MVT::f32 || VT == MVT::i32) 15572 return std::make_pair(0U, &PPC::F4RCRegClass); 15573 if (VT == MVT::f64 || VT == MVT::i64) 15574 return std::make_pair(0U, &PPC::F8RCRegClass); 15575 } 15576 break; 15577 case 'v': 15578 if (Subtarget.hasAltivec()) 15579 return std::make_pair(0U, &PPC::VRRCRegClass); 15580 break; 15581 case 'y': // crrc 15582 return std::make_pair(0U, &PPC::CRRCRegClass); 15583 } 15584 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15585 // An individual CR bit. 15586 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15587 } else if ((Constraint == "wa" || Constraint == "wd" || 15588 Constraint == "wf" || Constraint == "wi") && 15589 Subtarget.hasVSX()) { 15590 return std::make_pair(0U, &PPC::VSRCRegClass); 15591 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15592 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15593 return std::make_pair(0U, &PPC::VSSRCRegClass); 15594 else 15595 return std::make_pair(0U, &PPC::VSFRCRegClass); 15596 } 15597 15598 // If we name a VSX register, we can't defer to the base class because it 15599 // will not recognize the correct register (their names will be VSL{0-31} 15600 // and V{0-31} so they won't match). So we match them here. 15601 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15602 int VSNum = atoi(Constraint.data() + 3); 15603 assert(VSNum >= 0 && VSNum <= 63 && 15604 "Attempted to access a vsr out of range"); 15605 if (VSNum < 32) 15606 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15607 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15608 } 15609 std::pair<unsigned, const TargetRegisterClass *> R = 15610 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15611 15612 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15613 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15614 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15615 // register. 15616 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15617 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15618 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15619 PPC::GPRCRegClass.contains(R.first)) 15620 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15621 PPC::sub_32, &PPC::G8RCRegClass), 15622 &PPC::G8RCRegClass); 15623 15624 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15625 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15626 R.first = PPC::CR0; 15627 R.second = &PPC::CRRCRegClass; 15628 } 15629 15630 return R; 15631 } 15632 15633 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15634 /// vector. If it is invalid, don't add anything to Ops. 15635 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15636 std::string &Constraint, 15637 std::vector<SDValue>&Ops, 15638 SelectionDAG &DAG) const { 15639 SDValue Result; 15640 15641 // Only support length 1 constraints. 15642 if (Constraint.length() > 1) return; 15643 15644 char Letter = Constraint[0]; 15645 switch (Letter) { 15646 default: break; 15647 case 'I': 15648 case 'J': 15649 case 'K': 15650 case 'L': 15651 case 'M': 15652 case 'N': 15653 case 'O': 15654 case 'P': { 15655 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15656 if (!CST) return; // Must be an immediate to match. 15657 SDLoc dl(Op); 15658 int64_t Value = CST->getSExtValue(); 15659 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15660 // numbers are printed as such. 15661 switch (Letter) { 15662 default: llvm_unreachable("Unknown constraint letter!"); 15663 case 'I': // "I" is a signed 16-bit constant. 15664 if (isInt<16>(Value)) 15665 Result = DAG.getTargetConstant(Value, dl, TCVT); 15666 break; 15667 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15668 if (isShiftedUInt<16, 16>(Value)) 15669 Result = DAG.getTargetConstant(Value, dl, TCVT); 15670 break; 15671 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15672 if (isShiftedInt<16, 16>(Value)) 15673 Result = DAG.getTargetConstant(Value, dl, TCVT); 15674 break; 15675 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15676 if (isUInt<16>(Value)) 15677 Result = DAG.getTargetConstant(Value, dl, TCVT); 15678 break; 15679 case 'M': // "M" is a constant that is greater than 31. 15680 if (Value > 31) 15681 Result = DAG.getTargetConstant(Value, dl, TCVT); 15682 break; 15683 case 'N': // "N" is a positive constant that is an exact power of two. 15684 if (Value > 0 && isPowerOf2_64(Value)) 15685 Result = DAG.getTargetConstant(Value, dl, TCVT); 15686 break; 15687 case 'O': // "O" is the constant zero. 15688 if (Value == 0) 15689 Result = DAG.getTargetConstant(Value, dl, TCVT); 15690 break; 15691 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15692 if (isInt<16>(-Value)) 15693 Result = DAG.getTargetConstant(Value, dl, TCVT); 15694 break; 15695 } 15696 break; 15697 } 15698 } 15699 15700 if (Result.getNode()) { 15701 Ops.push_back(Result); 15702 return; 15703 } 15704 15705 // Handle standard constraint letters. 15706 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15707 } 15708 15709 // isLegalAddressingMode - Return true if the addressing mode represented 15710 // by AM is legal for this target, for a load/store of the specified type. 15711 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15712 const AddrMode &AM, Type *Ty, 15713 unsigned AS, 15714 Instruction *I) const { 15715 // Vector type r+i form is supported since power9 as DQ form. We don't check 15716 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15717 // imm form is preferred and the offset can be adjusted to use imm form later 15718 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15719 // max offset to check legal addressing mode, we should be a little aggressive 15720 // to contain other offsets for that LSRUse. 15721 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15722 return false; 15723 15724 // PPC allows a sign-extended 16-bit immediate field. 15725 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15726 return false; 15727 15728 // No global is ever allowed as a base. 15729 if (AM.BaseGV) 15730 return false; 15731 15732 // PPC only support r+r, 15733 switch (AM.Scale) { 15734 case 0: // "r+i" or just "i", depending on HasBaseReg. 15735 break; 15736 case 1: 15737 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15738 return false; 15739 // Otherwise we have r+r or r+i. 15740 break; 15741 case 2: 15742 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15743 return false; 15744 // Allow 2*r as r+r. 15745 break; 15746 default: 15747 // No other scales are supported. 15748 return false; 15749 } 15750 15751 return true; 15752 } 15753 15754 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15755 SelectionDAG &DAG) const { 15756 MachineFunction &MF = DAG.getMachineFunction(); 15757 MachineFrameInfo &MFI = MF.getFrameInfo(); 15758 MFI.setReturnAddressIsTaken(true); 15759 15760 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15761 return SDValue(); 15762 15763 SDLoc dl(Op); 15764 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15765 15766 // Make sure the function does not optimize away the store of the RA to 15767 // the stack. 15768 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15769 FuncInfo->setLRStoreRequired(); 15770 bool isPPC64 = Subtarget.isPPC64(); 15771 auto PtrVT = getPointerTy(MF.getDataLayout()); 15772 15773 if (Depth > 0) { 15774 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15775 SDValue Offset = 15776 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15777 isPPC64 ? MVT::i64 : MVT::i32); 15778 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15779 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15780 MachinePointerInfo()); 15781 } 15782 15783 // Just load the return address off the stack. 15784 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15785 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15786 MachinePointerInfo()); 15787 } 15788 15789 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15790 SelectionDAG &DAG) const { 15791 SDLoc dl(Op); 15792 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15793 15794 MachineFunction &MF = DAG.getMachineFunction(); 15795 MachineFrameInfo &MFI = MF.getFrameInfo(); 15796 MFI.setFrameAddressIsTaken(true); 15797 15798 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15799 bool isPPC64 = PtrVT == MVT::i64; 15800 15801 // Naked functions never have a frame pointer, and so we use r1. For all 15802 // other functions, this decision must be delayed until during PEI. 15803 unsigned FrameReg; 15804 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15805 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15806 else 15807 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15808 15809 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15810 PtrVT); 15811 while (Depth--) 15812 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15813 FrameAddr, MachinePointerInfo()); 15814 return FrameAddr; 15815 } 15816 15817 // FIXME? Maybe this could be a TableGen attribute on some registers and 15818 // this table could be generated automatically from RegInfo. 15819 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15820 const MachineFunction &MF) const { 15821 bool isPPC64 = Subtarget.isPPC64(); 15822 15823 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15824 if (!is64Bit && VT != LLT::scalar(32)) 15825 report_fatal_error("Invalid register global variable type"); 15826 15827 Register Reg = StringSwitch<Register>(RegName) 15828 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15829 .Case("r2", isPPC64 ? Register() : PPC::R2) 15830 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15831 .Default(Register()); 15832 15833 if (Reg) 15834 return Reg; 15835 report_fatal_error("Invalid register name global variable"); 15836 } 15837 15838 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15839 // 32-bit SVR4 ABI access everything as got-indirect. 15840 if (Subtarget.is32BitELFABI()) 15841 return true; 15842 15843 // AIX accesses everything indirectly through the TOC, which is similar to 15844 // the GOT. 15845 if (Subtarget.isAIXABI()) 15846 return true; 15847 15848 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15849 // If it is small or large code model, module locals are accessed 15850 // indirectly by loading their address from .toc/.got. 15851 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15852 return true; 15853 15854 // JumpTable and BlockAddress are accessed as got-indirect. 15855 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15856 return true; 15857 15858 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15859 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15860 15861 return false; 15862 } 15863 15864 bool 15865 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15866 // The PowerPC target isn't yet aware of offsets. 15867 return false; 15868 } 15869 15870 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15871 const CallInst &I, 15872 MachineFunction &MF, 15873 unsigned Intrinsic) const { 15874 switch (Intrinsic) { 15875 case Intrinsic::ppc_altivec_lvx: 15876 case Intrinsic::ppc_altivec_lvxl: 15877 case Intrinsic::ppc_altivec_lvebx: 15878 case Intrinsic::ppc_altivec_lvehx: 15879 case Intrinsic::ppc_altivec_lvewx: 15880 case Intrinsic::ppc_vsx_lxvd2x: 15881 case Intrinsic::ppc_vsx_lxvw4x: 15882 case Intrinsic::ppc_vsx_lxvd2x_be: 15883 case Intrinsic::ppc_vsx_lxvw4x_be: 15884 case Intrinsic::ppc_vsx_lxvl: 15885 case Intrinsic::ppc_vsx_lxvll: { 15886 EVT VT; 15887 switch (Intrinsic) { 15888 case Intrinsic::ppc_altivec_lvebx: 15889 VT = MVT::i8; 15890 break; 15891 case Intrinsic::ppc_altivec_lvehx: 15892 VT = MVT::i16; 15893 break; 15894 case Intrinsic::ppc_altivec_lvewx: 15895 VT = MVT::i32; 15896 break; 15897 case Intrinsic::ppc_vsx_lxvd2x: 15898 case Intrinsic::ppc_vsx_lxvd2x_be: 15899 VT = MVT::v2f64; 15900 break; 15901 default: 15902 VT = MVT::v4i32; 15903 break; 15904 } 15905 15906 Info.opc = ISD::INTRINSIC_W_CHAIN; 15907 Info.memVT = VT; 15908 Info.ptrVal = I.getArgOperand(0); 15909 Info.offset = -VT.getStoreSize()+1; 15910 Info.size = 2*VT.getStoreSize()-1; 15911 Info.align = Align(1); 15912 Info.flags = MachineMemOperand::MOLoad; 15913 return true; 15914 } 15915 case Intrinsic::ppc_altivec_stvx: 15916 case Intrinsic::ppc_altivec_stvxl: 15917 case Intrinsic::ppc_altivec_stvebx: 15918 case Intrinsic::ppc_altivec_stvehx: 15919 case Intrinsic::ppc_altivec_stvewx: 15920 case Intrinsic::ppc_vsx_stxvd2x: 15921 case Intrinsic::ppc_vsx_stxvw4x: 15922 case Intrinsic::ppc_vsx_stxvd2x_be: 15923 case Intrinsic::ppc_vsx_stxvw4x_be: 15924 case Intrinsic::ppc_vsx_stxvl: 15925 case Intrinsic::ppc_vsx_stxvll: { 15926 EVT VT; 15927 switch (Intrinsic) { 15928 case Intrinsic::ppc_altivec_stvebx: 15929 VT = MVT::i8; 15930 break; 15931 case Intrinsic::ppc_altivec_stvehx: 15932 VT = MVT::i16; 15933 break; 15934 case Intrinsic::ppc_altivec_stvewx: 15935 VT = MVT::i32; 15936 break; 15937 case Intrinsic::ppc_vsx_stxvd2x: 15938 case Intrinsic::ppc_vsx_stxvd2x_be: 15939 VT = MVT::v2f64; 15940 break; 15941 default: 15942 VT = MVT::v4i32; 15943 break; 15944 } 15945 15946 Info.opc = ISD::INTRINSIC_VOID; 15947 Info.memVT = VT; 15948 Info.ptrVal = I.getArgOperand(1); 15949 Info.offset = -VT.getStoreSize()+1; 15950 Info.size = 2*VT.getStoreSize()-1; 15951 Info.align = Align(1); 15952 Info.flags = MachineMemOperand::MOStore; 15953 return true; 15954 } 15955 default: 15956 break; 15957 } 15958 15959 return false; 15960 } 15961 15962 /// It returns EVT::Other if the type should be determined using generic 15963 /// target-independent logic. 15964 EVT PPCTargetLowering::getOptimalMemOpType( 15965 const MemOp &Op, const AttributeList &FuncAttributes) const { 15966 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15967 // We should use Altivec/VSX loads and stores when available. For unaligned 15968 // addresses, unaligned VSX loads are only fast starting with the P8. 15969 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15970 (Op.isAligned(Align(16)) || 15971 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15972 return MVT::v4i32; 15973 } 15974 15975 if (Subtarget.isPPC64()) { 15976 return MVT::i64; 15977 } 15978 15979 return MVT::i32; 15980 } 15981 15982 /// Returns true if it is beneficial to convert a load of a constant 15983 /// to just the constant itself. 15984 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15985 Type *Ty) const { 15986 assert(Ty->isIntegerTy()); 15987 15988 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15989 return !(BitSize == 0 || BitSize > 64); 15990 } 15991 15992 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15993 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15994 return false; 15995 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15996 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15997 return NumBits1 == 64 && NumBits2 == 32; 15998 } 15999 16000 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16001 if (!VT1.isInteger() || !VT2.isInteger()) 16002 return false; 16003 unsigned NumBits1 = VT1.getSizeInBits(); 16004 unsigned NumBits2 = VT2.getSizeInBits(); 16005 return NumBits1 == 64 && NumBits2 == 32; 16006 } 16007 16008 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16009 // Generally speaking, zexts are not free, but they are free when they can be 16010 // folded with other operations. 16011 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16012 EVT MemVT = LD->getMemoryVT(); 16013 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16014 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16015 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16016 LD->getExtensionType() == ISD::ZEXTLOAD)) 16017 return true; 16018 } 16019 16020 // FIXME: Add other cases... 16021 // - 32-bit shifts with a zext to i64 16022 // - zext after ctlz, bswap, etc. 16023 // - zext after and by a constant mask 16024 16025 return TargetLowering::isZExtFree(Val, VT2); 16026 } 16027 16028 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16029 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16030 "invalid fpext types"); 16031 // Extending to float128 is not free. 16032 if (DestVT == MVT::f128) 16033 return false; 16034 return true; 16035 } 16036 16037 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16038 return isInt<16>(Imm) || isUInt<16>(Imm); 16039 } 16040 16041 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16042 return isInt<16>(Imm) || isUInt<16>(Imm); 16043 } 16044 16045 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 16046 unsigned, 16047 unsigned, 16048 MachineMemOperand::Flags, 16049 bool *Fast) const { 16050 if (DisablePPCUnaligned) 16051 return false; 16052 16053 // PowerPC supports unaligned memory access for simple non-vector types. 16054 // Although accessing unaligned addresses is not as efficient as accessing 16055 // aligned addresses, it is generally more efficient than manual expansion, 16056 // and generally only traps for software emulation when crossing page 16057 // boundaries. 16058 16059 if (!VT.isSimple()) 16060 return false; 16061 16062 if (VT.isFloatingPoint() && !VT.isVector() && 16063 !Subtarget.allowsUnalignedFPAccess()) 16064 return false; 16065 16066 if (VT.getSimpleVT().isVector()) { 16067 if (Subtarget.hasVSX()) { 16068 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16069 VT != MVT::v4f32 && VT != MVT::v4i32) 16070 return false; 16071 } else { 16072 return false; 16073 } 16074 } 16075 16076 if (VT == MVT::ppcf128) 16077 return false; 16078 16079 if (Fast) 16080 *Fast = true; 16081 16082 return true; 16083 } 16084 16085 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16086 SDValue C) const { 16087 // Check integral scalar types. 16088 if (!VT.isScalarInteger()) 16089 return false; 16090 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16091 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16092 return false; 16093 // This transformation will generate >= 2 operations. But the following 16094 // cases will generate <= 2 instructions during ISEL. So exclude them. 16095 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16096 // HW instruction, ie. MULLI 16097 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16098 // instruction is needed than case 1, ie. MULLI and RLDICR 16099 int64_t Imm = ConstNode->getSExtValue(); 16100 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16101 Imm >>= Shift; 16102 if (isInt<16>(Imm)) 16103 return false; 16104 uint64_t UImm = static_cast<uint64_t>(Imm); 16105 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16106 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16107 return true; 16108 } 16109 return false; 16110 } 16111 16112 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16113 EVT VT) const { 16114 return isFMAFasterThanFMulAndFAdd( 16115 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16116 } 16117 16118 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16119 Type *Ty) const { 16120 switch (Ty->getScalarType()->getTypeID()) { 16121 case Type::FloatTyID: 16122 case Type::DoubleTyID: 16123 return true; 16124 case Type::FP128TyID: 16125 return Subtarget.hasP9Vector(); 16126 default: 16127 return false; 16128 } 16129 } 16130 16131 // FIXME: add more patterns which are not profitable to hoist. 16132 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16133 if (!I->hasOneUse()) 16134 return true; 16135 16136 Instruction *User = I->user_back(); 16137 assert(User && "A single use instruction with no uses."); 16138 16139 switch (I->getOpcode()) { 16140 case Instruction::FMul: { 16141 // Don't break FMA, PowerPC prefers FMA. 16142 if (User->getOpcode() != Instruction::FSub && 16143 User->getOpcode() != Instruction::FAdd) 16144 return true; 16145 16146 const TargetOptions &Options = getTargetMachine().Options; 16147 const Function *F = I->getFunction(); 16148 const DataLayout &DL = F->getParent()->getDataLayout(); 16149 Type *Ty = User->getOperand(0)->getType(); 16150 16151 return !( 16152 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16153 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16154 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16155 } 16156 case Instruction::Load: { 16157 // Don't break "store (load float*)" pattern, this pattern will be combined 16158 // to "store (load int32)" in later InstCombine pass. See function 16159 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16160 // cycles than loading a 32 bit integer. 16161 LoadInst *LI = cast<LoadInst>(I); 16162 // For the loads that combineLoadToOperationType does nothing, like 16163 // ordered load, it should be profitable to hoist them. 16164 // For swifterror load, it can only be used for pointer to pointer type, so 16165 // later type check should get rid of this case. 16166 if (!LI->isUnordered()) 16167 return true; 16168 16169 if (User->getOpcode() != Instruction::Store) 16170 return true; 16171 16172 if (I->getType()->getTypeID() != Type::FloatTyID) 16173 return true; 16174 16175 return false; 16176 } 16177 default: 16178 return true; 16179 } 16180 return true; 16181 } 16182 16183 const MCPhysReg * 16184 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16185 // LR is a callee-save register, but we must treat it as clobbered by any call 16186 // site. Hence we include LR in the scratch registers, which are in turn added 16187 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16188 // to CTR, which is used by any indirect call. 16189 static const MCPhysReg ScratchRegs[] = { 16190 PPC::X12, PPC::LR8, PPC::CTR8, 0 16191 }; 16192 16193 return ScratchRegs; 16194 } 16195 16196 Register PPCTargetLowering::getExceptionPointerRegister( 16197 const Constant *PersonalityFn) const { 16198 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16199 } 16200 16201 Register PPCTargetLowering::getExceptionSelectorRegister( 16202 const Constant *PersonalityFn) const { 16203 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16204 } 16205 16206 bool 16207 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16208 EVT VT , unsigned DefinedValues) const { 16209 if (VT == MVT::v2i64) 16210 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16211 16212 if (Subtarget.hasVSX()) 16213 return true; 16214 16215 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16216 } 16217 16218 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16219 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16220 return TargetLowering::getSchedulingPreference(N); 16221 16222 return Sched::ILP; 16223 } 16224 16225 // Create a fast isel object. 16226 FastISel * 16227 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16228 const TargetLibraryInfo *LibInfo) const { 16229 return PPC::createFastISel(FuncInfo, LibInfo); 16230 } 16231 16232 // 'Inverted' means the FMA opcode after negating one multiplicand. 16233 // For example, (fma -a b c) = (fnmsub a b c) 16234 static unsigned invertFMAOpcode(unsigned Opc) { 16235 switch (Opc) { 16236 default: 16237 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16238 case ISD::FMA: 16239 return PPCISD::FNMSUB; 16240 case PPCISD::FNMSUB: 16241 return ISD::FMA; 16242 } 16243 } 16244 16245 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16246 bool LegalOps, bool OptForSize, 16247 NegatibleCost &Cost, 16248 unsigned Depth) const { 16249 if (Depth > SelectionDAG::MaxRecursionDepth) 16250 return SDValue(); 16251 16252 unsigned Opc = Op.getOpcode(); 16253 EVT VT = Op.getValueType(); 16254 SDNodeFlags Flags = Op.getNode()->getFlags(); 16255 16256 switch (Opc) { 16257 case PPCISD::FNMSUB: 16258 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16259 break; 16260 16261 const TargetOptions &Options = getTargetMachine().Options; 16262 SDValue N0 = Op.getOperand(0); 16263 SDValue N1 = Op.getOperand(1); 16264 SDValue N2 = Op.getOperand(2); 16265 SDLoc Loc(Op); 16266 16267 NegatibleCost N2Cost = NegatibleCost::Expensive; 16268 SDValue NegN2 = 16269 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16270 16271 if (!NegN2) 16272 return SDValue(); 16273 16274 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16275 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16276 // These transformations may change sign of zeroes. For example, 16277 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16278 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16279 // Try and choose the cheaper one to negate. 16280 NegatibleCost N0Cost = NegatibleCost::Expensive; 16281 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16282 N0Cost, Depth + 1); 16283 16284 NegatibleCost N1Cost = NegatibleCost::Expensive; 16285 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16286 N1Cost, Depth + 1); 16287 16288 if (NegN0 && N0Cost <= N1Cost) { 16289 Cost = std::min(N0Cost, N2Cost); 16290 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16291 } else if (NegN1) { 16292 Cost = std::min(N1Cost, N2Cost); 16293 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16294 } 16295 } 16296 16297 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16298 if (isOperationLegal(ISD::FMA, VT)) { 16299 Cost = N2Cost; 16300 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16301 } 16302 16303 break; 16304 } 16305 16306 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16307 Cost, Depth); 16308 } 16309 16310 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16311 bool PPCTargetLowering::useLoadStackGuardNode() const { 16312 if (!Subtarget.isTargetLinux()) 16313 return TargetLowering::useLoadStackGuardNode(); 16314 return true; 16315 } 16316 16317 // Override to disable global variable loading on Linux. 16318 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16319 if (!Subtarget.isTargetLinux()) 16320 return TargetLowering::insertSSPDeclarations(M); 16321 } 16322 16323 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16324 bool ForCodeSize) const { 16325 if (!VT.isSimple() || !Subtarget.hasVSX()) 16326 return false; 16327 16328 switch(VT.getSimpleVT().SimpleTy) { 16329 default: 16330 // For FP types that are currently not supported by PPC backend, return 16331 // false. Examples: f16, f80. 16332 return false; 16333 case MVT::f32: 16334 case MVT::f64: 16335 if (Subtarget.hasPrefixInstrs()) { 16336 // With prefixed instructions, we can materialize anything that can be 16337 // represented with a 32-bit immediate, not just positive zero. 16338 APFloat APFloatOfImm = Imm; 16339 return convertToNonDenormSingle(APFloatOfImm); 16340 } 16341 LLVM_FALLTHROUGH; 16342 case MVT::ppcf128: 16343 return Imm.isPosZero(); 16344 } 16345 } 16346 16347 // For vector shift operation op, fold 16348 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16349 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16350 SelectionDAG &DAG) { 16351 SDValue N0 = N->getOperand(0); 16352 SDValue N1 = N->getOperand(1); 16353 EVT VT = N0.getValueType(); 16354 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16355 unsigned Opcode = N->getOpcode(); 16356 unsigned TargetOpcode; 16357 16358 switch (Opcode) { 16359 default: 16360 llvm_unreachable("Unexpected shift operation"); 16361 case ISD::SHL: 16362 TargetOpcode = PPCISD::SHL; 16363 break; 16364 case ISD::SRL: 16365 TargetOpcode = PPCISD::SRL; 16366 break; 16367 case ISD::SRA: 16368 TargetOpcode = PPCISD::SRA; 16369 break; 16370 } 16371 16372 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16373 N1->getOpcode() == ISD::AND) 16374 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16375 if (Mask->getZExtValue() == OpSizeInBits - 1) 16376 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16377 16378 return SDValue(); 16379 } 16380 16381 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16382 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16383 return Value; 16384 16385 SDValue N0 = N->getOperand(0); 16386 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16387 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 16388 N0.getOpcode() != ISD::SIGN_EXTEND || 16389 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 16390 N->getValueType(0) != MVT::i64) 16391 return SDValue(); 16392 16393 // We can't save an operation here if the value is already extended, and 16394 // the existing shift is easier to combine. 16395 SDValue ExtsSrc = N0.getOperand(0); 16396 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16397 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16398 return SDValue(); 16399 16400 SDLoc DL(N0); 16401 SDValue ShiftBy = SDValue(CN1, 0); 16402 // We want the shift amount to be i32 on the extswli, but the shift could 16403 // have an i64. 16404 if (ShiftBy.getValueType() == MVT::i64) 16405 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16406 16407 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16408 ShiftBy); 16409 } 16410 16411 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16412 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16413 return Value; 16414 16415 return SDValue(); 16416 } 16417 16418 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16419 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16420 return Value; 16421 16422 return SDValue(); 16423 } 16424 16425 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16426 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16427 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16428 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16429 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16430 const PPCSubtarget &Subtarget) { 16431 if (!Subtarget.isPPC64()) 16432 return SDValue(); 16433 16434 SDValue LHS = N->getOperand(0); 16435 SDValue RHS = N->getOperand(1); 16436 16437 auto isZextOfCompareWithConstant = [](SDValue Op) { 16438 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16439 Op.getValueType() != MVT::i64) 16440 return false; 16441 16442 SDValue Cmp = Op.getOperand(0); 16443 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16444 Cmp.getOperand(0).getValueType() != MVT::i64) 16445 return false; 16446 16447 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16448 int64_t NegConstant = 0 - Constant->getSExtValue(); 16449 // Due to the limitations of the addi instruction, 16450 // -C is required to be [-32768, 32767]. 16451 return isInt<16>(NegConstant); 16452 } 16453 16454 return false; 16455 }; 16456 16457 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16458 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16459 16460 // If there is a pattern, canonicalize a zext operand to the RHS. 16461 if (LHSHasPattern && !RHSHasPattern) 16462 std::swap(LHS, RHS); 16463 else if (!LHSHasPattern && !RHSHasPattern) 16464 return SDValue(); 16465 16466 SDLoc DL(N); 16467 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16468 SDValue Cmp = RHS.getOperand(0); 16469 SDValue Z = Cmp.getOperand(0); 16470 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16471 16472 assert(Constant && "Constant Should not be a null pointer."); 16473 int64_t NegConstant = 0 - Constant->getSExtValue(); 16474 16475 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16476 default: break; 16477 case ISD::SETNE: { 16478 // when C == 0 16479 // --> addze X, (addic Z, -1).carry 16480 // / 16481 // add X, (zext(setne Z, C))-- 16482 // \ when -32768 <= -C <= 32767 && C != 0 16483 // --> addze X, (addic (addi Z, -C), -1).carry 16484 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16485 DAG.getConstant(NegConstant, DL, MVT::i64)); 16486 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16487 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16488 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16489 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16490 SDValue(Addc.getNode(), 1)); 16491 } 16492 case ISD::SETEQ: { 16493 // when C == 0 16494 // --> addze X, (subfic Z, 0).carry 16495 // / 16496 // add X, (zext(sete Z, C))-- 16497 // \ when -32768 <= -C <= 32767 && C != 0 16498 // --> addze X, (subfic (addi Z, -C), 0).carry 16499 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16500 DAG.getConstant(NegConstant, DL, MVT::i64)); 16501 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16502 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16503 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16504 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16505 SDValue(Subc.getNode(), 1)); 16506 } 16507 } 16508 16509 return SDValue(); 16510 } 16511 16512 // Transform 16513 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16514 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16515 // In this case both C1 and C2 must be known constants. 16516 // C1+C2 must fit into a 34 bit signed integer. 16517 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16518 const PPCSubtarget &Subtarget) { 16519 if (!Subtarget.isUsingPCRelativeCalls()) 16520 return SDValue(); 16521 16522 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16523 // If we find that node try to cast the Global Address and the Constant. 16524 SDValue LHS = N->getOperand(0); 16525 SDValue RHS = N->getOperand(1); 16526 16527 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16528 std::swap(LHS, RHS); 16529 16530 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16531 return SDValue(); 16532 16533 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16534 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16535 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16536 16537 // Check that both casts succeeded. 16538 if (!GSDN || !ConstNode) 16539 return SDValue(); 16540 16541 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16542 SDLoc DL(GSDN); 16543 16544 // The signed int offset needs to fit in 34 bits. 16545 if (!isInt<34>(NewOffset)) 16546 return SDValue(); 16547 16548 // The new global address is a copy of the old global address except 16549 // that it has the updated Offset. 16550 SDValue GA = 16551 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16552 NewOffset, GSDN->getTargetFlags()); 16553 SDValue MatPCRel = 16554 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16555 return MatPCRel; 16556 } 16557 16558 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16559 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16560 return Value; 16561 16562 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16563 return Value; 16564 16565 return SDValue(); 16566 } 16567 16568 // Detect TRUNCATE operations on bitcasts of float128 values. 16569 // What we are looking for here is the situtation where we extract a subset 16570 // of bits from a 128 bit float. 16571 // This can be of two forms: 16572 // 1) BITCAST of f128 feeding TRUNCATE 16573 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16574 // The reason this is required is because we do not have a legal i128 type 16575 // and so we want to prevent having to store the f128 and then reload part 16576 // of it. 16577 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16578 DAGCombinerInfo &DCI) const { 16579 // If we are using CRBits then try that first. 16580 if (Subtarget.useCRBits()) { 16581 // Check if CRBits did anything and return that if it did. 16582 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16583 return CRTruncValue; 16584 } 16585 16586 SDLoc dl(N); 16587 SDValue Op0 = N->getOperand(0); 16588 16589 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16590 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16591 EVT VT = N->getValueType(0); 16592 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16593 return SDValue(); 16594 SDValue Sub = Op0.getOperand(0); 16595 if (Sub.getOpcode() == ISD::SUB) { 16596 SDValue SubOp0 = Sub.getOperand(0); 16597 SDValue SubOp1 = Sub.getOperand(1); 16598 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16599 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16600 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16601 SubOp1.getOperand(0), 16602 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16603 } 16604 } 16605 } 16606 16607 // Looking for a truncate of i128 to i64. 16608 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16609 return SDValue(); 16610 16611 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16612 16613 // SRL feeding TRUNCATE. 16614 if (Op0.getOpcode() == ISD::SRL) { 16615 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16616 // The right shift has to be by 64 bits. 16617 if (!ConstNode || ConstNode->getZExtValue() != 64) 16618 return SDValue(); 16619 16620 // Switch the element number to extract. 16621 EltToExtract = EltToExtract ? 0 : 1; 16622 // Update Op0 past the SRL. 16623 Op0 = Op0.getOperand(0); 16624 } 16625 16626 // BITCAST feeding a TRUNCATE possibly via SRL. 16627 if (Op0.getOpcode() == ISD::BITCAST && 16628 Op0.getValueType() == MVT::i128 && 16629 Op0.getOperand(0).getValueType() == MVT::f128) { 16630 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16631 return DCI.DAG.getNode( 16632 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16633 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16634 } 16635 return SDValue(); 16636 } 16637 16638 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16639 SelectionDAG &DAG = DCI.DAG; 16640 16641 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16642 if (!ConstOpOrElement) 16643 return SDValue(); 16644 16645 // An imul is usually smaller than the alternative sequence for legal type. 16646 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16647 isOperationLegal(ISD::MUL, N->getValueType(0))) 16648 return SDValue(); 16649 16650 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16651 switch (this->Subtarget.getCPUDirective()) { 16652 default: 16653 // TODO: enhance the condition for subtarget before pwr8 16654 return false; 16655 case PPC::DIR_PWR8: 16656 // type mul add shl 16657 // scalar 4 1 1 16658 // vector 7 2 2 16659 return true; 16660 case PPC::DIR_PWR9: 16661 case PPC::DIR_PWR10: 16662 case PPC::DIR_PWR_FUTURE: 16663 // type mul add shl 16664 // scalar 5 2 2 16665 // vector 7 2 2 16666 16667 // The cycle RATIO of related operations are showed as a table above. 16668 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16669 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16670 // are 4, it is always profitable; but for 3 instrs patterns 16671 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16672 // So we should only do it for vector type. 16673 return IsAddOne && IsNeg ? VT.isVector() : true; 16674 } 16675 }; 16676 16677 EVT VT = N->getValueType(0); 16678 SDLoc DL(N); 16679 16680 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16681 bool IsNeg = MulAmt.isNegative(); 16682 APInt MulAmtAbs = MulAmt.abs(); 16683 16684 if ((MulAmtAbs - 1).isPowerOf2()) { 16685 // (mul x, 2^N + 1) => (add (shl x, N), x) 16686 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16687 16688 if (!IsProfitable(IsNeg, true, VT)) 16689 return SDValue(); 16690 16691 SDValue Op0 = N->getOperand(0); 16692 SDValue Op1 = 16693 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16694 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16695 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16696 16697 if (!IsNeg) 16698 return Res; 16699 16700 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16701 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16702 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16703 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16704 16705 if (!IsProfitable(IsNeg, false, VT)) 16706 return SDValue(); 16707 16708 SDValue Op0 = N->getOperand(0); 16709 SDValue Op1 = 16710 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16711 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16712 16713 if (!IsNeg) 16714 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16715 else 16716 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16717 16718 } else { 16719 return SDValue(); 16720 } 16721 } 16722 16723 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16724 // in combiner since we need to check SD flags and other subtarget features. 16725 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16726 DAGCombinerInfo &DCI) const { 16727 SDValue N0 = N->getOperand(0); 16728 SDValue N1 = N->getOperand(1); 16729 SDValue N2 = N->getOperand(2); 16730 SDNodeFlags Flags = N->getFlags(); 16731 EVT VT = N->getValueType(0); 16732 SelectionDAG &DAG = DCI.DAG; 16733 const TargetOptions &Options = getTargetMachine().Options; 16734 unsigned Opc = N->getOpcode(); 16735 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16736 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16737 SDLoc Loc(N); 16738 16739 if (!isOperationLegal(ISD::FMA, VT)) 16740 return SDValue(); 16741 16742 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16743 // since (fnmsub a b c)=-0 while c-ab=+0. 16744 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16745 return SDValue(); 16746 16747 // (fma (fneg a) b c) => (fnmsub a b c) 16748 // (fnmsub (fneg a) b c) => (fma a b c) 16749 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16750 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16751 16752 // (fma a (fneg b) c) => (fnmsub a b c) 16753 // (fnmsub a (fneg b) c) => (fma a b c) 16754 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16755 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16756 16757 return SDValue(); 16758 } 16759 16760 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16761 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16762 if (!Subtarget.is64BitELFABI()) 16763 return false; 16764 16765 // If not a tail call then no need to proceed. 16766 if (!CI->isTailCall()) 16767 return false; 16768 16769 // If sibling calls have been disabled and tail-calls aren't guaranteed 16770 // there is no reason to duplicate. 16771 auto &TM = getTargetMachine(); 16772 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16773 return false; 16774 16775 // Can't tail call a function called indirectly, or if it has variadic args. 16776 const Function *Callee = CI->getCalledFunction(); 16777 if (!Callee || Callee->isVarArg()) 16778 return false; 16779 16780 // Make sure the callee and caller calling conventions are eligible for tco. 16781 const Function *Caller = CI->getParent()->getParent(); 16782 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16783 CI->getCallingConv())) 16784 return false; 16785 16786 // If the function is local then we have a good chance at tail-calling it 16787 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16788 } 16789 16790 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16791 if (!Subtarget.hasVSX()) 16792 return false; 16793 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16794 return true; 16795 return VT == MVT::f32 || VT == MVT::f64 || 16796 VT == MVT::v4f32 || VT == MVT::v2f64; 16797 } 16798 16799 bool PPCTargetLowering:: 16800 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16801 const Value *Mask = AndI.getOperand(1); 16802 // If the mask is suitable for andi. or andis. we should sink the and. 16803 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16804 // Can't handle constants wider than 64-bits. 16805 if (CI->getBitWidth() > 64) 16806 return false; 16807 int64_t ConstVal = CI->getZExtValue(); 16808 return isUInt<16>(ConstVal) || 16809 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16810 } 16811 16812 // For non-constant masks, we can always use the record-form and. 16813 return true; 16814 } 16815 16816 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16817 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16818 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16819 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16820 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16821 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16822 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16823 assert(Subtarget.hasP9Altivec() && 16824 "Only combine this when P9 altivec supported!"); 16825 EVT VT = N->getValueType(0); 16826 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16827 return SDValue(); 16828 16829 SelectionDAG &DAG = DCI.DAG; 16830 SDLoc dl(N); 16831 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16832 // Even for signed integers, if it's known to be positive (as signed 16833 // integer) due to zero-extended inputs. 16834 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16835 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16836 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16837 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16838 (SubOpcd1 == ISD::ZERO_EXTEND || 16839 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16840 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16841 N->getOperand(0)->getOperand(0), 16842 N->getOperand(0)->getOperand(1), 16843 DAG.getTargetConstant(0, dl, MVT::i32)); 16844 } 16845 16846 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16847 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16848 N->getOperand(0).hasOneUse()) { 16849 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16850 N->getOperand(0)->getOperand(0), 16851 N->getOperand(0)->getOperand(1), 16852 DAG.getTargetConstant(1, dl, MVT::i32)); 16853 } 16854 } 16855 16856 return SDValue(); 16857 } 16858 16859 // For type v4i32/v8ii16/v16i8, transform 16860 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16861 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16862 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16863 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16864 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16865 DAGCombinerInfo &DCI) const { 16866 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16867 assert(Subtarget.hasP9Altivec() && 16868 "Only combine this when P9 altivec supported!"); 16869 16870 SelectionDAG &DAG = DCI.DAG; 16871 SDLoc dl(N); 16872 SDValue Cond = N->getOperand(0); 16873 SDValue TrueOpnd = N->getOperand(1); 16874 SDValue FalseOpnd = N->getOperand(2); 16875 EVT VT = N->getOperand(1).getValueType(); 16876 16877 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16878 FalseOpnd.getOpcode() != ISD::SUB) 16879 return SDValue(); 16880 16881 // ABSD only available for type v4i32/v8i16/v16i8 16882 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16883 return SDValue(); 16884 16885 // At least to save one more dependent computation 16886 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16887 return SDValue(); 16888 16889 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16890 16891 // Can only handle unsigned comparison here 16892 switch (CC) { 16893 default: 16894 return SDValue(); 16895 case ISD::SETUGT: 16896 case ISD::SETUGE: 16897 break; 16898 case ISD::SETULT: 16899 case ISD::SETULE: 16900 std::swap(TrueOpnd, FalseOpnd); 16901 break; 16902 } 16903 16904 SDValue CmpOpnd1 = Cond.getOperand(0); 16905 SDValue CmpOpnd2 = Cond.getOperand(1); 16906 16907 // SETCC CmpOpnd1 CmpOpnd2 cond 16908 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16909 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16910 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16911 TrueOpnd.getOperand(1) == CmpOpnd2 && 16912 FalseOpnd.getOperand(0) == CmpOpnd2 && 16913 FalseOpnd.getOperand(1) == CmpOpnd1) { 16914 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16915 CmpOpnd1, CmpOpnd2, 16916 DAG.getTargetConstant(0, dl, MVT::i32)); 16917 } 16918 16919 return SDValue(); 16920 } 16921