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::UDIV, MVT::v1i128, Legal); 892 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 893 } 894 895 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 896 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 897 898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 900 901 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 902 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 903 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 904 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 905 906 // Altivec does not contain unordered floating-point compare instructions 907 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 908 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 909 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 910 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 911 912 if (Subtarget.hasVSX()) { 913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 914 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 915 if (Subtarget.hasP8Vector()) { 916 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 918 } 919 if (Subtarget.hasDirectMove() && isPPC64) { 920 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 921 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 922 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 923 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 924 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 926 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 928 } 929 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 930 931 // The nearbyint variants are not allowed to raise the inexact exception 932 // so we can only code-gen them with unsafe math. 933 if (TM.Options.UnsafeFPMath) { 934 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 935 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 936 } 937 938 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 939 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 940 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 941 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 942 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 943 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 944 setOperationAction(ISD::FROUND, MVT::f64, Legal); 945 setOperationAction(ISD::FRINT, MVT::f64, Legal); 946 947 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 948 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 949 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 950 setOperationAction(ISD::FROUND, MVT::f32, Legal); 951 setOperationAction(ISD::FRINT, MVT::f32, Legal); 952 953 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 954 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 955 956 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 957 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 958 959 // Share the Altivec comparison restrictions. 960 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 961 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 962 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 963 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 964 965 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 966 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 967 968 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 969 970 if (Subtarget.hasP8Vector()) 971 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 972 973 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 974 975 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 976 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 977 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 978 979 if (Subtarget.hasP8Altivec()) { 980 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 981 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 982 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 983 984 // 128 bit shifts can be accomplished via 3 instructions for SHL and 985 // SRL, but not for SRA because of the instructions available: 986 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 987 // doing 988 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 989 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 990 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 991 992 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 993 } 994 else { 995 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 996 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 997 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 998 999 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1000 1001 // VSX v2i64 only supports non-arithmetic operations. 1002 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1003 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1004 } 1005 1006 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1007 1008 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1009 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1010 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1011 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1012 1013 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1014 1015 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1016 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1017 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1018 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1019 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1020 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1021 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1022 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1023 1024 // Custom handling for partial vectors of integers converted to 1025 // floating point. We already have optimal handling for v2i32 through 1026 // the DAG combine, so those aren't necessary. 1027 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1028 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1029 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1030 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1031 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1032 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1033 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1034 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1035 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1036 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1037 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1038 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1039 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1040 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1041 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1042 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1043 1044 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1045 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1046 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1047 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1048 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1049 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1050 1051 if (Subtarget.hasDirectMove()) 1052 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1053 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1054 1055 // Handle constrained floating-point operations of vector. 1056 // The predictor is `hasVSX` because altivec instruction has 1057 // no exception but VSX vector instruction has. 1058 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1059 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1060 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1061 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1062 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1063 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1064 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1065 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1066 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1067 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1068 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1069 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1070 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1071 1072 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1073 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1074 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1075 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1076 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1077 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1078 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1079 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1080 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1081 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1082 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1083 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1084 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1085 1086 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1087 } 1088 1089 if (Subtarget.hasP8Altivec()) { 1090 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1091 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1092 } 1093 1094 if (Subtarget.hasP9Vector()) { 1095 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1096 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1097 1098 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1099 // SRL, but not for SRA because of the instructions available: 1100 // VS{RL} and VS{RL}O. 1101 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1102 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1103 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1104 1105 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1106 setOperationAction(ISD::FADD, MVT::f128, Legal); 1107 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1108 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1109 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1110 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1111 // No extending loads to f128 on PPC. 1112 for (MVT FPT : MVT::fp_valuetypes()) 1113 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1114 setOperationAction(ISD::FMA, MVT::f128, Legal); 1115 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1116 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1117 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1118 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1119 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1120 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1121 1122 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1123 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1124 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1125 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1126 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1127 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1128 1129 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1130 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1131 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1132 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1133 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1134 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1135 // No implementation for these ops for PowerPC. 1136 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1137 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1138 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1139 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1140 setOperationAction(ISD::FREM, MVT::f128, Expand); 1141 1142 // Handle constrained floating-point operations of fp128 1143 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1144 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1145 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1146 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1147 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1148 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1149 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1150 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1151 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1152 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1153 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1154 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1155 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1156 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1157 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1158 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1159 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1160 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1161 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1162 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1163 } 1164 1165 if (Subtarget.hasP9Altivec()) { 1166 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1167 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1168 1169 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1170 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1171 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1172 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1173 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1174 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1175 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1176 } 1177 } 1178 1179 if (Subtarget.has64BitSupport()) 1180 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1181 1182 if (Subtarget.isISA3_1()) 1183 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1184 1185 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1186 1187 if (!isPPC64) { 1188 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1189 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1190 } 1191 1192 setBooleanContents(ZeroOrOneBooleanContent); 1193 1194 if (Subtarget.hasAltivec()) { 1195 // Altivec instructions set fields to all zeros or all ones. 1196 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1197 } 1198 1199 if (!isPPC64) { 1200 // These libcalls are not available in 32-bit. 1201 setLibcallName(RTLIB::SHL_I128, nullptr); 1202 setLibcallName(RTLIB::SRL_I128, nullptr); 1203 setLibcallName(RTLIB::SRA_I128, nullptr); 1204 } 1205 1206 if (!isPPC64) 1207 setMaxAtomicSizeInBitsSupported(32); 1208 1209 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1210 1211 // We have target-specific dag combine patterns for the following nodes: 1212 setTargetDAGCombine(ISD::ADD); 1213 setTargetDAGCombine(ISD::SHL); 1214 setTargetDAGCombine(ISD::SRA); 1215 setTargetDAGCombine(ISD::SRL); 1216 setTargetDAGCombine(ISD::MUL); 1217 setTargetDAGCombine(ISD::FMA); 1218 setTargetDAGCombine(ISD::SINT_TO_FP); 1219 setTargetDAGCombine(ISD::BUILD_VECTOR); 1220 if (Subtarget.hasFPCVT()) 1221 setTargetDAGCombine(ISD::UINT_TO_FP); 1222 setTargetDAGCombine(ISD::LOAD); 1223 setTargetDAGCombine(ISD::STORE); 1224 setTargetDAGCombine(ISD::BR_CC); 1225 if (Subtarget.useCRBits()) 1226 setTargetDAGCombine(ISD::BRCOND); 1227 setTargetDAGCombine(ISD::BSWAP); 1228 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1229 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1230 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1231 1232 setTargetDAGCombine(ISD::SIGN_EXTEND); 1233 setTargetDAGCombine(ISD::ZERO_EXTEND); 1234 setTargetDAGCombine(ISD::ANY_EXTEND); 1235 1236 setTargetDAGCombine(ISD::TRUNCATE); 1237 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1238 1239 1240 if (Subtarget.useCRBits()) { 1241 setTargetDAGCombine(ISD::TRUNCATE); 1242 setTargetDAGCombine(ISD::SETCC); 1243 setTargetDAGCombine(ISD::SELECT_CC); 1244 } 1245 1246 if (Subtarget.hasP9Altivec()) { 1247 setTargetDAGCombine(ISD::ABS); 1248 setTargetDAGCombine(ISD::VSELECT); 1249 } 1250 1251 setLibcallName(RTLIB::LOG_F128, "logf128"); 1252 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1253 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1254 setLibcallName(RTLIB::EXP_F128, "expf128"); 1255 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1256 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1257 setLibcallName(RTLIB::COS_F128, "cosf128"); 1258 setLibcallName(RTLIB::POW_F128, "powf128"); 1259 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1260 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1261 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1262 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1263 1264 // With 32 condition bits, we don't need to sink (and duplicate) compares 1265 // aggressively in CodeGenPrep. 1266 if (Subtarget.useCRBits()) { 1267 setHasMultipleConditionRegisters(); 1268 setJumpIsExpensive(); 1269 } 1270 1271 setMinFunctionAlignment(Align(4)); 1272 1273 switch (Subtarget.getCPUDirective()) { 1274 default: break; 1275 case PPC::DIR_970: 1276 case PPC::DIR_A2: 1277 case PPC::DIR_E500: 1278 case PPC::DIR_E500mc: 1279 case PPC::DIR_E5500: 1280 case PPC::DIR_PWR4: 1281 case PPC::DIR_PWR5: 1282 case PPC::DIR_PWR5X: 1283 case PPC::DIR_PWR6: 1284 case PPC::DIR_PWR6X: 1285 case PPC::DIR_PWR7: 1286 case PPC::DIR_PWR8: 1287 case PPC::DIR_PWR9: 1288 case PPC::DIR_PWR10: 1289 case PPC::DIR_PWR_FUTURE: 1290 setPrefLoopAlignment(Align(16)); 1291 setPrefFunctionAlignment(Align(16)); 1292 break; 1293 } 1294 1295 if (Subtarget.enableMachineScheduler()) 1296 setSchedulingPreference(Sched::Source); 1297 else 1298 setSchedulingPreference(Sched::Hybrid); 1299 1300 computeRegisterProperties(STI.getRegisterInfo()); 1301 1302 // The Freescale cores do better with aggressive inlining of memcpy and 1303 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1304 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1305 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1306 MaxStoresPerMemset = 32; 1307 MaxStoresPerMemsetOptSize = 16; 1308 MaxStoresPerMemcpy = 32; 1309 MaxStoresPerMemcpyOptSize = 8; 1310 MaxStoresPerMemmove = 32; 1311 MaxStoresPerMemmoveOptSize = 8; 1312 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1313 // The A2 also benefits from (very) aggressive inlining of memcpy and 1314 // friends. The overhead of a the function call, even when warm, can be 1315 // over one hundred cycles. 1316 MaxStoresPerMemset = 128; 1317 MaxStoresPerMemcpy = 128; 1318 MaxStoresPerMemmove = 128; 1319 MaxLoadsPerMemcmp = 128; 1320 } else { 1321 MaxLoadsPerMemcmp = 8; 1322 MaxLoadsPerMemcmpOptSize = 4; 1323 } 1324 1325 IsStrictFPEnabled = true; 1326 1327 // Let the subtarget (CPU) decide if a predictable select is more expensive 1328 // than the corresponding branch. This information is used in CGP to decide 1329 // when to convert selects into branches. 1330 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1331 } 1332 1333 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1334 /// the desired ByVal argument alignment. 1335 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1336 if (MaxAlign == MaxMaxAlign) 1337 return; 1338 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1339 if (MaxMaxAlign >= 32 && 1340 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1341 MaxAlign = Align(32); 1342 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1343 MaxAlign < 16) 1344 MaxAlign = Align(16); 1345 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1346 Align EltAlign; 1347 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1348 if (EltAlign > MaxAlign) 1349 MaxAlign = EltAlign; 1350 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1351 for (auto *EltTy : STy->elements()) { 1352 Align EltAlign; 1353 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1354 if (EltAlign > MaxAlign) 1355 MaxAlign = EltAlign; 1356 if (MaxAlign == MaxMaxAlign) 1357 break; 1358 } 1359 } 1360 } 1361 1362 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1363 /// function arguments in the caller parameter area. 1364 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1365 const DataLayout &DL) const { 1366 // 16byte and wider vectors are passed on 16byte boundary. 1367 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1368 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1369 if (Subtarget.hasAltivec()) 1370 getMaxByValAlign(Ty, Alignment, Align(16)); 1371 return Alignment.value(); 1372 } 1373 1374 bool PPCTargetLowering::useSoftFloat() const { 1375 return Subtarget.useSoftFloat(); 1376 } 1377 1378 bool PPCTargetLowering::hasSPE() const { 1379 return Subtarget.hasSPE(); 1380 } 1381 1382 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1383 return VT.isScalarInteger(); 1384 } 1385 1386 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1387 /// type is cheaper than a multiply followed by a shift. 1388 /// This is true for words and doublewords on 64-bit PowerPC. 1389 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1390 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1391 isOperationLegal(ISD::MULHU, Type))) 1392 return true; 1393 return TargetLowering::isMulhCheaperThanMulShift(Type); 1394 } 1395 1396 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1397 switch ((PPCISD::NodeType)Opcode) { 1398 case PPCISD::FIRST_NUMBER: break; 1399 case PPCISD::FSEL: return "PPCISD::FSEL"; 1400 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1401 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1402 case PPCISD::FCFID: return "PPCISD::FCFID"; 1403 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1404 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1405 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1406 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1407 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1408 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1409 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1410 case PPCISD::FP_TO_UINT_IN_VSR: 1411 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1412 case PPCISD::FP_TO_SINT_IN_VSR: 1413 return "PPCISD::FP_TO_SINT_IN_VSR"; 1414 case PPCISD::FRE: return "PPCISD::FRE"; 1415 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1416 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1417 case PPCISD::VPERM: return "PPCISD::VPERM"; 1418 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1419 case PPCISD::XXSPLTI_SP_TO_DP: 1420 return "PPCISD::XXSPLTI_SP_TO_DP"; 1421 case PPCISD::XXSPLTI32DX: 1422 return "PPCISD::XXSPLTI32DX"; 1423 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1424 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1425 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1426 case PPCISD::CMPB: return "PPCISD::CMPB"; 1427 case PPCISD::Hi: return "PPCISD::Hi"; 1428 case PPCISD::Lo: return "PPCISD::Lo"; 1429 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1430 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1431 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1432 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1433 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1434 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1435 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1436 case PPCISD::SRL: return "PPCISD::SRL"; 1437 case PPCISD::SRA: return "PPCISD::SRA"; 1438 case PPCISD::SHL: return "PPCISD::SHL"; 1439 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1440 case PPCISD::CALL: return "PPCISD::CALL"; 1441 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1442 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1443 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1444 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1445 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1446 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1447 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1448 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1449 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1450 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1451 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1452 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1453 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1454 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1455 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1456 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1457 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1458 case PPCISD::ANDI_rec_1_EQ_BIT: 1459 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1460 case PPCISD::ANDI_rec_1_GT_BIT: 1461 return "PPCISD::ANDI_rec_1_GT_BIT"; 1462 case PPCISD::VCMP: return "PPCISD::VCMP"; 1463 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1464 case PPCISD::LBRX: return "PPCISD::LBRX"; 1465 case PPCISD::STBRX: return "PPCISD::STBRX"; 1466 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1467 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1468 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1469 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1470 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1471 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1472 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1473 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1474 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1475 case PPCISD::ST_VSR_SCAL_INT: 1476 return "PPCISD::ST_VSR_SCAL_INT"; 1477 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1478 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1479 case PPCISD::BDZ: return "PPCISD::BDZ"; 1480 case PPCISD::MFFS: return "PPCISD::MFFS"; 1481 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1482 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1483 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1484 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1485 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1486 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1487 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1488 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1489 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1490 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1491 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1492 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1493 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1494 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1495 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1496 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1497 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1498 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1499 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1500 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1501 case PPCISD::SC: return "PPCISD::SC"; 1502 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1503 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1504 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1505 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1506 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1507 case PPCISD::VABSD: return "PPCISD::VABSD"; 1508 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1509 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1510 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1511 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1512 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1513 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1514 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1515 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1516 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1517 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1518 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1519 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1520 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1521 case PPCISD::STRICT_FADDRTZ: 1522 return "PPCISD::STRICT_FADDRTZ"; 1523 case PPCISD::STRICT_FCTIDZ: 1524 return "PPCISD::STRICT_FCTIDZ"; 1525 case PPCISD::STRICT_FCTIWZ: 1526 return "PPCISD::STRICT_FCTIWZ"; 1527 case PPCISD::STRICT_FCTIDUZ: 1528 return "PPCISD::STRICT_FCTIDUZ"; 1529 case PPCISD::STRICT_FCTIWUZ: 1530 return "PPCISD::STRICT_FCTIWUZ"; 1531 case PPCISD::STRICT_FCFID: 1532 return "PPCISD::STRICT_FCFID"; 1533 case PPCISD::STRICT_FCFIDU: 1534 return "PPCISD::STRICT_FCFIDU"; 1535 case PPCISD::STRICT_FCFIDS: 1536 return "PPCISD::STRICT_FCFIDS"; 1537 case PPCISD::STRICT_FCFIDUS: 1538 return "PPCISD::STRICT_FCFIDUS"; 1539 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1540 } 1541 return nullptr; 1542 } 1543 1544 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1545 EVT VT) const { 1546 if (!VT.isVector()) 1547 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1548 1549 return VT.changeVectorElementTypeToInteger(); 1550 } 1551 1552 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1553 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1554 return true; 1555 } 1556 1557 //===----------------------------------------------------------------------===// 1558 // Node matching predicates, for use by the tblgen matching code. 1559 //===----------------------------------------------------------------------===// 1560 1561 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1562 static bool isFloatingPointZero(SDValue Op) { 1563 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1564 return CFP->getValueAPF().isZero(); 1565 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1566 // Maybe this has already been legalized into the constant pool? 1567 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1568 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1569 return CFP->getValueAPF().isZero(); 1570 } 1571 return false; 1572 } 1573 1574 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1575 /// true if Op is undef or if it matches the specified value. 1576 static bool isConstantOrUndef(int Op, int Val) { 1577 return Op < 0 || Op == Val; 1578 } 1579 1580 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1581 /// VPKUHUM instruction. 1582 /// The ShuffleKind distinguishes between big-endian operations with 1583 /// two different inputs (0), either-endian operations with two identical 1584 /// inputs (1), and little-endian operations with two different inputs (2). 1585 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1586 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1587 SelectionDAG &DAG) { 1588 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1589 if (ShuffleKind == 0) { 1590 if (IsLE) 1591 return false; 1592 for (unsigned i = 0; i != 16; ++i) 1593 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1594 return false; 1595 } else if (ShuffleKind == 2) { 1596 if (!IsLE) 1597 return false; 1598 for (unsigned i = 0; i != 16; ++i) 1599 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1600 return false; 1601 } else if (ShuffleKind == 1) { 1602 unsigned j = IsLE ? 0 : 1; 1603 for (unsigned i = 0; i != 8; ++i) 1604 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1605 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1606 return false; 1607 } 1608 return true; 1609 } 1610 1611 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1612 /// VPKUWUM instruction. 1613 /// The ShuffleKind distinguishes between big-endian operations with 1614 /// two different inputs (0), either-endian operations with two identical 1615 /// inputs (1), and little-endian operations with two different inputs (2). 1616 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1617 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1618 SelectionDAG &DAG) { 1619 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1620 if (ShuffleKind == 0) { 1621 if (IsLE) 1622 return false; 1623 for (unsigned i = 0; i != 16; i += 2) 1624 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1625 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1626 return false; 1627 } else if (ShuffleKind == 2) { 1628 if (!IsLE) 1629 return false; 1630 for (unsigned i = 0; i != 16; i += 2) 1631 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1632 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1633 return false; 1634 } else if (ShuffleKind == 1) { 1635 unsigned j = IsLE ? 0 : 2; 1636 for (unsigned i = 0; i != 8; i += 2) 1637 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1638 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1639 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1640 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1641 return false; 1642 } 1643 return true; 1644 } 1645 1646 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1647 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1648 /// current subtarget. 1649 /// 1650 /// The ShuffleKind distinguishes between big-endian operations with 1651 /// two different inputs (0), either-endian operations with two identical 1652 /// inputs (1), and little-endian operations with two different inputs (2). 1653 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1654 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1655 SelectionDAG &DAG) { 1656 const PPCSubtarget& Subtarget = 1657 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1658 if (!Subtarget.hasP8Vector()) 1659 return false; 1660 1661 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1662 if (ShuffleKind == 0) { 1663 if (IsLE) 1664 return false; 1665 for (unsigned i = 0; i != 16; i += 4) 1666 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1667 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1668 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1669 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1670 return false; 1671 } else if (ShuffleKind == 2) { 1672 if (!IsLE) 1673 return false; 1674 for (unsigned i = 0; i != 16; i += 4) 1675 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1676 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1677 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1678 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1679 return false; 1680 } else if (ShuffleKind == 1) { 1681 unsigned j = IsLE ? 0 : 4; 1682 for (unsigned i = 0; i != 8; i += 4) 1683 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1684 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1685 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1686 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1687 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1688 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1689 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1690 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1691 return false; 1692 } 1693 return true; 1694 } 1695 1696 /// isVMerge - Common function, used to match vmrg* shuffles. 1697 /// 1698 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1699 unsigned LHSStart, unsigned RHSStart) { 1700 if (N->getValueType(0) != MVT::v16i8) 1701 return false; 1702 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1703 "Unsupported merge size!"); 1704 1705 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1706 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1707 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1708 LHSStart+j+i*UnitSize) || 1709 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1710 RHSStart+j+i*UnitSize)) 1711 return false; 1712 } 1713 return true; 1714 } 1715 1716 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1717 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1718 /// The ShuffleKind distinguishes between big-endian merges with two 1719 /// different inputs (0), either-endian merges with two identical inputs (1), 1720 /// and little-endian merges with two different inputs (2). For the latter, 1721 /// the input operands are swapped (see PPCInstrAltivec.td). 1722 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1723 unsigned ShuffleKind, SelectionDAG &DAG) { 1724 if (DAG.getDataLayout().isLittleEndian()) { 1725 if (ShuffleKind == 1) // unary 1726 return isVMerge(N, UnitSize, 0, 0); 1727 else if (ShuffleKind == 2) // swapped 1728 return isVMerge(N, UnitSize, 0, 16); 1729 else 1730 return false; 1731 } else { 1732 if (ShuffleKind == 1) // unary 1733 return isVMerge(N, UnitSize, 8, 8); 1734 else if (ShuffleKind == 0) // normal 1735 return isVMerge(N, UnitSize, 8, 24); 1736 else 1737 return false; 1738 } 1739 } 1740 1741 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1742 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1743 /// The ShuffleKind distinguishes between big-endian merges with two 1744 /// different inputs (0), either-endian merges with two identical inputs (1), 1745 /// and little-endian merges with two different inputs (2). For the latter, 1746 /// the input operands are swapped (see PPCInstrAltivec.td). 1747 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1748 unsigned ShuffleKind, SelectionDAG &DAG) { 1749 if (DAG.getDataLayout().isLittleEndian()) { 1750 if (ShuffleKind == 1) // unary 1751 return isVMerge(N, UnitSize, 8, 8); 1752 else if (ShuffleKind == 2) // swapped 1753 return isVMerge(N, UnitSize, 8, 24); 1754 else 1755 return false; 1756 } else { 1757 if (ShuffleKind == 1) // unary 1758 return isVMerge(N, UnitSize, 0, 0); 1759 else if (ShuffleKind == 0) // normal 1760 return isVMerge(N, UnitSize, 0, 16); 1761 else 1762 return false; 1763 } 1764 } 1765 1766 /** 1767 * Common function used to match vmrgew and vmrgow shuffles 1768 * 1769 * The indexOffset determines whether to look for even or odd words in 1770 * the shuffle mask. This is based on the of the endianness of the target 1771 * machine. 1772 * - Little Endian: 1773 * - Use offset of 0 to check for odd elements 1774 * - Use offset of 4 to check for even elements 1775 * - Big Endian: 1776 * - Use offset of 0 to check for even elements 1777 * - Use offset of 4 to check for odd elements 1778 * A detailed description of the vector element ordering for little endian and 1779 * big endian can be found at 1780 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1781 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1782 * compiler differences mean to you 1783 * 1784 * The mask to the shuffle vector instruction specifies the indices of the 1785 * elements from the two input vectors to place in the result. The elements are 1786 * numbered in array-access order, starting with the first vector. These vectors 1787 * are always of type v16i8, thus each vector will contain 16 elements of size 1788 * 8. More info on the shuffle vector can be found in the 1789 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1790 * Language Reference. 1791 * 1792 * The RHSStartValue indicates whether the same input vectors are used (unary) 1793 * or two different input vectors are used, based on the following: 1794 * - If the instruction uses the same vector for both inputs, the range of the 1795 * indices will be 0 to 15. In this case, the RHSStart value passed should 1796 * be 0. 1797 * - If the instruction has two different vectors then the range of the 1798 * indices will be 0 to 31. In this case, the RHSStart value passed should 1799 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1800 * to 31 specify elements in the second vector). 1801 * 1802 * \param[in] N The shuffle vector SD Node to analyze 1803 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1804 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1805 * vector to the shuffle_vector instruction 1806 * \return true iff this shuffle vector represents an even or odd word merge 1807 */ 1808 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1809 unsigned RHSStartValue) { 1810 if (N->getValueType(0) != MVT::v16i8) 1811 return false; 1812 1813 for (unsigned i = 0; i < 2; ++i) 1814 for (unsigned j = 0; j < 4; ++j) 1815 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1816 i*RHSStartValue+j+IndexOffset) || 1817 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1818 i*RHSStartValue+j+IndexOffset+8)) 1819 return false; 1820 return true; 1821 } 1822 1823 /** 1824 * Determine if the specified shuffle mask is suitable for the vmrgew or 1825 * vmrgow instructions. 1826 * 1827 * \param[in] N The shuffle vector SD Node to analyze 1828 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1829 * \param[in] ShuffleKind Identify the type of merge: 1830 * - 0 = big-endian merge with two different inputs; 1831 * - 1 = either-endian merge with two identical inputs; 1832 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1833 * little-endian merges). 1834 * \param[in] DAG The current SelectionDAG 1835 * \return true iff this shuffle mask 1836 */ 1837 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1838 unsigned ShuffleKind, SelectionDAG &DAG) { 1839 if (DAG.getDataLayout().isLittleEndian()) { 1840 unsigned indexOffset = CheckEven ? 4 : 0; 1841 if (ShuffleKind == 1) // Unary 1842 return isVMerge(N, indexOffset, 0); 1843 else if (ShuffleKind == 2) // swapped 1844 return isVMerge(N, indexOffset, 16); 1845 else 1846 return false; 1847 } 1848 else { 1849 unsigned indexOffset = CheckEven ? 0 : 4; 1850 if (ShuffleKind == 1) // Unary 1851 return isVMerge(N, indexOffset, 0); 1852 else if (ShuffleKind == 0) // Normal 1853 return isVMerge(N, indexOffset, 16); 1854 else 1855 return false; 1856 } 1857 return false; 1858 } 1859 1860 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1861 /// amount, otherwise return -1. 1862 /// The ShuffleKind distinguishes between big-endian operations with two 1863 /// different inputs (0), either-endian operations with two identical inputs 1864 /// (1), and little-endian operations with two different inputs (2). For the 1865 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1866 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1867 SelectionDAG &DAG) { 1868 if (N->getValueType(0) != MVT::v16i8) 1869 return -1; 1870 1871 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1872 1873 // Find the first non-undef value in the shuffle mask. 1874 unsigned i; 1875 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1876 /*search*/; 1877 1878 if (i == 16) return -1; // all undef. 1879 1880 // Otherwise, check to see if the rest of the elements are consecutively 1881 // numbered from this value. 1882 unsigned ShiftAmt = SVOp->getMaskElt(i); 1883 if (ShiftAmt < i) return -1; 1884 1885 ShiftAmt -= i; 1886 bool isLE = DAG.getDataLayout().isLittleEndian(); 1887 1888 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1889 // Check the rest of the elements to see if they are consecutive. 1890 for (++i; i != 16; ++i) 1891 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1892 return -1; 1893 } else if (ShuffleKind == 1) { 1894 // Check the rest of the elements to see if they are consecutive. 1895 for (++i; i != 16; ++i) 1896 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1897 return -1; 1898 } else 1899 return -1; 1900 1901 if (isLE) 1902 ShiftAmt = 16 - ShiftAmt; 1903 1904 return ShiftAmt; 1905 } 1906 1907 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1908 /// specifies a splat of a single element that is suitable for input to 1909 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1910 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1911 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1912 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1913 1914 // The consecutive indices need to specify an element, not part of two 1915 // different elements. So abandon ship early if this isn't the case. 1916 if (N->getMaskElt(0) % EltSize != 0) 1917 return false; 1918 1919 // This is a splat operation if each element of the permute is the same, and 1920 // if the value doesn't reference the second vector. 1921 unsigned ElementBase = N->getMaskElt(0); 1922 1923 // FIXME: Handle UNDEF elements too! 1924 if (ElementBase >= 16) 1925 return false; 1926 1927 // Check that the indices are consecutive, in the case of a multi-byte element 1928 // splatted with a v16i8 mask. 1929 for (unsigned i = 1; i != EltSize; ++i) 1930 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1931 return false; 1932 1933 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1934 if (N->getMaskElt(i) < 0) continue; 1935 for (unsigned j = 0; j != EltSize; ++j) 1936 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1937 return false; 1938 } 1939 return true; 1940 } 1941 1942 /// Check that the mask is shuffling N byte elements. Within each N byte 1943 /// element of the mask, the indices could be either in increasing or 1944 /// decreasing order as long as they are consecutive. 1945 /// \param[in] N the shuffle vector SD Node to analyze 1946 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1947 /// Word/DoubleWord/QuadWord). 1948 /// \param[in] StepLen the delta indices number among the N byte element, if 1949 /// the mask is in increasing/decreasing order then it is 1/-1. 1950 /// \return true iff the mask is shuffling N byte elements. 1951 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1952 int StepLen) { 1953 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1954 "Unexpected element width."); 1955 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1956 1957 unsigned NumOfElem = 16 / Width; 1958 unsigned MaskVal[16]; // Width is never greater than 16 1959 for (unsigned i = 0; i < NumOfElem; ++i) { 1960 MaskVal[0] = N->getMaskElt(i * Width); 1961 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1962 return false; 1963 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1964 return false; 1965 } 1966 1967 for (unsigned int j = 1; j < Width; ++j) { 1968 MaskVal[j] = N->getMaskElt(i * Width + j); 1969 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1970 return false; 1971 } 1972 } 1973 } 1974 1975 return true; 1976 } 1977 1978 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1979 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1980 if (!isNByteElemShuffleMask(N, 4, 1)) 1981 return false; 1982 1983 // Now we look at mask elements 0,4,8,12 1984 unsigned M0 = N->getMaskElt(0) / 4; 1985 unsigned M1 = N->getMaskElt(4) / 4; 1986 unsigned M2 = N->getMaskElt(8) / 4; 1987 unsigned M3 = N->getMaskElt(12) / 4; 1988 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1989 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1990 1991 // Below, let H and L be arbitrary elements of the shuffle mask 1992 // where H is in the range [4,7] and L is in the range [0,3]. 1993 // H, 1, 2, 3 or L, 5, 6, 7 1994 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1995 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1996 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1997 InsertAtByte = IsLE ? 12 : 0; 1998 Swap = M0 < 4; 1999 return true; 2000 } 2001 // 0, H, 2, 3 or 4, L, 6, 7 2002 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2003 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2004 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2005 InsertAtByte = IsLE ? 8 : 4; 2006 Swap = M1 < 4; 2007 return true; 2008 } 2009 // 0, 1, H, 3 or 4, 5, L, 7 2010 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2011 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2012 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2013 InsertAtByte = IsLE ? 4 : 8; 2014 Swap = M2 < 4; 2015 return true; 2016 } 2017 // 0, 1, 2, H or 4, 5, 6, L 2018 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2019 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2020 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2021 InsertAtByte = IsLE ? 0 : 12; 2022 Swap = M3 < 4; 2023 return true; 2024 } 2025 2026 // If both vector operands for the shuffle are the same vector, the mask will 2027 // contain only elements from the first one and the second one will be undef. 2028 if (N->getOperand(1).isUndef()) { 2029 ShiftElts = 0; 2030 Swap = true; 2031 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2032 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2033 InsertAtByte = IsLE ? 12 : 0; 2034 return true; 2035 } 2036 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2037 InsertAtByte = IsLE ? 8 : 4; 2038 return true; 2039 } 2040 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2041 InsertAtByte = IsLE ? 4 : 8; 2042 return true; 2043 } 2044 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2045 InsertAtByte = IsLE ? 0 : 12; 2046 return true; 2047 } 2048 } 2049 2050 return false; 2051 } 2052 2053 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2054 bool &Swap, bool IsLE) { 2055 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2056 // Ensure each byte index of the word is consecutive. 2057 if (!isNByteElemShuffleMask(N, 4, 1)) 2058 return false; 2059 2060 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2061 unsigned M0 = N->getMaskElt(0) / 4; 2062 unsigned M1 = N->getMaskElt(4) / 4; 2063 unsigned M2 = N->getMaskElt(8) / 4; 2064 unsigned M3 = N->getMaskElt(12) / 4; 2065 2066 // If both vector operands for the shuffle are the same vector, the mask will 2067 // contain only elements from the first one and the second one will be undef. 2068 if (N->getOperand(1).isUndef()) { 2069 assert(M0 < 4 && "Indexing into an undef vector?"); 2070 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2071 return false; 2072 2073 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2074 Swap = false; 2075 return true; 2076 } 2077 2078 // Ensure each word index of the ShuffleVector Mask is consecutive. 2079 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2080 return false; 2081 2082 if (IsLE) { 2083 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2084 // Input vectors don't need to be swapped if the leading element 2085 // of the result is one of the 3 left elements of the second vector 2086 // (or if there is no shift to be done at all). 2087 Swap = false; 2088 ShiftElts = (8 - M0) % 8; 2089 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2090 // Input vectors need to be swapped if the leading element 2091 // of the result is one of the 3 left elements of the first vector 2092 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2093 Swap = true; 2094 ShiftElts = (4 - M0) % 4; 2095 } 2096 2097 return true; 2098 } else { // BE 2099 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2100 // Input vectors don't need to be swapped if the leading element 2101 // of the result is one of the 4 elements of the first vector. 2102 Swap = false; 2103 ShiftElts = M0; 2104 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2105 // Input vectors need to be swapped if the leading element 2106 // of the result is one of the 4 elements of the right vector. 2107 Swap = true; 2108 ShiftElts = M0 - 4; 2109 } 2110 2111 return true; 2112 } 2113 } 2114 2115 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2116 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2117 2118 if (!isNByteElemShuffleMask(N, Width, -1)) 2119 return false; 2120 2121 for (int i = 0; i < 16; i += Width) 2122 if (N->getMaskElt(i) != i + Width - 1) 2123 return false; 2124 2125 return true; 2126 } 2127 2128 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2129 return isXXBRShuffleMaskHelper(N, 2); 2130 } 2131 2132 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2133 return isXXBRShuffleMaskHelper(N, 4); 2134 } 2135 2136 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2137 return isXXBRShuffleMaskHelper(N, 8); 2138 } 2139 2140 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2141 return isXXBRShuffleMaskHelper(N, 16); 2142 } 2143 2144 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2145 /// if the inputs to the instruction should be swapped and set \p DM to the 2146 /// value for the immediate. 2147 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2148 /// AND element 0 of the result comes from the first input (LE) or second input 2149 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2150 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2151 /// mask. 2152 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2153 bool &Swap, bool IsLE) { 2154 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2155 2156 // Ensure each byte index of the double word is consecutive. 2157 if (!isNByteElemShuffleMask(N, 8, 1)) 2158 return false; 2159 2160 unsigned M0 = N->getMaskElt(0) / 8; 2161 unsigned M1 = N->getMaskElt(8) / 8; 2162 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2163 2164 // If both vector operands for the shuffle are the same vector, the mask will 2165 // contain only elements from the first one and the second one will be undef. 2166 if (N->getOperand(1).isUndef()) { 2167 if ((M0 | M1) < 2) { 2168 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2169 Swap = false; 2170 return true; 2171 } else 2172 return false; 2173 } 2174 2175 if (IsLE) { 2176 if (M0 > 1 && M1 < 2) { 2177 Swap = false; 2178 } else if (M0 < 2 && M1 > 1) { 2179 M0 = (M0 + 2) % 4; 2180 M1 = (M1 + 2) % 4; 2181 Swap = true; 2182 } else 2183 return false; 2184 2185 // Note: if control flow comes here that means Swap is already set above 2186 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2187 return true; 2188 } else { // BE 2189 if (M0 < 2 && M1 > 1) { 2190 Swap = false; 2191 } else if (M0 > 1 && M1 < 2) { 2192 M0 = (M0 + 2) % 4; 2193 M1 = (M1 + 2) % 4; 2194 Swap = true; 2195 } else 2196 return false; 2197 2198 // Note: if control flow comes here that means Swap is already set above 2199 DM = (M0 << 1) + (M1 & 1); 2200 return true; 2201 } 2202 } 2203 2204 2205 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2206 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2207 /// elements are counted from the left of the vector register). 2208 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2209 SelectionDAG &DAG) { 2210 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2211 assert(isSplatShuffleMask(SVOp, EltSize)); 2212 if (DAG.getDataLayout().isLittleEndian()) 2213 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2214 else 2215 return SVOp->getMaskElt(0) / EltSize; 2216 } 2217 2218 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2219 /// by using a vspltis[bhw] instruction of the specified element size, return 2220 /// the constant being splatted. The ByteSize field indicates the number of 2221 /// bytes of each element [124] -> [bhw]. 2222 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2223 SDValue OpVal(nullptr, 0); 2224 2225 // If ByteSize of the splat is bigger than the element size of the 2226 // build_vector, then we have a case where we are checking for a splat where 2227 // multiple elements of the buildvector are folded together into a single 2228 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2229 unsigned EltSize = 16/N->getNumOperands(); 2230 if (EltSize < ByteSize) { 2231 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2232 SDValue UniquedVals[4]; 2233 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2234 2235 // See if all of the elements in the buildvector agree across. 2236 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2237 if (N->getOperand(i).isUndef()) continue; 2238 // If the element isn't a constant, bail fully out. 2239 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2240 2241 if (!UniquedVals[i&(Multiple-1)].getNode()) 2242 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2243 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2244 return SDValue(); // no match. 2245 } 2246 2247 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2248 // either constant or undef values that are identical for each chunk. See 2249 // if these chunks can form into a larger vspltis*. 2250 2251 // Check to see if all of the leading entries are either 0 or -1. If 2252 // neither, then this won't fit into the immediate field. 2253 bool LeadingZero = true; 2254 bool LeadingOnes = true; 2255 for (unsigned i = 0; i != Multiple-1; ++i) { 2256 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2257 2258 LeadingZero &= isNullConstant(UniquedVals[i]); 2259 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2260 } 2261 // Finally, check the least significant entry. 2262 if (LeadingZero) { 2263 if (!UniquedVals[Multiple-1].getNode()) 2264 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2265 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2266 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2267 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2268 } 2269 if (LeadingOnes) { 2270 if (!UniquedVals[Multiple-1].getNode()) 2271 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2272 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2273 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2274 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2275 } 2276 2277 return SDValue(); 2278 } 2279 2280 // Check to see if this buildvec has a single non-undef value in its elements. 2281 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2282 if (N->getOperand(i).isUndef()) continue; 2283 if (!OpVal.getNode()) 2284 OpVal = N->getOperand(i); 2285 else if (OpVal != N->getOperand(i)) 2286 return SDValue(); 2287 } 2288 2289 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2290 2291 unsigned ValSizeInBytes = EltSize; 2292 uint64_t Value = 0; 2293 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2294 Value = CN->getZExtValue(); 2295 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2296 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2297 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2298 } 2299 2300 // If the splat value is larger than the element value, then we can never do 2301 // this splat. The only case that we could fit the replicated bits into our 2302 // immediate field for would be zero, and we prefer to use vxor for it. 2303 if (ValSizeInBytes < ByteSize) return SDValue(); 2304 2305 // If the element value is larger than the splat value, check if it consists 2306 // of a repeated bit pattern of size ByteSize. 2307 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2308 return SDValue(); 2309 2310 // Properly sign extend the value. 2311 int MaskVal = SignExtend32(Value, ByteSize * 8); 2312 2313 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2314 if (MaskVal == 0) return SDValue(); 2315 2316 // Finally, if this value fits in a 5 bit sext field, return it 2317 if (SignExtend32<5>(MaskVal) == MaskVal) 2318 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2319 return SDValue(); 2320 } 2321 2322 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2323 /// amount, otherwise return -1. 2324 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2325 EVT VT = N->getValueType(0); 2326 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2327 return -1; 2328 2329 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2330 2331 // Find the first non-undef value in the shuffle mask. 2332 unsigned i; 2333 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2334 /*search*/; 2335 2336 if (i == 4) return -1; // all undef. 2337 2338 // Otherwise, check to see if the rest of the elements are consecutively 2339 // numbered from this value. 2340 unsigned ShiftAmt = SVOp->getMaskElt(i); 2341 if (ShiftAmt < i) return -1; 2342 ShiftAmt -= i; 2343 2344 // Check the rest of the elements to see if they are consecutive. 2345 for (++i; i != 4; ++i) 2346 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2347 return -1; 2348 2349 return ShiftAmt; 2350 } 2351 2352 //===----------------------------------------------------------------------===// 2353 // Addressing Mode Selection 2354 //===----------------------------------------------------------------------===// 2355 2356 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2357 /// or 64-bit immediate, and if the value can be accurately represented as a 2358 /// sign extension from a 16-bit value. If so, this returns true and the 2359 /// immediate. 2360 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2361 if (!isa<ConstantSDNode>(N)) 2362 return false; 2363 2364 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2365 if (N->getValueType(0) == MVT::i32) 2366 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2367 else 2368 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2369 } 2370 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2371 return isIntS16Immediate(Op.getNode(), Imm); 2372 } 2373 2374 2375 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2376 /// be represented as an indexed [r+r] operation. 2377 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2378 SDValue &Index, 2379 SelectionDAG &DAG) const { 2380 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2381 UI != E; ++UI) { 2382 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2383 if (Memop->getMemoryVT() == MVT::f64) { 2384 Base = N.getOperand(0); 2385 Index = N.getOperand(1); 2386 return true; 2387 } 2388 } 2389 } 2390 return false; 2391 } 2392 2393 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2394 /// can be represented as an indexed [r+r] operation. Returns false if it 2395 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2396 /// non-zero and N can be represented by a base register plus a signed 16-bit 2397 /// displacement, make a more precise judgement by checking (displacement % \p 2398 /// EncodingAlignment). 2399 bool PPCTargetLowering::SelectAddressRegReg( 2400 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2401 MaybeAlign EncodingAlignment) const { 2402 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2403 // a [pc+imm]. 2404 if (SelectAddressPCRel(N, Base)) 2405 return false; 2406 2407 int16_t Imm = 0; 2408 if (N.getOpcode() == ISD::ADD) { 2409 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2410 // SPE load/store can only handle 8-bit offsets. 2411 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2412 return true; 2413 if (isIntS16Immediate(N.getOperand(1), Imm) && 2414 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2415 return false; // r+i 2416 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2417 return false; // r+i 2418 2419 Base = N.getOperand(0); 2420 Index = N.getOperand(1); 2421 return true; 2422 } else if (N.getOpcode() == ISD::OR) { 2423 if (isIntS16Immediate(N.getOperand(1), Imm) && 2424 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2425 return false; // r+i can fold it if we can. 2426 2427 // If this is an or of disjoint bitfields, we can codegen this as an add 2428 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2429 // disjoint. 2430 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2431 2432 if (LHSKnown.Zero.getBoolValue()) { 2433 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2434 // If all of the bits are known zero on the LHS or RHS, the add won't 2435 // carry. 2436 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2437 Base = N.getOperand(0); 2438 Index = N.getOperand(1); 2439 return true; 2440 } 2441 } 2442 } 2443 2444 return false; 2445 } 2446 2447 // If we happen to be doing an i64 load or store into a stack slot that has 2448 // less than a 4-byte alignment, then the frame-index elimination may need to 2449 // use an indexed load or store instruction (because the offset may not be a 2450 // multiple of 4). The extra register needed to hold the offset comes from the 2451 // register scavenger, and it is possible that the scavenger will need to use 2452 // an emergency spill slot. As a result, we need to make sure that a spill slot 2453 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2454 // stack slot. 2455 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2456 // FIXME: This does not handle the LWA case. 2457 if (VT != MVT::i64) 2458 return; 2459 2460 // NOTE: We'll exclude negative FIs here, which come from argument 2461 // lowering, because there are no known test cases triggering this problem 2462 // using packed structures (or similar). We can remove this exclusion if 2463 // we find such a test case. The reason why this is so test-case driven is 2464 // because this entire 'fixup' is only to prevent crashes (from the 2465 // register scavenger) on not-really-valid inputs. For example, if we have: 2466 // %a = alloca i1 2467 // %b = bitcast i1* %a to i64* 2468 // store i64* a, i64 b 2469 // then the store should really be marked as 'align 1', but is not. If it 2470 // were marked as 'align 1' then the indexed form would have been 2471 // instruction-selected initially, and the problem this 'fixup' is preventing 2472 // won't happen regardless. 2473 if (FrameIdx < 0) 2474 return; 2475 2476 MachineFunction &MF = DAG.getMachineFunction(); 2477 MachineFrameInfo &MFI = MF.getFrameInfo(); 2478 2479 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2480 return; 2481 2482 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2483 FuncInfo->setHasNonRISpills(); 2484 } 2485 2486 /// Returns true if the address N can be represented by a base register plus 2487 /// a signed 16-bit displacement [r+imm], and if it is not better 2488 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2489 /// displacements that are multiples of that value. 2490 bool PPCTargetLowering::SelectAddressRegImm( 2491 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2492 MaybeAlign EncodingAlignment) const { 2493 // FIXME dl should come from parent load or store, not from address 2494 SDLoc dl(N); 2495 2496 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2497 // a [pc+imm]. 2498 if (SelectAddressPCRel(N, Base)) 2499 return false; 2500 2501 // If this can be more profitably realized as r+r, fail. 2502 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2503 return false; 2504 2505 if (N.getOpcode() == ISD::ADD) { 2506 int16_t imm = 0; 2507 if (isIntS16Immediate(N.getOperand(1), imm) && 2508 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2509 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2510 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2511 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2512 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2513 } else { 2514 Base = N.getOperand(0); 2515 } 2516 return true; // [r+i] 2517 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2518 // Match LOAD (ADD (X, Lo(G))). 2519 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2520 && "Cannot handle constant offsets yet!"); 2521 Disp = N.getOperand(1).getOperand(0); // The global address. 2522 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2523 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2524 Disp.getOpcode() == ISD::TargetConstantPool || 2525 Disp.getOpcode() == ISD::TargetJumpTable); 2526 Base = N.getOperand(0); 2527 return true; // [&g+r] 2528 } 2529 } else if (N.getOpcode() == ISD::OR) { 2530 int16_t imm = 0; 2531 if (isIntS16Immediate(N.getOperand(1), imm) && 2532 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2533 // If this is an or of disjoint bitfields, we can codegen this as an add 2534 // (for better address arithmetic) if the LHS and RHS of the OR are 2535 // provably disjoint. 2536 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2537 2538 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2539 // If all of the bits are known zero on the LHS or RHS, the add won't 2540 // carry. 2541 if (FrameIndexSDNode *FI = 2542 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2543 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2544 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2545 } else { 2546 Base = N.getOperand(0); 2547 } 2548 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2549 return true; 2550 } 2551 } 2552 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2553 // Loading from a constant address. 2554 2555 // If this address fits entirely in a 16-bit sext immediate field, codegen 2556 // this as "d, 0" 2557 int16_t Imm; 2558 if (isIntS16Immediate(CN, Imm) && 2559 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2560 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2561 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2562 CN->getValueType(0)); 2563 return true; 2564 } 2565 2566 // Handle 32-bit sext immediates with LIS + addr mode. 2567 if ((CN->getValueType(0) == MVT::i32 || 2568 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2569 (!EncodingAlignment || 2570 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2571 int Addr = (int)CN->getZExtValue(); 2572 2573 // Otherwise, break this down into an LIS + disp. 2574 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2575 2576 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2577 MVT::i32); 2578 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2579 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2580 return true; 2581 } 2582 } 2583 2584 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2585 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2586 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2587 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2588 } else 2589 Base = N; 2590 return true; // [r+0] 2591 } 2592 2593 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2594 /// represented as an indexed [r+r] operation. 2595 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2596 SDValue &Index, 2597 SelectionDAG &DAG) const { 2598 // Check to see if we can easily represent this as an [r+r] address. This 2599 // will fail if it thinks that the address is more profitably represented as 2600 // reg+imm, e.g. where imm = 0. 2601 if (SelectAddressRegReg(N, Base, Index, DAG)) 2602 return true; 2603 2604 // If the address is the result of an add, we will utilize the fact that the 2605 // address calculation includes an implicit add. However, we can reduce 2606 // register pressure if we do not materialize a constant just for use as the 2607 // index register. We only get rid of the add if it is not an add of a 2608 // value and a 16-bit signed constant and both have a single use. 2609 int16_t imm = 0; 2610 if (N.getOpcode() == ISD::ADD && 2611 (!isIntS16Immediate(N.getOperand(1), imm) || 2612 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2613 Base = N.getOperand(0); 2614 Index = N.getOperand(1); 2615 return true; 2616 } 2617 2618 // Otherwise, do it the hard way, using R0 as the base register. 2619 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2620 N.getValueType()); 2621 Index = N; 2622 return true; 2623 } 2624 2625 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2626 Ty *PCRelCand = dyn_cast<Ty>(N); 2627 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2628 } 2629 2630 /// Returns true if this address is a PC Relative address. 2631 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2632 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2633 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2634 // This is a materialize PC Relative node. Always select this as PC Relative. 2635 Base = N; 2636 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2637 return true; 2638 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2639 isValidPCRelNode<GlobalAddressSDNode>(N) || 2640 isValidPCRelNode<JumpTableSDNode>(N) || 2641 isValidPCRelNode<BlockAddressSDNode>(N)) 2642 return true; 2643 return false; 2644 } 2645 2646 /// Returns true if we should use a direct load into vector instruction 2647 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2648 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2649 2650 // If there are any other uses other than scalar to vector, then we should 2651 // keep it as a scalar load -> direct move pattern to prevent multiple 2652 // loads. 2653 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2654 if (!LD) 2655 return false; 2656 2657 EVT MemVT = LD->getMemoryVT(); 2658 if (!MemVT.isSimple()) 2659 return false; 2660 switch(MemVT.getSimpleVT().SimpleTy) { 2661 case MVT::i64: 2662 break; 2663 case MVT::i32: 2664 if (!ST.hasP8Vector()) 2665 return false; 2666 break; 2667 case MVT::i16: 2668 case MVT::i8: 2669 if (!ST.hasP9Vector()) 2670 return false; 2671 break; 2672 default: 2673 return false; 2674 } 2675 2676 SDValue LoadedVal(N, 0); 2677 if (!LoadedVal.hasOneUse()) 2678 return false; 2679 2680 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2681 UI != UE; ++UI) 2682 if (UI.getUse().get().getResNo() == 0 && 2683 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2684 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2685 return false; 2686 2687 return true; 2688 } 2689 2690 /// getPreIndexedAddressParts - returns true by value, base pointer and 2691 /// offset pointer and addressing mode by reference if the node's address 2692 /// can be legally represented as pre-indexed load / store address. 2693 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2694 SDValue &Offset, 2695 ISD::MemIndexedMode &AM, 2696 SelectionDAG &DAG) const { 2697 if (DisablePPCPreinc) return false; 2698 2699 bool isLoad = true; 2700 SDValue Ptr; 2701 EVT VT; 2702 unsigned Alignment; 2703 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2704 Ptr = LD->getBasePtr(); 2705 VT = LD->getMemoryVT(); 2706 Alignment = LD->getAlignment(); 2707 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2708 Ptr = ST->getBasePtr(); 2709 VT = ST->getMemoryVT(); 2710 Alignment = ST->getAlignment(); 2711 isLoad = false; 2712 } else 2713 return false; 2714 2715 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2716 // instructions because we can fold these into a more efficient instruction 2717 // instead, (such as LXSD). 2718 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2719 return false; 2720 } 2721 2722 // PowerPC doesn't have preinc load/store instructions for vectors 2723 if (VT.isVector()) 2724 return false; 2725 2726 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2727 // Common code will reject creating a pre-inc form if the base pointer 2728 // is a frame index, or if N is a store and the base pointer is either 2729 // the same as or a predecessor of the value being stored. Check for 2730 // those situations here, and try with swapped Base/Offset instead. 2731 bool Swap = false; 2732 2733 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2734 Swap = true; 2735 else if (!isLoad) { 2736 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2737 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2738 Swap = true; 2739 } 2740 2741 if (Swap) 2742 std::swap(Base, Offset); 2743 2744 AM = ISD::PRE_INC; 2745 return true; 2746 } 2747 2748 // LDU/STU can only handle immediates that are a multiple of 4. 2749 if (VT != MVT::i64) { 2750 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2751 return false; 2752 } else { 2753 // LDU/STU need an address with at least 4-byte alignment. 2754 if (Alignment < 4) 2755 return false; 2756 2757 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2758 return false; 2759 } 2760 2761 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2762 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2763 // sext i32 to i64 when addr mode is r+i. 2764 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2765 LD->getExtensionType() == ISD::SEXTLOAD && 2766 isa<ConstantSDNode>(Offset)) 2767 return false; 2768 } 2769 2770 AM = ISD::PRE_INC; 2771 return true; 2772 } 2773 2774 //===----------------------------------------------------------------------===// 2775 // LowerOperation implementation 2776 //===----------------------------------------------------------------------===// 2777 2778 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2779 /// and LoOpFlags to the target MO flags. 2780 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2781 unsigned &HiOpFlags, unsigned &LoOpFlags, 2782 const GlobalValue *GV = nullptr) { 2783 HiOpFlags = PPCII::MO_HA; 2784 LoOpFlags = PPCII::MO_LO; 2785 2786 // Don't use the pic base if not in PIC relocation model. 2787 if (IsPIC) { 2788 HiOpFlags |= PPCII::MO_PIC_FLAG; 2789 LoOpFlags |= PPCII::MO_PIC_FLAG; 2790 } 2791 } 2792 2793 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2794 SelectionDAG &DAG) { 2795 SDLoc DL(HiPart); 2796 EVT PtrVT = HiPart.getValueType(); 2797 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2798 2799 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2800 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2801 2802 // With PIC, the first instruction is actually "GR+hi(&G)". 2803 if (isPIC) 2804 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2805 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2806 2807 // Generate non-pic code that has direct accesses to the constant pool. 2808 // The address of the global is just (hi(&g)+lo(&g)). 2809 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2810 } 2811 2812 static void setUsesTOCBasePtr(MachineFunction &MF) { 2813 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2814 FuncInfo->setUsesTOCBasePtr(); 2815 } 2816 2817 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2818 setUsesTOCBasePtr(DAG.getMachineFunction()); 2819 } 2820 2821 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2822 SDValue GA) const { 2823 const bool Is64Bit = Subtarget.isPPC64(); 2824 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2825 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2826 : Subtarget.isAIXABI() 2827 ? DAG.getRegister(PPC::R2, VT) 2828 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2829 SDValue Ops[] = { GA, Reg }; 2830 return DAG.getMemIntrinsicNode( 2831 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2832 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2833 MachineMemOperand::MOLoad); 2834 } 2835 2836 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2837 SelectionDAG &DAG) const { 2838 EVT PtrVT = Op.getValueType(); 2839 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2840 const Constant *C = CP->getConstVal(); 2841 2842 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2843 // The actual address of the GlobalValue is stored in the TOC. 2844 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2845 if (Subtarget.isUsingPCRelativeCalls()) { 2846 SDLoc DL(CP); 2847 EVT Ty = getPointerTy(DAG.getDataLayout()); 2848 SDValue ConstPool = DAG.getTargetConstantPool( 2849 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2850 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2851 } 2852 setUsesTOCBasePtr(DAG); 2853 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2854 return getTOCEntry(DAG, SDLoc(CP), GA); 2855 } 2856 2857 unsigned MOHiFlag, MOLoFlag; 2858 bool IsPIC = isPositionIndependent(); 2859 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2860 2861 if (IsPIC && Subtarget.isSVR4ABI()) { 2862 SDValue GA = 2863 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2864 return getTOCEntry(DAG, SDLoc(CP), GA); 2865 } 2866 2867 SDValue CPIHi = 2868 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2869 SDValue CPILo = 2870 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2871 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2872 } 2873 2874 // For 64-bit PowerPC, prefer the more compact relative encodings. 2875 // This trades 32 bits per jump table entry for one or two instructions 2876 // on the jump site. 2877 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2878 if (isJumpTableRelative()) 2879 return MachineJumpTableInfo::EK_LabelDifference32; 2880 2881 return TargetLowering::getJumpTableEncoding(); 2882 } 2883 2884 bool PPCTargetLowering::isJumpTableRelative() const { 2885 if (UseAbsoluteJumpTables) 2886 return false; 2887 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2888 return true; 2889 return TargetLowering::isJumpTableRelative(); 2890 } 2891 2892 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2893 SelectionDAG &DAG) const { 2894 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2895 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2896 2897 switch (getTargetMachine().getCodeModel()) { 2898 case CodeModel::Small: 2899 case CodeModel::Medium: 2900 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2901 default: 2902 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2903 getPointerTy(DAG.getDataLayout())); 2904 } 2905 } 2906 2907 const MCExpr * 2908 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2909 unsigned JTI, 2910 MCContext &Ctx) const { 2911 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2912 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2913 2914 switch (getTargetMachine().getCodeModel()) { 2915 case CodeModel::Small: 2916 case CodeModel::Medium: 2917 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2918 default: 2919 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2920 } 2921 } 2922 2923 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2924 EVT PtrVT = Op.getValueType(); 2925 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2926 2927 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2928 if (Subtarget.isUsingPCRelativeCalls()) { 2929 SDLoc DL(JT); 2930 EVT Ty = getPointerTy(DAG.getDataLayout()); 2931 SDValue GA = 2932 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2933 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2934 return MatAddr; 2935 } 2936 2937 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2938 // The actual address of the GlobalValue is stored in the TOC. 2939 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2940 setUsesTOCBasePtr(DAG); 2941 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2942 return getTOCEntry(DAG, SDLoc(JT), GA); 2943 } 2944 2945 unsigned MOHiFlag, MOLoFlag; 2946 bool IsPIC = isPositionIndependent(); 2947 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2948 2949 if (IsPIC && Subtarget.isSVR4ABI()) { 2950 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2951 PPCII::MO_PIC_FLAG); 2952 return getTOCEntry(DAG, SDLoc(GA), GA); 2953 } 2954 2955 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2956 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2957 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2958 } 2959 2960 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2961 SelectionDAG &DAG) const { 2962 EVT PtrVT = Op.getValueType(); 2963 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2964 const BlockAddress *BA = BASDN->getBlockAddress(); 2965 2966 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2967 if (Subtarget.isUsingPCRelativeCalls()) { 2968 SDLoc DL(BASDN); 2969 EVT Ty = getPointerTy(DAG.getDataLayout()); 2970 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2971 PPCII::MO_PCREL_FLAG); 2972 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2973 return MatAddr; 2974 } 2975 2976 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2977 // The actual BlockAddress is stored in the TOC. 2978 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2979 setUsesTOCBasePtr(DAG); 2980 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2981 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2982 } 2983 2984 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2985 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2986 return getTOCEntry( 2987 DAG, SDLoc(BASDN), 2988 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2989 2990 unsigned MOHiFlag, MOLoFlag; 2991 bool IsPIC = isPositionIndependent(); 2992 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2993 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2994 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2995 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2996 } 2997 2998 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2999 SelectionDAG &DAG) const { 3000 // FIXME: TLS addresses currently use medium model code sequences, 3001 // which is the most useful form. Eventually support for small and 3002 // large models could be added if users need it, at the cost of 3003 // additional complexity. 3004 if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS) 3005 report_fatal_error("Thread local storage is not supported with pc-relative" 3006 " addressing - please compile with -mno-pcrel"); 3007 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3008 if (DAG.getTarget().useEmulatedTLS()) 3009 return LowerToTLSEmulatedModel(GA, DAG); 3010 3011 SDLoc dl(GA); 3012 const GlobalValue *GV = GA->getGlobal(); 3013 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3014 bool is64bit = Subtarget.isPPC64(); 3015 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3016 PICLevel::Level picLevel = M->getPICLevel(); 3017 3018 const TargetMachine &TM = getTargetMachine(); 3019 TLSModel::Model Model = TM.getTLSModel(GV); 3020 3021 if (Model == TLSModel::LocalExec) { 3022 if (Subtarget.isUsingPCRelativeCalls()) { 3023 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3024 SDValue TGA = DAG.getTargetGlobalAddress( 3025 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3026 SDValue MatAddr = 3027 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3028 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3029 } 3030 3031 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3032 PPCII::MO_TPREL_HA); 3033 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3034 PPCII::MO_TPREL_LO); 3035 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3036 : DAG.getRegister(PPC::R2, MVT::i32); 3037 3038 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3039 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3040 } 3041 3042 if (Model == TLSModel::InitialExec) { 3043 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3044 SDValue TGA = DAG.getTargetGlobalAddress( 3045 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3046 SDValue TGATLS = DAG.getTargetGlobalAddress( 3047 GV, dl, PtrVT, 0, 3048 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3049 SDValue TPOffset; 3050 if (IsPCRel) { 3051 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3052 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3053 MachinePointerInfo()); 3054 } else { 3055 SDValue GOTPtr; 3056 if (is64bit) { 3057 setUsesTOCBasePtr(DAG); 3058 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3059 GOTPtr = 3060 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3061 } else { 3062 if (!TM.isPositionIndependent()) 3063 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3064 else if (picLevel == PICLevel::SmallPIC) 3065 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3066 else 3067 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3068 } 3069 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3070 } 3071 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3072 } 3073 3074 if (Model == TLSModel::GeneralDynamic) { 3075 if (Subtarget.isUsingPCRelativeCalls()) { 3076 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3077 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3078 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3079 } 3080 3081 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3082 SDValue GOTPtr; 3083 if (is64bit) { 3084 setUsesTOCBasePtr(DAG); 3085 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3086 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3087 GOTReg, TGA); 3088 } else { 3089 if (picLevel == PICLevel::SmallPIC) 3090 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3091 else 3092 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3093 } 3094 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3095 GOTPtr, TGA, TGA); 3096 } 3097 3098 if (Model == TLSModel::LocalDynamic) { 3099 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3100 SDValue GOTPtr; 3101 if (is64bit) { 3102 setUsesTOCBasePtr(DAG); 3103 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3104 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3105 GOTReg, TGA); 3106 } else { 3107 if (picLevel == PICLevel::SmallPIC) 3108 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3109 else 3110 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3111 } 3112 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3113 PtrVT, GOTPtr, TGA, TGA); 3114 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3115 PtrVT, TLSAddr, TGA); 3116 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3117 } 3118 3119 llvm_unreachable("Unknown TLS model!"); 3120 } 3121 3122 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3123 SelectionDAG &DAG) const { 3124 EVT PtrVT = Op.getValueType(); 3125 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3126 SDLoc DL(GSDN); 3127 const GlobalValue *GV = GSDN->getGlobal(); 3128 3129 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3130 // The actual address of the GlobalValue is stored in the TOC. 3131 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3132 if (Subtarget.isUsingPCRelativeCalls()) { 3133 EVT Ty = getPointerTy(DAG.getDataLayout()); 3134 if (isAccessedAsGotIndirect(Op)) { 3135 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3136 PPCII::MO_PCREL_FLAG | 3137 PPCII::MO_GOT_FLAG); 3138 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3139 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3140 MachinePointerInfo()); 3141 return Load; 3142 } else { 3143 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3144 PPCII::MO_PCREL_FLAG); 3145 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3146 } 3147 } 3148 setUsesTOCBasePtr(DAG); 3149 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3150 return getTOCEntry(DAG, DL, GA); 3151 } 3152 3153 unsigned MOHiFlag, MOLoFlag; 3154 bool IsPIC = isPositionIndependent(); 3155 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3156 3157 if (IsPIC && Subtarget.isSVR4ABI()) { 3158 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3159 GSDN->getOffset(), 3160 PPCII::MO_PIC_FLAG); 3161 return getTOCEntry(DAG, DL, GA); 3162 } 3163 3164 SDValue GAHi = 3165 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3166 SDValue GALo = 3167 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3168 3169 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3170 } 3171 3172 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3173 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3174 SDLoc dl(Op); 3175 3176 if (Op.getValueType() == MVT::v2i64) { 3177 // When the operands themselves are v2i64 values, we need to do something 3178 // special because VSX has no underlying comparison operations for these. 3179 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3180 // Equality can be handled by casting to the legal type for Altivec 3181 // comparisons, everything else needs to be expanded. 3182 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3183 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3184 DAG.getSetCC(dl, MVT::v4i32, 3185 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3186 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3187 CC)); 3188 } 3189 3190 return SDValue(); 3191 } 3192 3193 // We handle most of these in the usual way. 3194 return Op; 3195 } 3196 3197 // If we're comparing for equality to zero, expose the fact that this is 3198 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3199 // fold the new nodes. 3200 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3201 return V; 3202 3203 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3204 // Leave comparisons against 0 and -1 alone for now, since they're usually 3205 // optimized. FIXME: revisit this when we can custom lower all setcc 3206 // optimizations. 3207 if (C->isAllOnesValue() || C->isNullValue()) 3208 return SDValue(); 3209 } 3210 3211 // If we have an integer seteq/setne, turn it into a compare against zero 3212 // by xor'ing the rhs with the lhs, which is faster than setting a 3213 // condition register, reading it back out, and masking the correct bit. The 3214 // normal approach here uses sub to do this instead of xor. Using xor exposes 3215 // the result to other bit-twiddling opportunities. 3216 EVT LHSVT = Op.getOperand(0).getValueType(); 3217 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3218 EVT VT = Op.getValueType(); 3219 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3220 Op.getOperand(1)); 3221 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3222 } 3223 return SDValue(); 3224 } 3225 3226 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3227 SDNode *Node = Op.getNode(); 3228 EVT VT = Node->getValueType(0); 3229 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3230 SDValue InChain = Node->getOperand(0); 3231 SDValue VAListPtr = Node->getOperand(1); 3232 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3233 SDLoc dl(Node); 3234 3235 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3236 3237 // gpr_index 3238 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3239 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3240 InChain = GprIndex.getValue(1); 3241 3242 if (VT == MVT::i64) { 3243 // Check if GprIndex is even 3244 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3245 DAG.getConstant(1, dl, MVT::i32)); 3246 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3247 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3248 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3249 DAG.getConstant(1, dl, MVT::i32)); 3250 // Align GprIndex to be even if it isn't 3251 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3252 GprIndex); 3253 } 3254 3255 // fpr index is 1 byte after gpr 3256 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3257 DAG.getConstant(1, dl, MVT::i32)); 3258 3259 // fpr 3260 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3261 FprPtr, MachinePointerInfo(SV), MVT::i8); 3262 InChain = FprIndex.getValue(1); 3263 3264 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3265 DAG.getConstant(8, dl, MVT::i32)); 3266 3267 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3268 DAG.getConstant(4, dl, MVT::i32)); 3269 3270 // areas 3271 SDValue OverflowArea = 3272 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3273 InChain = OverflowArea.getValue(1); 3274 3275 SDValue RegSaveArea = 3276 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3277 InChain = RegSaveArea.getValue(1); 3278 3279 // select overflow_area if index > 8 3280 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3281 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3282 3283 // adjustment constant gpr_index * 4/8 3284 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3285 VT.isInteger() ? GprIndex : FprIndex, 3286 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3287 MVT::i32)); 3288 3289 // OurReg = RegSaveArea + RegConstant 3290 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3291 RegConstant); 3292 3293 // Floating types are 32 bytes into RegSaveArea 3294 if (VT.isFloatingPoint()) 3295 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3296 DAG.getConstant(32, dl, MVT::i32)); 3297 3298 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3299 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3300 VT.isInteger() ? GprIndex : FprIndex, 3301 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3302 MVT::i32)); 3303 3304 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3305 VT.isInteger() ? VAListPtr : FprPtr, 3306 MachinePointerInfo(SV), MVT::i8); 3307 3308 // determine if we should load from reg_save_area or overflow_area 3309 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3310 3311 // increase overflow_area by 4/8 if gpr/fpr > 8 3312 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3313 DAG.getConstant(VT.isInteger() ? 4 : 8, 3314 dl, MVT::i32)); 3315 3316 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3317 OverflowAreaPlusN); 3318 3319 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3320 MachinePointerInfo(), MVT::i32); 3321 3322 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3323 } 3324 3325 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3326 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3327 3328 // We have to copy the entire va_list struct: 3329 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3330 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3331 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3332 false, true, false, MachinePointerInfo(), 3333 MachinePointerInfo()); 3334 } 3335 3336 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3337 SelectionDAG &DAG) const { 3338 if (Subtarget.isAIXABI()) 3339 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3340 3341 return Op.getOperand(0); 3342 } 3343 3344 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3345 SelectionDAG &DAG) const { 3346 if (Subtarget.isAIXABI()) 3347 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3348 3349 SDValue Chain = Op.getOperand(0); 3350 SDValue Trmp = Op.getOperand(1); // trampoline 3351 SDValue FPtr = Op.getOperand(2); // nested function 3352 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3353 SDLoc dl(Op); 3354 3355 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3356 bool isPPC64 = (PtrVT == MVT::i64); 3357 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3358 3359 TargetLowering::ArgListTy Args; 3360 TargetLowering::ArgListEntry Entry; 3361 3362 Entry.Ty = IntPtrTy; 3363 Entry.Node = Trmp; Args.push_back(Entry); 3364 3365 // TrampSize == (isPPC64 ? 48 : 40); 3366 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3367 isPPC64 ? MVT::i64 : MVT::i32); 3368 Args.push_back(Entry); 3369 3370 Entry.Node = FPtr; Args.push_back(Entry); 3371 Entry.Node = Nest; Args.push_back(Entry); 3372 3373 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3374 TargetLowering::CallLoweringInfo CLI(DAG); 3375 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3376 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3377 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3378 3379 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3380 return CallResult.second; 3381 } 3382 3383 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3384 MachineFunction &MF = DAG.getMachineFunction(); 3385 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3386 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3387 3388 SDLoc dl(Op); 3389 3390 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3391 // vastart just stores the address of the VarArgsFrameIndex slot into the 3392 // memory location argument. 3393 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3394 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3395 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3396 MachinePointerInfo(SV)); 3397 } 3398 3399 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3400 // We suppose the given va_list is already allocated. 3401 // 3402 // typedef struct { 3403 // char gpr; /* index into the array of 8 GPRs 3404 // * stored in the register save area 3405 // * gpr=0 corresponds to r3, 3406 // * gpr=1 to r4, etc. 3407 // */ 3408 // char fpr; /* index into the array of 8 FPRs 3409 // * stored in the register save area 3410 // * fpr=0 corresponds to f1, 3411 // * fpr=1 to f2, etc. 3412 // */ 3413 // char *overflow_arg_area; 3414 // /* location on stack that holds 3415 // * the next overflow argument 3416 // */ 3417 // char *reg_save_area; 3418 // /* where r3:r10 and f1:f8 (if saved) 3419 // * are stored 3420 // */ 3421 // } va_list[1]; 3422 3423 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3424 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3425 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3426 PtrVT); 3427 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3428 PtrVT); 3429 3430 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3431 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3432 3433 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3434 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3435 3436 uint64_t FPROffset = 1; 3437 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3438 3439 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3440 3441 // Store first byte : number of int regs 3442 SDValue firstStore = 3443 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3444 MachinePointerInfo(SV), MVT::i8); 3445 uint64_t nextOffset = FPROffset; 3446 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3447 ConstFPROffset); 3448 3449 // Store second byte : number of float regs 3450 SDValue secondStore = 3451 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3452 MachinePointerInfo(SV, nextOffset), MVT::i8); 3453 nextOffset += StackOffset; 3454 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3455 3456 // Store second word : arguments given on stack 3457 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3458 MachinePointerInfo(SV, nextOffset)); 3459 nextOffset += FrameOffset; 3460 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3461 3462 // Store third word : arguments given in registers 3463 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3464 MachinePointerInfo(SV, nextOffset)); 3465 } 3466 3467 /// FPR - The set of FP registers that should be allocated for arguments 3468 /// on Darwin and AIX. 3469 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3470 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3471 PPC::F11, PPC::F12, PPC::F13}; 3472 3473 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3474 /// the stack. 3475 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3476 unsigned PtrByteSize) { 3477 unsigned ArgSize = ArgVT.getStoreSize(); 3478 if (Flags.isByVal()) 3479 ArgSize = Flags.getByValSize(); 3480 3481 // Round up to multiples of the pointer size, except for array members, 3482 // which are always packed. 3483 if (!Flags.isInConsecutiveRegs()) 3484 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3485 3486 return ArgSize; 3487 } 3488 3489 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3490 /// on the stack. 3491 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3492 ISD::ArgFlagsTy Flags, 3493 unsigned PtrByteSize) { 3494 Align Alignment(PtrByteSize); 3495 3496 // Altivec parameters are padded to a 16 byte boundary. 3497 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3498 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3499 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3500 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3501 Alignment = Align(16); 3502 3503 // ByVal parameters are aligned as requested. 3504 if (Flags.isByVal()) { 3505 auto BVAlign = Flags.getNonZeroByValAlign(); 3506 if (BVAlign > PtrByteSize) { 3507 if (BVAlign.value() % PtrByteSize != 0) 3508 llvm_unreachable( 3509 "ByVal alignment is not a multiple of the pointer size"); 3510 3511 Alignment = BVAlign; 3512 } 3513 } 3514 3515 // Array members are always packed to their original alignment. 3516 if (Flags.isInConsecutiveRegs()) { 3517 // If the array member was split into multiple registers, the first 3518 // needs to be aligned to the size of the full type. (Except for 3519 // ppcf128, which is only aligned as its f64 components.) 3520 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3521 Alignment = Align(OrigVT.getStoreSize()); 3522 else 3523 Alignment = Align(ArgVT.getStoreSize()); 3524 } 3525 3526 return Alignment; 3527 } 3528 3529 /// CalculateStackSlotUsed - Return whether this argument will use its 3530 /// stack slot (instead of being passed in registers). ArgOffset, 3531 /// AvailableFPRs, and AvailableVRs must hold the current argument 3532 /// position, and will be updated to account for this argument. 3533 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3534 unsigned PtrByteSize, unsigned LinkageSize, 3535 unsigned ParamAreaSize, unsigned &ArgOffset, 3536 unsigned &AvailableFPRs, 3537 unsigned &AvailableVRs) { 3538 bool UseMemory = false; 3539 3540 // Respect alignment of argument on the stack. 3541 Align Alignment = 3542 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3543 ArgOffset = alignTo(ArgOffset, Alignment); 3544 // If there's no space left in the argument save area, we must 3545 // use memory (this check also catches zero-sized arguments). 3546 if (ArgOffset >= LinkageSize + ParamAreaSize) 3547 UseMemory = true; 3548 3549 // Allocate argument on the stack. 3550 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3551 if (Flags.isInConsecutiveRegsLast()) 3552 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3553 // If we overran the argument save area, we must use memory 3554 // (this check catches arguments passed partially in memory) 3555 if (ArgOffset > LinkageSize + ParamAreaSize) 3556 UseMemory = true; 3557 3558 // However, if the argument is actually passed in an FPR or a VR, 3559 // we don't use memory after all. 3560 if (!Flags.isByVal()) { 3561 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3562 if (AvailableFPRs > 0) { 3563 --AvailableFPRs; 3564 return false; 3565 } 3566 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3567 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3568 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3569 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3570 if (AvailableVRs > 0) { 3571 --AvailableVRs; 3572 return false; 3573 } 3574 } 3575 3576 return UseMemory; 3577 } 3578 3579 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3580 /// ensure minimum alignment required for target. 3581 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3582 unsigned NumBytes) { 3583 return alignTo(NumBytes, Lowering->getStackAlign()); 3584 } 3585 3586 SDValue PPCTargetLowering::LowerFormalArguments( 3587 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3588 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3589 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3590 if (Subtarget.isAIXABI()) 3591 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3592 InVals); 3593 if (Subtarget.is64BitELFABI()) 3594 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3595 InVals); 3596 if (Subtarget.is32BitELFABI()) 3597 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3598 InVals); 3599 3600 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3601 InVals); 3602 } 3603 3604 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3605 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3606 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3607 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3608 3609 // 32-bit SVR4 ABI Stack Frame Layout: 3610 // +-----------------------------------+ 3611 // +--> | Back chain | 3612 // | +-----------------------------------+ 3613 // | | Floating-point register save area | 3614 // | +-----------------------------------+ 3615 // | | General register save area | 3616 // | +-----------------------------------+ 3617 // | | CR save word | 3618 // | +-----------------------------------+ 3619 // | | VRSAVE save word | 3620 // | +-----------------------------------+ 3621 // | | Alignment padding | 3622 // | +-----------------------------------+ 3623 // | | Vector register save area | 3624 // | +-----------------------------------+ 3625 // | | Local variable space | 3626 // | +-----------------------------------+ 3627 // | | Parameter list area | 3628 // | +-----------------------------------+ 3629 // | | LR save word | 3630 // | +-----------------------------------+ 3631 // SP--> +--- | Back chain | 3632 // +-----------------------------------+ 3633 // 3634 // Specifications: 3635 // System V Application Binary Interface PowerPC Processor Supplement 3636 // AltiVec Technology Programming Interface Manual 3637 3638 MachineFunction &MF = DAG.getMachineFunction(); 3639 MachineFrameInfo &MFI = MF.getFrameInfo(); 3640 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3641 3642 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3643 // Potential tail calls could cause overwriting of argument stack slots. 3644 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3645 (CallConv == CallingConv::Fast)); 3646 const Align PtrAlign(4); 3647 3648 // Assign locations to all of the incoming arguments. 3649 SmallVector<CCValAssign, 16> ArgLocs; 3650 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3651 *DAG.getContext()); 3652 3653 // Reserve space for the linkage area on the stack. 3654 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3655 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3656 if (useSoftFloat()) 3657 CCInfo.PreAnalyzeFormalArguments(Ins); 3658 3659 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3660 CCInfo.clearWasPPCF128(); 3661 3662 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3663 CCValAssign &VA = ArgLocs[i]; 3664 3665 // Arguments stored in registers. 3666 if (VA.isRegLoc()) { 3667 const TargetRegisterClass *RC; 3668 EVT ValVT = VA.getValVT(); 3669 3670 switch (ValVT.getSimpleVT().SimpleTy) { 3671 default: 3672 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3673 case MVT::i1: 3674 case MVT::i32: 3675 RC = &PPC::GPRCRegClass; 3676 break; 3677 case MVT::f32: 3678 if (Subtarget.hasP8Vector()) 3679 RC = &PPC::VSSRCRegClass; 3680 else if (Subtarget.hasSPE()) 3681 RC = &PPC::GPRCRegClass; 3682 else 3683 RC = &PPC::F4RCRegClass; 3684 break; 3685 case MVT::f64: 3686 if (Subtarget.hasVSX()) 3687 RC = &PPC::VSFRCRegClass; 3688 else if (Subtarget.hasSPE()) 3689 // SPE passes doubles in GPR pairs. 3690 RC = &PPC::GPRCRegClass; 3691 else 3692 RC = &PPC::F8RCRegClass; 3693 break; 3694 case MVT::v16i8: 3695 case MVT::v8i16: 3696 case MVT::v4i32: 3697 RC = &PPC::VRRCRegClass; 3698 break; 3699 case MVT::v4f32: 3700 RC = &PPC::VRRCRegClass; 3701 break; 3702 case MVT::v2f64: 3703 case MVT::v2i64: 3704 RC = &PPC::VRRCRegClass; 3705 break; 3706 } 3707 3708 SDValue ArgValue; 3709 // Transform the arguments stored in physical registers into 3710 // virtual ones. 3711 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3712 assert(i + 1 < e && "No second half of double precision argument"); 3713 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3714 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3715 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3716 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3717 if (!Subtarget.isLittleEndian()) 3718 std::swap (ArgValueLo, ArgValueHi); 3719 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3720 ArgValueHi); 3721 } else { 3722 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3723 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3724 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3725 if (ValVT == MVT::i1) 3726 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3727 } 3728 3729 InVals.push_back(ArgValue); 3730 } else { 3731 // Argument stored in memory. 3732 assert(VA.isMemLoc()); 3733 3734 // Get the extended size of the argument type in stack 3735 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3736 // Get the actual size of the argument type 3737 unsigned ObjSize = VA.getValVT().getStoreSize(); 3738 unsigned ArgOffset = VA.getLocMemOffset(); 3739 // Stack objects in PPC32 are right justified. 3740 ArgOffset += ArgSize - ObjSize; 3741 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3742 3743 // Create load nodes to retrieve arguments from the stack. 3744 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3745 InVals.push_back( 3746 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3747 } 3748 } 3749 3750 // Assign locations to all of the incoming aggregate by value arguments. 3751 // Aggregates passed by value are stored in the local variable space of the 3752 // caller's stack frame, right above the parameter list area. 3753 SmallVector<CCValAssign, 16> ByValArgLocs; 3754 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3755 ByValArgLocs, *DAG.getContext()); 3756 3757 // Reserve stack space for the allocations in CCInfo. 3758 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3759 3760 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3761 3762 // Area that is at least reserved in the caller of this function. 3763 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3764 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3765 3766 // Set the size that is at least reserved in caller of this function. Tail 3767 // call optimized function's reserved stack space needs to be aligned so that 3768 // taking the difference between two stack areas will result in an aligned 3769 // stack. 3770 MinReservedArea = 3771 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3772 FuncInfo->setMinReservedArea(MinReservedArea); 3773 3774 SmallVector<SDValue, 8> MemOps; 3775 3776 // If the function takes variable number of arguments, make a frame index for 3777 // the start of the first vararg value... for expansion of llvm.va_start. 3778 if (isVarArg) { 3779 static const MCPhysReg GPArgRegs[] = { 3780 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3781 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3782 }; 3783 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3784 3785 static const MCPhysReg FPArgRegs[] = { 3786 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3787 PPC::F8 3788 }; 3789 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3790 3791 if (useSoftFloat() || hasSPE()) 3792 NumFPArgRegs = 0; 3793 3794 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3795 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3796 3797 // Make room for NumGPArgRegs and NumFPArgRegs. 3798 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3799 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3800 3801 FuncInfo->setVarArgsStackOffset( 3802 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3803 CCInfo.getNextStackOffset(), true)); 3804 3805 FuncInfo->setVarArgsFrameIndex( 3806 MFI.CreateStackObject(Depth, Align(8), false)); 3807 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3808 3809 // The fixed integer arguments of a variadic function are stored to the 3810 // VarArgsFrameIndex on the stack so that they may be loaded by 3811 // dereferencing the result of va_next. 3812 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3813 // Get an existing live-in vreg, or add a new one. 3814 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3815 if (!VReg) 3816 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3817 3818 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3819 SDValue Store = 3820 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3821 MemOps.push_back(Store); 3822 // Increment the address by four for the next argument to store 3823 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3824 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3825 } 3826 3827 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3828 // is set. 3829 // The double arguments are stored to the VarArgsFrameIndex 3830 // on the stack. 3831 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3832 // Get an existing live-in vreg, or add a new one. 3833 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3834 if (!VReg) 3835 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3836 3837 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3838 SDValue Store = 3839 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3840 MemOps.push_back(Store); 3841 // Increment the address by eight for the next argument to store 3842 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3843 PtrVT); 3844 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3845 } 3846 } 3847 3848 if (!MemOps.empty()) 3849 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3850 3851 return Chain; 3852 } 3853 3854 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3855 // value to MVT::i64 and then truncate to the correct register size. 3856 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3857 EVT ObjectVT, SelectionDAG &DAG, 3858 SDValue ArgVal, 3859 const SDLoc &dl) const { 3860 if (Flags.isSExt()) 3861 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3862 DAG.getValueType(ObjectVT)); 3863 else if (Flags.isZExt()) 3864 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3865 DAG.getValueType(ObjectVT)); 3866 3867 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3868 } 3869 3870 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3871 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3872 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3873 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3874 // TODO: add description of PPC stack frame format, or at least some docs. 3875 // 3876 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3877 bool isLittleEndian = Subtarget.isLittleEndian(); 3878 MachineFunction &MF = DAG.getMachineFunction(); 3879 MachineFrameInfo &MFI = MF.getFrameInfo(); 3880 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3881 3882 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3883 "fastcc not supported on varargs functions"); 3884 3885 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3886 // Potential tail calls could cause overwriting of argument stack slots. 3887 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3888 (CallConv == CallingConv::Fast)); 3889 unsigned PtrByteSize = 8; 3890 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3891 3892 static const MCPhysReg GPR[] = { 3893 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3894 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3895 }; 3896 static const MCPhysReg VR[] = { 3897 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3898 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3899 }; 3900 3901 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3902 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3903 const unsigned Num_VR_Regs = array_lengthof(VR); 3904 3905 // Do a first pass over the arguments to determine whether the ABI 3906 // guarantees that our caller has allocated the parameter save area 3907 // on its stack frame. In the ELFv1 ABI, this is always the case; 3908 // in the ELFv2 ABI, it is true if this is a vararg function or if 3909 // any parameter is located in a stack slot. 3910 3911 bool HasParameterArea = !isELFv2ABI || isVarArg; 3912 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3913 unsigned NumBytes = LinkageSize; 3914 unsigned AvailableFPRs = Num_FPR_Regs; 3915 unsigned AvailableVRs = Num_VR_Regs; 3916 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3917 if (Ins[i].Flags.isNest()) 3918 continue; 3919 3920 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3921 PtrByteSize, LinkageSize, ParamAreaSize, 3922 NumBytes, AvailableFPRs, AvailableVRs)) 3923 HasParameterArea = true; 3924 } 3925 3926 // Add DAG nodes to load the arguments or copy them out of registers. On 3927 // entry to a function on PPC, the arguments start after the linkage area, 3928 // although the first ones are often in registers. 3929 3930 unsigned ArgOffset = LinkageSize; 3931 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3932 SmallVector<SDValue, 8> MemOps; 3933 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3934 unsigned CurArgIdx = 0; 3935 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3936 SDValue ArgVal; 3937 bool needsLoad = false; 3938 EVT ObjectVT = Ins[ArgNo].VT; 3939 EVT OrigVT = Ins[ArgNo].ArgVT; 3940 unsigned ObjSize = ObjectVT.getStoreSize(); 3941 unsigned ArgSize = ObjSize; 3942 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3943 if (Ins[ArgNo].isOrigArg()) { 3944 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3945 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3946 } 3947 // We re-align the argument offset for each argument, except when using the 3948 // fast calling convention, when we need to make sure we do that only when 3949 // we'll actually use a stack slot. 3950 unsigned CurArgOffset; 3951 Align Alignment; 3952 auto ComputeArgOffset = [&]() { 3953 /* Respect alignment of argument on the stack. */ 3954 Alignment = 3955 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3956 ArgOffset = alignTo(ArgOffset, Alignment); 3957 CurArgOffset = ArgOffset; 3958 }; 3959 3960 if (CallConv != CallingConv::Fast) { 3961 ComputeArgOffset(); 3962 3963 /* Compute GPR index associated with argument offset. */ 3964 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3965 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3966 } 3967 3968 // FIXME the codegen can be much improved in some cases. 3969 // We do not have to keep everything in memory. 3970 if (Flags.isByVal()) { 3971 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3972 3973 if (CallConv == CallingConv::Fast) 3974 ComputeArgOffset(); 3975 3976 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3977 ObjSize = Flags.getByValSize(); 3978 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3979 // Empty aggregate parameters do not take up registers. Examples: 3980 // struct { } a; 3981 // union { } b; 3982 // int c[0]; 3983 // etc. However, we have to provide a place-holder in InVals, so 3984 // pretend we have an 8-byte item at the current address for that 3985 // purpose. 3986 if (!ObjSize) { 3987 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3988 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3989 InVals.push_back(FIN); 3990 continue; 3991 } 3992 3993 // Create a stack object covering all stack doublewords occupied 3994 // by the argument. If the argument is (fully or partially) on 3995 // the stack, or if the argument is fully in registers but the 3996 // caller has allocated the parameter save anyway, we can refer 3997 // directly to the caller's stack frame. Otherwise, create a 3998 // local copy in our own frame. 3999 int FI; 4000 if (HasParameterArea || 4001 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4002 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4003 else 4004 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4005 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4006 4007 // Handle aggregates smaller than 8 bytes. 4008 if (ObjSize < PtrByteSize) { 4009 // The value of the object is its address, which differs from the 4010 // address of the enclosing doubleword on big-endian systems. 4011 SDValue Arg = FIN; 4012 if (!isLittleEndian) { 4013 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4014 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4015 } 4016 InVals.push_back(Arg); 4017 4018 if (GPR_idx != Num_GPR_Regs) { 4019 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4020 FuncInfo->addLiveInAttr(VReg, Flags); 4021 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4022 SDValue Store; 4023 4024 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4025 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4026 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4027 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4028 MachinePointerInfo(&*FuncArg), ObjType); 4029 } else { 4030 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4031 // store the whole register as-is to the parameter save area 4032 // slot. 4033 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4034 MachinePointerInfo(&*FuncArg)); 4035 } 4036 4037 MemOps.push_back(Store); 4038 } 4039 // Whether we copied from a register or not, advance the offset 4040 // into the parameter save area by a full doubleword. 4041 ArgOffset += PtrByteSize; 4042 continue; 4043 } 4044 4045 // The value of the object is its address, which is the address of 4046 // its first stack doubleword. 4047 InVals.push_back(FIN); 4048 4049 // Store whatever pieces of the object are in registers to memory. 4050 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4051 if (GPR_idx == Num_GPR_Regs) 4052 break; 4053 4054 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4055 FuncInfo->addLiveInAttr(VReg, Flags); 4056 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4057 SDValue Addr = FIN; 4058 if (j) { 4059 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4060 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4061 } 4062 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4063 MachinePointerInfo(&*FuncArg, j)); 4064 MemOps.push_back(Store); 4065 ++GPR_idx; 4066 } 4067 ArgOffset += ArgSize; 4068 continue; 4069 } 4070 4071 switch (ObjectVT.getSimpleVT().SimpleTy) { 4072 default: llvm_unreachable("Unhandled argument type!"); 4073 case MVT::i1: 4074 case MVT::i32: 4075 case MVT::i64: 4076 if (Flags.isNest()) { 4077 // The 'nest' parameter, if any, is passed in R11. 4078 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4079 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4080 4081 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4082 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4083 4084 break; 4085 } 4086 4087 // These can be scalar arguments or elements of an integer array type 4088 // passed directly. Clang may use those instead of "byval" aggregate 4089 // types to avoid forcing arguments to memory unnecessarily. 4090 if (GPR_idx != Num_GPR_Regs) { 4091 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4092 FuncInfo->addLiveInAttr(VReg, Flags); 4093 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4094 4095 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4096 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4097 // value to MVT::i64 and then truncate to the correct register size. 4098 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4099 } else { 4100 if (CallConv == CallingConv::Fast) 4101 ComputeArgOffset(); 4102 4103 needsLoad = true; 4104 ArgSize = PtrByteSize; 4105 } 4106 if (CallConv != CallingConv::Fast || needsLoad) 4107 ArgOffset += 8; 4108 break; 4109 4110 case MVT::f32: 4111 case MVT::f64: 4112 // These can be scalar arguments or elements of a float array type 4113 // passed directly. The latter are used to implement ELFv2 homogenous 4114 // float aggregates. 4115 if (FPR_idx != Num_FPR_Regs) { 4116 unsigned VReg; 4117 4118 if (ObjectVT == MVT::f32) 4119 VReg = MF.addLiveIn(FPR[FPR_idx], 4120 Subtarget.hasP8Vector() 4121 ? &PPC::VSSRCRegClass 4122 : &PPC::F4RCRegClass); 4123 else 4124 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4125 ? &PPC::VSFRCRegClass 4126 : &PPC::F8RCRegClass); 4127 4128 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4129 ++FPR_idx; 4130 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4131 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4132 // once we support fp <-> gpr moves. 4133 4134 // This can only ever happen in the presence of f32 array types, 4135 // since otherwise we never run out of FPRs before running out 4136 // of GPRs. 4137 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4138 FuncInfo->addLiveInAttr(VReg, Flags); 4139 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4140 4141 if (ObjectVT == MVT::f32) { 4142 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4143 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4144 DAG.getConstant(32, dl, MVT::i32)); 4145 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4146 } 4147 4148 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4149 } else { 4150 if (CallConv == CallingConv::Fast) 4151 ComputeArgOffset(); 4152 4153 needsLoad = true; 4154 } 4155 4156 // When passing an array of floats, the array occupies consecutive 4157 // space in the argument area; only round up to the next doubleword 4158 // at the end of the array. Otherwise, each float takes 8 bytes. 4159 if (CallConv != CallingConv::Fast || needsLoad) { 4160 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4161 ArgOffset += ArgSize; 4162 if (Flags.isInConsecutiveRegsLast()) 4163 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4164 } 4165 break; 4166 case MVT::v4f32: 4167 case MVT::v4i32: 4168 case MVT::v8i16: 4169 case MVT::v16i8: 4170 case MVT::v2f64: 4171 case MVT::v2i64: 4172 case MVT::v1i128: 4173 case MVT::f128: 4174 // These can be scalar arguments or elements of a vector array type 4175 // passed directly. The latter are used to implement ELFv2 homogenous 4176 // vector aggregates. 4177 if (VR_idx != Num_VR_Regs) { 4178 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4179 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4180 ++VR_idx; 4181 } else { 4182 if (CallConv == CallingConv::Fast) 4183 ComputeArgOffset(); 4184 needsLoad = true; 4185 } 4186 if (CallConv != CallingConv::Fast || needsLoad) 4187 ArgOffset += 16; 4188 break; 4189 } 4190 4191 // We need to load the argument to a virtual register if we determined 4192 // above that we ran out of physical registers of the appropriate type. 4193 if (needsLoad) { 4194 if (ObjSize < ArgSize && !isLittleEndian) 4195 CurArgOffset += ArgSize - ObjSize; 4196 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4197 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4198 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4199 } 4200 4201 InVals.push_back(ArgVal); 4202 } 4203 4204 // Area that is at least reserved in the caller of this function. 4205 unsigned MinReservedArea; 4206 if (HasParameterArea) 4207 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4208 else 4209 MinReservedArea = LinkageSize; 4210 4211 // Set the size that is at least reserved in caller of this function. Tail 4212 // call optimized functions' reserved stack space needs to be aligned so that 4213 // taking the difference between two stack areas will result in an aligned 4214 // stack. 4215 MinReservedArea = 4216 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4217 FuncInfo->setMinReservedArea(MinReservedArea); 4218 4219 // If the function takes variable number of arguments, make a frame index for 4220 // the start of the first vararg value... for expansion of llvm.va_start. 4221 // On ELFv2ABI spec, it writes: 4222 // C programs that are intended to be *portable* across different compilers 4223 // and architectures must use the header file <stdarg.h> to deal with variable 4224 // argument lists. 4225 if (isVarArg && MFI.hasVAStart()) { 4226 int Depth = ArgOffset; 4227 4228 FuncInfo->setVarArgsFrameIndex( 4229 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4230 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4231 4232 // If this function is vararg, store any remaining integer argument regs 4233 // to their spots on the stack so that they may be loaded by dereferencing 4234 // the result of va_next. 4235 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4236 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4237 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4238 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4239 SDValue Store = 4240 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4241 MemOps.push_back(Store); 4242 // Increment the address by four for the next argument to store 4243 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4244 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4245 } 4246 } 4247 4248 if (!MemOps.empty()) 4249 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4250 4251 return Chain; 4252 } 4253 4254 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4255 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4256 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4257 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4258 // TODO: add description of PPC stack frame format, or at least some docs. 4259 // 4260 MachineFunction &MF = DAG.getMachineFunction(); 4261 MachineFrameInfo &MFI = MF.getFrameInfo(); 4262 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4263 4264 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4265 bool isPPC64 = PtrVT == MVT::i64; 4266 // Potential tail calls could cause overwriting of argument stack slots. 4267 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4268 (CallConv == CallingConv::Fast)); 4269 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4270 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4271 unsigned ArgOffset = LinkageSize; 4272 // Area that is at least reserved in caller of this function. 4273 unsigned MinReservedArea = ArgOffset; 4274 4275 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4276 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4277 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4278 }; 4279 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4280 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4281 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4282 }; 4283 static const MCPhysReg VR[] = { 4284 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4285 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4286 }; 4287 4288 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4289 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4290 const unsigned Num_VR_Regs = array_lengthof( VR); 4291 4292 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4293 4294 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4295 4296 // In 32-bit non-varargs functions, the stack space for vectors is after the 4297 // stack space for non-vectors. We do not use this space unless we have 4298 // too many vectors to fit in registers, something that only occurs in 4299 // constructed examples:), but we have to walk the arglist to figure 4300 // that out...for the pathological case, compute VecArgOffset as the 4301 // start of the vector parameter area. Computing VecArgOffset is the 4302 // entire point of the following loop. 4303 unsigned VecArgOffset = ArgOffset; 4304 if (!isVarArg && !isPPC64) { 4305 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4306 ++ArgNo) { 4307 EVT ObjectVT = Ins[ArgNo].VT; 4308 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4309 4310 if (Flags.isByVal()) { 4311 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4312 unsigned ObjSize = Flags.getByValSize(); 4313 unsigned ArgSize = 4314 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4315 VecArgOffset += ArgSize; 4316 continue; 4317 } 4318 4319 switch(ObjectVT.getSimpleVT().SimpleTy) { 4320 default: llvm_unreachable("Unhandled argument type!"); 4321 case MVT::i1: 4322 case MVT::i32: 4323 case MVT::f32: 4324 VecArgOffset += 4; 4325 break; 4326 case MVT::i64: // PPC64 4327 case MVT::f64: 4328 // FIXME: We are guaranteed to be !isPPC64 at this point. 4329 // Does MVT::i64 apply? 4330 VecArgOffset += 8; 4331 break; 4332 case MVT::v4f32: 4333 case MVT::v4i32: 4334 case MVT::v8i16: 4335 case MVT::v16i8: 4336 // Nothing to do, we're only looking at Nonvector args here. 4337 break; 4338 } 4339 } 4340 } 4341 // We've found where the vector parameter area in memory is. Skip the 4342 // first 12 parameters; these don't use that memory. 4343 VecArgOffset = ((VecArgOffset+15)/16)*16; 4344 VecArgOffset += 12*16; 4345 4346 // Add DAG nodes to load the arguments or copy them out of registers. On 4347 // entry to a function on PPC, the arguments start after the linkage area, 4348 // although the first ones are often in registers. 4349 4350 SmallVector<SDValue, 8> MemOps; 4351 unsigned nAltivecParamsAtEnd = 0; 4352 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4353 unsigned CurArgIdx = 0; 4354 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4355 SDValue ArgVal; 4356 bool needsLoad = false; 4357 EVT ObjectVT = Ins[ArgNo].VT; 4358 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4359 unsigned ArgSize = ObjSize; 4360 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4361 if (Ins[ArgNo].isOrigArg()) { 4362 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4363 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4364 } 4365 unsigned CurArgOffset = ArgOffset; 4366 4367 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4368 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4369 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4370 if (isVarArg || isPPC64) { 4371 MinReservedArea = ((MinReservedArea+15)/16)*16; 4372 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4373 Flags, 4374 PtrByteSize); 4375 } else nAltivecParamsAtEnd++; 4376 } else 4377 // Calculate min reserved area. 4378 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4379 Flags, 4380 PtrByteSize); 4381 4382 // FIXME the codegen can be much improved in some cases. 4383 // We do not have to keep everything in memory. 4384 if (Flags.isByVal()) { 4385 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4386 4387 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4388 ObjSize = Flags.getByValSize(); 4389 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4390 // Objects of size 1 and 2 are right justified, everything else is 4391 // left justified. This means the memory address is adjusted forwards. 4392 if (ObjSize==1 || ObjSize==2) { 4393 CurArgOffset = CurArgOffset + (4 - ObjSize); 4394 } 4395 // The value of the object is its address. 4396 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4397 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4398 InVals.push_back(FIN); 4399 if (ObjSize==1 || ObjSize==2) { 4400 if (GPR_idx != Num_GPR_Regs) { 4401 unsigned VReg; 4402 if (isPPC64) 4403 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4404 else 4405 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4406 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4407 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4408 SDValue Store = 4409 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4410 MachinePointerInfo(&*FuncArg), ObjType); 4411 MemOps.push_back(Store); 4412 ++GPR_idx; 4413 } 4414 4415 ArgOffset += PtrByteSize; 4416 4417 continue; 4418 } 4419 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4420 // Store whatever pieces of the object are in registers 4421 // to memory. ArgOffset will be the address of the beginning 4422 // of the object. 4423 if (GPR_idx != Num_GPR_Regs) { 4424 unsigned VReg; 4425 if (isPPC64) 4426 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4427 else 4428 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4429 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4430 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4431 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4432 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4433 MachinePointerInfo(&*FuncArg, j)); 4434 MemOps.push_back(Store); 4435 ++GPR_idx; 4436 ArgOffset += PtrByteSize; 4437 } else { 4438 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4439 break; 4440 } 4441 } 4442 continue; 4443 } 4444 4445 switch (ObjectVT.getSimpleVT().SimpleTy) { 4446 default: llvm_unreachable("Unhandled argument type!"); 4447 case MVT::i1: 4448 case MVT::i32: 4449 if (!isPPC64) { 4450 if (GPR_idx != Num_GPR_Regs) { 4451 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4452 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4453 4454 if (ObjectVT == MVT::i1) 4455 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4456 4457 ++GPR_idx; 4458 } else { 4459 needsLoad = true; 4460 ArgSize = PtrByteSize; 4461 } 4462 // All int arguments reserve stack space in the Darwin ABI. 4463 ArgOffset += PtrByteSize; 4464 break; 4465 } 4466 LLVM_FALLTHROUGH; 4467 case MVT::i64: // PPC64 4468 if (GPR_idx != Num_GPR_Regs) { 4469 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4470 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4471 4472 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4473 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4474 // value to MVT::i64 and then truncate to the correct register size. 4475 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4476 4477 ++GPR_idx; 4478 } else { 4479 needsLoad = true; 4480 ArgSize = PtrByteSize; 4481 } 4482 // All int arguments reserve stack space in the Darwin ABI. 4483 ArgOffset += 8; 4484 break; 4485 4486 case MVT::f32: 4487 case MVT::f64: 4488 // Every 4 bytes of argument space consumes one of the GPRs available for 4489 // argument passing. 4490 if (GPR_idx != Num_GPR_Regs) { 4491 ++GPR_idx; 4492 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4493 ++GPR_idx; 4494 } 4495 if (FPR_idx != Num_FPR_Regs) { 4496 unsigned VReg; 4497 4498 if (ObjectVT == MVT::f32) 4499 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4500 else 4501 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4502 4503 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4504 ++FPR_idx; 4505 } else { 4506 needsLoad = true; 4507 } 4508 4509 // All FP arguments reserve stack space in the Darwin ABI. 4510 ArgOffset += isPPC64 ? 8 : ObjSize; 4511 break; 4512 case MVT::v4f32: 4513 case MVT::v4i32: 4514 case MVT::v8i16: 4515 case MVT::v16i8: 4516 // Note that vector arguments in registers don't reserve stack space, 4517 // except in varargs functions. 4518 if (VR_idx != Num_VR_Regs) { 4519 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4520 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4521 if (isVarArg) { 4522 while ((ArgOffset % 16) != 0) { 4523 ArgOffset += PtrByteSize; 4524 if (GPR_idx != Num_GPR_Regs) 4525 GPR_idx++; 4526 } 4527 ArgOffset += 16; 4528 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4529 } 4530 ++VR_idx; 4531 } else { 4532 if (!isVarArg && !isPPC64) { 4533 // Vectors go after all the nonvectors. 4534 CurArgOffset = VecArgOffset; 4535 VecArgOffset += 16; 4536 } else { 4537 // Vectors are aligned. 4538 ArgOffset = ((ArgOffset+15)/16)*16; 4539 CurArgOffset = ArgOffset; 4540 ArgOffset += 16; 4541 } 4542 needsLoad = true; 4543 } 4544 break; 4545 } 4546 4547 // We need to load the argument to a virtual register if we determined above 4548 // that we ran out of physical registers of the appropriate type. 4549 if (needsLoad) { 4550 int FI = MFI.CreateFixedObject(ObjSize, 4551 CurArgOffset + (ArgSize - ObjSize), 4552 isImmutable); 4553 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4554 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4555 } 4556 4557 InVals.push_back(ArgVal); 4558 } 4559 4560 // Allow for Altivec parameters at the end, if needed. 4561 if (nAltivecParamsAtEnd) { 4562 MinReservedArea = ((MinReservedArea+15)/16)*16; 4563 MinReservedArea += 16*nAltivecParamsAtEnd; 4564 } 4565 4566 // Area that is at least reserved in the caller of this function. 4567 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4568 4569 // Set the size that is at least reserved in caller of this function. Tail 4570 // call optimized functions' reserved stack space needs to be aligned so that 4571 // taking the difference between two stack areas will result in an aligned 4572 // stack. 4573 MinReservedArea = 4574 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4575 FuncInfo->setMinReservedArea(MinReservedArea); 4576 4577 // If the function takes variable number of arguments, make a frame index for 4578 // the start of the first vararg value... for expansion of llvm.va_start. 4579 if (isVarArg) { 4580 int Depth = ArgOffset; 4581 4582 FuncInfo->setVarArgsFrameIndex( 4583 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4584 Depth, true)); 4585 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4586 4587 // If this function is vararg, store any remaining integer argument regs 4588 // to their spots on the stack so that they may be loaded by dereferencing 4589 // the result of va_next. 4590 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4591 unsigned VReg; 4592 4593 if (isPPC64) 4594 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4595 else 4596 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4597 4598 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4599 SDValue Store = 4600 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4601 MemOps.push_back(Store); 4602 // Increment the address by four for the next argument to store 4603 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4604 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4605 } 4606 } 4607 4608 if (!MemOps.empty()) 4609 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4610 4611 return Chain; 4612 } 4613 4614 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4615 /// adjusted to accommodate the arguments for the tailcall. 4616 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4617 unsigned ParamSize) { 4618 4619 if (!isTailCall) return 0; 4620 4621 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4622 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4623 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4624 // Remember only if the new adjustment is bigger. 4625 if (SPDiff < FI->getTailCallSPDelta()) 4626 FI->setTailCallSPDelta(SPDiff); 4627 4628 return SPDiff; 4629 } 4630 4631 static bool isFunctionGlobalAddress(SDValue Callee); 4632 4633 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4634 const TargetMachine &TM) { 4635 // It does not make sense to call callsShareTOCBase() with a caller that 4636 // is PC Relative since PC Relative callers do not have a TOC. 4637 #ifndef NDEBUG 4638 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4639 assert(!STICaller->isUsingPCRelativeCalls() && 4640 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4641 #endif 4642 4643 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4644 // don't have enough information to determine if the caller and callee share 4645 // the same TOC base, so we have to pessimistically assume they don't for 4646 // correctness. 4647 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4648 if (!G) 4649 return false; 4650 4651 const GlobalValue *GV = G->getGlobal(); 4652 4653 // If the callee is preemptable, then the static linker will use a plt-stub 4654 // which saves the toc to the stack, and needs a nop after the call 4655 // instruction to convert to a toc-restore. 4656 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4657 return false; 4658 4659 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4660 // We may need a TOC restore in the situation where the caller requires a 4661 // valid TOC but the callee is PC Relative and does not. 4662 const Function *F = dyn_cast<Function>(GV); 4663 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4664 4665 // If we have an Alias we can try to get the function from there. 4666 if (Alias) { 4667 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4668 F = dyn_cast<Function>(GlobalObj); 4669 } 4670 4671 // If we still have no valid function pointer we do not have enough 4672 // information to determine if the callee uses PC Relative calls so we must 4673 // assume that it does. 4674 if (!F) 4675 return false; 4676 4677 // If the callee uses PC Relative we cannot guarantee that the callee won't 4678 // clobber the TOC of the caller and so we must assume that the two 4679 // functions do not share a TOC base. 4680 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4681 if (STICallee->isUsingPCRelativeCalls()) 4682 return false; 4683 4684 // The medium and large code models are expected to provide a sufficiently 4685 // large TOC to provide all data addressing needs of a module with a 4686 // single TOC. 4687 if (CodeModel::Medium == TM.getCodeModel() || 4688 CodeModel::Large == TM.getCodeModel()) 4689 return true; 4690 4691 // Otherwise we need to ensure callee and caller are in the same section, 4692 // since the linker may allocate multiple TOCs, and we don't know which 4693 // sections will belong to the same TOC base. 4694 if (!GV->isStrongDefinitionForLinker()) 4695 return false; 4696 4697 // Any explicitly-specified sections and section prefixes must also match. 4698 // Also, if we're using -ffunction-sections, then each function is always in 4699 // a different section (the same is true for COMDAT functions). 4700 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4701 GV->getSection() != Caller->getSection()) 4702 return false; 4703 if (const auto *F = dyn_cast<Function>(GV)) { 4704 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4705 return false; 4706 } 4707 4708 return true; 4709 } 4710 4711 static bool 4712 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4713 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4714 assert(Subtarget.is64BitELFABI()); 4715 4716 const unsigned PtrByteSize = 8; 4717 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4718 4719 static const MCPhysReg GPR[] = { 4720 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4721 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4722 }; 4723 static const MCPhysReg VR[] = { 4724 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4725 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4726 }; 4727 4728 const unsigned NumGPRs = array_lengthof(GPR); 4729 const unsigned NumFPRs = 13; 4730 const unsigned NumVRs = array_lengthof(VR); 4731 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4732 4733 unsigned NumBytes = LinkageSize; 4734 unsigned AvailableFPRs = NumFPRs; 4735 unsigned AvailableVRs = NumVRs; 4736 4737 for (const ISD::OutputArg& Param : Outs) { 4738 if (Param.Flags.isNest()) continue; 4739 4740 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4741 LinkageSize, ParamAreaSize, NumBytes, 4742 AvailableFPRs, AvailableVRs)) 4743 return true; 4744 } 4745 return false; 4746 } 4747 4748 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4749 if (CB.arg_size() != CallerFn->arg_size()) 4750 return false; 4751 4752 auto CalleeArgIter = CB.arg_begin(); 4753 auto CalleeArgEnd = CB.arg_end(); 4754 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4755 4756 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4757 const Value* CalleeArg = *CalleeArgIter; 4758 const Value* CallerArg = &(*CallerArgIter); 4759 if (CalleeArg == CallerArg) 4760 continue; 4761 4762 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4763 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4764 // } 4765 // 1st argument of callee is undef and has the same type as caller. 4766 if (CalleeArg->getType() == CallerArg->getType() && 4767 isa<UndefValue>(CalleeArg)) 4768 continue; 4769 4770 return false; 4771 } 4772 4773 return true; 4774 } 4775 4776 // Returns true if TCO is possible between the callers and callees 4777 // calling conventions. 4778 static bool 4779 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4780 CallingConv::ID CalleeCC) { 4781 // Tail calls are possible with fastcc and ccc. 4782 auto isTailCallableCC = [] (CallingConv::ID CC){ 4783 return CC == CallingConv::C || CC == CallingConv::Fast; 4784 }; 4785 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4786 return false; 4787 4788 // We can safely tail call both fastcc and ccc callees from a c calling 4789 // convention caller. If the caller is fastcc, we may have less stack space 4790 // than a non-fastcc caller with the same signature so disable tail-calls in 4791 // that case. 4792 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4793 } 4794 4795 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4796 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4797 const SmallVectorImpl<ISD::OutputArg> &Outs, 4798 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4799 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4800 4801 if (DisableSCO && !TailCallOpt) return false; 4802 4803 // Variadic argument functions are not supported. 4804 if (isVarArg) return false; 4805 4806 auto &Caller = DAG.getMachineFunction().getFunction(); 4807 // Check that the calling conventions are compatible for tco. 4808 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4809 return false; 4810 4811 // Caller contains any byval parameter is not supported. 4812 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4813 return false; 4814 4815 // Callee contains any byval parameter is not supported, too. 4816 // Note: This is a quick work around, because in some cases, e.g. 4817 // caller's stack size > callee's stack size, we are still able to apply 4818 // sibling call optimization. For example, gcc is able to do SCO for caller1 4819 // in the following example, but not for caller2. 4820 // struct test { 4821 // long int a; 4822 // char ary[56]; 4823 // } gTest; 4824 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4825 // b->a = v.a; 4826 // return 0; 4827 // } 4828 // void caller1(struct test a, struct test c, struct test *b) { 4829 // callee(gTest, b); } 4830 // void caller2(struct test *b) { callee(gTest, b); } 4831 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4832 return false; 4833 4834 // If callee and caller use different calling conventions, we cannot pass 4835 // parameters on stack since offsets for the parameter area may be different. 4836 if (Caller.getCallingConv() != CalleeCC && 4837 needStackSlotPassParameters(Subtarget, Outs)) 4838 return false; 4839 4840 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4841 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4842 // callee potentially have different TOC bases then we cannot tail call since 4843 // we need to restore the TOC pointer after the call. 4844 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4845 // We cannot guarantee this for indirect calls or calls to external functions. 4846 // When PC-Relative addressing is used, the concept of the TOC is no longer 4847 // applicable so this check is not required. 4848 // Check first for indirect calls. 4849 if (!Subtarget.isUsingPCRelativeCalls() && 4850 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4851 return false; 4852 4853 // Check if we share the TOC base. 4854 if (!Subtarget.isUsingPCRelativeCalls() && 4855 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4856 return false; 4857 4858 // TCO allows altering callee ABI, so we don't have to check further. 4859 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4860 return true; 4861 4862 if (DisableSCO) return false; 4863 4864 // If callee use the same argument list that caller is using, then we can 4865 // apply SCO on this case. If it is not, then we need to check if callee needs 4866 // stack for passing arguments. 4867 // PC Relative tail calls may not have a CallBase. 4868 // If there is no CallBase we cannot verify if we have the same argument 4869 // list so assume that we don't have the same argument list. 4870 if (CB && !hasSameArgumentList(&Caller, *CB) && 4871 needStackSlotPassParameters(Subtarget, Outs)) 4872 return false; 4873 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4874 return false; 4875 4876 return true; 4877 } 4878 4879 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4880 /// for tail call optimization. Targets which want to do tail call 4881 /// optimization should implement this function. 4882 bool 4883 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4884 CallingConv::ID CalleeCC, 4885 bool isVarArg, 4886 const SmallVectorImpl<ISD::InputArg> &Ins, 4887 SelectionDAG& DAG) const { 4888 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4889 return false; 4890 4891 // Variable argument functions are not supported. 4892 if (isVarArg) 4893 return false; 4894 4895 MachineFunction &MF = DAG.getMachineFunction(); 4896 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4897 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4898 // Functions containing by val parameters are not supported. 4899 for (unsigned i = 0; i != Ins.size(); i++) { 4900 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4901 if (Flags.isByVal()) return false; 4902 } 4903 4904 // Non-PIC/GOT tail calls are supported. 4905 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4906 return true; 4907 4908 // At the moment we can only do local tail calls (in same module, hidden 4909 // or protected) if we are generating PIC. 4910 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4911 return G->getGlobal()->hasHiddenVisibility() 4912 || G->getGlobal()->hasProtectedVisibility(); 4913 } 4914 4915 return false; 4916 } 4917 4918 /// isCallCompatibleAddress - Return the immediate to use if the specified 4919 /// 32-bit value is representable in the immediate field of a BxA instruction. 4920 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4921 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4922 if (!C) return nullptr; 4923 4924 int Addr = C->getZExtValue(); 4925 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4926 SignExtend32<26>(Addr) != Addr) 4927 return nullptr; // Top 6 bits have to be sext of immediate. 4928 4929 return DAG 4930 .getConstant( 4931 (int)C->getZExtValue() >> 2, SDLoc(Op), 4932 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4933 .getNode(); 4934 } 4935 4936 namespace { 4937 4938 struct TailCallArgumentInfo { 4939 SDValue Arg; 4940 SDValue FrameIdxOp; 4941 int FrameIdx = 0; 4942 4943 TailCallArgumentInfo() = default; 4944 }; 4945 4946 } // end anonymous namespace 4947 4948 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4949 static void StoreTailCallArgumentsToStackSlot( 4950 SelectionDAG &DAG, SDValue Chain, 4951 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4952 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4953 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4954 SDValue Arg = TailCallArgs[i].Arg; 4955 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4956 int FI = TailCallArgs[i].FrameIdx; 4957 // Store relative to framepointer. 4958 MemOpChains.push_back(DAG.getStore( 4959 Chain, dl, Arg, FIN, 4960 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4961 } 4962 } 4963 4964 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4965 /// the appropriate stack slot for the tail call optimized function call. 4966 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4967 SDValue OldRetAddr, SDValue OldFP, 4968 int SPDiff, const SDLoc &dl) { 4969 if (SPDiff) { 4970 // Calculate the new stack slot for the return address. 4971 MachineFunction &MF = DAG.getMachineFunction(); 4972 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4973 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4974 bool isPPC64 = Subtarget.isPPC64(); 4975 int SlotSize = isPPC64 ? 8 : 4; 4976 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4977 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4978 NewRetAddrLoc, true); 4979 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4980 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4981 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4982 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4983 } 4984 return Chain; 4985 } 4986 4987 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4988 /// the position of the argument. 4989 static void 4990 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4991 SDValue Arg, int SPDiff, unsigned ArgOffset, 4992 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4993 int Offset = ArgOffset + SPDiff; 4994 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4995 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4996 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4997 SDValue FIN = DAG.getFrameIndex(FI, VT); 4998 TailCallArgumentInfo Info; 4999 Info.Arg = Arg; 5000 Info.FrameIdxOp = FIN; 5001 Info.FrameIdx = FI; 5002 TailCallArguments.push_back(Info); 5003 } 5004 5005 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5006 /// stack slot. Returns the chain as result and the loaded frame pointers in 5007 /// LROpOut/FPOpout. Used when tail calling. 5008 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5009 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5010 SDValue &FPOpOut, const SDLoc &dl) const { 5011 if (SPDiff) { 5012 // Load the LR and FP stack slot for later adjusting. 5013 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5014 LROpOut = getReturnAddrFrameIndex(DAG); 5015 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5016 Chain = SDValue(LROpOut.getNode(), 1); 5017 } 5018 return Chain; 5019 } 5020 5021 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5022 /// by "Src" to address "Dst" of size "Size". Alignment information is 5023 /// specified by the specific parameter attribute. The copy will be passed as 5024 /// a byval function parameter. 5025 /// Sometimes what we are copying is the end of a larger object, the part that 5026 /// does not fit in registers. 5027 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5028 SDValue Chain, ISD::ArgFlagsTy Flags, 5029 SelectionDAG &DAG, const SDLoc &dl) { 5030 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5031 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5032 Flags.getNonZeroByValAlign(), false, false, false, 5033 MachinePointerInfo(), MachinePointerInfo()); 5034 } 5035 5036 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5037 /// tail calls. 5038 static void LowerMemOpCallTo( 5039 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5040 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5041 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5042 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5043 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5044 if (!isTailCall) { 5045 if (isVector) { 5046 SDValue StackPtr; 5047 if (isPPC64) 5048 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5049 else 5050 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5051 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5052 DAG.getConstant(ArgOffset, dl, PtrVT)); 5053 } 5054 MemOpChains.push_back( 5055 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5056 // Calculate and remember argument location. 5057 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5058 TailCallArguments); 5059 } 5060 5061 static void 5062 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5063 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5064 SDValue FPOp, 5065 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5066 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5067 // might overwrite each other in case of tail call optimization. 5068 SmallVector<SDValue, 8> MemOpChains2; 5069 // Do not flag preceding copytoreg stuff together with the following stuff. 5070 InFlag = SDValue(); 5071 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5072 MemOpChains2, dl); 5073 if (!MemOpChains2.empty()) 5074 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5075 5076 // Store the return address to the appropriate stack slot. 5077 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5078 5079 // Emit callseq_end just before tailcall node. 5080 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5081 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5082 InFlag = Chain.getValue(1); 5083 } 5084 5085 // Is this global address that of a function that can be called by name? (as 5086 // opposed to something that must hold a descriptor for an indirect call). 5087 static bool isFunctionGlobalAddress(SDValue Callee) { 5088 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5089 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5090 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5091 return false; 5092 5093 return G->getGlobal()->getValueType()->isFunctionTy(); 5094 } 5095 5096 return false; 5097 } 5098 5099 SDValue PPCTargetLowering::LowerCallResult( 5100 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5101 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5102 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5103 SmallVector<CCValAssign, 16> RVLocs; 5104 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5105 *DAG.getContext()); 5106 5107 CCRetInfo.AnalyzeCallResult( 5108 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5109 ? RetCC_PPC_Cold 5110 : RetCC_PPC); 5111 5112 // Copy all of the result registers out of their specified physreg. 5113 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5114 CCValAssign &VA = RVLocs[i]; 5115 assert(VA.isRegLoc() && "Can only return in registers!"); 5116 5117 SDValue Val; 5118 5119 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5120 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5121 InFlag); 5122 Chain = Lo.getValue(1); 5123 InFlag = Lo.getValue(2); 5124 VA = RVLocs[++i]; // skip ahead to next loc 5125 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5126 InFlag); 5127 Chain = Hi.getValue(1); 5128 InFlag = Hi.getValue(2); 5129 if (!Subtarget.isLittleEndian()) 5130 std::swap (Lo, Hi); 5131 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5132 } else { 5133 Val = DAG.getCopyFromReg(Chain, dl, 5134 VA.getLocReg(), VA.getLocVT(), InFlag); 5135 Chain = Val.getValue(1); 5136 InFlag = Val.getValue(2); 5137 } 5138 5139 switch (VA.getLocInfo()) { 5140 default: llvm_unreachable("Unknown loc info!"); 5141 case CCValAssign::Full: break; 5142 case CCValAssign::AExt: 5143 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5144 break; 5145 case CCValAssign::ZExt: 5146 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5147 DAG.getValueType(VA.getValVT())); 5148 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5149 break; 5150 case CCValAssign::SExt: 5151 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5152 DAG.getValueType(VA.getValVT())); 5153 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5154 break; 5155 } 5156 5157 InVals.push_back(Val); 5158 } 5159 5160 return Chain; 5161 } 5162 5163 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5164 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5165 // PatchPoint calls are not indirect. 5166 if (isPatchPoint) 5167 return false; 5168 5169 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5170 return false; 5171 5172 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5173 // becuase the immediate function pointer points to a descriptor instead of 5174 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5175 // pointer immediate points to the global entry point, while the BLA would 5176 // need to jump to the local entry point (see rL211174). 5177 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5178 isBLACompatibleAddress(Callee, DAG)) 5179 return false; 5180 5181 return true; 5182 } 5183 5184 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5185 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5186 return Subtarget.isAIXABI() || 5187 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5188 } 5189 5190 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5191 const Function &Caller, 5192 const SDValue &Callee, 5193 const PPCSubtarget &Subtarget, 5194 const TargetMachine &TM) { 5195 if (CFlags.IsTailCall) 5196 return PPCISD::TC_RETURN; 5197 5198 // This is a call through a function pointer. 5199 if (CFlags.IsIndirect) { 5200 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5201 // indirect calls. The save of the caller's TOC pointer to the stack will be 5202 // inserted into the DAG as part of call lowering. The restore of the TOC 5203 // pointer is modeled by using a pseudo instruction for the call opcode that 5204 // represents the 2 instruction sequence of an indirect branch and link, 5205 // immediately followed by a load of the TOC pointer from the the stack save 5206 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5207 // as it is not saved or used. 5208 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5209 : PPCISD::BCTRL; 5210 } 5211 5212 if (Subtarget.isUsingPCRelativeCalls()) { 5213 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5214 return PPCISD::CALL_NOTOC; 5215 } 5216 5217 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5218 // immediately following the call instruction if the caller and callee may 5219 // have different TOC bases. At link time if the linker determines the calls 5220 // may not share a TOC base, the call is redirected to a trampoline inserted 5221 // by the linker. The trampoline will (among other things) save the callers 5222 // TOC pointer at an ABI designated offset in the linkage area and the linker 5223 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5224 // into gpr2. 5225 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5226 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5227 : PPCISD::CALL_NOP; 5228 5229 return PPCISD::CALL; 5230 } 5231 5232 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5233 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5234 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5235 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5236 return SDValue(Dest, 0); 5237 5238 // Returns true if the callee is local, and false otherwise. 5239 auto isLocalCallee = [&]() { 5240 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5241 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5242 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5243 5244 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5245 !dyn_cast_or_null<GlobalIFunc>(GV); 5246 }; 5247 5248 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5249 // a static relocation model causes some versions of GNU LD (2.17.50, at 5250 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5251 // built with secure-PLT. 5252 bool UsePlt = 5253 Subtarget.is32BitELFABI() && !isLocalCallee() && 5254 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5255 5256 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5257 const TargetMachine &TM = Subtarget.getTargetMachine(); 5258 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5259 MCSymbolXCOFF *S = 5260 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5261 5262 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5263 return DAG.getMCSymbol(S, PtrVT); 5264 }; 5265 5266 if (isFunctionGlobalAddress(Callee)) { 5267 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5268 5269 if (Subtarget.isAIXABI()) { 5270 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5271 return getAIXFuncEntryPointSymbolSDNode(GV); 5272 } 5273 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5274 UsePlt ? PPCII::MO_PLT : 0); 5275 } 5276 5277 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5278 const char *SymName = S->getSymbol(); 5279 if (Subtarget.isAIXABI()) { 5280 // If there exists a user-declared function whose name is the same as the 5281 // ExternalSymbol's, then we pick up the user-declared version. 5282 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5283 if (const Function *F = 5284 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5285 return getAIXFuncEntryPointSymbolSDNode(F); 5286 5287 // On AIX, direct function calls reference the symbol for the function's 5288 // entry point, which is named by prepending a "." before the function's 5289 // C-linkage name. A Qualname is returned here because an external 5290 // function entry point is a csect with XTY_ER property. 5291 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5292 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5293 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5294 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5295 SectionKind::getMetadata()); 5296 return Sec->getQualNameSymbol(); 5297 }; 5298 5299 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5300 } 5301 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5302 UsePlt ? PPCII::MO_PLT : 0); 5303 } 5304 5305 // No transformation needed. 5306 assert(Callee.getNode() && "What no callee?"); 5307 return Callee; 5308 } 5309 5310 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5311 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5312 "Expected a CALLSEQ_STARTSDNode."); 5313 5314 // The last operand is the chain, except when the node has glue. If the node 5315 // has glue, then the last operand is the glue, and the chain is the second 5316 // last operand. 5317 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5318 if (LastValue.getValueType() != MVT::Glue) 5319 return LastValue; 5320 5321 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5322 } 5323 5324 // Creates the node that moves a functions address into the count register 5325 // to prepare for an indirect call instruction. 5326 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5327 SDValue &Glue, SDValue &Chain, 5328 const SDLoc &dl) { 5329 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5330 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5331 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5332 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5333 // The glue is the second value produced. 5334 Glue = Chain.getValue(1); 5335 } 5336 5337 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5338 SDValue &Glue, SDValue &Chain, 5339 SDValue CallSeqStart, 5340 const CallBase *CB, const SDLoc &dl, 5341 bool hasNest, 5342 const PPCSubtarget &Subtarget) { 5343 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5344 // entry point, but to the function descriptor (the function entry point 5345 // address is part of the function descriptor though). 5346 // The function descriptor is a three doubleword structure with the 5347 // following fields: function entry point, TOC base address and 5348 // environment pointer. 5349 // Thus for a call through a function pointer, the following actions need 5350 // to be performed: 5351 // 1. Save the TOC of the caller in the TOC save area of its stack 5352 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5353 // 2. Load the address of the function entry point from the function 5354 // descriptor. 5355 // 3. Load the TOC of the callee from the function descriptor into r2. 5356 // 4. Load the environment pointer from the function descriptor into 5357 // r11. 5358 // 5. Branch to the function entry point address. 5359 // 6. On return of the callee, the TOC of the caller needs to be 5360 // restored (this is done in FinishCall()). 5361 // 5362 // The loads are scheduled at the beginning of the call sequence, and the 5363 // register copies are flagged together to ensure that no other 5364 // operations can be scheduled in between. E.g. without flagging the 5365 // copies together, a TOC access in the caller could be scheduled between 5366 // the assignment of the callee TOC and the branch to the callee, which leads 5367 // to incorrect code. 5368 5369 // Start by loading the function address from the descriptor. 5370 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5371 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5372 ? (MachineMemOperand::MODereferenceable | 5373 MachineMemOperand::MOInvariant) 5374 : MachineMemOperand::MONone; 5375 5376 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5377 5378 // Registers used in building the DAG. 5379 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5380 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5381 5382 // Offsets of descriptor members. 5383 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5384 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5385 5386 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5387 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5388 5389 // One load for the functions entry point address. 5390 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5391 Alignment, MMOFlags); 5392 5393 // One for loading the TOC anchor for the module that contains the called 5394 // function. 5395 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5396 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5397 SDValue TOCPtr = 5398 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5399 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5400 5401 // One for loading the environment pointer. 5402 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5403 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5404 SDValue LoadEnvPtr = 5405 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5406 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5407 5408 5409 // Then copy the newly loaded TOC anchor to the TOC pointer. 5410 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5411 Chain = TOCVal.getValue(0); 5412 Glue = TOCVal.getValue(1); 5413 5414 // If the function call has an explicit 'nest' parameter, it takes the 5415 // place of the environment pointer. 5416 assert((!hasNest || !Subtarget.isAIXABI()) && 5417 "Nest parameter is not supported on AIX."); 5418 if (!hasNest) { 5419 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5420 Chain = EnvVal.getValue(0); 5421 Glue = EnvVal.getValue(1); 5422 } 5423 5424 // The rest of the indirect call sequence is the same as the non-descriptor 5425 // DAG. 5426 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5427 } 5428 5429 static void 5430 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5431 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5432 SelectionDAG &DAG, 5433 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5434 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5435 const PPCSubtarget &Subtarget) { 5436 const bool IsPPC64 = Subtarget.isPPC64(); 5437 // MVT for a general purpose register. 5438 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5439 5440 // First operand is always the chain. 5441 Ops.push_back(Chain); 5442 5443 // If it's a direct call pass the callee as the second operand. 5444 if (!CFlags.IsIndirect) 5445 Ops.push_back(Callee); 5446 else { 5447 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5448 5449 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5450 // on the stack (this would have been done in `LowerCall_64SVR4` or 5451 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5452 // represents both the indirect branch and a load that restores the TOC 5453 // pointer from the linkage area. The operand for the TOC restore is an add 5454 // of the TOC save offset to the stack pointer. This must be the second 5455 // operand: after the chain input but before any other variadic arguments. 5456 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5457 // saved or used. 5458 if (isTOCSaveRestoreRequired(Subtarget)) { 5459 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5460 5461 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5462 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5463 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5464 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5465 Ops.push_back(AddTOC); 5466 } 5467 5468 // Add the register used for the environment pointer. 5469 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5470 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5471 RegVT)); 5472 5473 5474 // Add CTR register as callee so a bctr can be emitted later. 5475 if (CFlags.IsTailCall) 5476 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5477 } 5478 5479 // If this is a tail call add stack pointer delta. 5480 if (CFlags.IsTailCall) 5481 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5482 5483 // Add argument registers to the end of the list so that they are known live 5484 // into the call. 5485 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5486 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5487 RegsToPass[i].second.getValueType())); 5488 5489 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5490 // no way to mark dependencies as implicit here. 5491 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5492 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5493 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5494 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5495 5496 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5497 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5498 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5499 5500 // Add a register mask operand representing the call-preserved registers. 5501 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5502 const uint32_t *Mask = 5503 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5504 assert(Mask && "Missing call preserved mask for calling convention"); 5505 Ops.push_back(DAG.getRegisterMask(Mask)); 5506 5507 // If the glue is valid, it is the last operand. 5508 if (Glue.getNode()) 5509 Ops.push_back(Glue); 5510 } 5511 5512 SDValue PPCTargetLowering::FinishCall( 5513 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5514 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5515 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5516 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5517 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5518 5519 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5520 Subtarget.isAIXABI()) 5521 setUsesTOCBasePtr(DAG); 5522 5523 unsigned CallOpc = 5524 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5525 Subtarget, DAG.getTarget()); 5526 5527 if (!CFlags.IsIndirect) 5528 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5529 else if (Subtarget.usesFunctionDescriptors()) 5530 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5531 dl, CFlags.HasNest, Subtarget); 5532 else 5533 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5534 5535 // Build the operand list for the call instruction. 5536 SmallVector<SDValue, 8> Ops; 5537 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5538 SPDiff, Subtarget); 5539 5540 // Emit tail call. 5541 if (CFlags.IsTailCall) { 5542 // Indirect tail call when using PC Relative calls do not have the same 5543 // constraints. 5544 assert(((Callee.getOpcode() == ISD::Register && 5545 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5546 Callee.getOpcode() == ISD::TargetExternalSymbol || 5547 Callee.getOpcode() == ISD::TargetGlobalAddress || 5548 isa<ConstantSDNode>(Callee) || 5549 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5550 "Expecting a global address, external symbol, absolute value, " 5551 "register or an indirect tail call when PC Relative calls are " 5552 "used."); 5553 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5554 assert(CallOpc == PPCISD::TC_RETURN && 5555 "Unexpected call opcode for a tail call."); 5556 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5557 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5558 } 5559 5560 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5561 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5562 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5563 Glue = Chain.getValue(1); 5564 5565 // When performing tail call optimization the callee pops its arguments off 5566 // the stack. Account for this here so these bytes can be pushed back on in 5567 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5568 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5569 getTargetMachine().Options.GuaranteedTailCallOpt) 5570 ? NumBytes 5571 : 0; 5572 5573 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5574 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5575 Glue, dl); 5576 Glue = Chain.getValue(1); 5577 5578 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5579 DAG, InVals); 5580 } 5581 5582 SDValue 5583 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5584 SmallVectorImpl<SDValue> &InVals) const { 5585 SelectionDAG &DAG = CLI.DAG; 5586 SDLoc &dl = CLI.DL; 5587 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5588 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5589 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5590 SDValue Chain = CLI.Chain; 5591 SDValue Callee = CLI.Callee; 5592 bool &isTailCall = CLI.IsTailCall; 5593 CallingConv::ID CallConv = CLI.CallConv; 5594 bool isVarArg = CLI.IsVarArg; 5595 bool isPatchPoint = CLI.IsPatchPoint; 5596 const CallBase *CB = CLI.CB; 5597 5598 if (isTailCall) { 5599 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5600 isTailCall = false; 5601 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5602 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5603 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5604 else 5605 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5606 Ins, DAG); 5607 if (isTailCall) { 5608 ++NumTailCalls; 5609 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5610 ++NumSiblingCalls; 5611 5612 // PC Relative calls no longer guarantee that the callee is a Global 5613 // Address Node. The callee could be an indirect tail call in which 5614 // case the SDValue for the callee could be a load (to load the address 5615 // of a function pointer) or it may be a register copy (to move the 5616 // address of the callee from a function parameter into a virtual 5617 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5618 assert((Subtarget.isUsingPCRelativeCalls() || 5619 isa<GlobalAddressSDNode>(Callee)) && 5620 "Callee should be an llvm::Function object."); 5621 5622 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5623 << "\nTCO callee: "); 5624 LLVM_DEBUG(Callee.dump()); 5625 } 5626 } 5627 5628 if (!isTailCall && CB && CB->isMustTailCall()) 5629 report_fatal_error("failed to perform tail call elimination on a call " 5630 "site marked musttail"); 5631 5632 // When long calls (i.e. indirect calls) are always used, calls are always 5633 // made via function pointer. If we have a function name, first translate it 5634 // into a pointer. 5635 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5636 !isTailCall) 5637 Callee = LowerGlobalAddress(Callee, DAG); 5638 5639 CallFlags CFlags( 5640 CallConv, isTailCall, isVarArg, isPatchPoint, 5641 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5642 // hasNest 5643 Subtarget.is64BitELFABI() && 5644 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5645 CLI.NoMerge); 5646 5647 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5648 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5649 InVals, CB); 5650 5651 if (Subtarget.isSVR4ABI()) 5652 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5653 InVals, CB); 5654 5655 if (Subtarget.isAIXABI()) 5656 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5657 InVals, CB); 5658 5659 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5660 InVals, CB); 5661 } 5662 5663 SDValue PPCTargetLowering::LowerCall_32SVR4( 5664 SDValue Chain, SDValue Callee, CallFlags CFlags, 5665 const SmallVectorImpl<ISD::OutputArg> &Outs, 5666 const SmallVectorImpl<SDValue> &OutVals, 5667 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5668 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5669 const CallBase *CB) const { 5670 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5671 // of the 32-bit SVR4 ABI stack frame layout. 5672 5673 const CallingConv::ID CallConv = CFlags.CallConv; 5674 const bool IsVarArg = CFlags.IsVarArg; 5675 const bool IsTailCall = CFlags.IsTailCall; 5676 5677 assert((CallConv == CallingConv::C || 5678 CallConv == CallingConv::Cold || 5679 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5680 5681 const Align PtrAlign(4); 5682 5683 MachineFunction &MF = DAG.getMachineFunction(); 5684 5685 // Mark this function as potentially containing a function that contains a 5686 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5687 // and restoring the callers stack pointer in this functions epilog. This is 5688 // done because by tail calling the called function might overwrite the value 5689 // in this function's (MF) stack pointer stack slot 0(SP). 5690 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5691 CallConv == CallingConv::Fast) 5692 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5693 5694 // Count how many bytes are to be pushed on the stack, including the linkage 5695 // area, parameter list area and the part of the local variable space which 5696 // contains copies of aggregates which are passed by value. 5697 5698 // Assign locations to all of the outgoing arguments. 5699 SmallVector<CCValAssign, 16> ArgLocs; 5700 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5701 5702 // Reserve space for the linkage area on the stack. 5703 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5704 PtrAlign); 5705 if (useSoftFloat()) 5706 CCInfo.PreAnalyzeCallOperands(Outs); 5707 5708 if (IsVarArg) { 5709 // Handle fixed and variable vector arguments differently. 5710 // Fixed vector arguments go into registers as long as registers are 5711 // available. Variable vector arguments always go into memory. 5712 unsigned NumArgs = Outs.size(); 5713 5714 for (unsigned i = 0; i != NumArgs; ++i) { 5715 MVT ArgVT = Outs[i].VT; 5716 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5717 bool Result; 5718 5719 if (Outs[i].IsFixed) { 5720 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5721 CCInfo); 5722 } else { 5723 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5724 ArgFlags, CCInfo); 5725 } 5726 5727 if (Result) { 5728 #ifndef NDEBUG 5729 errs() << "Call operand #" << i << " has unhandled type " 5730 << EVT(ArgVT).getEVTString() << "\n"; 5731 #endif 5732 llvm_unreachable(nullptr); 5733 } 5734 } 5735 } else { 5736 // All arguments are treated the same. 5737 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5738 } 5739 CCInfo.clearWasPPCF128(); 5740 5741 // Assign locations to all of the outgoing aggregate by value arguments. 5742 SmallVector<CCValAssign, 16> ByValArgLocs; 5743 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5744 5745 // Reserve stack space for the allocations in CCInfo. 5746 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5747 5748 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5749 5750 // Size of the linkage area, parameter list area and the part of the local 5751 // space variable where copies of aggregates which are passed by value are 5752 // stored. 5753 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5754 5755 // Calculate by how many bytes the stack has to be adjusted in case of tail 5756 // call optimization. 5757 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5758 5759 // Adjust the stack pointer for the new arguments... 5760 // These operations are automatically eliminated by the prolog/epilog pass 5761 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5762 SDValue CallSeqStart = Chain; 5763 5764 // Load the return address and frame pointer so it can be moved somewhere else 5765 // later. 5766 SDValue LROp, FPOp; 5767 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5768 5769 // Set up a copy of the stack pointer for use loading and storing any 5770 // arguments that may not fit in the registers available for argument 5771 // passing. 5772 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5773 5774 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5775 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5776 SmallVector<SDValue, 8> MemOpChains; 5777 5778 bool seenFloatArg = false; 5779 // Walk the register/memloc assignments, inserting copies/loads. 5780 // i - Tracks the index into the list of registers allocated for the call 5781 // RealArgIdx - Tracks the index into the list of actual function arguments 5782 // j - Tracks the index into the list of byval arguments 5783 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5784 i != e; 5785 ++i, ++RealArgIdx) { 5786 CCValAssign &VA = ArgLocs[i]; 5787 SDValue Arg = OutVals[RealArgIdx]; 5788 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5789 5790 if (Flags.isByVal()) { 5791 // Argument is an aggregate which is passed by value, thus we need to 5792 // create a copy of it in the local variable space of the current stack 5793 // frame (which is the stack frame of the caller) and pass the address of 5794 // this copy to the callee. 5795 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5796 CCValAssign &ByValVA = ByValArgLocs[j++]; 5797 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5798 5799 // Memory reserved in the local variable space of the callers stack frame. 5800 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5801 5802 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5803 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5804 StackPtr, PtrOff); 5805 5806 // Create a copy of the argument in the local area of the current 5807 // stack frame. 5808 SDValue MemcpyCall = 5809 CreateCopyOfByValArgument(Arg, PtrOff, 5810 CallSeqStart.getNode()->getOperand(0), 5811 Flags, DAG, dl); 5812 5813 // This must go outside the CALLSEQ_START..END. 5814 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5815 SDLoc(MemcpyCall)); 5816 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5817 NewCallSeqStart.getNode()); 5818 Chain = CallSeqStart = NewCallSeqStart; 5819 5820 // Pass the address of the aggregate copy on the stack either in a 5821 // physical register or in the parameter list area of the current stack 5822 // frame to the callee. 5823 Arg = PtrOff; 5824 } 5825 5826 // When useCRBits() is true, there can be i1 arguments. 5827 // It is because getRegisterType(MVT::i1) => MVT::i1, 5828 // and for other integer types getRegisterType() => MVT::i32. 5829 // Extend i1 and ensure callee will get i32. 5830 if (Arg.getValueType() == MVT::i1) 5831 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5832 dl, MVT::i32, Arg); 5833 5834 if (VA.isRegLoc()) { 5835 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5836 // Put argument in a physical register. 5837 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5838 bool IsLE = Subtarget.isLittleEndian(); 5839 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5840 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5841 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5842 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5843 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5844 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5845 SVal.getValue(0))); 5846 } else 5847 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5848 } else { 5849 // Put argument in the parameter list area of the current stack frame. 5850 assert(VA.isMemLoc()); 5851 unsigned LocMemOffset = VA.getLocMemOffset(); 5852 5853 if (!IsTailCall) { 5854 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5855 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5856 StackPtr, PtrOff); 5857 5858 MemOpChains.push_back( 5859 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5860 } else { 5861 // Calculate and remember argument location. 5862 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5863 TailCallArguments); 5864 } 5865 } 5866 } 5867 5868 if (!MemOpChains.empty()) 5869 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5870 5871 // Build a sequence of copy-to-reg nodes chained together with token chain 5872 // and flag operands which copy the outgoing args into the appropriate regs. 5873 SDValue InFlag; 5874 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5875 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5876 RegsToPass[i].second, InFlag); 5877 InFlag = Chain.getValue(1); 5878 } 5879 5880 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5881 // registers. 5882 if (IsVarArg) { 5883 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5884 SDValue Ops[] = { Chain, InFlag }; 5885 5886 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5887 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5888 5889 InFlag = Chain.getValue(1); 5890 } 5891 5892 if (IsTailCall) 5893 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5894 TailCallArguments); 5895 5896 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5897 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5898 } 5899 5900 // Copy an argument into memory, being careful to do this outside the 5901 // call sequence for the call to which the argument belongs. 5902 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5903 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5904 SelectionDAG &DAG, const SDLoc &dl) const { 5905 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5906 CallSeqStart.getNode()->getOperand(0), 5907 Flags, DAG, dl); 5908 // The MEMCPY must go outside the CALLSEQ_START..END. 5909 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5910 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5911 SDLoc(MemcpyCall)); 5912 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5913 NewCallSeqStart.getNode()); 5914 return NewCallSeqStart; 5915 } 5916 5917 SDValue PPCTargetLowering::LowerCall_64SVR4( 5918 SDValue Chain, SDValue Callee, CallFlags CFlags, 5919 const SmallVectorImpl<ISD::OutputArg> &Outs, 5920 const SmallVectorImpl<SDValue> &OutVals, 5921 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5922 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5923 const CallBase *CB) const { 5924 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5925 bool isLittleEndian = Subtarget.isLittleEndian(); 5926 unsigned NumOps = Outs.size(); 5927 bool IsSibCall = false; 5928 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5929 5930 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5931 unsigned PtrByteSize = 8; 5932 5933 MachineFunction &MF = DAG.getMachineFunction(); 5934 5935 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5936 IsSibCall = true; 5937 5938 // Mark this function as potentially containing a function that contains a 5939 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5940 // and restoring the callers stack pointer in this functions epilog. This is 5941 // done because by tail calling the called function might overwrite the value 5942 // in this function's (MF) stack pointer stack slot 0(SP). 5943 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5944 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5945 5946 assert(!(IsFastCall && CFlags.IsVarArg) && 5947 "fastcc not supported on varargs functions"); 5948 5949 // Count how many bytes are to be pushed on the stack, including the linkage 5950 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5951 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5952 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5953 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5954 unsigned NumBytes = LinkageSize; 5955 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5956 5957 static const MCPhysReg GPR[] = { 5958 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5959 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5960 }; 5961 static const MCPhysReg VR[] = { 5962 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5963 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5964 }; 5965 5966 const unsigned NumGPRs = array_lengthof(GPR); 5967 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5968 const unsigned NumVRs = array_lengthof(VR); 5969 5970 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5971 // can be passed to the callee in registers. 5972 // For the fast calling convention, there is another check below. 5973 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5974 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5975 if (!HasParameterArea) { 5976 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5977 unsigned AvailableFPRs = NumFPRs; 5978 unsigned AvailableVRs = NumVRs; 5979 unsigned NumBytesTmp = NumBytes; 5980 for (unsigned i = 0; i != NumOps; ++i) { 5981 if (Outs[i].Flags.isNest()) continue; 5982 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5983 PtrByteSize, LinkageSize, ParamAreaSize, 5984 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5985 HasParameterArea = true; 5986 } 5987 } 5988 5989 // When using the fast calling convention, we don't provide backing for 5990 // arguments that will be in registers. 5991 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5992 5993 // Avoid allocating parameter area for fastcc functions if all the arguments 5994 // can be passed in the registers. 5995 if (IsFastCall) 5996 HasParameterArea = false; 5997 5998 // Add up all the space actually used. 5999 for (unsigned i = 0; i != NumOps; ++i) { 6000 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6001 EVT ArgVT = Outs[i].VT; 6002 EVT OrigVT = Outs[i].ArgVT; 6003 6004 if (Flags.isNest()) 6005 continue; 6006 6007 if (IsFastCall) { 6008 if (Flags.isByVal()) { 6009 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6010 if (NumGPRsUsed > NumGPRs) 6011 HasParameterArea = true; 6012 } else { 6013 switch (ArgVT.getSimpleVT().SimpleTy) { 6014 default: llvm_unreachable("Unexpected ValueType for argument!"); 6015 case MVT::i1: 6016 case MVT::i32: 6017 case MVT::i64: 6018 if (++NumGPRsUsed <= NumGPRs) 6019 continue; 6020 break; 6021 case MVT::v4i32: 6022 case MVT::v8i16: 6023 case MVT::v16i8: 6024 case MVT::v2f64: 6025 case MVT::v2i64: 6026 case MVT::v1i128: 6027 case MVT::f128: 6028 if (++NumVRsUsed <= NumVRs) 6029 continue; 6030 break; 6031 case MVT::v4f32: 6032 if (++NumVRsUsed <= NumVRs) 6033 continue; 6034 break; 6035 case MVT::f32: 6036 case MVT::f64: 6037 if (++NumFPRsUsed <= NumFPRs) 6038 continue; 6039 break; 6040 } 6041 HasParameterArea = true; 6042 } 6043 } 6044 6045 /* Respect alignment of argument on the stack. */ 6046 auto Alignement = 6047 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6048 NumBytes = alignTo(NumBytes, Alignement); 6049 6050 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6051 if (Flags.isInConsecutiveRegsLast()) 6052 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6053 } 6054 6055 unsigned NumBytesActuallyUsed = NumBytes; 6056 6057 // In the old ELFv1 ABI, 6058 // the prolog code of the callee may store up to 8 GPR argument registers to 6059 // the stack, allowing va_start to index over them in memory if its varargs. 6060 // Because we cannot tell if this is needed on the caller side, we have to 6061 // conservatively assume that it is needed. As such, make sure we have at 6062 // least enough stack space for the caller to store the 8 GPRs. 6063 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6064 // really requires memory operands, e.g. a vararg function. 6065 if (HasParameterArea) 6066 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6067 else 6068 NumBytes = LinkageSize; 6069 6070 // Tail call needs the stack to be aligned. 6071 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6072 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6073 6074 int SPDiff = 0; 6075 6076 // Calculate by how many bytes the stack has to be adjusted in case of tail 6077 // call optimization. 6078 if (!IsSibCall) 6079 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6080 6081 // To protect arguments on the stack from being clobbered in a tail call, 6082 // force all the loads to happen before doing any other lowering. 6083 if (CFlags.IsTailCall) 6084 Chain = DAG.getStackArgumentTokenFactor(Chain); 6085 6086 // Adjust the stack pointer for the new arguments... 6087 // These operations are automatically eliminated by the prolog/epilog pass 6088 if (!IsSibCall) 6089 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6090 SDValue CallSeqStart = Chain; 6091 6092 // Load the return address and frame pointer so it can be move somewhere else 6093 // later. 6094 SDValue LROp, FPOp; 6095 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6096 6097 // Set up a copy of the stack pointer for use loading and storing any 6098 // arguments that may not fit in the registers available for argument 6099 // passing. 6100 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6101 6102 // Figure out which arguments are going to go in registers, and which in 6103 // memory. Also, if this is a vararg function, floating point operations 6104 // must be stored to our stack, and loaded into integer regs as well, if 6105 // any integer regs are available for argument passing. 6106 unsigned ArgOffset = LinkageSize; 6107 6108 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6109 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6110 6111 SmallVector<SDValue, 8> MemOpChains; 6112 for (unsigned i = 0; i != NumOps; ++i) { 6113 SDValue Arg = OutVals[i]; 6114 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6115 EVT ArgVT = Outs[i].VT; 6116 EVT OrigVT = Outs[i].ArgVT; 6117 6118 // PtrOff will be used to store the current argument to the stack if a 6119 // register cannot be found for it. 6120 SDValue PtrOff; 6121 6122 // We re-align the argument offset for each argument, except when using the 6123 // fast calling convention, when we need to make sure we do that only when 6124 // we'll actually use a stack slot. 6125 auto ComputePtrOff = [&]() { 6126 /* Respect alignment of argument on the stack. */ 6127 auto Alignment = 6128 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6129 ArgOffset = alignTo(ArgOffset, Alignment); 6130 6131 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6132 6133 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6134 }; 6135 6136 if (!IsFastCall) { 6137 ComputePtrOff(); 6138 6139 /* Compute GPR index associated with argument offset. */ 6140 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6141 GPR_idx = std::min(GPR_idx, NumGPRs); 6142 } 6143 6144 // Promote integers to 64-bit values. 6145 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6146 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6147 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6148 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6149 } 6150 6151 // FIXME memcpy is used way more than necessary. Correctness first. 6152 // Note: "by value" is code for passing a structure by value, not 6153 // basic types. 6154 if (Flags.isByVal()) { 6155 // Note: Size includes alignment padding, so 6156 // struct x { short a; char b; } 6157 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6158 // These are the proper values we need for right-justifying the 6159 // aggregate in a parameter register. 6160 unsigned Size = Flags.getByValSize(); 6161 6162 // An empty aggregate parameter takes up no storage and no 6163 // registers. 6164 if (Size == 0) 6165 continue; 6166 6167 if (IsFastCall) 6168 ComputePtrOff(); 6169 6170 // All aggregates smaller than 8 bytes must be passed right-justified. 6171 if (Size==1 || Size==2 || Size==4) { 6172 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6173 if (GPR_idx != NumGPRs) { 6174 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6175 MachinePointerInfo(), VT); 6176 MemOpChains.push_back(Load.getValue(1)); 6177 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6178 6179 ArgOffset += PtrByteSize; 6180 continue; 6181 } 6182 } 6183 6184 if (GPR_idx == NumGPRs && Size < 8) { 6185 SDValue AddPtr = PtrOff; 6186 if (!isLittleEndian) { 6187 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6188 PtrOff.getValueType()); 6189 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6190 } 6191 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6192 CallSeqStart, 6193 Flags, DAG, dl); 6194 ArgOffset += PtrByteSize; 6195 continue; 6196 } 6197 // Copy entire object into memory. There are cases where gcc-generated 6198 // code assumes it is there, even if it could be put entirely into 6199 // registers. (This is not what the doc says.) 6200 6201 // FIXME: The above statement is likely due to a misunderstanding of the 6202 // documents. All arguments must be copied into the parameter area BY 6203 // THE CALLEE in the event that the callee takes the address of any 6204 // formal argument. That has not yet been implemented. However, it is 6205 // reasonable to use the stack area as a staging area for the register 6206 // load. 6207 6208 // Skip this for small aggregates, as we will use the same slot for a 6209 // right-justified copy, below. 6210 if (Size >= 8) 6211 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6212 CallSeqStart, 6213 Flags, DAG, dl); 6214 6215 // When a register is available, pass a small aggregate right-justified. 6216 if (Size < 8 && GPR_idx != NumGPRs) { 6217 // The easiest way to get this right-justified in a register 6218 // is to copy the structure into the rightmost portion of a 6219 // local variable slot, then load the whole slot into the 6220 // register. 6221 // FIXME: The memcpy seems to produce pretty awful code for 6222 // small aggregates, particularly for packed ones. 6223 // FIXME: It would be preferable to use the slot in the 6224 // parameter save area instead of a new local variable. 6225 SDValue AddPtr = PtrOff; 6226 if (!isLittleEndian) { 6227 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6228 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6229 } 6230 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6231 CallSeqStart, 6232 Flags, DAG, dl); 6233 6234 // Load the slot into the register. 6235 SDValue Load = 6236 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6237 MemOpChains.push_back(Load.getValue(1)); 6238 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6239 6240 // Done with this argument. 6241 ArgOffset += PtrByteSize; 6242 continue; 6243 } 6244 6245 // For aggregates larger than PtrByteSize, copy the pieces of the 6246 // object that fit into registers from the parameter save area. 6247 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6248 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6249 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6250 if (GPR_idx != NumGPRs) { 6251 SDValue Load = 6252 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6253 MemOpChains.push_back(Load.getValue(1)); 6254 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6255 ArgOffset += PtrByteSize; 6256 } else { 6257 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6258 break; 6259 } 6260 } 6261 continue; 6262 } 6263 6264 switch (Arg.getSimpleValueType().SimpleTy) { 6265 default: llvm_unreachable("Unexpected ValueType for argument!"); 6266 case MVT::i1: 6267 case MVT::i32: 6268 case MVT::i64: 6269 if (Flags.isNest()) { 6270 // The 'nest' parameter, if any, is passed in R11. 6271 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6272 break; 6273 } 6274 6275 // These can be scalar arguments or elements of an integer array type 6276 // passed directly. Clang may use those instead of "byval" aggregate 6277 // types to avoid forcing arguments to memory unnecessarily. 6278 if (GPR_idx != NumGPRs) { 6279 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6280 } else { 6281 if (IsFastCall) 6282 ComputePtrOff(); 6283 6284 assert(HasParameterArea && 6285 "Parameter area must exist to pass an argument in memory."); 6286 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6287 true, CFlags.IsTailCall, false, MemOpChains, 6288 TailCallArguments, dl); 6289 if (IsFastCall) 6290 ArgOffset += PtrByteSize; 6291 } 6292 if (!IsFastCall) 6293 ArgOffset += PtrByteSize; 6294 break; 6295 case MVT::f32: 6296 case MVT::f64: { 6297 // These can be scalar arguments or elements of a float array type 6298 // passed directly. The latter are used to implement ELFv2 homogenous 6299 // float aggregates. 6300 6301 // Named arguments go into FPRs first, and once they overflow, the 6302 // remaining arguments go into GPRs and then the parameter save area. 6303 // Unnamed arguments for vararg functions always go to GPRs and 6304 // then the parameter save area. For now, put all arguments to vararg 6305 // routines always in both locations (FPR *and* GPR or stack slot). 6306 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6307 bool NeededLoad = false; 6308 6309 // First load the argument into the next available FPR. 6310 if (FPR_idx != NumFPRs) 6311 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6312 6313 // Next, load the argument into GPR or stack slot if needed. 6314 if (!NeedGPROrStack) 6315 ; 6316 else if (GPR_idx != NumGPRs && !IsFastCall) { 6317 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6318 // once we support fp <-> gpr moves. 6319 6320 // In the non-vararg case, this can only ever happen in the 6321 // presence of f32 array types, since otherwise we never run 6322 // out of FPRs before running out of GPRs. 6323 SDValue ArgVal; 6324 6325 // Double values are always passed in a single GPR. 6326 if (Arg.getValueType() != MVT::f32) { 6327 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6328 6329 // Non-array float values are extended and passed in a GPR. 6330 } else if (!Flags.isInConsecutiveRegs()) { 6331 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6332 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6333 6334 // If we have an array of floats, we collect every odd element 6335 // together with its predecessor into one GPR. 6336 } else if (ArgOffset % PtrByteSize != 0) { 6337 SDValue Lo, Hi; 6338 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6339 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6340 if (!isLittleEndian) 6341 std::swap(Lo, Hi); 6342 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6343 6344 // The final element, if even, goes into the first half of a GPR. 6345 } else if (Flags.isInConsecutiveRegsLast()) { 6346 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6347 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6348 if (!isLittleEndian) 6349 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6350 DAG.getConstant(32, dl, MVT::i32)); 6351 6352 // Non-final even elements are skipped; they will be handled 6353 // together the with subsequent argument on the next go-around. 6354 } else 6355 ArgVal = SDValue(); 6356 6357 if (ArgVal.getNode()) 6358 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6359 } else { 6360 if (IsFastCall) 6361 ComputePtrOff(); 6362 6363 // Single-precision floating-point values are mapped to the 6364 // second (rightmost) word of the stack doubleword. 6365 if (Arg.getValueType() == MVT::f32 && 6366 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6367 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6368 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6369 } 6370 6371 assert(HasParameterArea && 6372 "Parameter area must exist to pass an argument in memory."); 6373 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6374 true, CFlags.IsTailCall, false, MemOpChains, 6375 TailCallArguments, dl); 6376 6377 NeededLoad = true; 6378 } 6379 // When passing an array of floats, the array occupies consecutive 6380 // space in the argument area; only round up to the next doubleword 6381 // at the end of the array. Otherwise, each float takes 8 bytes. 6382 if (!IsFastCall || NeededLoad) { 6383 ArgOffset += (Arg.getValueType() == MVT::f32 && 6384 Flags.isInConsecutiveRegs()) ? 4 : 8; 6385 if (Flags.isInConsecutiveRegsLast()) 6386 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6387 } 6388 break; 6389 } 6390 case MVT::v4f32: 6391 case MVT::v4i32: 6392 case MVT::v8i16: 6393 case MVT::v16i8: 6394 case MVT::v2f64: 6395 case MVT::v2i64: 6396 case MVT::v1i128: 6397 case MVT::f128: 6398 // These can be scalar arguments or elements of a vector array type 6399 // passed directly. The latter are used to implement ELFv2 homogenous 6400 // vector aggregates. 6401 6402 // For a varargs call, named arguments go into VRs or on the stack as 6403 // usual; unnamed arguments always go to the stack or the corresponding 6404 // GPRs when within range. For now, we always put the value in both 6405 // locations (or even all three). 6406 if (CFlags.IsVarArg) { 6407 assert(HasParameterArea && 6408 "Parameter area must exist if we have a varargs call."); 6409 // We could elide this store in the case where the object fits 6410 // entirely in R registers. Maybe later. 6411 SDValue Store = 6412 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6413 MemOpChains.push_back(Store); 6414 if (VR_idx != NumVRs) { 6415 SDValue Load = 6416 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6417 MemOpChains.push_back(Load.getValue(1)); 6418 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6419 } 6420 ArgOffset += 16; 6421 for (unsigned i=0; i<16; i+=PtrByteSize) { 6422 if (GPR_idx == NumGPRs) 6423 break; 6424 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6425 DAG.getConstant(i, dl, PtrVT)); 6426 SDValue Load = 6427 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6428 MemOpChains.push_back(Load.getValue(1)); 6429 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6430 } 6431 break; 6432 } 6433 6434 // Non-varargs Altivec params go into VRs or on the stack. 6435 if (VR_idx != NumVRs) { 6436 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6437 } else { 6438 if (IsFastCall) 6439 ComputePtrOff(); 6440 6441 assert(HasParameterArea && 6442 "Parameter area must exist to pass an argument in memory."); 6443 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6444 true, CFlags.IsTailCall, true, MemOpChains, 6445 TailCallArguments, dl); 6446 if (IsFastCall) 6447 ArgOffset += 16; 6448 } 6449 6450 if (!IsFastCall) 6451 ArgOffset += 16; 6452 break; 6453 } 6454 } 6455 6456 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6457 "mismatch in size of parameter area"); 6458 (void)NumBytesActuallyUsed; 6459 6460 if (!MemOpChains.empty()) 6461 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6462 6463 // Check if this is an indirect call (MTCTR/BCTRL). 6464 // See prepareDescriptorIndirectCall and buildCallOperands for more 6465 // information about calls through function pointers in the 64-bit SVR4 ABI. 6466 if (CFlags.IsIndirect) { 6467 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6468 // caller in the TOC save area. 6469 if (isTOCSaveRestoreRequired(Subtarget)) { 6470 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6471 // Load r2 into a virtual register and store it to the TOC save area. 6472 setUsesTOCBasePtr(DAG); 6473 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6474 // TOC save area offset. 6475 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6476 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6477 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6478 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6479 MachinePointerInfo::getStack( 6480 DAG.getMachineFunction(), TOCSaveOffset)); 6481 } 6482 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6483 // This does not mean the MTCTR instruction must use R12; it's easier 6484 // to model this as an extra parameter, so do that. 6485 if (isELFv2ABI && !CFlags.IsPatchPoint) 6486 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6487 } 6488 6489 // Build a sequence of copy-to-reg nodes chained together with token chain 6490 // and flag operands which copy the outgoing args into the appropriate regs. 6491 SDValue InFlag; 6492 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6493 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6494 RegsToPass[i].second, InFlag); 6495 InFlag = Chain.getValue(1); 6496 } 6497 6498 if (CFlags.IsTailCall && !IsSibCall) 6499 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6500 TailCallArguments); 6501 6502 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6503 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6504 } 6505 6506 SDValue PPCTargetLowering::LowerCall_Darwin( 6507 SDValue Chain, SDValue Callee, CallFlags CFlags, 6508 const SmallVectorImpl<ISD::OutputArg> &Outs, 6509 const SmallVectorImpl<SDValue> &OutVals, 6510 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6511 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6512 const CallBase *CB) const { 6513 unsigned NumOps = Outs.size(); 6514 6515 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6516 bool isPPC64 = PtrVT == MVT::i64; 6517 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6518 6519 MachineFunction &MF = DAG.getMachineFunction(); 6520 6521 // Mark this function as potentially containing a function that contains a 6522 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6523 // and restoring the callers stack pointer in this functions epilog. This is 6524 // done because by tail calling the called function might overwrite the value 6525 // in this function's (MF) stack pointer stack slot 0(SP). 6526 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6527 CFlags.CallConv == CallingConv::Fast) 6528 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6529 6530 // Count how many bytes are to be pushed on the stack, including the linkage 6531 // area, and parameter passing area. We start with 24/48 bytes, which is 6532 // prereserved space for [SP][CR][LR][3 x unused]. 6533 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6534 unsigned NumBytes = LinkageSize; 6535 6536 // Add up all the space actually used. 6537 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6538 // they all go in registers, but we must reserve stack space for them for 6539 // possible use by the caller. In varargs or 64-bit calls, parameters are 6540 // assigned stack space in order, with padding so Altivec parameters are 6541 // 16-byte aligned. 6542 unsigned nAltivecParamsAtEnd = 0; 6543 for (unsigned i = 0; i != NumOps; ++i) { 6544 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6545 EVT ArgVT = Outs[i].VT; 6546 // Varargs Altivec parameters are padded to a 16 byte boundary. 6547 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6548 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6549 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6550 if (!CFlags.IsVarArg && !isPPC64) { 6551 // Non-varargs Altivec parameters go after all the non-Altivec 6552 // parameters; handle those later so we know how much padding we need. 6553 nAltivecParamsAtEnd++; 6554 continue; 6555 } 6556 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6557 NumBytes = ((NumBytes+15)/16)*16; 6558 } 6559 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6560 } 6561 6562 // Allow for Altivec parameters at the end, if needed. 6563 if (nAltivecParamsAtEnd) { 6564 NumBytes = ((NumBytes+15)/16)*16; 6565 NumBytes += 16*nAltivecParamsAtEnd; 6566 } 6567 6568 // The prolog code of the callee may store up to 8 GPR argument registers to 6569 // the stack, allowing va_start to index over them in memory if its varargs. 6570 // Because we cannot tell if this is needed on the caller side, we have to 6571 // conservatively assume that it is needed. As such, make sure we have at 6572 // least enough stack space for the caller to store the 8 GPRs. 6573 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6574 6575 // Tail call needs the stack to be aligned. 6576 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6577 CFlags.CallConv == CallingConv::Fast) 6578 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6579 6580 // Calculate by how many bytes the stack has to be adjusted in case of tail 6581 // call optimization. 6582 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6583 6584 // To protect arguments on the stack from being clobbered in a tail call, 6585 // force all the loads to happen before doing any other lowering. 6586 if (CFlags.IsTailCall) 6587 Chain = DAG.getStackArgumentTokenFactor(Chain); 6588 6589 // Adjust the stack pointer for the new arguments... 6590 // These operations are automatically eliminated by the prolog/epilog pass 6591 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6592 SDValue CallSeqStart = Chain; 6593 6594 // Load the return address and frame pointer so it can be move somewhere else 6595 // later. 6596 SDValue LROp, FPOp; 6597 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6598 6599 // Set up a copy of the stack pointer for use loading and storing any 6600 // arguments that may not fit in the registers available for argument 6601 // passing. 6602 SDValue StackPtr; 6603 if (isPPC64) 6604 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6605 else 6606 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6607 6608 // Figure out which arguments are going to go in registers, and which in 6609 // memory. Also, if this is a vararg function, floating point operations 6610 // must be stored to our stack, and loaded into integer regs as well, if 6611 // any integer regs are available for argument passing. 6612 unsigned ArgOffset = LinkageSize; 6613 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6614 6615 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6616 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6617 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6618 }; 6619 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6620 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6621 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6622 }; 6623 static const MCPhysReg VR[] = { 6624 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6625 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6626 }; 6627 const unsigned NumGPRs = array_lengthof(GPR_32); 6628 const unsigned NumFPRs = 13; 6629 const unsigned NumVRs = array_lengthof(VR); 6630 6631 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6632 6633 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6634 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6635 6636 SmallVector<SDValue, 8> MemOpChains; 6637 for (unsigned i = 0; i != NumOps; ++i) { 6638 SDValue Arg = OutVals[i]; 6639 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6640 6641 // PtrOff will be used to store the current argument to the stack if a 6642 // register cannot be found for it. 6643 SDValue PtrOff; 6644 6645 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6646 6647 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6648 6649 // On PPC64, promote integers to 64-bit values. 6650 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6651 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6652 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6653 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6654 } 6655 6656 // FIXME memcpy is used way more than necessary. Correctness first. 6657 // Note: "by value" is code for passing a structure by value, not 6658 // basic types. 6659 if (Flags.isByVal()) { 6660 unsigned Size = Flags.getByValSize(); 6661 // Very small objects are passed right-justified. Everything else is 6662 // passed left-justified. 6663 if (Size==1 || Size==2) { 6664 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6665 if (GPR_idx != NumGPRs) { 6666 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6667 MachinePointerInfo(), VT); 6668 MemOpChains.push_back(Load.getValue(1)); 6669 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6670 6671 ArgOffset += PtrByteSize; 6672 } else { 6673 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6674 PtrOff.getValueType()); 6675 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6676 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6677 CallSeqStart, 6678 Flags, DAG, dl); 6679 ArgOffset += PtrByteSize; 6680 } 6681 continue; 6682 } 6683 // Copy entire object into memory. There are cases where gcc-generated 6684 // code assumes it is there, even if it could be put entirely into 6685 // registers. (This is not what the doc says.) 6686 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6687 CallSeqStart, 6688 Flags, DAG, dl); 6689 6690 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6691 // copy the pieces of the object that fit into registers from the 6692 // parameter save area. 6693 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6694 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6695 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6696 if (GPR_idx != NumGPRs) { 6697 SDValue Load = 6698 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6699 MemOpChains.push_back(Load.getValue(1)); 6700 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6701 ArgOffset += PtrByteSize; 6702 } else { 6703 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6704 break; 6705 } 6706 } 6707 continue; 6708 } 6709 6710 switch (Arg.getSimpleValueType().SimpleTy) { 6711 default: llvm_unreachable("Unexpected ValueType for argument!"); 6712 case MVT::i1: 6713 case MVT::i32: 6714 case MVT::i64: 6715 if (GPR_idx != NumGPRs) { 6716 if (Arg.getValueType() == MVT::i1) 6717 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6718 6719 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6720 } else { 6721 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6722 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6723 TailCallArguments, dl); 6724 } 6725 ArgOffset += PtrByteSize; 6726 break; 6727 case MVT::f32: 6728 case MVT::f64: 6729 if (FPR_idx != NumFPRs) { 6730 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6731 6732 if (CFlags.IsVarArg) { 6733 SDValue Store = 6734 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6735 MemOpChains.push_back(Store); 6736 6737 // Float varargs are always shadowed in available integer registers 6738 if (GPR_idx != NumGPRs) { 6739 SDValue Load = 6740 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6741 MemOpChains.push_back(Load.getValue(1)); 6742 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6743 } 6744 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6745 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6746 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6747 SDValue Load = 6748 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6749 MemOpChains.push_back(Load.getValue(1)); 6750 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6751 } 6752 } else { 6753 // If we have any FPRs remaining, we may also have GPRs remaining. 6754 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6755 // GPRs. 6756 if (GPR_idx != NumGPRs) 6757 ++GPR_idx; 6758 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6759 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6760 ++GPR_idx; 6761 } 6762 } else 6763 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6764 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6765 TailCallArguments, dl); 6766 if (isPPC64) 6767 ArgOffset += 8; 6768 else 6769 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6770 break; 6771 case MVT::v4f32: 6772 case MVT::v4i32: 6773 case MVT::v8i16: 6774 case MVT::v16i8: 6775 if (CFlags.IsVarArg) { 6776 // These go aligned on the stack, or in the corresponding R registers 6777 // when within range. The Darwin PPC ABI doc claims they also go in 6778 // V registers; in fact gcc does this only for arguments that are 6779 // prototyped, not for those that match the ... We do it for all 6780 // arguments, seems to work. 6781 while (ArgOffset % 16 !=0) { 6782 ArgOffset += PtrByteSize; 6783 if (GPR_idx != NumGPRs) 6784 GPR_idx++; 6785 } 6786 // We could elide this store in the case where the object fits 6787 // entirely in R registers. Maybe later. 6788 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6789 DAG.getConstant(ArgOffset, dl, PtrVT)); 6790 SDValue Store = 6791 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6792 MemOpChains.push_back(Store); 6793 if (VR_idx != NumVRs) { 6794 SDValue Load = 6795 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6796 MemOpChains.push_back(Load.getValue(1)); 6797 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6798 } 6799 ArgOffset += 16; 6800 for (unsigned i=0; i<16; i+=PtrByteSize) { 6801 if (GPR_idx == NumGPRs) 6802 break; 6803 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6804 DAG.getConstant(i, dl, PtrVT)); 6805 SDValue Load = 6806 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6807 MemOpChains.push_back(Load.getValue(1)); 6808 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6809 } 6810 break; 6811 } 6812 6813 // Non-varargs Altivec params generally go in registers, but have 6814 // stack space allocated at the end. 6815 if (VR_idx != NumVRs) { 6816 // Doesn't have GPR space allocated. 6817 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6818 } else if (nAltivecParamsAtEnd==0) { 6819 // We are emitting Altivec params in order. 6820 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6821 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6822 TailCallArguments, dl); 6823 ArgOffset += 16; 6824 } 6825 break; 6826 } 6827 } 6828 // If all Altivec parameters fit in registers, as they usually do, 6829 // they get stack space following the non-Altivec parameters. We 6830 // don't track this here because nobody below needs it. 6831 // If there are more Altivec parameters than fit in registers emit 6832 // the stores here. 6833 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6834 unsigned j = 0; 6835 // Offset is aligned; skip 1st 12 params which go in V registers. 6836 ArgOffset = ((ArgOffset+15)/16)*16; 6837 ArgOffset += 12*16; 6838 for (unsigned i = 0; i != NumOps; ++i) { 6839 SDValue Arg = OutVals[i]; 6840 EVT ArgType = Outs[i].VT; 6841 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6842 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6843 if (++j > NumVRs) { 6844 SDValue PtrOff; 6845 // We are emitting Altivec params in order. 6846 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6847 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6848 TailCallArguments, dl); 6849 ArgOffset += 16; 6850 } 6851 } 6852 } 6853 } 6854 6855 if (!MemOpChains.empty()) 6856 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6857 6858 // On Darwin, R12 must contain the address of an indirect callee. This does 6859 // not mean the MTCTR instruction must use R12; it's easier to model this as 6860 // an extra parameter, so do that. 6861 if (CFlags.IsIndirect) { 6862 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6863 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6864 PPC::R12), Callee)); 6865 } 6866 6867 // Build a sequence of copy-to-reg nodes chained together with token chain 6868 // and flag operands which copy the outgoing args into the appropriate regs. 6869 SDValue InFlag; 6870 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6871 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6872 RegsToPass[i].second, InFlag); 6873 InFlag = Chain.getValue(1); 6874 } 6875 6876 if (CFlags.IsTailCall) 6877 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6878 TailCallArguments); 6879 6880 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6881 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6882 } 6883 6884 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6885 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6886 CCState &State) { 6887 6888 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6889 State.getMachineFunction().getSubtarget()); 6890 const bool IsPPC64 = Subtarget.isPPC64(); 6891 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6892 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6893 6894 assert((!ValVT.isInteger() || 6895 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6896 "Integer argument exceeds register size: should have been legalized"); 6897 6898 if (ValVT == MVT::f128) 6899 report_fatal_error("f128 is unimplemented on AIX."); 6900 6901 if (ArgFlags.isNest()) 6902 report_fatal_error("Nest arguments are unimplemented."); 6903 6904 if (ValVT.isVector() || LocVT.isVector()) 6905 report_fatal_error("Vector arguments are unimplemented on AIX."); 6906 6907 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6908 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6909 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6910 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6911 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6912 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6913 6914 if (ArgFlags.isByVal()) { 6915 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6916 report_fatal_error("Pass-by-value arguments with alignment greater than " 6917 "register width are not supported."); 6918 6919 const unsigned ByValSize = ArgFlags.getByValSize(); 6920 6921 // An empty aggregate parameter takes up no storage and no registers, 6922 // but needs a MemLoc for a stack slot for the formal arguments side. 6923 if (ByValSize == 0) { 6924 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6925 State.getNextStackOffset(), RegVT, 6926 LocInfo)); 6927 return false; 6928 } 6929 6930 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6931 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6932 for (const unsigned E = Offset + StackSize; Offset < E; 6933 Offset += PtrAlign.value()) { 6934 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6935 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6936 else { 6937 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6938 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6939 LocInfo)); 6940 break; 6941 } 6942 } 6943 return false; 6944 } 6945 6946 // Arguments always reserve parameter save area. 6947 switch (ValVT.SimpleTy) { 6948 default: 6949 report_fatal_error("Unhandled value type for argument."); 6950 case MVT::i64: 6951 // i64 arguments should have been split to i32 for PPC32. 6952 assert(IsPPC64 && "PPC32 should have split i64 values."); 6953 LLVM_FALLTHROUGH; 6954 case MVT::i1: 6955 case MVT::i32: { 6956 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6957 // AIX integer arguments are always passed in register width. 6958 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6959 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6960 : CCValAssign::LocInfo::ZExt; 6961 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6962 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6963 else 6964 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6965 6966 return false; 6967 } 6968 case MVT::f32: 6969 case MVT::f64: { 6970 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6971 const unsigned StoreSize = LocVT.getStoreSize(); 6972 // Floats are always 4-byte aligned in the PSA on AIX. 6973 // This includes f64 in 64-bit mode for ABI compatibility. 6974 const unsigned Offset = 6975 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6976 unsigned FReg = State.AllocateReg(FPR); 6977 if (FReg) 6978 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6979 6980 // Reserve and initialize GPRs or initialize the PSA as required. 6981 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6982 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6983 assert(FReg && "An FPR should be available when a GPR is reserved."); 6984 if (State.isVarArg()) { 6985 // Successfully reserved GPRs are only initialized for vararg calls. 6986 // Custom handling is required for: 6987 // f64 in PPC32 needs to be split into 2 GPRs. 6988 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6989 State.addLoc( 6990 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6991 } 6992 } else { 6993 // If there are insufficient GPRs, the PSA needs to be initialized. 6994 // Initialization occurs even if an FPR was initialized for 6995 // compatibility with the AIX XL compiler. The full memory for the 6996 // argument will be initialized even if a prior word is saved in GPR. 6997 // A custom memLoc is used when the argument also passes in FPR so 6998 // that the callee handling can skip over it easily. 6999 State.addLoc( 7000 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7001 LocInfo) 7002 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7003 break; 7004 } 7005 } 7006 7007 return false; 7008 } 7009 } 7010 return true; 7011 } 7012 7013 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7014 bool IsPPC64) { 7015 assert((IsPPC64 || SVT != MVT::i64) && 7016 "i64 should have been split for 32-bit codegen."); 7017 7018 switch (SVT) { 7019 default: 7020 report_fatal_error("Unexpected value type for formal argument"); 7021 case MVT::i1: 7022 case MVT::i32: 7023 case MVT::i64: 7024 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7025 case MVT::f32: 7026 return &PPC::F4RCRegClass; 7027 case MVT::f64: 7028 return &PPC::F8RCRegClass; 7029 } 7030 } 7031 7032 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7033 SelectionDAG &DAG, SDValue ArgValue, 7034 MVT LocVT, const SDLoc &dl) { 7035 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7036 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7037 7038 if (Flags.isSExt()) 7039 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7040 DAG.getValueType(ValVT)); 7041 else if (Flags.isZExt()) 7042 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7043 DAG.getValueType(ValVT)); 7044 7045 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7046 } 7047 7048 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7049 const unsigned LASize = FL->getLinkageSize(); 7050 7051 if (PPC::GPRCRegClass.contains(Reg)) { 7052 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7053 "Reg must be a valid argument register!"); 7054 return LASize + 4 * (Reg - PPC::R3); 7055 } 7056 7057 if (PPC::G8RCRegClass.contains(Reg)) { 7058 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7059 "Reg must be a valid argument register!"); 7060 return LASize + 8 * (Reg - PPC::X3); 7061 } 7062 7063 llvm_unreachable("Only general purpose registers expected."); 7064 } 7065 7066 // AIX ABI Stack Frame Layout: 7067 // 7068 // Low Memory +--------------------------------------------+ 7069 // SP +---> | Back chain | ---+ 7070 // | +--------------------------------------------+ | 7071 // | | Saved Condition Register | | 7072 // | +--------------------------------------------+ | 7073 // | | Saved Linkage Register | | 7074 // | +--------------------------------------------+ | Linkage Area 7075 // | | Reserved for compilers | | 7076 // | +--------------------------------------------+ | 7077 // | | Reserved for binders | | 7078 // | +--------------------------------------------+ | 7079 // | | Saved TOC pointer | ---+ 7080 // | +--------------------------------------------+ 7081 // | | Parameter save area | 7082 // | +--------------------------------------------+ 7083 // | | Alloca space | 7084 // | +--------------------------------------------+ 7085 // | | Local variable space | 7086 // | +--------------------------------------------+ 7087 // | | Float/int conversion temporary | 7088 // | +--------------------------------------------+ 7089 // | | Save area for AltiVec registers | 7090 // | +--------------------------------------------+ 7091 // | | AltiVec alignment padding | 7092 // | +--------------------------------------------+ 7093 // | | Save area for VRSAVE register | 7094 // | +--------------------------------------------+ 7095 // | | Save area for General Purpose registers | 7096 // | +--------------------------------------------+ 7097 // | | Save area for Floating Point registers | 7098 // | +--------------------------------------------+ 7099 // +---- | Back chain | 7100 // High Memory +--------------------------------------------+ 7101 // 7102 // Specifications: 7103 // AIX 7.2 Assembler Language Reference 7104 // Subroutine linkage convention 7105 7106 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7107 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7108 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7109 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7110 7111 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7112 CallConv == CallingConv::Fast) && 7113 "Unexpected calling convention!"); 7114 7115 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7116 report_fatal_error("Tail call support is unimplemented on AIX."); 7117 7118 if (useSoftFloat()) 7119 report_fatal_error("Soft float support is unimplemented on AIX."); 7120 7121 const PPCSubtarget &Subtarget = 7122 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7123 7124 const bool IsPPC64 = Subtarget.isPPC64(); 7125 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7126 7127 // Assign locations to all of the incoming arguments. 7128 SmallVector<CCValAssign, 16> ArgLocs; 7129 MachineFunction &MF = DAG.getMachineFunction(); 7130 MachineFrameInfo &MFI = MF.getFrameInfo(); 7131 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7132 7133 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7134 // Reserve space for the linkage area on the stack. 7135 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7136 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7137 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7138 7139 SmallVector<SDValue, 8> MemOps; 7140 7141 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7142 CCValAssign &VA = ArgLocs[I++]; 7143 MVT LocVT = VA.getLocVT(); 7144 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7145 7146 // For compatibility with the AIX XL compiler, the float args in the 7147 // parameter save area are initialized even if the argument is available 7148 // in register. The caller is required to initialize both the register 7149 // and memory, however, the callee can choose to expect it in either. 7150 // The memloc is dismissed here because the argument is retrieved from 7151 // the register. 7152 if (VA.isMemLoc() && VA.needsCustom()) 7153 continue; 7154 7155 if (Flags.isByVal() && VA.isMemLoc()) { 7156 const unsigned Size = 7157 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7158 PtrByteSize); 7159 const int FI = MF.getFrameInfo().CreateFixedObject( 7160 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7161 /* IsAliased */ true); 7162 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7163 InVals.push_back(FIN); 7164 7165 continue; 7166 } 7167 7168 if (Flags.isByVal()) { 7169 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7170 7171 const MCPhysReg ArgReg = VA.getLocReg(); 7172 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7173 7174 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7175 report_fatal_error("Over aligned byvals not supported yet."); 7176 7177 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7178 const int FI = MF.getFrameInfo().CreateFixedObject( 7179 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7180 /* IsAliased */ true); 7181 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7182 InVals.push_back(FIN); 7183 7184 // Add live ins for all the RegLocs for the same ByVal. 7185 const TargetRegisterClass *RegClass = 7186 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7187 7188 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7189 unsigned Offset) { 7190 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7191 // Since the callers side has left justified the aggregate in the 7192 // register, we can simply store the entire register into the stack 7193 // slot. 7194 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7195 // The store to the fixedstack object is needed becuase accessing a 7196 // field of the ByVal will use a gep and load. Ideally we will optimize 7197 // to extracting the value from the register directly, and elide the 7198 // stores when the arguments address is not taken, but that will need to 7199 // be future work. 7200 SDValue Store = DAG.getStore( 7201 CopyFrom.getValue(1), dl, CopyFrom, 7202 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7203 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7204 7205 MemOps.push_back(Store); 7206 }; 7207 7208 unsigned Offset = 0; 7209 HandleRegLoc(VA.getLocReg(), Offset); 7210 Offset += PtrByteSize; 7211 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7212 Offset += PtrByteSize) { 7213 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7214 "RegLocs should be for ByVal argument."); 7215 7216 const CCValAssign RL = ArgLocs[I++]; 7217 HandleRegLoc(RL.getLocReg(), Offset); 7218 } 7219 7220 if (Offset != StackSize) { 7221 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7222 "Expected MemLoc for remaining bytes."); 7223 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7224 // Consume the MemLoc.The InVal has already been emitted, so nothing 7225 // more needs to be done. 7226 ++I; 7227 } 7228 7229 continue; 7230 } 7231 7232 EVT ValVT = VA.getValVT(); 7233 if (VA.isRegLoc() && !VA.needsCustom()) { 7234 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7235 unsigned VReg = 7236 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7237 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7238 if (ValVT.isScalarInteger() && 7239 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7240 ArgValue = 7241 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7242 } 7243 InVals.push_back(ArgValue); 7244 continue; 7245 } 7246 if (VA.isMemLoc()) { 7247 const unsigned LocSize = LocVT.getStoreSize(); 7248 const unsigned ValSize = ValVT.getStoreSize(); 7249 assert((ValSize <= LocSize) && 7250 "Object size is larger than size of MemLoc"); 7251 int CurArgOffset = VA.getLocMemOffset(); 7252 // Objects are right-justified because AIX is big-endian. 7253 if (LocSize > ValSize) 7254 CurArgOffset += LocSize - ValSize; 7255 // Potential tail calls could cause overwriting of argument stack slots. 7256 const bool IsImmutable = 7257 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7258 (CallConv == CallingConv::Fast)); 7259 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7260 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7261 SDValue ArgValue = 7262 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7263 InVals.push_back(ArgValue); 7264 continue; 7265 } 7266 } 7267 7268 // On AIX a minimum of 8 words is saved to the parameter save area. 7269 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7270 // Area that is at least reserved in the caller of this function. 7271 unsigned CallerReservedArea = 7272 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7273 7274 // Set the size that is at least reserved in caller of this function. Tail 7275 // call optimized function's reserved stack space needs to be aligned so 7276 // that taking the difference between two stack areas will result in an 7277 // aligned stack. 7278 CallerReservedArea = 7279 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7280 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7281 FuncInfo->setMinReservedArea(CallerReservedArea); 7282 7283 if (isVarArg) { 7284 FuncInfo->setVarArgsFrameIndex( 7285 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7286 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7287 7288 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7289 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7290 7291 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7292 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7293 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7294 7295 // The fixed integer arguments of a variadic function are stored to the 7296 // VarArgsFrameIndex on the stack so that they may be loaded by 7297 // dereferencing the result of va_next. 7298 for (unsigned GPRIndex = 7299 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7300 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7301 7302 const unsigned VReg = 7303 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7304 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7305 7306 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7307 SDValue Store = 7308 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7309 MemOps.push_back(Store); 7310 // Increment the address for the next argument to store. 7311 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7312 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7313 } 7314 } 7315 7316 if (!MemOps.empty()) 7317 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7318 7319 return Chain; 7320 } 7321 7322 SDValue PPCTargetLowering::LowerCall_AIX( 7323 SDValue Chain, SDValue Callee, CallFlags CFlags, 7324 const SmallVectorImpl<ISD::OutputArg> &Outs, 7325 const SmallVectorImpl<SDValue> &OutVals, 7326 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7327 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7328 const CallBase *CB) const { 7329 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7330 // AIX ABI stack frame layout. 7331 7332 assert((CFlags.CallConv == CallingConv::C || 7333 CFlags.CallConv == CallingConv::Cold || 7334 CFlags.CallConv == CallingConv::Fast) && 7335 "Unexpected calling convention!"); 7336 7337 if (CFlags.IsPatchPoint) 7338 report_fatal_error("This call type is unimplemented on AIX."); 7339 7340 const PPCSubtarget& Subtarget = 7341 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7342 if (Subtarget.hasAltivec()) 7343 report_fatal_error("Altivec support is unimplemented on AIX."); 7344 7345 MachineFunction &MF = DAG.getMachineFunction(); 7346 SmallVector<CCValAssign, 16> ArgLocs; 7347 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7348 *DAG.getContext()); 7349 7350 // Reserve space for the linkage save area (LSA) on the stack. 7351 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7352 // [SP][CR][LR][2 x reserved][TOC]. 7353 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7354 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7355 const bool IsPPC64 = Subtarget.isPPC64(); 7356 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7357 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7358 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7359 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7360 7361 // The prolog code of the callee may store up to 8 GPR argument registers to 7362 // the stack, allowing va_start to index over them in memory if the callee 7363 // is variadic. 7364 // Because we cannot tell if this is needed on the caller side, we have to 7365 // conservatively assume that it is needed. As such, make sure we have at 7366 // least enough stack space for the caller to store the 8 GPRs. 7367 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7368 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7369 CCInfo.getNextStackOffset()); 7370 7371 // Adjust the stack pointer for the new arguments... 7372 // These operations are automatically eliminated by the prolog/epilog pass. 7373 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7374 SDValue CallSeqStart = Chain; 7375 7376 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7377 SmallVector<SDValue, 8> MemOpChains; 7378 7379 // Set up a copy of the stack pointer for loading and storing any 7380 // arguments that may not fit in the registers available for argument 7381 // passing. 7382 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7383 : DAG.getRegister(PPC::R1, MVT::i32); 7384 7385 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7386 const unsigned ValNo = ArgLocs[I].getValNo(); 7387 SDValue Arg = OutVals[ValNo]; 7388 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7389 7390 if (Flags.isByVal()) { 7391 const unsigned ByValSize = Flags.getByValSize(); 7392 7393 // Nothing to do for zero-sized ByVals on the caller side. 7394 if (!ByValSize) { 7395 ++I; 7396 continue; 7397 } 7398 7399 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7400 return DAG.getExtLoad( 7401 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7402 (LoadOffset != 0) 7403 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7404 : Arg, 7405 MachinePointerInfo(), VT); 7406 }; 7407 7408 unsigned LoadOffset = 0; 7409 7410 // Initialize registers, which are fully occupied by the by-val argument. 7411 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7412 SDValue Load = GetLoad(PtrVT, LoadOffset); 7413 MemOpChains.push_back(Load.getValue(1)); 7414 LoadOffset += PtrByteSize; 7415 const CCValAssign &ByValVA = ArgLocs[I++]; 7416 assert(ByValVA.getValNo() == ValNo && 7417 "Unexpected location for pass-by-value argument."); 7418 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7419 } 7420 7421 if (LoadOffset == ByValSize) 7422 continue; 7423 7424 // There must be one more loc to handle the remainder. 7425 assert(ArgLocs[I].getValNo() == ValNo && 7426 "Expected additional location for by-value argument."); 7427 7428 if (ArgLocs[I].isMemLoc()) { 7429 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7430 const CCValAssign &ByValVA = ArgLocs[I++]; 7431 ISD::ArgFlagsTy MemcpyFlags = Flags; 7432 // Only memcpy the bytes that don't pass in register. 7433 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7434 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7435 (LoadOffset != 0) 7436 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7437 : Arg, 7438 DAG.getObjectPtrOffset(dl, StackPtr, 7439 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7440 CallSeqStart, MemcpyFlags, DAG, dl); 7441 continue; 7442 } 7443 7444 // Initialize the final register residue. 7445 // Any residue that occupies the final by-val arg register must be 7446 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7447 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7448 // 2 and 1 byte loads. 7449 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7450 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7451 "Unexpected register residue for by-value argument."); 7452 SDValue ResidueVal; 7453 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7454 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7455 const MVT VT = 7456 N == 1 ? MVT::i8 7457 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7458 SDValue Load = GetLoad(VT, LoadOffset); 7459 MemOpChains.push_back(Load.getValue(1)); 7460 LoadOffset += N; 7461 Bytes += N; 7462 7463 // By-val arguments are passed left-justfied in register. 7464 // Every load here needs to be shifted, otherwise a full register load 7465 // should have been used. 7466 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7467 "Unexpected load emitted during handling of pass-by-value " 7468 "argument."); 7469 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7470 EVT ShiftAmountTy = 7471 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7472 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7473 SDValue ShiftedLoad = 7474 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7475 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7476 ShiftedLoad) 7477 : ShiftedLoad; 7478 } 7479 7480 const CCValAssign &ByValVA = ArgLocs[I++]; 7481 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7482 continue; 7483 } 7484 7485 CCValAssign &VA = ArgLocs[I++]; 7486 const MVT LocVT = VA.getLocVT(); 7487 const MVT ValVT = VA.getValVT(); 7488 7489 switch (VA.getLocInfo()) { 7490 default: 7491 report_fatal_error("Unexpected argument extension type."); 7492 case CCValAssign::Full: 7493 break; 7494 case CCValAssign::ZExt: 7495 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7496 break; 7497 case CCValAssign::SExt: 7498 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7499 break; 7500 } 7501 7502 if (VA.isRegLoc() && !VA.needsCustom()) { 7503 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7504 continue; 7505 } 7506 7507 if (VA.isMemLoc()) { 7508 SDValue PtrOff = 7509 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7510 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7511 MemOpChains.push_back( 7512 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7513 7514 continue; 7515 } 7516 7517 // Custom handling is used for GPR initializations for vararg float 7518 // arguments. 7519 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7520 ValVT.isFloatingPoint() && LocVT.isInteger() && 7521 "Unexpected register handling for calling convention."); 7522 7523 SDValue ArgAsInt = 7524 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7525 7526 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7527 // f32 in 32-bit GPR 7528 // f64 in 64-bit GPR 7529 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7530 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7531 // f32 in 64-bit GPR. 7532 RegsToPass.push_back(std::make_pair( 7533 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7534 else { 7535 // f64 in two 32-bit GPRs 7536 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7537 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7538 "Unexpected custom register for argument!"); 7539 CCValAssign &GPR1 = VA; 7540 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7541 DAG.getConstant(32, dl, MVT::i8)); 7542 RegsToPass.push_back(std::make_pair( 7543 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7544 7545 if (I != E) { 7546 // If only 1 GPR was available, there will only be one custom GPR and 7547 // the argument will also pass in memory. 7548 CCValAssign &PeekArg = ArgLocs[I]; 7549 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7550 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7551 CCValAssign &GPR2 = ArgLocs[I++]; 7552 RegsToPass.push_back(std::make_pair( 7553 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7554 } 7555 } 7556 } 7557 } 7558 7559 if (!MemOpChains.empty()) 7560 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7561 7562 // For indirect calls, we need to save the TOC base to the stack for 7563 // restoration after the call. 7564 if (CFlags.IsIndirect) { 7565 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7566 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7567 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7568 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7569 const unsigned TOCSaveOffset = 7570 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7571 7572 setUsesTOCBasePtr(DAG); 7573 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7574 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7575 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7576 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7577 Chain = DAG.getStore( 7578 Val.getValue(1), dl, Val, AddPtr, 7579 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7580 } 7581 7582 // Build a sequence of copy-to-reg nodes chained together with token chain 7583 // and flag operands which copy the outgoing args into the appropriate regs. 7584 SDValue InFlag; 7585 for (auto Reg : RegsToPass) { 7586 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7587 InFlag = Chain.getValue(1); 7588 } 7589 7590 const int SPDiff = 0; 7591 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7592 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7593 } 7594 7595 bool 7596 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7597 MachineFunction &MF, bool isVarArg, 7598 const SmallVectorImpl<ISD::OutputArg> &Outs, 7599 LLVMContext &Context) const { 7600 SmallVector<CCValAssign, 16> RVLocs; 7601 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7602 return CCInfo.CheckReturn( 7603 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7604 ? RetCC_PPC_Cold 7605 : RetCC_PPC); 7606 } 7607 7608 SDValue 7609 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7610 bool isVarArg, 7611 const SmallVectorImpl<ISD::OutputArg> &Outs, 7612 const SmallVectorImpl<SDValue> &OutVals, 7613 const SDLoc &dl, SelectionDAG &DAG) const { 7614 SmallVector<CCValAssign, 16> RVLocs; 7615 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7616 *DAG.getContext()); 7617 CCInfo.AnalyzeReturn(Outs, 7618 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7619 ? RetCC_PPC_Cold 7620 : RetCC_PPC); 7621 7622 SDValue Flag; 7623 SmallVector<SDValue, 4> RetOps(1, Chain); 7624 7625 // Copy the result values into the output registers. 7626 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7627 CCValAssign &VA = RVLocs[i]; 7628 assert(VA.isRegLoc() && "Can only return in registers!"); 7629 7630 SDValue Arg = OutVals[RealResIdx]; 7631 7632 switch (VA.getLocInfo()) { 7633 default: llvm_unreachable("Unknown loc info!"); 7634 case CCValAssign::Full: break; 7635 case CCValAssign::AExt: 7636 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7637 break; 7638 case CCValAssign::ZExt: 7639 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7640 break; 7641 case CCValAssign::SExt: 7642 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7643 break; 7644 } 7645 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7646 bool isLittleEndian = Subtarget.isLittleEndian(); 7647 // Legalize ret f64 -> ret 2 x i32. 7648 SDValue SVal = 7649 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7650 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7651 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7652 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7653 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7654 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7655 Flag = Chain.getValue(1); 7656 VA = RVLocs[++i]; // skip ahead to next loc 7657 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7658 } else 7659 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7660 Flag = Chain.getValue(1); 7661 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7662 } 7663 7664 RetOps[0] = Chain; // Update chain. 7665 7666 // Add the flag if we have it. 7667 if (Flag.getNode()) 7668 RetOps.push_back(Flag); 7669 7670 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7671 } 7672 7673 SDValue 7674 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7675 SelectionDAG &DAG) const { 7676 SDLoc dl(Op); 7677 7678 // Get the correct type for integers. 7679 EVT IntVT = Op.getValueType(); 7680 7681 // Get the inputs. 7682 SDValue Chain = Op.getOperand(0); 7683 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7684 // Build a DYNAREAOFFSET node. 7685 SDValue Ops[2] = {Chain, FPSIdx}; 7686 SDVTList VTs = DAG.getVTList(IntVT); 7687 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7688 } 7689 7690 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7691 SelectionDAG &DAG) const { 7692 // When we pop the dynamic allocation we need to restore the SP link. 7693 SDLoc dl(Op); 7694 7695 // Get the correct type for pointers. 7696 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7697 7698 // Construct the stack pointer operand. 7699 bool isPPC64 = Subtarget.isPPC64(); 7700 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7701 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7702 7703 // Get the operands for the STACKRESTORE. 7704 SDValue Chain = Op.getOperand(0); 7705 SDValue SaveSP = Op.getOperand(1); 7706 7707 // Load the old link SP. 7708 SDValue LoadLinkSP = 7709 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7710 7711 // Restore the stack pointer. 7712 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7713 7714 // Store the old link SP. 7715 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7716 } 7717 7718 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7719 MachineFunction &MF = DAG.getMachineFunction(); 7720 bool isPPC64 = Subtarget.isPPC64(); 7721 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7722 7723 // Get current frame pointer save index. The users of this index will be 7724 // primarily DYNALLOC instructions. 7725 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7726 int RASI = FI->getReturnAddrSaveIndex(); 7727 7728 // If the frame pointer save index hasn't been defined yet. 7729 if (!RASI) { 7730 // Find out what the fix offset of the frame pointer save area. 7731 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7732 // Allocate the frame index for frame pointer save area. 7733 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7734 // Save the result. 7735 FI->setReturnAddrSaveIndex(RASI); 7736 } 7737 return DAG.getFrameIndex(RASI, PtrVT); 7738 } 7739 7740 SDValue 7741 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7742 MachineFunction &MF = DAG.getMachineFunction(); 7743 bool isPPC64 = Subtarget.isPPC64(); 7744 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7745 7746 // Get current frame pointer save index. The users of this index will be 7747 // primarily DYNALLOC instructions. 7748 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7749 int FPSI = FI->getFramePointerSaveIndex(); 7750 7751 // If the frame pointer save index hasn't been defined yet. 7752 if (!FPSI) { 7753 // Find out what the fix offset of the frame pointer save area. 7754 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7755 // Allocate the frame index for frame pointer save area. 7756 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7757 // Save the result. 7758 FI->setFramePointerSaveIndex(FPSI); 7759 } 7760 return DAG.getFrameIndex(FPSI, PtrVT); 7761 } 7762 7763 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7764 SelectionDAG &DAG) const { 7765 MachineFunction &MF = DAG.getMachineFunction(); 7766 // Get the inputs. 7767 SDValue Chain = Op.getOperand(0); 7768 SDValue Size = Op.getOperand(1); 7769 SDLoc dl(Op); 7770 7771 // Get the correct type for pointers. 7772 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7773 // Negate the size. 7774 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7775 DAG.getConstant(0, dl, PtrVT), Size); 7776 // Construct a node for the frame pointer save index. 7777 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7778 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7779 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7780 if (hasInlineStackProbe(MF)) 7781 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7782 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7783 } 7784 7785 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7786 SelectionDAG &DAG) const { 7787 MachineFunction &MF = DAG.getMachineFunction(); 7788 7789 bool isPPC64 = Subtarget.isPPC64(); 7790 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7791 7792 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7793 return DAG.getFrameIndex(FI, PtrVT); 7794 } 7795 7796 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7797 SelectionDAG &DAG) const { 7798 SDLoc DL(Op); 7799 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7800 DAG.getVTList(MVT::i32, MVT::Other), 7801 Op.getOperand(0), Op.getOperand(1)); 7802 } 7803 7804 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7805 SelectionDAG &DAG) const { 7806 SDLoc DL(Op); 7807 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7808 Op.getOperand(0), Op.getOperand(1)); 7809 } 7810 7811 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7812 7813 assert(Op.getValueType() == MVT::i1 && 7814 "Custom lowering only for i1 loads"); 7815 7816 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7817 7818 SDLoc dl(Op); 7819 LoadSDNode *LD = cast<LoadSDNode>(Op); 7820 7821 SDValue Chain = LD->getChain(); 7822 SDValue BasePtr = LD->getBasePtr(); 7823 MachineMemOperand *MMO = LD->getMemOperand(); 7824 7825 SDValue NewLD = 7826 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7827 BasePtr, MVT::i8, MMO); 7828 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7829 7830 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7831 return DAG.getMergeValues(Ops, dl); 7832 } 7833 7834 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7835 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7836 "Custom lowering only for i1 stores"); 7837 7838 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7839 7840 SDLoc dl(Op); 7841 StoreSDNode *ST = cast<StoreSDNode>(Op); 7842 7843 SDValue Chain = ST->getChain(); 7844 SDValue BasePtr = ST->getBasePtr(); 7845 SDValue Value = ST->getValue(); 7846 MachineMemOperand *MMO = ST->getMemOperand(); 7847 7848 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7849 Value); 7850 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7851 } 7852 7853 // FIXME: Remove this once the ANDI glue bug is fixed: 7854 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7855 assert(Op.getValueType() == MVT::i1 && 7856 "Custom lowering only for i1 results"); 7857 7858 SDLoc DL(Op); 7859 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7860 } 7861 7862 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7863 SelectionDAG &DAG) const { 7864 7865 // Implements a vector truncate that fits in a vector register as a shuffle. 7866 // We want to legalize vector truncates down to where the source fits in 7867 // a vector register (and target is therefore smaller than vector register 7868 // size). At that point legalization will try to custom lower the sub-legal 7869 // result and get here - where we can contain the truncate as a single target 7870 // operation. 7871 7872 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7873 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7874 // 7875 // We will implement it for big-endian ordering as this (where x denotes 7876 // undefined): 7877 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7878 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7879 // 7880 // The same operation in little-endian ordering will be: 7881 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7882 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7883 7884 EVT TrgVT = Op.getValueType(); 7885 assert(TrgVT.isVector() && "Vector type expected."); 7886 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7887 EVT EltVT = TrgVT.getVectorElementType(); 7888 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7889 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7890 !isPowerOf2_32(EltVT.getSizeInBits())) 7891 return SDValue(); 7892 7893 SDValue N1 = Op.getOperand(0); 7894 EVT SrcVT = N1.getValueType(); 7895 unsigned SrcSize = SrcVT.getSizeInBits(); 7896 if (SrcSize > 256 || 7897 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7898 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7899 return SDValue(); 7900 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7901 return SDValue(); 7902 7903 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7904 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7905 7906 SDLoc DL(Op); 7907 SDValue Op1, Op2; 7908 if (SrcSize == 256) { 7909 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7910 EVT SplitVT = 7911 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7912 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7913 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7914 DAG.getConstant(0, DL, VecIdxTy)); 7915 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7916 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7917 } 7918 else { 7919 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7920 Op2 = DAG.getUNDEF(WideVT); 7921 } 7922 7923 // First list the elements we want to keep. 7924 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7925 SmallVector<int, 16> ShuffV; 7926 if (Subtarget.isLittleEndian()) 7927 for (unsigned i = 0; i < TrgNumElts; ++i) 7928 ShuffV.push_back(i * SizeMult); 7929 else 7930 for (unsigned i = 1; i <= TrgNumElts; ++i) 7931 ShuffV.push_back(i * SizeMult - 1); 7932 7933 // Populate the remaining elements with undefs. 7934 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7935 // ShuffV.push_back(i + WideNumElts); 7936 ShuffV.push_back(WideNumElts + 1); 7937 7938 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7939 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7940 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7941 } 7942 7943 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7944 /// possible. 7945 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7946 // Not FP, or using SPE? Not a fsel. 7947 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7948 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7949 return Op; 7950 7951 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7952 7953 EVT ResVT = Op.getValueType(); 7954 EVT CmpVT = Op.getOperand(0).getValueType(); 7955 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7956 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7957 SDLoc dl(Op); 7958 SDNodeFlags Flags = Op.getNode()->getFlags(); 7959 7960 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7961 // presence of infinities. 7962 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7963 switch (CC) { 7964 default: 7965 break; 7966 case ISD::SETOGT: 7967 case ISD::SETGT: 7968 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7969 case ISD::SETOLT: 7970 case ISD::SETLT: 7971 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7972 } 7973 } 7974 7975 // We might be able to do better than this under some circumstances, but in 7976 // general, fsel-based lowering of select is a finite-math-only optimization. 7977 // For more information, see section F.3 of the 2.06 ISA specification. 7978 // With ISA 3.0 7979 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7980 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7981 return Op; 7982 7983 // If the RHS of the comparison is a 0.0, we don't need to do the 7984 // subtraction at all. 7985 SDValue Sel1; 7986 if (isFloatingPointZero(RHS)) 7987 switch (CC) { 7988 default: break; // SETUO etc aren't handled by fsel. 7989 case ISD::SETNE: 7990 std::swap(TV, FV); 7991 LLVM_FALLTHROUGH; 7992 case ISD::SETEQ: 7993 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7994 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7995 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7996 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7997 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7998 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7999 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8000 case ISD::SETULT: 8001 case ISD::SETLT: 8002 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8003 LLVM_FALLTHROUGH; 8004 case ISD::SETOGE: 8005 case ISD::SETGE: 8006 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8007 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8008 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8009 case ISD::SETUGT: 8010 case ISD::SETGT: 8011 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8012 LLVM_FALLTHROUGH; 8013 case ISD::SETOLE: 8014 case ISD::SETLE: 8015 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8016 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8017 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8018 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8019 } 8020 8021 SDValue Cmp; 8022 switch (CC) { 8023 default: break; // SETUO etc aren't handled by fsel. 8024 case ISD::SETNE: 8025 std::swap(TV, FV); 8026 LLVM_FALLTHROUGH; 8027 case ISD::SETEQ: 8028 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8029 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8030 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8031 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8032 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8033 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8034 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8035 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8036 case ISD::SETULT: 8037 case ISD::SETLT: 8038 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8039 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8040 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8041 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8042 case ISD::SETOGE: 8043 case ISD::SETGE: 8044 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8045 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8046 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8047 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8048 case ISD::SETUGT: 8049 case ISD::SETGT: 8050 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8051 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8052 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8053 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8054 case ISD::SETOLE: 8055 case ISD::SETLE: 8056 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8057 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8058 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8059 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8060 } 8061 return Op; 8062 } 8063 8064 static unsigned getPPCStrictOpcode(unsigned Opc) { 8065 switch (Opc) { 8066 default: 8067 llvm_unreachable("No strict version of this opcode!"); 8068 case PPCISD::FCTIDZ: 8069 return PPCISD::STRICT_FCTIDZ; 8070 case PPCISD::FCTIWZ: 8071 return PPCISD::STRICT_FCTIWZ; 8072 case PPCISD::FCTIDUZ: 8073 return PPCISD::STRICT_FCTIDUZ; 8074 case PPCISD::FCTIWUZ: 8075 return PPCISD::STRICT_FCTIWUZ; 8076 case PPCISD::FCFID: 8077 return PPCISD::STRICT_FCFID; 8078 case PPCISD::FCFIDU: 8079 return PPCISD::STRICT_FCFIDU; 8080 case PPCISD::FCFIDS: 8081 return PPCISD::STRICT_FCFIDS; 8082 case PPCISD::FCFIDUS: 8083 return PPCISD::STRICT_FCFIDUS; 8084 } 8085 } 8086 8087 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8088 const PPCSubtarget &Subtarget) { 8089 SDLoc dl(Op); 8090 bool IsStrict = Op->isStrictFPOpcode(); 8091 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8092 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8093 8094 // TODO: Any other flags to propagate? 8095 SDNodeFlags Flags; 8096 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8097 8098 // For strict nodes, source is the second operand. 8099 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8100 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8101 assert(Src.getValueType().isFloatingPoint()); 8102 if (Src.getValueType() == MVT::f32) { 8103 if (IsStrict) { 8104 Src = 8105 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8106 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8107 Chain = Src.getValue(1); 8108 } else 8109 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8110 } 8111 SDValue Conv; 8112 unsigned Opc = ISD::DELETED_NODE; 8113 switch (Op.getSimpleValueType().SimpleTy) { 8114 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8115 case MVT::i32: 8116 Opc = IsSigned ? PPCISD::FCTIWZ 8117 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8118 break; 8119 case MVT::i64: 8120 assert((IsSigned || Subtarget.hasFPCVT()) && 8121 "i64 FP_TO_UINT is supported only with FPCVT"); 8122 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8123 } 8124 if (IsStrict) { 8125 Opc = getPPCStrictOpcode(Opc); 8126 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8127 {Chain, Src}, Flags); 8128 } else { 8129 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8130 } 8131 return Conv; 8132 } 8133 8134 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8135 SelectionDAG &DAG, 8136 const SDLoc &dl) const { 8137 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8138 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8139 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8140 bool IsStrict = Op->isStrictFPOpcode(); 8141 8142 // Convert the FP value to an int value through memory. 8143 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8144 (IsSigned || Subtarget.hasFPCVT()); 8145 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8146 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8147 MachinePointerInfo MPI = 8148 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8149 8150 // Emit a store to the stack slot. 8151 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8152 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8153 if (i32Stack) { 8154 MachineFunction &MF = DAG.getMachineFunction(); 8155 Alignment = Align(4); 8156 MachineMemOperand *MMO = 8157 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8158 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8159 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8160 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8161 } else 8162 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8163 8164 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8165 // add in a bias on big endian. 8166 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8167 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8168 DAG.getConstant(4, dl, FIPtr.getValueType())); 8169 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8170 } 8171 8172 RLI.Chain = Chain; 8173 RLI.Ptr = FIPtr; 8174 RLI.MPI = MPI; 8175 RLI.Alignment = Alignment; 8176 } 8177 8178 /// Custom lowers floating point to integer conversions to use 8179 /// the direct move instructions available in ISA 2.07 to avoid the 8180 /// need for load/store combinations. 8181 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8182 SelectionDAG &DAG, 8183 const SDLoc &dl) const { 8184 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8185 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8186 if (Op->isStrictFPOpcode()) 8187 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8188 else 8189 return Mov; 8190 } 8191 8192 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8193 const SDLoc &dl) const { 8194 bool IsStrict = Op->isStrictFPOpcode(); 8195 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8196 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8197 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8198 EVT SrcVT = Src.getValueType(); 8199 EVT DstVT = Op.getValueType(); 8200 8201 // FP to INT conversions are legal for f128. 8202 if (SrcVT == MVT::f128) 8203 return Op; 8204 8205 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8206 // PPC (the libcall is not available). 8207 if (SrcVT == MVT::ppcf128) { 8208 if (DstVT == MVT::i32) { 8209 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8210 // set other fast-math flags to FP operations in both strict and 8211 // non-strict cases. (FP_TO_SINT, FSUB) 8212 SDNodeFlags Flags; 8213 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8214 8215 if (IsSigned) { 8216 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8217 DAG.getIntPtrConstant(0, dl)); 8218 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8219 DAG.getIntPtrConstant(1, dl)); 8220 8221 // Add the two halves of the long double in round-to-zero mode, and use 8222 // a smaller FP_TO_SINT. 8223 if (IsStrict) { 8224 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8225 DAG.getVTList(MVT::f64, MVT::Other), 8226 {Op.getOperand(0), Lo, Hi}, Flags); 8227 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8228 DAG.getVTList(MVT::i32, MVT::Other), 8229 {Res.getValue(1), Res}, Flags); 8230 } else { 8231 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8232 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8233 } 8234 } else { 8235 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8236 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8237 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8238 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8239 if (IsStrict) { 8240 // Sel = Src < 0x80000000 8241 // FltOfs = select Sel, 0.0, 0x80000000 8242 // IntOfs = select Sel, 0, 0x80000000 8243 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8244 SDValue Chain = Op.getOperand(0); 8245 EVT SetCCVT = 8246 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8247 EVT DstSetCCVT = 8248 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8249 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8250 SDNodeFlags(), Chain, true); 8251 Chain = Sel.getValue(1); 8252 8253 SDValue FltOfs = DAG.getSelect( 8254 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8255 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8256 8257 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8258 DAG.getVTList(SrcVT, MVT::Other), 8259 {Chain, Src, FltOfs}, Flags); 8260 Chain = Val.getValue(1); 8261 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8262 DAG.getVTList(DstVT, MVT::Other), 8263 {Chain, Val}, Flags); 8264 Chain = SInt.getValue(1); 8265 SDValue IntOfs = DAG.getSelect( 8266 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8267 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8268 return DAG.getMergeValues({Result, Chain}, dl); 8269 } else { 8270 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8271 // FIXME: generated code sucks. 8272 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8273 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8274 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8275 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8276 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8277 } 8278 } 8279 } 8280 8281 return SDValue(); 8282 } 8283 8284 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8285 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8286 8287 ReuseLoadInfo RLI; 8288 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8289 8290 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8291 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8292 } 8293 8294 // We're trying to insert a regular store, S, and then a load, L. If the 8295 // incoming value, O, is a load, we might just be able to have our load use the 8296 // address used by O. However, we don't know if anything else will store to 8297 // that address before we can load from it. To prevent this situation, we need 8298 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8299 // the same chain operand as O, we create a token factor from the chain results 8300 // of O and L, and we replace all uses of O's chain result with that token 8301 // factor (see spliceIntoChain below for this last part). 8302 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8303 ReuseLoadInfo &RLI, 8304 SelectionDAG &DAG, 8305 ISD::LoadExtType ET) const { 8306 // Conservatively skip reusing for constrained FP nodes. 8307 if (Op->isStrictFPOpcode()) 8308 return false; 8309 8310 SDLoc dl(Op); 8311 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8312 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8313 if (ET == ISD::NON_EXTLOAD && 8314 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8315 isOperationLegalOrCustom(Op.getOpcode(), 8316 Op.getOperand(0).getValueType())) { 8317 8318 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8319 return true; 8320 } 8321 8322 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8323 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8324 LD->isNonTemporal()) 8325 return false; 8326 if (LD->getMemoryVT() != MemVT) 8327 return false; 8328 8329 RLI.Ptr = LD->getBasePtr(); 8330 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8331 assert(LD->getAddressingMode() == ISD::PRE_INC && 8332 "Non-pre-inc AM on PPC?"); 8333 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8334 LD->getOffset()); 8335 } 8336 8337 RLI.Chain = LD->getChain(); 8338 RLI.MPI = LD->getPointerInfo(); 8339 RLI.IsDereferenceable = LD->isDereferenceable(); 8340 RLI.IsInvariant = LD->isInvariant(); 8341 RLI.Alignment = LD->getAlign(); 8342 RLI.AAInfo = LD->getAAInfo(); 8343 RLI.Ranges = LD->getRanges(); 8344 8345 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8346 return true; 8347 } 8348 8349 // Given the head of the old chain, ResChain, insert a token factor containing 8350 // it and NewResChain, and make users of ResChain now be users of that token 8351 // factor. 8352 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8353 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8354 SDValue NewResChain, 8355 SelectionDAG &DAG) const { 8356 if (!ResChain) 8357 return; 8358 8359 SDLoc dl(NewResChain); 8360 8361 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8362 NewResChain, DAG.getUNDEF(MVT::Other)); 8363 assert(TF.getNode() != NewResChain.getNode() && 8364 "A new TF really is required here"); 8365 8366 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8367 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8368 } 8369 8370 /// Analyze profitability of direct move 8371 /// prefer float load to int load plus direct move 8372 /// when there is no integer use of int load 8373 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8374 SDNode *Origin = Op.getOperand(0).getNode(); 8375 if (Origin->getOpcode() != ISD::LOAD) 8376 return true; 8377 8378 // If there is no LXSIBZX/LXSIHZX, like Power8, 8379 // prefer direct move if the memory size is 1 or 2 bytes. 8380 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8381 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8382 return true; 8383 8384 for (SDNode::use_iterator UI = Origin->use_begin(), 8385 UE = Origin->use_end(); 8386 UI != UE; ++UI) { 8387 8388 // Only look at the users of the loaded value. 8389 if (UI.getUse().get().getResNo() != 0) 8390 continue; 8391 8392 if (UI->getOpcode() != ISD::SINT_TO_FP && 8393 UI->getOpcode() != ISD::UINT_TO_FP && 8394 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8395 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8396 return true; 8397 } 8398 8399 return false; 8400 } 8401 8402 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8403 const PPCSubtarget &Subtarget, 8404 SDValue Chain = SDValue()) { 8405 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8406 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8407 SDLoc dl(Op); 8408 8409 // TODO: Any other flags to propagate? 8410 SDNodeFlags Flags; 8411 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8412 8413 // If we have FCFIDS, then use it when converting to single-precision. 8414 // Otherwise, convert to double-precision and then round. 8415 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8416 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8417 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8418 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8419 if (Op->isStrictFPOpcode()) { 8420 if (!Chain) 8421 Chain = Op.getOperand(0); 8422 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8423 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8424 } else 8425 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8426 } 8427 8428 /// Custom lowers integer to floating point conversions to use 8429 /// the direct move instructions available in ISA 2.07 to avoid the 8430 /// need for load/store combinations. 8431 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8432 SelectionDAG &DAG, 8433 const SDLoc &dl) const { 8434 assert((Op.getValueType() == MVT::f32 || 8435 Op.getValueType() == MVT::f64) && 8436 "Invalid floating point type as target of conversion"); 8437 assert(Subtarget.hasFPCVT() && 8438 "Int to FP conversions with direct moves require FPCVT"); 8439 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8440 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8441 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8442 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8443 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8444 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8445 return convertIntToFP(Op, Mov, DAG, Subtarget); 8446 } 8447 8448 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8449 8450 EVT VecVT = Vec.getValueType(); 8451 assert(VecVT.isVector() && "Expected a vector type."); 8452 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8453 8454 EVT EltVT = VecVT.getVectorElementType(); 8455 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8456 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8457 8458 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8459 SmallVector<SDValue, 16> Ops(NumConcat); 8460 Ops[0] = Vec; 8461 SDValue UndefVec = DAG.getUNDEF(VecVT); 8462 for (unsigned i = 1; i < NumConcat; ++i) 8463 Ops[i] = UndefVec; 8464 8465 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8466 } 8467 8468 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8469 const SDLoc &dl) const { 8470 bool IsStrict = Op->isStrictFPOpcode(); 8471 unsigned Opc = Op.getOpcode(); 8472 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8473 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8474 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8475 "Unexpected conversion type"); 8476 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8477 "Supports conversions to v2f64/v4f32 only."); 8478 8479 // TODO: Any other flags to propagate? 8480 SDNodeFlags Flags; 8481 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8482 8483 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8484 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8485 8486 SDValue Wide = widenVec(DAG, Src, dl); 8487 EVT WideVT = Wide.getValueType(); 8488 unsigned WideNumElts = WideVT.getVectorNumElements(); 8489 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8490 8491 SmallVector<int, 16> ShuffV; 8492 for (unsigned i = 0; i < WideNumElts; ++i) 8493 ShuffV.push_back(i + WideNumElts); 8494 8495 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8496 int SaveElts = FourEltRes ? 4 : 2; 8497 if (Subtarget.isLittleEndian()) 8498 for (int i = 0; i < SaveElts; i++) 8499 ShuffV[i * Stride] = i; 8500 else 8501 for (int i = 1; i <= SaveElts; i++) 8502 ShuffV[i * Stride - 1] = i - 1; 8503 8504 SDValue ShuffleSrc2 = 8505 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8506 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8507 8508 SDValue Extend; 8509 if (SignedConv) { 8510 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8511 EVT ExtVT = Src.getValueType(); 8512 if (Subtarget.hasP9Altivec()) 8513 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8514 IntermediateVT.getVectorNumElements()); 8515 8516 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8517 DAG.getValueType(ExtVT)); 8518 } else 8519 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8520 8521 if (IsStrict) 8522 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8523 {Op.getOperand(0), Extend}, Flags); 8524 8525 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8526 } 8527 8528 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8529 SelectionDAG &DAG) const { 8530 SDLoc dl(Op); 8531 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8532 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8533 bool IsStrict = Op->isStrictFPOpcode(); 8534 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8535 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8536 8537 // TODO: Any other flags to propagate? 8538 SDNodeFlags Flags; 8539 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8540 8541 EVT InVT = Src.getValueType(); 8542 EVT OutVT = Op.getValueType(); 8543 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8544 isOperationCustom(Op.getOpcode(), InVT)) 8545 return LowerINT_TO_FPVector(Op, DAG, dl); 8546 8547 // Conversions to f128 are legal. 8548 if (Op.getValueType() == MVT::f128) 8549 return Op; 8550 8551 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8552 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8553 return SDValue(); 8554 8555 if (Src.getValueType() == MVT::i1) 8556 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8557 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8558 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8559 8560 // If we have direct moves, we can do all the conversion, skip the store/load 8561 // however, without FPCVT we can't do most conversions. 8562 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8563 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8564 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8565 8566 assert((IsSigned || Subtarget.hasFPCVT()) && 8567 "UINT_TO_FP is supported only with FPCVT"); 8568 8569 if (Src.getValueType() == MVT::i64) { 8570 SDValue SINT = Src; 8571 // When converting to single-precision, we actually need to convert 8572 // to double-precision first and then round to single-precision. 8573 // To avoid double-rounding effects during that operation, we have 8574 // to prepare the input operand. Bits that might be truncated when 8575 // converting to double-precision are replaced by a bit that won't 8576 // be lost at this stage, but is below the single-precision rounding 8577 // position. 8578 // 8579 // However, if -enable-unsafe-fp-math is in effect, accept double 8580 // rounding to avoid the extra overhead. 8581 if (Op.getValueType() == MVT::f32 && 8582 !Subtarget.hasFPCVT() && 8583 !DAG.getTarget().Options.UnsafeFPMath) { 8584 8585 // Twiddle input to make sure the low 11 bits are zero. (If this 8586 // is the case, we are guaranteed the value will fit into the 53 bit 8587 // mantissa of an IEEE double-precision value without rounding.) 8588 // If any of those low 11 bits were not zero originally, make sure 8589 // bit 12 (value 2048) is set instead, so that the final rounding 8590 // to single-precision gets the correct result. 8591 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8592 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8593 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8594 Round, DAG.getConstant(2047, dl, MVT::i64)); 8595 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8596 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8597 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8598 8599 // However, we cannot use that value unconditionally: if the magnitude 8600 // of the input value is small, the bit-twiddling we did above might 8601 // end up visibly changing the output. Fortunately, in that case, we 8602 // don't need to twiddle bits since the original input will convert 8603 // exactly to double-precision floating-point already. Therefore, 8604 // construct a conditional to use the original value if the top 11 8605 // bits are all sign-bit copies, and use the rounded value computed 8606 // above otherwise. 8607 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8608 SINT, DAG.getConstant(53, dl, MVT::i32)); 8609 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8610 Cond, DAG.getConstant(1, dl, MVT::i64)); 8611 Cond = DAG.getSetCC( 8612 dl, 8613 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8614 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8615 8616 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8617 } 8618 8619 ReuseLoadInfo RLI; 8620 SDValue Bits; 8621 8622 MachineFunction &MF = DAG.getMachineFunction(); 8623 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8624 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8625 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8626 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8627 } else if (Subtarget.hasLFIWAX() && 8628 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8629 MachineMemOperand *MMO = 8630 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8631 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8632 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8633 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8634 DAG.getVTList(MVT::f64, MVT::Other), 8635 Ops, MVT::i32, MMO); 8636 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8637 } else if (Subtarget.hasFPCVT() && 8638 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8639 MachineMemOperand *MMO = 8640 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8641 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8642 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8643 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8644 DAG.getVTList(MVT::f64, MVT::Other), 8645 Ops, MVT::i32, MMO); 8646 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8647 } else if (((Subtarget.hasLFIWAX() && 8648 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8649 (Subtarget.hasFPCVT() && 8650 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8651 SINT.getOperand(0).getValueType() == MVT::i32) { 8652 MachineFrameInfo &MFI = MF.getFrameInfo(); 8653 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8654 8655 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8656 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8657 8658 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8659 MachinePointerInfo::getFixedStack( 8660 DAG.getMachineFunction(), FrameIdx)); 8661 Chain = Store; 8662 8663 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8664 "Expected an i32 store"); 8665 8666 RLI.Ptr = FIdx; 8667 RLI.Chain = Chain; 8668 RLI.MPI = 8669 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8670 RLI.Alignment = Align(4); 8671 8672 MachineMemOperand *MMO = 8673 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8674 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8675 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8676 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8677 PPCISD::LFIWZX : PPCISD::LFIWAX, 8678 dl, DAG.getVTList(MVT::f64, MVT::Other), 8679 Ops, MVT::i32, MMO); 8680 Chain = Bits.getValue(1); 8681 } else 8682 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8683 8684 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8685 if (IsStrict) 8686 Chain = FP.getValue(1); 8687 8688 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8689 if (IsStrict) 8690 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8691 DAG.getVTList(MVT::f32, MVT::Other), 8692 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8693 else 8694 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8695 DAG.getIntPtrConstant(0, dl)); 8696 } 8697 return FP; 8698 } 8699 8700 assert(Src.getValueType() == MVT::i32 && 8701 "Unhandled INT_TO_FP type in custom expander!"); 8702 // Since we only generate this in 64-bit mode, we can take advantage of 8703 // 64-bit registers. In particular, sign extend the input value into the 8704 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8705 // then lfd it and fcfid it. 8706 MachineFunction &MF = DAG.getMachineFunction(); 8707 MachineFrameInfo &MFI = MF.getFrameInfo(); 8708 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8709 8710 SDValue Ld; 8711 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8712 ReuseLoadInfo RLI; 8713 bool ReusingLoad; 8714 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8715 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8716 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8717 8718 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8719 MachinePointerInfo::getFixedStack( 8720 DAG.getMachineFunction(), FrameIdx)); 8721 Chain = Store; 8722 8723 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8724 "Expected an i32 store"); 8725 8726 RLI.Ptr = FIdx; 8727 RLI.Chain = Chain; 8728 RLI.MPI = 8729 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8730 RLI.Alignment = Align(4); 8731 } 8732 8733 MachineMemOperand *MMO = 8734 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8735 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8736 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8737 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8738 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8739 MVT::i32, MMO); 8740 Chain = Ld.getValue(1); 8741 if (ReusingLoad) 8742 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8743 } else { 8744 assert(Subtarget.isPPC64() && 8745 "i32->FP without LFIWAX supported only on PPC64"); 8746 8747 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8748 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8749 8750 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8751 8752 // STD the extended value into the stack slot. 8753 SDValue Store = DAG.getStore( 8754 Chain, dl, Ext64, FIdx, 8755 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8756 Chain = Store; 8757 8758 // Load the value as a double. 8759 Ld = DAG.getLoad( 8760 MVT::f64, dl, Chain, FIdx, 8761 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8762 Chain = Ld.getValue(1); 8763 } 8764 8765 // FCFID it and return it. 8766 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8767 if (IsStrict) 8768 Chain = FP.getValue(1); 8769 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8770 if (IsStrict) 8771 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8772 DAG.getVTList(MVT::f32, MVT::Other), 8773 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8774 else 8775 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8776 DAG.getIntPtrConstant(0, dl)); 8777 } 8778 return FP; 8779 } 8780 8781 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8782 SelectionDAG &DAG) const { 8783 SDLoc dl(Op); 8784 /* 8785 The rounding mode is in bits 30:31 of FPSR, and has the following 8786 settings: 8787 00 Round to nearest 8788 01 Round to 0 8789 10 Round to +inf 8790 11 Round to -inf 8791 8792 FLT_ROUNDS, on the other hand, expects the following: 8793 -1 Undefined 8794 0 Round to 0 8795 1 Round to nearest 8796 2 Round to +inf 8797 3 Round to -inf 8798 8799 To perform the conversion, we do: 8800 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8801 */ 8802 8803 MachineFunction &MF = DAG.getMachineFunction(); 8804 EVT VT = Op.getValueType(); 8805 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8806 8807 // Save FP Control Word to register 8808 SDValue Chain = Op.getOperand(0); 8809 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8810 Chain = MFFS.getValue(1); 8811 8812 // Save FP register to stack slot 8813 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8814 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8815 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8816 8817 // Load FP Control Word from low 32 bits of stack slot. 8818 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8819 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8820 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8821 Chain = CWD.getValue(1); 8822 8823 // Transform as necessary 8824 SDValue CWD1 = 8825 DAG.getNode(ISD::AND, dl, MVT::i32, 8826 CWD, DAG.getConstant(3, dl, MVT::i32)); 8827 SDValue CWD2 = 8828 DAG.getNode(ISD::SRL, dl, MVT::i32, 8829 DAG.getNode(ISD::AND, dl, MVT::i32, 8830 DAG.getNode(ISD::XOR, dl, MVT::i32, 8831 CWD, DAG.getConstant(3, dl, MVT::i32)), 8832 DAG.getConstant(3, dl, MVT::i32)), 8833 DAG.getConstant(1, dl, MVT::i32)); 8834 8835 SDValue RetVal = 8836 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8837 8838 RetVal = 8839 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8840 dl, VT, RetVal); 8841 8842 return DAG.getMergeValues({RetVal, Chain}, dl); 8843 } 8844 8845 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8846 EVT VT = Op.getValueType(); 8847 unsigned BitWidth = VT.getSizeInBits(); 8848 SDLoc dl(Op); 8849 assert(Op.getNumOperands() == 3 && 8850 VT == Op.getOperand(1).getValueType() && 8851 "Unexpected SHL!"); 8852 8853 // Expand into a bunch of logical ops. Note that these ops 8854 // depend on the PPC behavior for oversized shift amounts. 8855 SDValue Lo = Op.getOperand(0); 8856 SDValue Hi = Op.getOperand(1); 8857 SDValue Amt = Op.getOperand(2); 8858 EVT AmtVT = Amt.getValueType(); 8859 8860 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8861 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8862 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8863 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8864 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8865 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8866 DAG.getConstant(-BitWidth, dl, AmtVT)); 8867 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8868 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8869 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8870 SDValue OutOps[] = { OutLo, OutHi }; 8871 return DAG.getMergeValues(OutOps, dl); 8872 } 8873 8874 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8875 EVT VT = Op.getValueType(); 8876 SDLoc dl(Op); 8877 unsigned BitWidth = VT.getSizeInBits(); 8878 assert(Op.getNumOperands() == 3 && 8879 VT == Op.getOperand(1).getValueType() && 8880 "Unexpected SRL!"); 8881 8882 // Expand into a bunch of logical ops. Note that these ops 8883 // depend on the PPC behavior for oversized shift amounts. 8884 SDValue Lo = Op.getOperand(0); 8885 SDValue Hi = Op.getOperand(1); 8886 SDValue Amt = Op.getOperand(2); 8887 EVT AmtVT = Amt.getValueType(); 8888 8889 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8890 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8891 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8892 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8893 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8894 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8895 DAG.getConstant(-BitWidth, dl, AmtVT)); 8896 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8897 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8898 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8899 SDValue OutOps[] = { OutLo, OutHi }; 8900 return DAG.getMergeValues(OutOps, dl); 8901 } 8902 8903 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8904 SDLoc dl(Op); 8905 EVT VT = Op.getValueType(); 8906 unsigned BitWidth = VT.getSizeInBits(); 8907 assert(Op.getNumOperands() == 3 && 8908 VT == Op.getOperand(1).getValueType() && 8909 "Unexpected SRA!"); 8910 8911 // Expand into a bunch of logical ops, followed by a select_cc. 8912 SDValue Lo = Op.getOperand(0); 8913 SDValue Hi = Op.getOperand(1); 8914 SDValue Amt = Op.getOperand(2); 8915 EVT AmtVT = Amt.getValueType(); 8916 8917 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8918 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8919 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8920 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8921 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8922 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8923 DAG.getConstant(-BitWidth, dl, AmtVT)); 8924 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8925 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8926 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8927 Tmp4, Tmp6, ISD::SETLE); 8928 SDValue OutOps[] = { OutLo, OutHi }; 8929 return DAG.getMergeValues(OutOps, dl); 8930 } 8931 8932 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8933 SelectionDAG &DAG) const { 8934 SDLoc dl(Op); 8935 EVT VT = Op.getValueType(); 8936 unsigned BitWidth = VT.getSizeInBits(); 8937 8938 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8939 SDValue X = Op.getOperand(0); 8940 SDValue Y = Op.getOperand(1); 8941 SDValue Z = Op.getOperand(2); 8942 EVT AmtVT = Z.getValueType(); 8943 8944 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8945 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8946 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8947 // on PowerPC shift by BW being well defined. 8948 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8949 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8950 SDValue SubZ = 8951 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8952 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8953 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8954 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8955 } 8956 8957 //===----------------------------------------------------------------------===// 8958 // Vector related lowering. 8959 // 8960 8961 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8962 /// element size of SplatSize. Cast the result to VT. 8963 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8964 SelectionDAG &DAG, const SDLoc &dl) { 8965 static const MVT VTys[] = { // canonical VT to use for each size. 8966 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8967 }; 8968 8969 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8970 8971 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8972 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 8973 SplatSize = 1; 8974 Val = 0xFF; 8975 } 8976 8977 EVT CanonicalVT = VTys[SplatSize-1]; 8978 8979 // Build a canonical splat for this value. 8980 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8981 } 8982 8983 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8984 /// specified intrinsic ID. 8985 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8986 const SDLoc &dl, EVT DestVT = MVT::Other) { 8987 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8988 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8989 DAG.getConstant(IID, dl, MVT::i32), Op); 8990 } 8991 8992 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8993 /// specified intrinsic ID. 8994 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8995 SelectionDAG &DAG, const SDLoc &dl, 8996 EVT DestVT = MVT::Other) { 8997 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8998 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8999 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 9000 } 9001 9002 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 9003 /// specified intrinsic ID. 9004 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 9005 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 9006 EVT DestVT = MVT::Other) { 9007 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 9008 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9009 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 9010 } 9011 9012 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 9013 /// amount. The result has the specified value type. 9014 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 9015 SelectionDAG &DAG, const SDLoc &dl) { 9016 // Force LHS/RHS to be the right type. 9017 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 9018 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 9019 9020 int Ops[16]; 9021 for (unsigned i = 0; i != 16; ++i) 9022 Ops[i] = i + Amt; 9023 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 9024 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9025 } 9026 9027 /// Do we have an efficient pattern in a .td file for this node? 9028 /// 9029 /// \param V - pointer to the BuildVectorSDNode being matched 9030 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9031 /// 9032 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9033 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9034 /// the opposite is true (expansion is beneficial) are: 9035 /// - The node builds a vector out of integers that are not 32 or 64-bits 9036 /// - The node builds a vector out of constants 9037 /// - The node is a "load-and-splat" 9038 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9039 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9040 bool HasDirectMove, 9041 bool HasP8Vector) { 9042 EVT VecVT = V->getValueType(0); 9043 bool RightType = VecVT == MVT::v2f64 || 9044 (HasP8Vector && VecVT == MVT::v4f32) || 9045 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9046 if (!RightType) 9047 return false; 9048 9049 bool IsSplat = true; 9050 bool IsLoad = false; 9051 SDValue Op0 = V->getOperand(0); 9052 9053 // This function is called in a block that confirms the node is not a constant 9054 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9055 // different constants. 9056 if (V->isConstant()) 9057 return false; 9058 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9059 if (V->getOperand(i).isUndef()) 9060 return false; 9061 // We want to expand nodes that represent load-and-splat even if the 9062 // loaded value is a floating point truncation or conversion to int. 9063 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9064 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9065 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9066 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9067 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9068 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9069 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9070 IsLoad = true; 9071 // If the operands are different or the input is not a load and has more 9072 // uses than just this BV node, then it isn't a splat. 9073 if (V->getOperand(i) != Op0 || 9074 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9075 IsSplat = false; 9076 } 9077 return !(IsSplat && IsLoad); 9078 } 9079 9080 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9081 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9082 9083 SDLoc dl(Op); 9084 SDValue Op0 = Op->getOperand(0); 9085 9086 if ((Op.getValueType() != MVT::f128) || 9087 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9088 (Op0.getOperand(0).getValueType() != MVT::i64) || 9089 (Op0.getOperand(1).getValueType() != MVT::i64)) 9090 return SDValue(); 9091 9092 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9093 Op0.getOperand(1)); 9094 } 9095 9096 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9097 const SDValue *InputLoad = &Op; 9098 if (InputLoad->getOpcode() == ISD::BITCAST) 9099 InputLoad = &InputLoad->getOperand(0); 9100 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9101 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9102 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9103 InputLoad = &InputLoad->getOperand(0); 9104 } 9105 if (InputLoad->getOpcode() != ISD::LOAD) 9106 return nullptr; 9107 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9108 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9109 } 9110 9111 // Convert the argument APFloat to a single precision APFloat if there is no 9112 // loss in information during the conversion to single precision APFloat and the 9113 // resulting number is not a denormal number. Return true if successful. 9114 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9115 APFloat APFloatToConvert = ArgAPFloat; 9116 bool LosesInfo = true; 9117 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9118 &LosesInfo); 9119 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9120 if (Success) 9121 ArgAPFloat = APFloatToConvert; 9122 return Success; 9123 } 9124 9125 // Bitcast the argument APInt to a double and convert it to a single precision 9126 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9127 // argument if there is no loss in information during the conversion from 9128 // double to single precision APFloat and the resulting number is not a denormal 9129 // number. Return true if successful. 9130 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9131 double DpValue = ArgAPInt.bitsToDouble(); 9132 APFloat APFloatDp(DpValue); 9133 bool Success = convertToNonDenormSingle(APFloatDp); 9134 if (Success) 9135 ArgAPInt = APFloatDp.bitcastToAPInt(); 9136 return Success; 9137 } 9138 9139 // If this is a case we can't handle, return null and let the default 9140 // expansion code take care of it. If we CAN select this case, and if it 9141 // selects to a single instruction, return Op. Otherwise, if we can codegen 9142 // this case more efficiently than a constant pool load, lower it to the 9143 // sequence of ops that should be used. 9144 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9145 SelectionDAG &DAG) const { 9146 SDLoc dl(Op); 9147 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9148 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9149 9150 // Check if this is a splat of a constant value. 9151 APInt APSplatBits, APSplatUndef; 9152 unsigned SplatBitSize; 9153 bool HasAnyUndefs; 9154 bool BVNIsConstantSplat = 9155 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9156 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9157 9158 // If it is a splat of a double, check if we can shrink it to a 32 bit 9159 // non-denormal float which when converted back to double gives us the same 9160 // double. This is to exploit the XXSPLTIDP instruction. 9161 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 9162 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 9163 convertToNonDenormSingle(APSplatBits)) { 9164 SDValue SplatNode = DAG.getNode( 9165 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9166 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9167 return DAG.getBitcast(Op.getValueType(), SplatNode); 9168 } 9169 9170 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9171 9172 bool IsPermutedLoad = false; 9173 const SDValue *InputLoad = 9174 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9175 // Handle load-and-splat patterns as we have instructions that will do this 9176 // in one go. 9177 if (InputLoad && DAG.isSplatValue(Op, true)) { 9178 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9179 9180 // We have handling for 4 and 8 byte elements. 9181 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9182 9183 // Checking for a single use of this load, we have to check for vector 9184 // width (128 bits) / ElementSize uses (since each operand of the 9185 // BUILD_VECTOR is a separate use of the value. 9186 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9187 ((Subtarget.hasVSX() && ElementSize == 64) || 9188 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9189 SDValue Ops[] = { 9190 LD->getChain(), // Chain 9191 LD->getBasePtr(), // Ptr 9192 DAG.getValueType(Op.getValueType()) // VT 9193 }; 9194 return 9195 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9196 DAG.getVTList(Op.getValueType(), MVT::Other), 9197 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9198 } 9199 } 9200 9201 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9202 // lowered to VSX instructions under certain conditions. 9203 // Without VSX, there is no pattern more efficient than expanding the node. 9204 if (Subtarget.hasVSX() && 9205 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9206 Subtarget.hasP8Vector())) 9207 return Op; 9208 return SDValue(); 9209 } 9210 9211 uint64_t SplatBits = APSplatBits.getZExtValue(); 9212 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9213 unsigned SplatSize = SplatBitSize / 8; 9214 9215 // First, handle single instruction cases. 9216 9217 // All zeros? 9218 if (SplatBits == 0) { 9219 // Canonicalize all zero vectors to be v4i32. 9220 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9221 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9222 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9223 } 9224 return Op; 9225 } 9226 9227 // We have XXSPLTIW for constant splats four bytes wide. 9228 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9229 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9230 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9231 // turned into a 4-byte splat of 0xABABABAB. 9232 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9233 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 9234 Op.getValueType(), DAG, dl); 9235 9236 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9237 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9238 dl); 9239 9240 // We have XXSPLTIB for constant splats one byte wide. 9241 if (Subtarget.hasP9Vector() && SplatSize == 1) 9242 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9243 dl); 9244 9245 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9246 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9247 (32-SplatBitSize)); 9248 if (SextVal >= -16 && SextVal <= 15) 9249 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9250 dl); 9251 9252 // Two instruction sequences. 9253 9254 // If this value is in the range [-32,30] and is even, use: 9255 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9256 // If this value is in the range [17,31] and is odd, use: 9257 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9258 // If this value is in the range [-31,-17] and is odd, use: 9259 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9260 // Note the last two are three-instruction sequences. 9261 if (SextVal >= -32 && SextVal <= 31) { 9262 // To avoid having these optimizations undone by constant folding, 9263 // we convert to a pseudo that will be expanded later into one of 9264 // the above forms. 9265 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9266 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9267 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9268 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9269 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9270 if (VT == Op.getValueType()) 9271 return RetVal; 9272 else 9273 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9274 } 9275 9276 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9277 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9278 // for fneg/fabs. 9279 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9280 // Make -1 and vspltisw -1: 9281 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9282 9283 // Make the VSLW intrinsic, computing 0x8000_0000. 9284 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9285 OnesV, DAG, dl); 9286 9287 // xor by OnesV to invert it. 9288 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9289 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9290 } 9291 9292 // Check to see if this is a wide variety of vsplti*, binop self cases. 9293 static const signed char SplatCsts[] = { 9294 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9295 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9296 }; 9297 9298 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9299 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9300 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9301 int i = SplatCsts[idx]; 9302 9303 // Figure out what shift amount will be used by altivec if shifted by i in 9304 // this splat size. 9305 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9306 9307 // vsplti + shl self. 9308 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9309 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9310 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9311 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9312 Intrinsic::ppc_altivec_vslw 9313 }; 9314 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9315 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9316 } 9317 9318 // vsplti + srl self. 9319 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9320 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9321 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9322 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9323 Intrinsic::ppc_altivec_vsrw 9324 }; 9325 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9326 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9327 } 9328 9329 // vsplti + sra self. 9330 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9331 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9332 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9333 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9334 Intrinsic::ppc_altivec_vsraw 9335 }; 9336 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9337 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9338 } 9339 9340 // vsplti + rol self. 9341 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9342 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9343 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9344 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9345 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9346 Intrinsic::ppc_altivec_vrlw 9347 }; 9348 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9349 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9350 } 9351 9352 // t = vsplti c, result = vsldoi t, t, 1 9353 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9354 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9355 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9356 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9357 } 9358 // t = vsplti c, result = vsldoi t, t, 2 9359 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9360 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9361 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9362 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9363 } 9364 // t = vsplti c, result = vsldoi t, t, 3 9365 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9366 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9367 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9368 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9369 } 9370 } 9371 9372 return SDValue(); 9373 } 9374 9375 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9376 /// the specified operations to build the shuffle. 9377 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9378 SDValue RHS, SelectionDAG &DAG, 9379 const SDLoc &dl) { 9380 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9381 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9382 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9383 9384 enum { 9385 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9386 OP_VMRGHW, 9387 OP_VMRGLW, 9388 OP_VSPLTISW0, 9389 OP_VSPLTISW1, 9390 OP_VSPLTISW2, 9391 OP_VSPLTISW3, 9392 OP_VSLDOI4, 9393 OP_VSLDOI8, 9394 OP_VSLDOI12 9395 }; 9396 9397 if (OpNum == OP_COPY) { 9398 if (LHSID == (1*9+2)*9+3) return LHS; 9399 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9400 return RHS; 9401 } 9402 9403 SDValue OpLHS, OpRHS; 9404 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9405 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9406 9407 int ShufIdxs[16]; 9408 switch (OpNum) { 9409 default: llvm_unreachable("Unknown i32 permute!"); 9410 case OP_VMRGHW: 9411 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9412 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9413 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9414 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9415 break; 9416 case OP_VMRGLW: 9417 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9418 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9419 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9420 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9421 break; 9422 case OP_VSPLTISW0: 9423 for (unsigned i = 0; i != 16; ++i) 9424 ShufIdxs[i] = (i&3)+0; 9425 break; 9426 case OP_VSPLTISW1: 9427 for (unsigned i = 0; i != 16; ++i) 9428 ShufIdxs[i] = (i&3)+4; 9429 break; 9430 case OP_VSPLTISW2: 9431 for (unsigned i = 0; i != 16; ++i) 9432 ShufIdxs[i] = (i&3)+8; 9433 break; 9434 case OP_VSPLTISW3: 9435 for (unsigned i = 0; i != 16; ++i) 9436 ShufIdxs[i] = (i&3)+12; 9437 break; 9438 case OP_VSLDOI4: 9439 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9440 case OP_VSLDOI8: 9441 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9442 case OP_VSLDOI12: 9443 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9444 } 9445 EVT VT = OpLHS.getValueType(); 9446 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9447 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9448 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9449 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9450 } 9451 9452 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9453 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9454 /// SDValue. 9455 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9456 SelectionDAG &DAG) const { 9457 const unsigned BytesInVector = 16; 9458 bool IsLE = Subtarget.isLittleEndian(); 9459 SDLoc dl(N); 9460 SDValue V1 = N->getOperand(0); 9461 SDValue V2 = N->getOperand(1); 9462 unsigned ShiftElts = 0, InsertAtByte = 0; 9463 bool Swap = false; 9464 9465 // Shifts required to get the byte we want at element 7. 9466 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9467 0, 15, 14, 13, 12, 11, 10, 9}; 9468 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9469 1, 2, 3, 4, 5, 6, 7, 8}; 9470 9471 ArrayRef<int> Mask = N->getMask(); 9472 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9473 9474 // For each mask element, find out if we're just inserting something 9475 // from V2 into V1 or vice versa. 9476 // Possible permutations inserting an element from V2 into V1: 9477 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9478 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9479 // ... 9480 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9481 // Inserting from V1 into V2 will be similar, except mask range will be 9482 // [16,31]. 9483 9484 bool FoundCandidate = false; 9485 // If both vector operands for the shuffle are the same vector, the mask 9486 // will contain only elements from the first one and the second one will be 9487 // undef. 9488 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9489 // Go through the mask of half-words to find an element that's being moved 9490 // from one vector to the other. 9491 for (unsigned i = 0; i < BytesInVector; ++i) { 9492 unsigned CurrentElement = Mask[i]; 9493 // If 2nd operand is undefined, we should only look for element 7 in the 9494 // Mask. 9495 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9496 continue; 9497 9498 bool OtherElementsInOrder = true; 9499 // Examine the other elements in the Mask to see if they're in original 9500 // order. 9501 for (unsigned j = 0; j < BytesInVector; ++j) { 9502 if (j == i) 9503 continue; 9504 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9505 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9506 // in which we always assume we're always picking from the 1st operand. 9507 int MaskOffset = 9508 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9509 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9510 OtherElementsInOrder = false; 9511 break; 9512 } 9513 } 9514 // If other elements are in original order, we record the number of shifts 9515 // we need to get the element we want into element 7. Also record which byte 9516 // in the vector we should insert into. 9517 if (OtherElementsInOrder) { 9518 // If 2nd operand is undefined, we assume no shifts and no swapping. 9519 if (V2.isUndef()) { 9520 ShiftElts = 0; 9521 Swap = false; 9522 } else { 9523 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9524 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9525 : BigEndianShifts[CurrentElement & 0xF]; 9526 Swap = CurrentElement < BytesInVector; 9527 } 9528 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9529 FoundCandidate = true; 9530 break; 9531 } 9532 } 9533 9534 if (!FoundCandidate) 9535 return SDValue(); 9536 9537 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9538 // optionally with VECSHL if shift is required. 9539 if (Swap) 9540 std::swap(V1, V2); 9541 if (V2.isUndef()) 9542 V2 = V1; 9543 if (ShiftElts) { 9544 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9545 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9546 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9547 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9548 } 9549 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9550 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9551 } 9552 9553 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9554 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9555 /// SDValue. 9556 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9557 SelectionDAG &DAG) const { 9558 const unsigned NumHalfWords = 8; 9559 const unsigned BytesInVector = NumHalfWords * 2; 9560 // Check that the shuffle is on half-words. 9561 if (!isNByteElemShuffleMask(N, 2, 1)) 9562 return SDValue(); 9563 9564 bool IsLE = Subtarget.isLittleEndian(); 9565 SDLoc dl(N); 9566 SDValue V1 = N->getOperand(0); 9567 SDValue V2 = N->getOperand(1); 9568 unsigned ShiftElts = 0, InsertAtByte = 0; 9569 bool Swap = false; 9570 9571 // Shifts required to get the half-word we want at element 3. 9572 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9573 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9574 9575 uint32_t Mask = 0; 9576 uint32_t OriginalOrderLow = 0x1234567; 9577 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9578 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9579 // 32-bit space, only need 4-bit nibbles per element. 9580 for (unsigned i = 0; i < NumHalfWords; ++i) { 9581 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9582 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9583 } 9584 9585 // For each mask element, find out if we're just inserting something 9586 // from V2 into V1 or vice versa. Possible permutations inserting an element 9587 // from V2 into V1: 9588 // X, 1, 2, 3, 4, 5, 6, 7 9589 // 0, X, 2, 3, 4, 5, 6, 7 9590 // 0, 1, X, 3, 4, 5, 6, 7 9591 // 0, 1, 2, X, 4, 5, 6, 7 9592 // 0, 1, 2, 3, X, 5, 6, 7 9593 // 0, 1, 2, 3, 4, X, 6, 7 9594 // 0, 1, 2, 3, 4, 5, X, 7 9595 // 0, 1, 2, 3, 4, 5, 6, X 9596 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9597 9598 bool FoundCandidate = false; 9599 // Go through the mask of half-words to find an element that's being moved 9600 // from one vector to the other. 9601 for (unsigned i = 0; i < NumHalfWords; ++i) { 9602 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9603 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9604 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9605 uint32_t TargetOrder = 0x0; 9606 9607 // If both vector operands for the shuffle are the same vector, the mask 9608 // will contain only elements from the first one and the second one will be 9609 // undef. 9610 if (V2.isUndef()) { 9611 ShiftElts = 0; 9612 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9613 TargetOrder = OriginalOrderLow; 9614 Swap = false; 9615 // Skip if not the correct element or mask of other elements don't equal 9616 // to our expected order. 9617 if (MaskOneElt == VINSERTHSrcElem && 9618 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9619 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9620 FoundCandidate = true; 9621 break; 9622 } 9623 } else { // If both operands are defined. 9624 // Target order is [8,15] if the current mask is between [0,7]. 9625 TargetOrder = 9626 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9627 // Skip if mask of other elements don't equal our expected order. 9628 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9629 // We only need the last 3 bits for the number of shifts. 9630 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9631 : BigEndianShifts[MaskOneElt & 0x7]; 9632 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9633 Swap = MaskOneElt < NumHalfWords; 9634 FoundCandidate = true; 9635 break; 9636 } 9637 } 9638 } 9639 9640 if (!FoundCandidate) 9641 return SDValue(); 9642 9643 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9644 // optionally with VECSHL if shift is required. 9645 if (Swap) 9646 std::swap(V1, V2); 9647 if (V2.isUndef()) 9648 V2 = V1; 9649 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9650 if (ShiftElts) { 9651 // Double ShiftElts because we're left shifting on v16i8 type. 9652 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9653 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9654 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9655 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9656 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9657 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9658 } 9659 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9660 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9661 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9662 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9663 } 9664 9665 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9666 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9667 /// return the default SDValue. 9668 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9669 SelectionDAG &DAG) const { 9670 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9671 // to v16i8. Peek through the bitcasts to get the actual operands. 9672 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9673 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9674 9675 auto ShuffleMask = SVN->getMask(); 9676 SDValue VecShuffle(SVN, 0); 9677 SDLoc DL(SVN); 9678 9679 // Check that we have a four byte shuffle. 9680 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9681 return SDValue(); 9682 9683 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9684 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9685 std::swap(LHS, RHS); 9686 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9687 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9688 } 9689 9690 // Ensure that the RHS is a vector of constants. 9691 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9692 if (!BVN) 9693 return SDValue(); 9694 9695 // Check if RHS is a splat of 4-bytes (or smaller). 9696 APInt APSplatValue, APSplatUndef; 9697 unsigned SplatBitSize; 9698 bool HasAnyUndefs; 9699 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9700 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9701 SplatBitSize > 32) 9702 return SDValue(); 9703 9704 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9705 // The instruction splats a constant C into two words of the source vector 9706 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9707 // Thus we check that the shuffle mask is the equivalent of 9708 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9709 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9710 // within each word are consecutive, so we only need to check the first byte. 9711 SDValue Index; 9712 bool IsLE = Subtarget.isLittleEndian(); 9713 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9714 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9715 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9716 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9717 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9718 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9719 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9720 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9721 else 9722 return SDValue(); 9723 9724 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9725 // for XXSPLTI32DX. 9726 unsigned SplatVal = APSplatValue.getZExtValue(); 9727 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9728 SplatVal |= (SplatVal << SplatBitSize); 9729 9730 SDValue SplatNode = DAG.getNode( 9731 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9732 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9733 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9734 } 9735 9736 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9737 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9738 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9739 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9740 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9741 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9742 assert(Op.getValueType() == MVT::v1i128 && 9743 "Only set v1i128 as custom, other type shouldn't reach here!"); 9744 SDLoc dl(Op); 9745 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9746 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9747 unsigned SHLAmt = N1.getConstantOperandVal(0); 9748 if (SHLAmt % 8 == 0) { 9749 SmallVector<int, 16> Mask(16, 0); 9750 std::iota(Mask.begin(), Mask.end(), 0); 9751 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9752 if (SDValue Shuffle = 9753 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9754 DAG.getUNDEF(MVT::v16i8), Mask)) 9755 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9756 } 9757 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9758 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9759 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9760 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9761 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9762 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9763 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9764 } 9765 9766 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9767 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9768 /// return the code it can be lowered into. Worst case, it can always be 9769 /// lowered into a vperm. 9770 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9771 SelectionDAG &DAG) const { 9772 SDLoc dl(Op); 9773 SDValue V1 = Op.getOperand(0); 9774 SDValue V2 = Op.getOperand(1); 9775 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9776 9777 // Any nodes that were combined in the target-independent combiner prior 9778 // to vector legalization will not be sent to the target combine. Try to 9779 // combine it here. 9780 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9781 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9782 return NewShuffle; 9783 Op = NewShuffle; 9784 SVOp = cast<ShuffleVectorSDNode>(Op); 9785 V1 = Op.getOperand(0); 9786 V2 = Op.getOperand(1); 9787 } 9788 EVT VT = Op.getValueType(); 9789 bool isLittleEndian = Subtarget.isLittleEndian(); 9790 9791 unsigned ShiftElts, InsertAtByte; 9792 bool Swap = false; 9793 9794 // If this is a load-and-splat, we can do that with a single instruction 9795 // in some cases. However if the load has multiple uses, we don't want to 9796 // combine it because that will just produce multiple loads. 9797 bool IsPermutedLoad = false; 9798 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9799 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9800 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9801 InputLoad->hasOneUse()) { 9802 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9803 int SplatIdx = 9804 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9805 9806 // The splat index for permuted loads will be in the left half of the vector 9807 // which is strictly wider than the loaded value by 8 bytes. So we need to 9808 // adjust the splat index to point to the correct address in memory. 9809 if (IsPermutedLoad) { 9810 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9811 SplatIdx += IsFourByte ? 2 : 1; 9812 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9813 "Splat of a value outside of the loaded memory"); 9814 } 9815 9816 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9817 // For 4-byte load-and-splat, we need Power9. 9818 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9819 uint64_t Offset = 0; 9820 if (IsFourByte) 9821 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9822 else 9823 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9824 9825 SDValue BasePtr = LD->getBasePtr(); 9826 if (Offset != 0) 9827 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9828 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9829 SDValue Ops[] = { 9830 LD->getChain(), // Chain 9831 BasePtr, // BasePtr 9832 DAG.getValueType(Op.getValueType()) // VT 9833 }; 9834 SDVTList VTL = 9835 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9836 SDValue LdSplt = 9837 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9838 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9839 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9840 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9841 return LdSplt; 9842 } 9843 } 9844 if (Subtarget.hasP9Vector() && 9845 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9846 isLittleEndian)) { 9847 if (Swap) 9848 std::swap(V1, V2); 9849 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9850 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9851 if (ShiftElts) { 9852 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9853 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9854 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9855 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9856 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9857 } 9858 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9859 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9860 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9861 } 9862 9863 if (Subtarget.hasPrefixInstrs()) { 9864 SDValue SplatInsertNode; 9865 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9866 return SplatInsertNode; 9867 } 9868 9869 if (Subtarget.hasP9Altivec()) { 9870 SDValue NewISDNode; 9871 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9872 return NewISDNode; 9873 9874 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9875 return NewISDNode; 9876 } 9877 9878 if (Subtarget.hasVSX() && 9879 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9880 if (Swap) 9881 std::swap(V1, V2); 9882 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9883 SDValue Conv2 = 9884 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9885 9886 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9887 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9888 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9889 } 9890 9891 if (Subtarget.hasVSX() && 9892 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9893 if (Swap) 9894 std::swap(V1, V2); 9895 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9896 SDValue Conv2 = 9897 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9898 9899 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9900 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9901 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9902 } 9903 9904 if (Subtarget.hasP9Vector()) { 9905 if (PPC::isXXBRHShuffleMask(SVOp)) { 9906 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9907 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9908 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9909 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9910 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9911 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9912 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9913 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9914 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9915 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9916 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9917 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9918 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9919 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9920 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9921 } 9922 } 9923 9924 if (Subtarget.hasVSX()) { 9925 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9926 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9927 9928 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9929 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9930 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9931 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9932 } 9933 9934 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9935 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9936 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9937 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9938 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9939 } 9940 } 9941 9942 // Cases that are handled by instructions that take permute immediates 9943 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9944 // selected by the instruction selector. 9945 if (V2.isUndef()) { 9946 if (PPC::isSplatShuffleMask(SVOp, 1) || 9947 PPC::isSplatShuffleMask(SVOp, 2) || 9948 PPC::isSplatShuffleMask(SVOp, 4) || 9949 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9950 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9951 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9952 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9953 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9954 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9955 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9956 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9957 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9958 (Subtarget.hasP8Altivec() && ( 9959 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9960 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9961 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9962 return Op; 9963 } 9964 } 9965 9966 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9967 // and produce a fixed permutation. If any of these match, do not lower to 9968 // VPERM. 9969 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9970 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9971 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9972 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9973 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9974 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9975 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9976 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9977 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9978 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9979 (Subtarget.hasP8Altivec() && ( 9980 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9981 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9982 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9983 return Op; 9984 9985 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9986 // perfect shuffle table to emit an optimal matching sequence. 9987 ArrayRef<int> PermMask = SVOp->getMask(); 9988 9989 unsigned PFIndexes[4]; 9990 bool isFourElementShuffle = true; 9991 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9992 unsigned EltNo = 8; // Start out undef. 9993 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9994 if (PermMask[i*4+j] < 0) 9995 continue; // Undef, ignore it. 9996 9997 unsigned ByteSource = PermMask[i*4+j]; 9998 if ((ByteSource & 3) != j) { 9999 isFourElementShuffle = false; 10000 break; 10001 } 10002 10003 if (EltNo == 8) { 10004 EltNo = ByteSource/4; 10005 } else if (EltNo != ByteSource/4) { 10006 isFourElementShuffle = false; 10007 break; 10008 } 10009 } 10010 PFIndexes[i] = EltNo; 10011 } 10012 10013 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10014 // perfect shuffle vector to determine if it is cost effective to do this as 10015 // discrete instructions, or whether we should use a vperm. 10016 // For now, we skip this for little endian until such time as we have a 10017 // little-endian perfect shuffle table. 10018 if (isFourElementShuffle && !isLittleEndian) { 10019 // Compute the index in the perfect shuffle table. 10020 unsigned PFTableIndex = 10021 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10022 10023 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10024 unsigned Cost = (PFEntry >> 30); 10025 10026 // Determining when to avoid vperm is tricky. Many things affect the cost 10027 // of vperm, particularly how many times the perm mask needs to be computed. 10028 // For example, if the perm mask can be hoisted out of a loop or is already 10029 // used (perhaps because there are multiple permutes with the same shuffle 10030 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10031 // the loop requires an extra register. 10032 // 10033 // As a compromise, we only emit discrete instructions if the shuffle can be 10034 // generated in 3 or fewer operations. When we have loop information 10035 // available, if this block is within a loop, we should avoid using vperm 10036 // for 3-operation perms and use a constant pool load instead. 10037 if (Cost < 3) 10038 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10039 } 10040 10041 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10042 // vector that will get spilled to the constant pool. 10043 if (V2.isUndef()) V2 = V1; 10044 10045 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10046 // that it is in input element units, not in bytes. Convert now. 10047 10048 // For little endian, the order of the input vectors is reversed, and 10049 // the permutation mask is complemented with respect to 31. This is 10050 // necessary to produce proper semantics with the big-endian-biased vperm 10051 // instruction. 10052 EVT EltVT = V1.getValueType().getVectorElementType(); 10053 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10054 10055 SmallVector<SDValue, 16> ResultMask; 10056 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10057 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10058 10059 for (unsigned j = 0; j != BytesPerElement; ++j) 10060 if (isLittleEndian) 10061 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10062 dl, MVT::i32)); 10063 else 10064 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10065 MVT::i32)); 10066 } 10067 10068 ShufflesHandledWithVPERM++; 10069 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10070 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10071 LLVM_DEBUG(SVOp->dump()); 10072 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10073 LLVM_DEBUG(VPermMask.dump()); 10074 10075 if (isLittleEndian) 10076 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10077 V2, V1, VPermMask); 10078 else 10079 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10080 V1, V2, VPermMask); 10081 } 10082 10083 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10084 /// vector comparison. If it is, return true and fill in Opc/isDot with 10085 /// information about the intrinsic. 10086 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10087 bool &isDot, const PPCSubtarget &Subtarget) { 10088 unsigned IntrinsicID = 10089 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10090 CompareOpc = -1; 10091 isDot = false; 10092 switch (IntrinsicID) { 10093 default: 10094 return false; 10095 // Comparison predicates. 10096 case Intrinsic::ppc_altivec_vcmpbfp_p: 10097 CompareOpc = 966; 10098 isDot = true; 10099 break; 10100 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10101 CompareOpc = 198; 10102 isDot = true; 10103 break; 10104 case Intrinsic::ppc_altivec_vcmpequb_p: 10105 CompareOpc = 6; 10106 isDot = true; 10107 break; 10108 case Intrinsic::ppc_altivec_vcmpequh_p: 10109 CompareOpc = 70; 10110 isDot = true; 10111 break; 10112 case Intrinsic::ppc_altivec_vcmpequw_p: 10113 CompareOpc = 134; 10114 isDot = true; 10115 break; 10116 case Intrinsic::ppc_altivec_vcmpequd_p: 10117 if (Subtarget.hasP8Altivec()) { 10118 CompareOpc = 199; 10119 isDot = true; 10120 } else 10121 return false; 10122 break; 10123 case Intrinsic::ppc_altivec_vcmpneb_p: 10124 case Intrinsic::ppc_altivec_vcmpneh_p: 10125 case Intrinsic::ppc_altivec_vcmpnew_p: 10126 case Intrinsic::ppc_altivec_vcmpnezb_p: 10127 case Intrinsic::ppc_altivec_vcmpnezh_p: 10128 case Intrinsic::ppc_altivec_vcmpnezw_p: 10129 if (Subtarget.hasP9Altivec()) { 10130 switch (IntrinsicID) { 10131 default: 10132 llvm_unreachable("Unknown comparison intrinsic."); 10133 case Intrinsic::ppc_altivec_vcmpneb_p: 10134 CompareOpc = 7; 10135 break; 10136 case Intrinsic::ppc_altivec_vcmpneh_p: 10137 CompareOpc = 71; 10138 break; 10139 case Intrinsic::ppc_altivec_vcmpnew_p: 10140 CompareOpc = 135; 10141 break; 10142 case Intrinsic::ppc_altivec_vcmpnezb_p: 10143 CompareOpc = 263; 10144 break; 10145 case Intrinsic::ppc_altivec_vcmpnezh_p: 10146 CompareOpc = 327; 10147 break; 10148 case Intrinsic::ppc_altivec_vcmpnezw_p: 10149 CompareOpc = 391; 10150 break; 10151 } 10152 isDot = true; 10153 } else 10154 return false; 10155 break; 10156 case Intrinsic::ppc_altivec_vcmpgefp_p: 10157 CompareOpc = 454; 10158 isDot = true; 10159 break; 10160 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10161 CompareOpc = 710; 10162 isDot = true; 10163 break; 10164 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10165 CompareOpc = 774; 10166 isDot = true; 10167 break; 10168 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10169 CompareOpc = 838; 10170 isDot = true; 10171 break; 10172 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10173 CompareOpc = 902; 10174 isDot = true; 10175 break; 10176 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10177 if (Subtarget.hasP8Altivec()) { 10178 CompareOpc = 967; 10179 isDot = true; 10180 } else 10181 return false; 10182 break; 10183 case Intrinsic::ppc_altivec_vcmpgtub_p: 10184 CompareOpc = 518; 10185 isDot = true; 10186 break; 10187 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10188 CompareOpc = 582; 10189 isDot = true; 10190 break; 10191 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10192 CompareOpc = 646; 10193 isDot = true; 10194 break; 10195 case Intrinsic::ppc_altivec_vcmpgtud_p: 10196 if (Subtarget.hasP8Altivec()) { 10197 CompareOpc = 711; 10198 isDot = true; 10199 } else 10200 return false; 10201 break; 10202 10203 // VSX predicate comparisons use the same infrastructure 10204 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10205 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10206 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10207 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10208 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10209 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10210 if (Subtarget.hasVSX()) { 10211 switch (IntrinsicID) { 10212 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10213 CompareOpc = 99; 10214 break; 10215 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10216 CompareOpc = 115; 10217 break; 10218 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10219 CompareOpc = 107; 10220 break; 10221 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10222 CompareOpc = 67; 10223 break; 10224 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10225 CompareOpc = 83; 10226 break; 10227 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10228 CompareOpc = 75; 10229 break; 10230 } 10231 isDot = true; 10232 } else 10233 return false; 10234 break; 10235 10236 // Normal Comparisons. 10237 case Intrinsic::ppc_altivec_vcmpbfp: 10238 CompareOpc = 966; 10239 break; 10240 case Intrinsic::ppc_altivec_vcmpeqfp: 10241 CompareOpc = 198; 10242 break; 10243 case Intrinsic::ppc_altivec_vcmpequb: 10244 CompareOpc = 6; 10245 break; 10246 case Intrinsic::ppc_altivec_vcmpequh: 10247 CompareOpc = 70; 10248 break; 10249 case Intrinsic::ppc_altivec_vcmpequw: 10250 CompareOpc = 134; 10251 break; 10252 case Intrinsic::ppc_altivec_vcmpequd: 10253 if (Subtarget.hasP8Altivec()) 10254 CompareOpc = 199; 10255 else 10256 return false; 10257 break; 10258 case Intrinsic::ppc_altivec_vcmpneb: 10259 case Intrinsic::ppc_altivec_vcmpneh: 10260 case Intrinsic::ppc_altivec_vcmpnew: 10261 case Intrinsic::ppc_altivec_vcmpnezb: 10262 case Intrinsic::ppc_altivec_vcmpnezh: 10263 case Intrinsic::ppc_altivec_vcmpnezw: 10264 if (Subtarget.hasP9Altivec()) 10265 switch (IntrinsicID) { 10266 default: 10267 llvm_unreachable("Unknown comparison intrinsic."); 10268 case Intrinsic::ppc_altivec_vcmpneb: 10269 CompareOpc = 7; 10270 break; 10271 case Intrinsic::ppc_altivec_vcmpneh: 10272 CompareOpc = 71; 10273 break; 10274 case Intrinsic::ppc_altivec_vcmpnew: 10275 CompareOpc = 135; 10276 break; 10277 case Intrinsic::ppc_altivec_vcmpnezb: 10278 CompareOpc = 263; 10279 break; 10280 case Intrinsic::ppc_altivec_vcmpnezh: 10281 CompareOpc = 327; 10282 break; 10283 case Intrinsic::ppc_altivec_vcmpnezw: 10284 CompareOpc = 391; 10285 break; 10286 } 10287 else 10288 return false; 10289 break; 10290 case Intrinsic::ppc_altivec_vcmpgefp: 10291 CompareOpc = 454; 10292 break; 10293 case Intrinsic::ppc_altivec_vcmpgtfp: 10294 CompareOpc = 710; 10295 break; 10296 case Intrinsic::ppc_altivec_vcmpgtsb: 10297 CompareOpc = 774; 10298 break; 10299 case Intrinsic::ppc_altivec_vcmpgtsh: 10300 CompareOpc = 838; 10301 break; 10302 case Intrinsic::ppc_altivec_vcmpgtsw: 10303 CompareOpc = 902; 10304 break; 10305 case Intrinsic::ppc_altivec_vcmpgtsd: 10306 if (Subtarget.hasP8Altivec()) 10307 CompareOpc = 967; 10308 else 10309 return false; 10310 break; 10311 case Intrinsic::ppc_altivec_vcmpgtub: 10312 CompareOpc = 518; 10313 break; 10314 case Intrinsic::ppc_altivec_vcmpgtuh: 10315 CompareOpc = 582; 10316 break; 10317 case Intrinsic::ppc_altivec_vcmpgtuw: 10318 CompareOpc = 646; 10319 break; 10320 case Intrinsic::ppc_altivec_vcmpgtud: 10321 if (Subtarget.hasP8Altivec()) 10322 CompareOpc = 711; 10323 else 10324 return false; 10325 break; 10326 } 10327 return true; 10328 } 10329 10330 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10331 /// lower, do it, otherwise return null. 10332 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10333 SelectionDAG &DAG) const { 10334 unsigned IntrinsicID = 10335 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10336 10337 SDLoc dl(Op); 10338 10339 if (IntrinsicID == Intrinsic::thread_pointer) { 10340 // Reads the thread pointer register, used for __builtin_thread_pointer. 10341 if (Subtarget.isPPC64()) 10342 return DAG.getRegister(PPC::X13, MVT::i64); 10343 return DAG.getRegister(PPC::R2, MVT::i32); 10344 } 10345 10346 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10347 // opcode number of the comparison. 10348 int CompareOpc; 10349 bool isDot; 10350 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10351 return SDValue(); // Don't custom lower most intrinsics. 10352 10353 // If this is a non-dot comparison, make the VCMP node and we are done. 10354 if (!isDot) { 10355 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10356 Op.getOperand(1), Op.getOperand(2), 10357 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10358 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10359 } 10360 10361 // Create the PPCISD altivec 'dot' comparison node. 10362 SDValue Ops[] = { 10363 Op.getOperand(2), // LHS 10364 Op.getOperand(3), // RHS 10365 DAG.getConstant(CompareOpc, dl, MVT::i32) 10366 }; 10367 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10368 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10369 10370 // Now that we have the comparison, emit a copy from the CR to a GPR. 10371 // This is flagged to the above dot comparison. 10372 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10373 DAG.getRegister(PPC::CR6, MVT::i32), 10374 CompNode.getValue(1)); 10375 10376 // Unpack the result based on how the target uses it. 10377 unsigned BitNo; // Bit # of CR6. 10378 bool InvertBit; // Invert result? 10379 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10380 default: // Can't happen, don't crash on invalid number though. 10381 case 0: // Return the value of the EQ bit of CR6. 10382 BitNo = 0; InvertBit = false; 10383 break; 10384 case 1: // Return the inverted value of the EQ bit of CR6. 10385 BitNo = 0; InvertBit = true; 10386 break; 10387 case 2: // Return the value of the LT bit of CR6. 10388 BitNo = 2; InvertBit = false; 10389 break; 10390 case 3: // Return the inverted value of the LT bit of CR6. 10391 BitNo = 2; InvertBit = true; 10392 break; 10393 } 10394 10395 // Shift the bit into the low position. 10396 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10397 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10398 // Isolate the bit. 10399 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10400 DAG.getConstant(1, dl, MVT::i32)); 10401 10402 // If we are supposed to, toggle the bit. 10403 if (InvertBit) 10404 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10405 DAG.getConstant(1, dl, MVT::i32)); 10406 return Flags; 10407 } 10408 10409 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10410 SelectionDAG &DAG) const { 10411 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10412 // the beginning of the argument list. 10413 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10414 SDLoc DL(Op); 10415 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10416 case Intrinsic::ppc_cfence: { 10417 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10418 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10419 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10420 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10421 Op.getOperand(ArgStart + 1)), 10422 Op.getOperand(0)), 10423 0); 10424 } 10425 default: 10426 break; 10427 } 10428 return SDValue(); 10429 } 10430 10431 // Lower scalar BSWAP64 to xxbrd. 10432 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10433 SDLoc dl(Op); 10434 // MTVSRDD 10435 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10436 Op.getOperand(0)); 10437 // XXBRD 10438 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10439 // MFVSRD 10440 int VectorIndex = 0; 10441 if (Subtarget.isLittleEndian()) 10442 VectorIndex = 1; 10443 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10444 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10445 return Op; 10446 } 10447 10448 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10449 // compared to a value that is atomically loaded (atomic loads zero-extend). 10450 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10451 SelectionDAG &DAG) const { 10452 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10453 "Expecting an atomic compare-and-swap here."); 10454 SDLoc dl(Op); 10455 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10456 EVT MemVT = AtomicNode->getMemoryVT(); 10457 if (MemVT.getSizeInBits() >= 32) 10458 return Op; 10459 10460 SDValue CmpOp = Op.getOperand(2); 10461 // If this is already correctly zero-extended, leave it alone. 10462 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10463 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10464 return Op; 10465 10466 // Clear the high bits of the compare operand. 10467 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10468 SDValue NewCmpOp = 10469 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10470 DAG.getConstant(MaskVal, dl, MVT::i32)); 10471 10472 // Replace the existing compare operand with the properly zero-extended one. 10473 SmallVector<SDValue, 4> Ops; 10474 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10475 Ops.push_back(AtomicNode->getOperand(i)); 10476 Ops[2] = NewCmpOp; 10477 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10478 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10479 auto NodeTy = 10480 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10481 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10482 } 10483 10484 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10485 SelectionDAG &DAG) const { 10486 SDLoc dl(Op); 10487 // Create a stack slot that is 16-byte aligned. 10488 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10489 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10490 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10491 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10492 10493 // Store the input value into Value#0 of the stack slot. 10494 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10495 MachinePointerInfo()); 10496 // Load it out. 10497 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10498 } 10499 10500 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10501 SelectionDAG &DAG) const { 10502 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10503 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10504 10505 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10506 // We have legal lowering for constant indices but not for variable ones. 10507 if (!C) 10508 return SDValue(); 10509 10510 EVT VT = Op.getValueType(); 10511 SDLoc dl(Op); 10512 SDValue V1 = Op.getOperand(0); 10513 SDValue V2 = Op.getOperand(1); 10514 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10515 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10516 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10517 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10518 unsigned InsertAtElement = C->getZExtValue(); 10519 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10520 if (Subtarget.isLittleEndian()) { 10521 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10522 } 10523 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10524 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10525 } 10526 return Op; 10527 } 10528 10529 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10530 SDLoc dl(Op); 10531 if (Op.getValueType() == MVT::v4i32) { 10532 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10533 10534 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10535 // +16 as shift amt. 10536 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10537 SDValue RHSSwap = // = vrlw RHS, 16 10538 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10539 10540 // Shrinkify inputs to v8i16. 10541 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10542 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10543 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10544 10545 // Low parts multiplied together, generating 32-bit results (we ignore the 10546 // top parts). 10547 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10548 LHS, RHS, DAG, dl, MVT::v4i32); 10549 10550 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10551 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10552 // Shift the high parts up 16 bits. 10553 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10554 Neg16, DAG, dl); 10555 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10556 } else if (Op.getValueType() == MVT::v16i8) { 10557 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10558 bool isLittleEndian = Subtarget.isLittleEndian(); 10559 10560 // Multiply the even 8-bit parts, producing 16-bit sums. 10561 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10562 LHS, RHS, DAG, dl, MVT::v8i16); 10563 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10564 10565 // Multiply the odd 8-bit parts, producing 16-bit sums. 10566 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10567 LHS, RHS, DAG, dl, MVT::v8i16); 10568 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10569 10570 // Merge the results together. Because vmuleub and vmuloub are 10571 // instructions with a big-endian bias, we must reverse the 10572 // element numbering and reverse the meaning of "odd" and "even" 10573 // when generating little endian code. 10574 int Ops[16]; 10575 for (unsigned i = 0; i != 8; ++i) { 10576 if (isLittleEndian) { 10577 Ops[i*2 ] = 2*i; 10578 Ops[i*2+1] = 2*i+16; 10579 } else { 10580 Ops[i*2 ] = 2*i+1; 10581 Ops[i*2+1] = 2*i+1+16; 10582 } 10583 } 10584 if (isLittleEndian) 10585 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10586 else 10587 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10588 } else { 10589 llvm_unreachable("Unknown mul to lower!"); 10590 } 10591 } 10592 10593 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10594 10595 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10596 10597 EVT VT = Op.getValueType(); 10598 assert(VT.isVector() && 10599 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10600 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10601 VT == MVT::v16i8) && 10602 "Unexpected vector element type!"); 10603 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10604 "Current subtarget doesn't support smax v2i64!"); 10605 10606 // For vector abs, it can be lowered to: 10607 // abs x 10608 // ==> 10609 // y = -x 10610 // smax(x, y) 10611 10612 SDLoc dl(Op); 10613 SDValue X = Op.getOperand(0); 10614 SDValue Zero = DAG.getConstant(0, dl, VT); 10615 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10616 10617 // SMAX patch https://reviews.llvm.org/D47332 10618 // hasn't landed yet, so use intrinsic first here. 10619 // TODO: Should use SMAX directly once SMAX patch landed 10620 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10621 if (VT == MVT::v2i64) 10622 BifID = Intrinsic::ppc_altivec_vmaxsd; 10623 else if (VT == MVT::v8i16) 10624 BifID = Intrinsic::ppc_altivec_vmaxsh; 10625 else if (VT == MVT::v16i8) 10626 BifID = Intrinsic::ppc_altivec_vmaxsb; 10627 10628 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10629 } 10630 10631 // Custom lowering for fpext vf32 to v2f64 10632 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10633 10634 assert(Op.getOpcode() == ISD::FP_EXTEND && 10635 "Should only be called for ISD::FP_EXTEND"); 10636 10637 // FIXME: handle extends from half precision float vectors on P9. 10638 // We only want to custom lower an extend from v2f32 to v2f64. 10639 if (Op.getValueType() != MVT::v2f64 || 10640 Op.getOperand(0).getValueType() != MVT::v2f32) 10641 return SDValue(); 10642 10643 SDLoc dl(Op); 10644 SDValue Op0 = Op.getOperand(0); 10645 10646 switch (Op0.getOpcode()) { 10647 default: 10648 return SDValue(); 10649 case ISD::EXTRACT_SUBVECTOR: { 10650 assert(Op0.getNumOperands() == 2 && 10651 isa<ConstantSDNode>(Op0->getOperand(1)) && 10652 "Node should have 2 operands with second one being a constant!"); 10653 10654 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10655 return SDValue(); 10656 10657 // Custom lower is only done for high or low doubleword. 10658 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10659 if (Idx % 2 != 0) 10660 return SDValue(); 10661 10662 // Since input is v4f32, at this point Idx is either 0 or 2. 10663 // Shift to get the doubleword position we want. 10664 int DWord = Idx >> 1; 10665 10666 // High and low word positions are different on little endian. 10667 if (Subtarget.isLittleEndian()) 10668 DWord ^= 0x1; 10669 10670 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10671 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10672 } 10673 case ISD::FADD: 10674 case ISD::FMUL: 10675 case ISD::FSUB: { 10676 SDValue NewLoad[2]; 10677 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10678 // Ensure both input are loads. 10679 SDValue LdOp = Op0.getOperand(i); 10680 if (LdOp.getOpcode() != ISD::LOAD) 10681 return SDValue(); 10682 // Generate new load node. 10683 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10684 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10685 NewLoad[i] = DAG.getMemIntrinsicNode( 10686 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10687 LD->getMemoryVT(), LD->getMemOperand()); 10688 } 10689 SDValue NewOp = 10690 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10691 NewLoad[1], Op0.getNode()->getFlags()); 10692 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10693 DAG.getConstant(0, dl, MVT::i32)); 10694 } 10695 case ISD::LOAD: { 10696 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10697 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10698 SDValue NewLd = DAG.getMemIntrinsicNode( 10699 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10700 LD->getMemoryVT(), LD->getMemOperand()); 10701 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10702 DAG.getConstant(0, dl, MVT::i32)); 10703 } 10704 } 10705 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10706 } 10707 10708 /// LowerOperation - Provide custom lowering hooks for some operations. 10709 /// 10710 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10711 switch (Op.getOpcode()) { 10712 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10713 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10714 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10715 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10716 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10717 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10718 case ISD::SETCC: return LowerSETCC(Op, DAG); 10719 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10720 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10721 10722 // Variable argument lowering. 10723 case ISD::VASTART: return LowerVASTART(Op, DAG); 10724 case ISD::VAARG: return LowerVAARG(Op, DAG); 10725 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10726 10727 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10728 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10729 case ISD::GET_DYNAMIC_AREA_OFFSET: 10730 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10731 10732 // Exception handling lowering. 10733 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10734 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10735 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10736 10737 case ISD::LOAD: return LowerLOAD(Op, DAG); 10738 case ISD::STORE: return LowerSTORE(Op, DAG); 10739 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10740 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10741 case ISD::STRICT_FP_TO_UINT: 10742 case ISD::STRICT_FP_TO_SINT: 10743 case ISD::FP_TO_UINT: 10744 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10745 case ISD::STRICT_UINT_TO_FP: 10746 case ISD::STRICT_SINT_TO_FP: 10747 case ISD::UINT_TO_FP: 10748 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10749 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10750 10751 // Lower 64-bit shifts. 10752 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10753 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10754 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10755 10756 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10757 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10758 10759 // Vector-related lowering. 10760 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10761 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10762 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10763 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10764 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10765 case ISD::MUL: return LowerMUL(Op, DAG); 10766 case ISD::ABS: return LowerABS(Op, DAG); 10767 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10768 case ISD::ROTL: return LowerROTL(Op, DAG); 10769 10770 // For counter-based loop handling. 10771 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10772 10773 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10774 10775 // Frame & Return address. 10776 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10777 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10778 10779 case ISD::INTRINSIC_VOID: 10780 return LowerINTRINSIC_VOID(Op, DAG); 10781 case ISD::BSWAP: 10782 return LowerBSWAP(Op, DAG); 10783 case ISD::ATOMIC_CMP_SWAP: 10784 return LowerATOMIC_CMP_SWAP(Op, DAG); 10785 } 10786 } 10787 10788 void PPCTargetLowering::LowerOperationWrapper(SDNode *N, 10789 SmallVectorImpl<SDValue> &Results, 10790 SelectionDAG &DAG) const { 10791 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10792 10793 if (!Res.getNode()) 10794 return; 10795 10796 // Take the return value as-is if original node has only one result. 10797 if (N->getNumValues() == 1) { 10798 Results.push_back(Res); 10799 return; 10800 } 10801 10802 // New node should have the same number of results. 10803 assert((N->getNumValues() == Res->getNumValues()) && 10804 "Lowering returned the wrong number of results!"); 10805 10806 for (unsigned i = 0; i < N->getNumValues(); ++i) 10807 Results.push_back(Res.getValue(i)); 10808 } 10809 10810 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10811 SmallVectorImpl<SDValue>&Results, 10812 SelectionDAG &DAG) const { 10813 SDLoc dl(N); 10814 switch (N->getOpcode()) { 10815 default: 10816 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10817 case ISD::READCYCLECOUNTER: { 10818 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10819 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10820 10821 Results.push_back( 10822 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10823 Results.push_back(RTB.getValue(2)); 10824 break; 10825 } 10826 case ISD::INTRINSIC_W_CHAIN: { 10827 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10828 Intrinsic::loop_decrement) 10829 break; 10830 10831 assert(N->getValueType(0) == MVT::i1 && 10832 "Unexpected result type for CTR decrement intrinsic"); 10833 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10834 N->getValueType(0)); 10835 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10836 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10837 N->getOperand(1)); 10838 10839 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10840 Results.push_back(NewInt.getValue(1)); 10841 break; 10842 } 10843 case ISD::VAARG: { 10844 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10845 return; 10846 10847 EVT VT = N->getValueType(0); 10848 10849 if (VT == MVT::i64) { 10850 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10851 10852 Results.push_back(NewNode); 10853 Results.push_back(NewNode.getValue(1)); 10854 } 10855 return; 10856 } 10857 case ISD::STRICT_FP_TO_SINT: 10858 case ISD::STRICT_FP_TO_UINT: 10859 case ISD::FP_TO_SINT: 10860 case ISD::FP_TO_UINT: 10861 // LowerFP_TO_INT() can only handle f32 and f64. 10862 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10863 MVT::ppcf128) 10864 return; 10865 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10866 return; 10867 case ISD::TRUNCATE: { 10868 if (!N->getValueType(0).isVector()) 10869 return; 10870 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10871 if (Lowered) 10872 Results.push_back(Lowered); 10873 return; 10874 } 10875 case ISD::BITCAST: 10876 // Don't handle bitcast here. 10877 return; 10878 case ISD::FP_EXTEND: 10879 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10880 if (Lowered) 10881 Results.push_back(Lowered); 10882 return; 10883 } 10884 } 10885 10886 //===----------------------------------------------------------------------===// 10887 // Other Lowering Code 10888 //===----------------------------------------------------------------------===// 10889 10890 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10891 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10892 Function *Func = Intrinsic::getDeclaration(M, Id); 10893 return Builder.CreateCall(Func, {}); 10894 } 10895 10896 // The mappings for emitLeading/TrailingFence is taken from 10897 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10898 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10899 Instruction *Inst, 10900 AtomicOrdering Ord) const { 10901 if (Ord == AtomicOrdering::SequentiallyConsistent) 10902 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10903 if (isReleaseOrStronger(Ord)) 10904 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10905 return nullptr; 10906 } 10907 10908 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10909 Instruction *Inst, 10910 AtomicOrdering Ord) const { 10911 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10912 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10913 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10914 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10915 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10916 return Builder.CreateCall( 10917 Intrinsic::getDeclaration( 10918 Builder.GetInsertBlock()->getParent()->getParent(), 10919 Intrinsic::ppc_cfence, {Inst->getType()}), 10920 {Inst}); 10921 // FIXME: Can use isync for rmw operation. 10922 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10923 } 10924 return nullptr; 10925 } 10926 10927 MachineBasicBlock * 10928 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10929 unsigned AtomicSize, 10930 unsigned BinOpcode, 10931 unsigned CmpOpcode, 10932 unsigned CmpPred) const { 10933 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10934 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10935 10936 auto LoadMnemonic = PPC::LDARX; 10937 auto StoreMnemonic = PPC::STDCX; 10938 switch (AtomicSize) { 10939 default: 10940 llvm_unreachable("Unexpected size of atomic entity"); 10941 case 1: 10942 LoadMnemonic = PPC::LBARX; 10943 StoreMnemonic = PPC::STBCX; 10944 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10945 break; 10946 case 2: 10947 LoadMnemonic = PPC::LHARX; 10948 StoreMnemonic = PPC::STHCX; 10949 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10950 break; 10951 case 4: 10952 LoadMnemonic = PPC::LWARX; 10953 StoreMnemonic = PPC::STWCX; 10954 break; 10955 case 8: 10956 LoadMnemonic = PPC::LDARX; 10957 StoreMnemonic = PPC::STDCX; 10958 break; 10959 } 10960 10961 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10962 MachineFunction *F = BB->getParent(); 10963 MachineFunction::iterator It = ++BB->getIterator(); 10964 10965 Register dest = MI.getOperand(0).getReg(); 10966 Register ptrA = MI.getOperand(1).getReg(); 10967 Register ptrB = MI.getOperand(2).getReg(); 10968 Register incr = MI.getOperand(3).getReg(); 10969 DebugLoc dl = MI.getDebugLoc(); 10970 10971 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10972 MachineBasicBlock *loop2MBB = 10973 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10974 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10975 F->insert(It, loopMBB); 10976 if (CmpOpcode) 10977 F->insert(It, loop2MBB); 10978 F->insert(It, exitMBB); 10979 exitMBB->splice(exitMBB->begin(), BB, 10980 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10981 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10982 10983 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10984 Register TmpReg = (!BinOpcode) ? incr : 10985 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10986 : &PPC::GPRCRegClass); 10987 10988 // thisMBB: 10989 // ... 10990 // fallthrough --> loopMBB 10991 BB->addSuccessor(loopMBB); 10992 10993 // loopMBB: 10994 // l[wd]arx dest, ptr 10995 // add r0, dest, incr 10996 // st[wd]cx. r0, ptr 10997 // bne- loopMBB 10998 // fallthrough --> exitMBB 10999 11000 // For max/min... 11001 // loopMBB: 11002 // l[wd]arx dest, ptr 11003 // cmpl?[wd] incr, dest 11004 // bgt exitMBB 11005 // loop2MBB: 11006 // st[wd]cx. dest, ptr 11007 // bne- loopMBB 11008 // fallthrough --> exitMBB 11009 11010 BB = loopMBB; 11011 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11012 .addReg(ptrA).addReg(ptrB); 11013 if (BinOpcode) 11014 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11015 if (CmpOpcode) { 11016 // Signed comparisons of byte or halfword values must be sign-extended. 11017 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11018 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11019 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11020 ExtReg).addReg(dest); 11021 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11022 .addReg(incr).addReg(ExtReg); 11023 } else 11024 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11025 .addReg(incr).addReg(dest); 11026 11027 BuildMI(BB, dl, TII->get(PPC::BCC)) 11028 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11029 BB->addSuccessor(loop2MBB); 11030 BB->addSuccessor(exitMBB); 11031 BB = loop2MBB; 11032 } 11033 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11034 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11035 BuildMI(BB, dl, TII->get(PPC::BCC)) 11036 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11037 BB->addSuccessor(loopMBB); 11038 BB->addSuccessor(exitMBB); 11039 11040 // exitMBB: 11041 // ... 11042 BB = exitMBB; 11043 return BB; 11044 } 11045 11046 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11047 MachineInstr &MI, MachineBasicBlock *BB, 11048 bool is8bit, // operation 11049 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11050 // If we support part-word atomic mnemonics, just use them 11051 if (Subtarget.hasPartwordAtomics()) 11052 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11053 CmpPred); 11054 11055 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11056 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11057 // In 64 bit mode we have to use 64 bits for addresses, even though the 11058 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11059 // registers without caring whether they're 32 or 64, but here we're 11060 // doing actual arithmetic on the addresses. 11061 bool is64bit = Subtarget.isPPC64(); 11062 bool isLittleEndian = Subtarget.isLittleEndian(); 11063 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11064 11065 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11066 MachineFunction *F = BB->getParent(); 11067 MachineFunction::iterator It = ++BB->getIterator(); 11068 11069 Register dest = MI.getOperand(0).getReg(); 11070 Register ptrA = MI.getOperand(1).getReg(); 11071 Register ptrB = MI.getOperand(2).getReg(); 11072 Register incr = MI.getOperand(3).getReg(); 11073 DebugLoc dl = MI.getDebugLoc(); 11074 11075 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11076 MachineBasicBlock *loop2MBB = 11077 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11078 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11079 F->insert(It, loopMBB); 11080 if (CmpOpcode) 11081 F->insert(It, loop2MBB); 11082 F->insert(It, exitMBB); 11083 exitMBB->splice(exitMBB->begin(), BB, 11084 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11085 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11086 11087 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11088 const TargetRegisterClass *RC = 11089 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11090 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11091 11092 Register PtrReg = RegInfo.createVirtualRegister(RC); 11093 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11094 Register ShiftReg = 11095 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11096 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11097 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11098 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11099 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11100 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11101 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11102 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11103 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11104 Register Ptr1Reg; 11105 Register TmpReg = 11106 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11107 11108 // thisMBB: 11109 // ... 11110 // fallthrough --> loopMBB 11111 BB->addSuccessor(loopMBB); 11112 11113 // The 4-byte load must be aligned, while a char or short may be 11114 // anywhere in the word. Hence all this nasty bookkeeping code. 11115 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11116 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11117 // xori shift, shift1, 24 [16] 11118 // rlwinm ptr, ptr1, 0, 0, 29 11119 // slw incr2, incr, shift 11120 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11121 // slw mask, mask2, shift 11122 // loopMBB: 11123 // lwarx tmpDest, ptr 11124 // add tmp, tmpDest, incr2 11125 // andc tmp2, tmpDest, mask 11126 // and tmp3, tmp, mask 11127 // or tmp4, tmp3, tmp2 11128 // stwcx. tmp4, ptr 11129 // bne- loopMBB 11130 // fallthrough --> exitMBB 11131 // srw dest, tmpDest, shift 11132 if (ptrA != ZeroReg) { 11133 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11134 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11135 .addReg(ptrA) 11136 .addReg(ptrB); 11137 } else { 11138 Ptr1Reg = ptrB; 11139 } 11140 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11141 // mode. 11142 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11143 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11144 .addImm(3) 11145 .addImm(27) 11146 .addImm(is8bit ? 28 : 27); 11147 if (!isLittleEndian) 11148 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11149 .addReg(Shift1Reg) 11150 .addImm(is8bit ? 24 : 16); 11151 if (is64bit) 11152 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11153 .addReg(Ptr1Reg) 11154 .addImm(0) 11155 .addImm(61); 11156 else 11157 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11158 .addReg(Ptr1Reg) 11159 .addImm(0) 11160 .addImm(0) 11161 .addImm(29); 11162 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11163 if (is8bit) 11164 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11165 else { 11166 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11167 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11168 .addReg(Mask3Reg) 11169 .addImm(65535); 11170 } 11171 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11172 .addReg(Mask2Reg) 11173 .addReg(ShiftReg); 11174 11175 BB = loopMBB; 11176 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11177 .addReg(ZeroReg) 11178 .addReg(PtrReg); 11179 if (BinOpcode) 11180 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11181 .addReg(Incr2Reg) 11182 .addReg(TmpDestReg); 11183 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11184 .addReg(TmpDestReg) 11185 .addReg(MaskReg); 11186 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11187 if (CmpOpcode) { 11188 // For unsigned comparisons, we can directly compare the shifted values. 11189 // For signed comparisons we shift and sign extend. 11190 Register SReg = RegInfo.createVirtualRegister(GPRC); 11191 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11192 .addReg(TmpDestReg) 11193 .addReg(MaskReg); 11194 unsigned ValueReg = SReg; 11195 unsigned CmpReg = Incr2Reg; 11196 if (CmpOpcode == PPC::CMPW) { 11197 ValueReg = RegInfo.createVirtualRegister(GPRC); 11198 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11199 .addReg(SReg) 11200 .addReg(ShiftReg); 11201 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11202 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11203 .addReg(ValueReg); 11204 ValueReg = ValueSReg; 11205 CmpReg = incr; 11206 } 11207 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11208 .addReg(CmpReg) 11209 .addReg(ValueReg); 11210 BuildMI(BB, dl, TII->get(PPC::BCC)) 11211 .addImm(CmpPred) 11212 .addReg(PPC::CR0) 11213 .addMBB(exitMBB); 11214 BB->addSuccessor(loop2MBB); 11215 BB->addSuccessor(exitMBB); 11216 BB = loop2MBB; 11217 } 11218 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11219 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11220 .addReg(Tmp4Reg) 11221 .addReg(ZeroReg) 11222 .addReg(PtrReg); 11223 BuildMI(BB, dl, TII->get(PPC::BCC)) 11224 .addImm(PPC::PRED_NE) 11225 .addReg(PPC::CR0) 11226 .addMBB(loopMBB); 11227 BB->addSuccessor(loopMBB); 11228 BB->addSuccessor(exitMBB); 11229 11230 // exitMBB: 11231 // ... 11232 BB = exitMBB; 11233 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11234 .addReg(TmpDestReg) 11235 .addReg(ShiftReg); 11236 return BB; 11237 } 11238 11239 llvm::MachineBasicBlock * 11240 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11241 MachineBasicBlock *MBB) const { 11242 DebugLoc DL = MI.getDebugLoc(); 11243 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11244 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11245 11246 MachineFunction *MF = MBB->getParent(); 11247 MachineRegisterInfo &MRI = MF->getRegInfo(); 11248 11249 const BasicBlock *BB = MBB->getBasicBlock(); 11250 MachineFunction::iterator I = ++MBB->getIterator(); 11251 11252 Register DstReg = MI.getOperand(0).getReg(); 11253 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11254 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11255 Register mainDstReg = MRI.createVirtualRegister(RC); 11256 Register restoreDstReg = MRI.createVirtualRegister(RC); 11257 11258 MVT PVT = getPointerTy(MF->getDataLayout()); 11259 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11260 "Invalid Pointer Size!"); 11261 // For v = setjmp(buf), we generate 11262 // 11263 // thisMBB: 11264 // SjLjSetup mainMBB 11265 // bl mainMBB 11266 // v_restore = 1 11267 // b sinkMBB 11268 // 11269 // mainMBB: 11270 // buf[LabelOffset] = LR 11271 // v_main = 0 11272 // 11273 // sinkMBB: 11274 // v = phi(main, restore) 11275 // 11276 11277 MachineBasicBlock *thisMBB = MBB; 11278 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11279 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11280 MF->insert(I, mainMBB); 11281 MF->insert(I, sinkMBB); 11282 11283 MachineInstrBuilder MIB; 11284 11285 // Transfer the remainder of BB and its successor edges to sinkMBB. 11286 sinkMBB->splice(sinkMBB->begin(), MBB, 11287 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11288 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11289 11290 // Note that the structure of the jmp_buf used here is not compatible 11291 // with that used by libc, and is not designed to be. Specifically, it 11292 // stores only those 'reserved' registers that LLVM does not otherwise 11293 // understand how to spill. Also, by convention, by the time this 11294 // intrinsic is called, Clang has already stored the frame address in the 11295 // first slot of the buffer and stack address in the third. Following the 11296 // X86 target code, we'll store the jump address in the second slot. We also 11297 // need to save the TOC pointer (R2) to handle jumps between shared 11298 // libraries, and that will be stored in the fourth slot. The thread 11299 // identifier (R13) is not affected. 11300 11301 // thisMBB: 11302 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11303 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11304 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11305 11306 // Prepare IP either in reg. 11307 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11308 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11309 Register BufReg = MI.getOperand(1).getReg(); 11310 11311 if (Subtarget.is64BitELFABI()) { 11312 setUsesTOCBasePtr(*MBB->getParent()); 11313 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11314 .addReg(PPC::X2) 11315 .addImm(TOCOffset) 11316 .addReg(BufReg) 11317 .cloneMemRefs(MI); 11318 } 11319 11320 // Naked functions never have a base pointer, and so we use r1. For all 11321 // other functions, this decision must be delayed until during PEI. 11322 unsigned BaseReg; 11323 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11324 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11325 else 11326 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11327 11328 MIB = BuildMI(*thisMBB, MI, DL, 11329 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11330 .addReg(BaseReg) 11331 .addImm(BPOffset) 11332 .addReg(BufReg) 11333 .cloneMemRefs(MI); 11334 11335 // Setup 11336 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11337 MIB.addRegMask(TRI->getNoPreservedMask()); 11338 11339 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11340 11341 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11342 .addMBB(mainMBB); 11343 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11344 11345 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11346 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11347 11348 // mainMBB: 11349 // mainDstReg = 0 11350 MIB = 11351 BuildMI(mainMBB, DL, 11352 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11353 11354 // Store IP 11355 if (Subtarget.isPPC64()) { 11356 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11357 .addReg(LabelReg) 11358 .addImm(LabelOffset) 11359 .addReg(BufReg); 11360 } else { 11361 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11362 .addReg(LabelReg) 11363 .addImm(LabelOffset) 11364 .addReg(BufReg); 11365 } 11366 MIB.cloneMemRefs(MI); 11367 11368 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11369 mainMBB->addSuccessor(sinkMBB); 11370 11371 // sinkMBB: 11372 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11373 TII->get(PPC::PHI), DstReg) 11374 .addReg(mainDstReg).addMBB(mainMBB) 11375 .addReg(restoreDstReg).addMBB(thisMBB); 11376 11377 MI.eraseFromParent(); 11378 return sinkMBB; 11379 } 11380 11381 MachineBasicBlock * 11382 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11383 MachineBasicBlock *MBB) const { 11384 DebugLoc DL = MI.getDebugLoc(); 11385 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11386 11387 MachineFunction *MF = MBB->getParent(); 11388 MachineRegisterInfo &MRI = MF->getRegInfo(); 11389 11390 MVT PVT = getPointerTy(MF->getDataLayout()); 11391 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11392 "Invalid Pointer Size!"); 11393 11394 const TargetRegisterClass *RC = 11395 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11396 Register Tmp = MRI.createVirtualRegister(RC); 11397 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11398 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11399 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11400 unsigned BP = 11401 (PVT == MVT::i64) 11402 ? PPC::X30 11403 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11404 : PPC::R30); 11405 11406 MachineInstrBuilder MIB; 11407 11408 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11409 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11410 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11411 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11412 11413 Register BufReg = MI.getOperand(0).getReg(); 11414 11415 // Reload FP (the jumped-to function may not have had a 11416 // frame pointer, and if so, then its r31 will be restored 11417 // as necessary). 11418 if (PVT == MVT::i64) { 11419 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11420 .addImm(0) 11421 .addReg(BufReg); 11422 } else { 11423 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11424 .addImm(0) 11425 .addReg(BufReg); 11426 } 11427 MIB.cloneMemRefs(MI); 11428 11429 // Reload IP 11430 if (PVT == MVT::i64) { 11431 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11432 .addImm(LabelOffset) 11433 .addReg(BufReg); 11434 } else { 11435 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11436 .addImm(LabelOffset) 11437 .addReg(BufReg); 11438 } 11439 MIB.cloneMemRefs(MI); 11440 11441 // Reload SP 11442 if (PVT == MVT::i64) { 11443 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11444 .addImm(SPOffset) 11445 .addReg(BufReg); 11446 } else { 11447 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11448 .addImm(SPOffset) 11449 .addReg(BufReg); 11450 } 11451 MIB.cloneMemRefs(MI); 11452 11453 // Reload BP 11454 if (PVT == MVT::i64) { 11455 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11456 .addImm(BPOffset) 11457 .addReg(BufReg); 11458 } else { 11459 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11460 .addImm(BPOffset) 11461 .addReg(BufReg); 11462 } 11463 MIB.cloneMemRefs(MI); 11464 11465 // Reload TOC 11466 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11467 setUsesTOCBasePtr(*MBB->getParent()); 11468 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11469 .addImm(TOCOffset) 11470 .addReg(BufReg) 11471 .cloneMemRefs(MI); 11472 } 11473 11474 // Jump 11475 BuildMI(*MBB, MI, DL, 11476 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11477 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11478 11479 MI.eraseFromParent(); 11480 return MBB; 11481 } 11482 11483 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11484 // If the function specifically requests inline stack probes, emit them. 11485 if (MF.getFunction().hasFnAttribute("probe-stack")) 11486 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11487 "inline-asm"; 11488 return false; 11489 } 11490 11491 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11492 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11493 unsigned StackAlign = TFI->getStackAlignment(); 11494 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11495 "Unexpected stack alignment"); 11496 // The default stack probe size is 4096 if the function has no 11497 // stack-probe-size attribute. 11498 unsigned StackProbeSize = 4096; 11499 const Function &Fn = MF.getFunction(); 11500 if (Fn.hasFnAttribute("stack-probe-size")) 11501 Fn.getFnAttribute("stack-probe-size") 11502 .getValueAsString() 11503 .getAsInteger(0, StackProbeSize); 11504 // Round down to the stack alignment. 11505 StackProbeSize &= ~(StackAlign - 1); 11506 return StackProbeSize ? StackProbeSize : StackAlign; 11507 } 11508 11509 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11510 // into three phases. In the first phase, it uses pseudo instruction 11511 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11512 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11513 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11514 // MaxCallFrameSize so that it can calculate correct data area pointer. 11515 MachineBasicBlock * 11516 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11517 MachineBasicBlock *MBB) const { 11518 const bool isPPC64 = Subtarget.isPPC64(); 11519 MachineFunction *MF = MBB->getParent(); 11520 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11521 DebugLoc DL = MI.getDebugLoc(); 11522 const unsigned ProbeSize = getStackProbeSize(*MF); 11523 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11524 MachineRegisterInfo &MRI = MF->getRegInfo(); 11525 // The CFG of probing stack looks as 11526 // +-----+ 11527 // | MBB | 11528 // +--+--+ 11529 // | 11530 // +----v----+ 11531 // +--->+ TestMBB +---+ 11532 // | +----+----+ | 11533 // | | | 11534 // | +-----v----+ | 11535 // +---+ BlockMBB | | 11536 // +----------+ | 11537 // | 11538 // +---------+ | 11539 // | TailMBB +<--+ 11540 // +---------+ 11541 // In MBB, calculate previous frame pointer and final stack pointer. 11542 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11543 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11544 // TailMBB is spliced via \p MI. 11545 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11546 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11547 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11548 11549 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11550 MF->insert(MBBIter, TestMBB); 11551 MF->insert(MBBIter, BlockMBB); 11552 MF->insert(MBBIter, TailMBB); 11553 11554 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11555 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11556 11557 Register DstReg = MI.getOperand(0).getReg(); 11558 Register NegSizeReg = MI.getOperand(1).getReg(); 11559 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11560 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11561 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11562 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11563 11564 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11565 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11566 // NegSize. 11567 unsigned ProbeOpc; 11568 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11569 ProbeOpc = 11570 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11571 else 11572 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11573 // and NegSizeReg will be allocated in the same phyreg to avoid 11574 // redundant copy when NegSizeReg has only one use which is current MI and 11575 // will be replaced by PREPARE_PROBED_ALLOCA then. 11576 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11577 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11578 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11579 .addDef(ActualNegSizeReg) 11580 .addReg(NegSizeReg) 11581 .add(MI.getOperand(2)) 11582 .add(MI.getOperand(3)); 11583 11584 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11585 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11586 FinalStackPtr) 11587 .addReg(SPReg) 11588 .addReg(ActualNegSizeReg); 11589 11590 // Materialize a scratch register for update. 11591 int64_t NegProbeSize = -(int64_t)ProbeSize; 11592 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11593 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11594 if (!isInt<16>(NegProbeSize)) { 11595 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11596 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11597 .addImm(NegProbeSize >> 16); 11598 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11599 ScratchReg) 11600 .addReg(TempReg) 11601 .addImm(NegProbeSize & 0xFFFF); 11602 } else 11603 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11604 .addImm(NegProbeSize); 11605 11606 { 11607 // Probing leading residual part. 11608 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11609 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11610 .addReg(ActualNegSizeReg) 11611 .addReg(ScratchReg); 11612 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11613 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11614 .addReg(Div) 11615 .addReg(ScratchReg); 11616 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11617 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11618 .addReg(Mul) 11619 .addReg(ActualNegSizeReg); 11620 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11621 .addReg(FramePointer) 11622 .addReg(SPReg) 11623 .addReg(NegMod); 11624 } 11625 11626 { 11627 // Remaining part should be multiple of ProbeSize. 11628 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11629 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11630 .addReg(SPReg) 11631 .addReg(FinalStackPtr); 11632 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11633 .addImm(PPC::PRED_EQ) 11634 .addReg(CmpResult) 11635 .addMBB(TailMBB); 11636 TestMBB->addSuccessor(BlockMBB); 11637 TestMBB->addSuccessor(TailMBB); 11638 } 11639 11640 { 11641 // Touch the block. 11642 // |P...|P...|P... 11643 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11644 .addReg(FramePointer) 11645 .addReg(SPReg) 11646 .addReg(ScratchReg); 11647 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11648 BlockMBB->addSuccessor(TestMBB); 11649 } 11650 11651 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11652 // DYNAREAOFFSET pseudo instruction to get the future result. 11653 Register MaxCallFrameSizeReg = 11654 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11655 BuildMI(TailMBB, DL, 11656 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11657 MaxCallFrameSizeReg) 11658 .add(MI.getOperand(2)) 11659 .add(MI.getOperand(3)); 11660 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11661 .addReg(SPReg) 11662 .addReg(MaxCallFrameSizeReg); 11663 11664 // Splice instructions after MI to TailMBB. 11665 TailMBB->splice(TailMBB->end(), MBB, 11666 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11667 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11668 MBB->addSuccessor(TestMBB); 11669 11670 // Delete the pseudo instruction. 11671 MI.eraseFromParent(); 11672 11673 ++NumDynamicAllocaProbed; 11674 return TailMBB; 11675 } 11676 11677 MachineBasicBlock * 11678 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11679 MachineBasicBlock *BB) const { 11680 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11681 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11682 if (Subtarget.is64BitELFABI() && 11683 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11684 !Subtarget.isUsingPCRelativeCalls()) { 11685 // Call lowering should have added an r2 operand to indicate a dependence 11686 // on the TOC base pointer value. It can't however, because there is no 11687 // way to mark the dependence as implicit there, and so the stackmap code 11688 // will confuse it with a regular operand. Instead, add the dependence 11689 // here. 11690 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11691 } 11692 11693 return emitPatchPoint(MI, BB); 11694 } 11695 11696 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11697 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11698 return emitEHSjLjSetJmp(MI, BB); 11699 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11700 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11701 return emitEHSjLjLongJmp(MI, BB); 11702 } 11703 11704 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11705 11706 // To "insert" these instructions we actually have to insert their 11707 // control-flow patterns. 11708 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11709 MachineFunction::iterator It = ++BB->getIterator(); 11710 11711 MachineFunction *F = BB->getParent(); 11712 11713 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11714 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11715 MI.getOpcode() == PPC::SELECT_I8) { 11716 SmallVector<MachineOperand, 2> Cond; 11717 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11718 MI.getOpcode() == PPC::SELECT_CC_I8) 11719 Cond.push_back(MI.getOperand(4)); 11720 else 11721 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11722 Cond.push_back(MI.getOperand(1)); 11723 11724 DebugLoc dl = MI.getDebugLoc(); 11725 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11726 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11727 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11728 MI.getOpcode() == PPC::SELECT_CC_F8 || 11729 MI.getOpcode() == PPC::SELECT_CC_F16 || 11730 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11731 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11732 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11733 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11734 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11735 MI.getOpcode() == PPC::SELECT_CC_SPE || 11736 MI.getOpcode() == PPC::SELECT_F4 || 11737 MI.getOpcode() == PPC::SELECT_F8 || 11738 MI.getOpcode() == PPC::SELECT_F16 || 11739 MI.getOpcode() == PPC::SELECT_SPE || 11740 MI.getOpcode() == PPC::SELECT_SPE4 || 11741 MI.getOpcode() == PPC::SELECT_VRRC || 11742 MI.getOpcode() == PPC::SELECT_VSFRC || 11743 MI.getOpcode() == PPC::SELECT_VSSRC || 11744 MI.getOpcode() == PPC::SELECT_VSRC) { 11745 // The incoming instruction knows the destination vreg to set, the 11746 // condition code register to branch on, the true/false values to 11747 // select between, and a branch opcode to use. 11748 11749 // thisMBB: 11750 // ... 11751 // TrueVal = ... 11752 // cmpTY ccX, r1, r2 11753 // bCC copy1MBB 11754 // fallthrough --> copy0MBB 11755 MachineBasicBlock *thisMBB = BB; 11756 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11757 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11758 DebugLoc dl = MI.getDebugLoc(); 11759 F->insert(It, copy0MBB); 11760 F->insert(It, sinkMBB); 11761 11762 // Transfer the remainder of BB and its successor edges to sinkMBB. 11763 sinkMBB->splice(sinkMBB->begin(), BB, 11764 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11765 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11766 11767 // Next, add the true and fallthrough blocks as its successors. 11768 BB->addSuccessor(copy0MBB); 11769 BB->addSuccessor(sinkMBB); 11770 11771 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11772 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11773 MI.getOpcode() == PPC::SELECT_F16 || 11774 MI.getOpcode() == PPC::SELECT_SPE4 || 11775 MI.getOpcode() == PPC::SELECT_SPE || 11776 MI.getOpcode() == PPC::SELECT_VRRC || 11777 MI.getOpcode() == PPC::SELECT_VSFRC || 11778 MI.getOpcode() == PPC::SELECT_VSSRC || 11779 MI.getOpcode() == PPC::SELECT_VSRC) { 11780 BuildMI(BB, dl, TII->get(PPC::BC)) 11781 .addReg(MI.getOperand(1).getReg()) 11782 .addMBB(sinkMBB); 11783 } else { 11784 unsigned SelectPred = MI.getOperand(4).getImm(); 11785 BuildMI(BB, dl, TII->get(PPC::BCC)) 11786 .addImm(SelectPred) 11787 .addReg(MI.getOperand(1).getReg()) 11788 .addMBB(sinkMBB); 11789 } 11790 11791 // copy0MBB: 11792 // %FalseValue = ... 11793 // # fallthrough to sinkMBB 11794 BB = copy0MBB; 11795 11796 // Update machine-CFG edges 11797 BB->addSuccessor(sinkMBB); 11798 11799 // sinkMBB: 11800 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11801 // ... 11802 BB = sinkMBB; 11803 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11804 .addReg(MI.getOperand(3).getReg()) 11805 .addMBB(copy0MBB) 11806 .addReg(MI.getOperand(2).getReg()) 11807 .addMBB(thisMBB); 11808 } else if (MI.getOpcode() == PPC::ReadTB) { 11809 // To read the 64-bit time-base register on a 32-bit target, we read the 11810 // two halves. Should the counter have wrapped while it was being read, we 11811 // need to try again. 11812 // ... 11813 // readLoop: 11814 // mfspr Rx,TBU # load from TBU 11815 // mfspr Ry,TB # load from TB 11816 // mfspr Rz,TBU # load from TBU 11817 // cmpw crX,Rx,Rz # check if 'old'='new' 11818 // bne readLoop # branch if they're not equal 11819 // ... 11820 11821 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11822 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11823 DebugLoc dl = MI.getDebugLoc(); 11824 F->insert(It, readMBB); 11825 F->insert(It, sinkMBB); 11826 11827 // Transfer the remainder of BB and its successor edges to sinkMBB. 11828 sinkMBB->splice(sinkMBB->begin(), BB, 11829 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11830 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11831 11832 BB->addSuccessor(readMBB); 11833 BB = readMBB; 11834 11835 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11836 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11837 Register LoReg = MI.getOperand(0).getReg(); 11838 Register HiReg = MI.getOperand(1).getReg(); 11839 11840 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11841 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11842 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11843 11844 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11845 11846 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11847 .addReg(HiReg) 11848 .addReg(ReadAgainReg); 11849 BuildMI(BB, dl, TII->get(PPC::BCC)) 11850 .addImm(PPC::PRED_NE) 11851 .addReg(CmpReg) 11852 .addMBB(readMBB); 11853 11854 BB->addSuccessor(readMBB); 11855 BB->addSuccessor(sinkMBB); 11856 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11857 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11858 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11859 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11860 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11861 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11862 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11863 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11864 11865 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11866 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11867 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11868 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11869 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11870 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11871 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11872 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11873 11874 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11875 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11876 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11877 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11878 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11879 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11880 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11881 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11882 11883 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11884 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11885 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11886 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11887 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11888 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11889 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11890 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11891 11892 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11893 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11894 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11895 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11896 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11897 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11898 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11899 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11900 11901 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11902 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11903 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11904 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11905 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11906 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11907 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11908 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11909 11910 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11911 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11912 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11913 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11914 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11915 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11916 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11917 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11918 11919 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11920 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11921 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11922 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11923 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11924 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11925 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11926 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11927 11928 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11929 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11930 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11931 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11932 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11933 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11934 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11935 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11936 11937 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11938 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11939 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11940 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11941 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11942 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11943 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11944 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11945 11946 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11947 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11948 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11949 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11950 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11951 BB = EmitAtomicBinary(MI, BB, 4, 0); 11952 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11953 BB = EmitAtomicBinary(MI, BB, 8, 0); 11954 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11955 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11956 (Subtarget.hasPartwordAtomics() && 11957 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11958 (Subtarget.hasPartwordAtomics() && 11959 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11960 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11961 11962 auto LoadMnemonic = PPC::LDARX; 11963 auto StoreMnemonic = PPC::STDCX; 11964 switch (MI.getOpcode()) { 11965 default: 11966 llvm_unreachable("Compare and swap of unknown size"); 11967 case PPC::ATOMIC_CMP_SWAP_I8: 11968 LoadMnemonic = PPC::LBARX; 11969 StoreMnemonic = PPC::STBCX; 11970 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11971 break; 11972 case PPC::ATOMIC_CMP_SWAP_I16: 11973 LoadMnemonic = PPC::LHARX; 11974 StoreMnemonic = PPC::STHCX; 11975 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11976 break; 11977 case PPC::ATOMIC_CMP_SWAP_I32: 11978 LoadMnemonic = PPC::LWARX; 11979 StoreMnemonic = PPC::STWCX; 11980 break; 11981 case PPC::ATOMIC_CMP_SWAP_I64: 11982 LoadMnemonic = PPC::LDARX; 11983 StoreMnemonic = PPC::STDCX; 11984 break; 11985 } 11986 Register dest = MI.getOperand(0).getReg(); 11987 Register ptrA = MI.getOperand(1).getReg(); 11988 Register ptrB = MI.getOperand(2).getReg(); 11989 Register oldval = MI.getOperand(3).getReg(); 11990 Register newval = MI.getOperand(4).getReg(); 11991 DebugLoc dl = MI.getDebugLoc(); 11992 11993 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11994 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11995 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11996 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11997 F->insert(It, loop1MBB); 11998 F->insert(It, loop2MBB); 11999 F->insert(It, midMBB); 12000 F->insert(It, exitMBB); 12001 exitMBB->splice(exitMBB->begin(), BB, 12002 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12003 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12004 12005 // thisMBB: 12006 // ... 12007 // fallthrough --> loopMBB 12008 BB->addSuccessor(loop1MBB); 12009 12010 // loop1MBB: 12011 // l[bhwd]arx dest, ptr 12012 // cmp[wd] dest, oldval 12013 // bne- midMBB 12014 // loop2MBB: 12015 // st[bhwd]cx. newval, ptr 12016 // bne- loopMBB 12017 // b exitBB 12018 // midMBB: 12019 // st[bhwd]cx. dest, ptr 12020 // exitBB: 12021 BB = loop1MBB; 12022 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12023 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12024 .addReg(oldval) 12025 .addReg(dest); 12026 BuildMI(BB, dl, TII->get(PPC::BCC)) 12027 .addImm(PPC::PRED_NE) 12028 .addReg(PPC::CR0) 12029 .addMBB(midMBB); 12030 BB->addSuccessor(loop2MBB); 12031 BB->addSuccessor(midMBB); 12032 12033 BB = loop2MBB; 12034 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12035 .addReg(newval) 12036 .addReg(ptrA) 12037 .addReg(ptrB); 12038 BuildMI(BB, dl, TII->get(PPC::BCC)) 12039 .addImm(PPC::PRED_NE) 12040 .addReg(PPC::CR0) 12041 .addMBB(loop1MBB); 12042 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12043 BB->addSuccessor(loop1MBB); 12044 BB->addSuccessor(exitMBB); 12045 12046 BB = midMBB; 12047 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12048 .addReg(dest) 12049 .addReg(ptrA) 12050 .addReg(ptrB); 12051 BB->addSuccessor(exitMBB); 12052 12053 // exitMBB: 12054 // ... 12055 BB = exitMBB; 12056 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12057 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12058 // We must use 64-bit registers for addresses when targeting 64-bit, 12059 // since we're actually doing arithmetic on them. Other registers 12060 // can be 32-bit. 12061 bool is64bit = Subtarget.isPPC64(); 12062 bool isLittleEndian = Subtarget.isLittleEndian(); 12063 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12064 12065 Register dest = MI.getOperand(0).getReg(); 12066 Register ptrA = MI.getOperand(1).getReg(); 12067 Register ptrB = MI.getOperand(2).getReg(); 12068 Register oldval = MI.getOperand(3).getReg(); 12069 Register newval = MI.getOperand(4).getReg(); 12070 DebugLoc dl = MI.getDebugLoc(); 12071 12072 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12073 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12074 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12075 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12076 F->insert(It, loop1MBB); 12077 F->insert(It, loop2MBB); 12078 F->insert(It, midMBB); 12079 F->insert(It, exitMBB); 12080 exitMBB->splice(exitMBB->begin(), BB, 12081 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12082 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12083 12084 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12085 const TargetRegisterClass *RC = 12086 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12087 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12088 12089 Register PtrReg = RegInfo.createVirtualRegister(RC); 12090 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12091 Register ShiftReg = 12092 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12093 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12094 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12095 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12096 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12097 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12098 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12099 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12100 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12101 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12102 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12103 Register Ptr1Reg; 12104 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12105 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12106 // thisMBB: 12107 // ... 12108 // fallthrough --> loopMBB 12109 BB->addSuccessor(loop1MBB); 12110 12111 // The 4-byte load must be aligned, while a char or short may be 12112 // anywhere in the word. Hence all this nasty bookkeeping code. 12113 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12114 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12115 // xori shift, shift1, 24 [16] 12116 // rlwinm ptr, ptr1, 0, 0, 29 12117 // slw newval2, newval, shift 12118 // slw oldval2, oldval,shift 12119 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12120 // slw mask, mask2, shift 12121 // and newval3, newval2, mask 12122 // and oldval3, oldval2, mask 12123 // loop1MBB: 12124 // lwarx tmpDest, ptr 12125 // and tmp, tmpDest, mask 12126 // cmpw tmp, oldval3 12127 // bne- midMBB 12128 // loop2MBB: 12129 // andc tmp2, tmpDest, mask 12130 // or tmp4, tmp2, newval3 12131 // stwcx. tmp4, ptr 12132 // bne- loop1MBB 12133 // b exitBB 12134 // midMBB: 12135 // stwcx. tmpDest, ptr 12136 // exitBB: 12137 // srw dest, tmpDest, shift 12138 if (ptrA != ZeroReg) { 12139 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12140 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12141 .addReg(ptrA) 12142 .addReg(ptrB); 12143 } else { 12144 Ptr1Reg = ptrB; 12145 } 12146 12147 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12148 // mode. 12149 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12150 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12151 .addImm(3) 12152 .addImm(27) 12153 .addImm(is8bit ? 28 : 27); 12154 if (!isLittleEndian) 12155 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12156 .addReg(Shift1Reg) 12157 .addImm(is8bit ? 24 : 16); 12158 if (is64bit) 12159 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12160 .addReg(Ptr1Reg) 12161 .addImm(0) 12162 .addImm(61); 12163 else 12164 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12165 .addReg(Ptr1Reg) 12166 .addImm(0) 12167 .addImm(0) 12168 .addImm(29); 12169 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12170 .addReg(newval) 12171 .addReg(ShiftReg); 12172 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12173 .addReg(oldval) 12174 .addReg(ShiftReg); 12175 if (is8bit) 12176 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12177 else { 12178 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12179 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12180 .addReg(Mask3Reg) 12181 .addImm(65535); 12182 } 12183 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12184 .addReg(Mask2Reg) 12185 .addReg(ShiftReg); 12186 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12187 .addReg(NewVal2Reg) 12188 .addReg(MaskReg); 12189 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12190 .addReg(OldVal2Reg) 12191 .addReg(MaskReg); 12192 12193 BB = loop1MBB; 12194 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12195 .addReg(ZeroReg) 12196 .addReg(PtrReg); 12197 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12198 .addReg(TmpDestReg) 12199 .addReg(MaskReg); 12200 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12201 .addReg(TmpReg) 12202 .addReg(OldVal3Reg); 12203 BuildMI(BB, dl, TII->get(PPC::BCC)) 12204 .addImm(PPC::PRED_NE) 12205 .addReg(PPC::CR0) 12206 .addMBB(midMBB); 12207 BB->addSuccessor(loop2MBB); 12208 BB->addSuccessor(midMBB); 12209 12210 BB = loop2MBB; 12211 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12212 .addReg(TmpDestReg) 12213 .addReg(MaskReg); 12214 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12215 .addReg(Tmp2Reg) 12216 .addReg(NewVal3Reg); 12217 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12218 .addReg(Tmp4Reg) 12219 .addReg(ZeroReg) 12220 .addReg(PtrReg); 12221 BuildMI(BB, dl, TII->get(PPC::BCC)) 12222 .addImm(PPC::PRED_NE) 12223 .addReg(PPC::CR0) 12224 .addMBB(loop1MBB); 12225 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12226 BB->addSuccessor(loop1MBB); 12227 BB->addSuccessor(exitMBB); 12228 12229 BB = midMBB; 12230 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12231 .addReg(TmpDestReg) 12232 .addReg(ZeroReg) 12233 .addReg(PtrReg); 12234 BB->addSuccessor(exitMBB); 12235 12236 // exitMBB: 12237 // ... 12238 BB = exitMBB; 12239 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12240 .addReg(TmpReg) 12241 .addReg(ShiftReg); 12242 } else if (MI.getOpcode() == PPC::FADDrtz) { 12243 // This pseudo performs an FADD with rounding mode temporarily forced 12244 // to round-to-zero. We emit this via custom inserter since the FPSCR 12245 // is not modeled at the SelectionDAG level. 12246 Register Dest = MI.getOperand(0).getReg(); 12247 Register Src1 = MI.getOperand(1).getReg(); 12248 Register Src2 = MI.getOperand(2).getReg(); 12249 DebugLoc dl = MI.getDebugLoc(); 12250 12251 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12252 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12253 12254 // Save FPSCR value. 12255 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12256 12257 // Set rounding mode to round-to-zero. 12258 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12259 .addImm(31) 12260 .addReg(PPC::RM, RegState::ImplicitDefine); 12261 12262 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12263 .addImm(30) 12264 .addReg(PPC::RM, RegState::ImplicitDefine); 12265 12266 // Perform addition. 12267 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12268 .addReg(Src1) 12269 .addReg(Src2); 12270 if (MI.getFlag(MachineInstr::NoFPExcept)) 12271 MIB.setMIFlag(MachineInstr::NoFPExcept); 12272 12273 // Restore FPSCR value. 12274 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12275 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12276 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12277 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12278 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12279 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12280 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12281 ? PPC::ANDI8_rec 12282 : PPC::ANDI_rec; 12283 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12284 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12285 12286 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12287 Register Dest = RegInfo.createVirtualRegister( 12288 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12289 12290 DebugLoc Dl = MI.getDebugLoc(); 12291 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12292 .addReg(MI.getOperand(1).getReg()) 12293 .addImm(1); 12294 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12295 MI.getOperand(0).getReg()) 12296 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12297 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12298 DebugLoc Dl = MI.getDebugLoc(); 12299 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12300 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12301 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12302 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12303 MI.getOperand(0).getReg()) 12304 .addReg(CRReg); 12305 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12306 DebugLoc Dl = MI.getDebugLoc(); 12307 unsigned Imm = MI.getOperand(1).getImm(); 12308 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12309 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12310 MI.getOperand(0).getReg()) 12311 .addReg(PPC::CR0EQ); 12312 } else if (MI.getOpcode() == PPC::SETRNDi) { 12313 DebugLoc dl = MI.getDebugLoc(); 12314 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12315 12316 // Save FPSCR value. 12317 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12318 12319 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12320 // the following settings: 12321 // 00 Round to nearest 12322 // 01 Round to 0 12323 // 10 Round to +inf 12324 // 11 Round to -inf 12325 12326 // When the operand is immediate, using the two least significant bits of 12327 // the immediate to set the bits 62:63 of FPSCR. 12328 unsigned Mode = MI.getOperand(1).getImm(); 12329 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12330 .addImm(31) 12331 .addReg(PPC::RM, RegState::ImplicitDefine); 12332 12333 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12334 .addImm(30) 12335 .addReg(PPC::RM, RegState::ImplicitDefine); 12336 } else if (MI.getOpcode() == PPC::SETRND) { 12337 DebugLoc dl = MI.getDebugLoc(); 12338 12339 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12340 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12341 // If the target doesn't have DirectMove, we should use stack to do the 12342 // conversion, because the target doesn't have the instructions like mtvsrd 12343 // or mfvsrd to do this conversion directly. 12344 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12345 if (Subtarget.hasDirectMove()) { 12346 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12347 .addReg(SrcReg); 12348 } else { 12349 // Use stack to do the register copy. 12350 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12351 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12352 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12353 if (RC == &PPC::F8RCRegClass) { 12354 // Copy register from F8RCRegClass to G8RCRegclass. 12355 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12356 "Unsupported RegClass."); 12357 12358 StoreOp = PPC::STFD; 12359 LoadOp = PPC::LD; 12360 } else { 12361 // Copy register from G8RCRegClass to F8RCRegclass. 12362 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12363 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12364 "Unsupported RegClass."); 12365 } 12366 12367 MachineFrameInfo &MFI = F->getFrameInfo(); 12368 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12369 12370 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12371 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12372 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12373 MFI.getObjectAlign(FrameIdx)); 12374 12375 // Store the SrcReg into the stack. 12376 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12377 .addReg(SrcReg) 12378 .addImm(0) 12379 .addFrameIndex(FrameIdx) 12380 .addMemOperand(MMOStore); 12381 12382 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12383 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12384 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12385 MFI.getObjectAlign(FrameIdx)); 12386 12387 // Load from the stack where SrcReg is stored, and save to DestReg, 12388 // so we have done the RegClass conversion from RegClass::SrcReg to 12389 // RegClass::DestReg. 12390 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12391 .addImm(0) 12392 .addFrameIndex(FrameIdx) 12393 .addMemOperand(MMOLoad); 12394 } 12395 }; 12396 12397 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12398 12399 // Save FPSCR value. 12400 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12401 12402 // When the operand is gprc register, use two least significant bits of the 12403 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12404 // 12405 // copy OldFPSCRTmpReg, OldFPSCRReg 12406 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12407 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12408 // copy NewFPSCRReg, NewFPSCRTmpReg 12409 // mtfsf 255, NewFPSCRReg 12410 MachineOperand SrcOp = MI.getOperand(1); 12411 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12412 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12413 12414 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12415 12416 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12417 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12418 12419 // The first operand of INSERT_SUBREG should be a register which has 12420 // subregisters, we only care about its RegClass, so we should use an 12421 // IMPLICIT_DEF register. 12422 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12423 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12424 .addReg(ImDefReg) 12425 .add(SrcOp) 12426 .addImm(1); 12427 12428 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12429 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12430 .addReg(OldFPSCRTmpReg) 12431 .addReg(ExtSrcReg) 12432 .addImm(0) 12433 .addImm(62); 12434 12435 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12436 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12437 12438 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12439 // bits of FPSCR. 12440 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12441 .addImm(255) 12442 .addReg(NewFPSCRReg) 12443 .addImm(0) 12444 .addImm(0); 12445 } else if (MI.getOpcode() == PPC::SETFLM) { 12446 DebugLoc Dl = MI.getDebugLoc(); 12447 12448 // Result of setflm is previous FPSCR content, so we need to save it first. 12449 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12450 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12451 12452 // Put bits in 32:63 to FPSCR. 12453 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12454 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12455 .addImm(255) 12456 .addReg(NewFPSCRReg) 12457 .addImm(0) 12458 .addImm(0); 12459 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12460 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12461 return emitProbedAlloca(MI, BB); 12462 } else { 12463 llvm_unreachable("Unexpected instr type to insert"); 12464 } 12465 12466 MI.eraseFromParent(); // The pseudo instruction is gone now. 12467 return BB; 12468 } 12469 12470 //===----------------------------------------------------------------------===// 12471 // Target Optimization Hooks 12472 //===----------------------------------------------------------------------===// 12473 12474 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12475 // For the estimates, convergence is quadratic, so we essentially double the 12476 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12477 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12478 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12479 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12480 if (VT.getScalarType() == MVT::f64) 12481 RefinementSteps++; 12482 return RefinementSteps; 12483 } 12484 12485 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12486 int Enabled, int &RefinementSteps, 12487 bool &UseOneConstNR, 12488 bool Reciprocal) const { 12489 EVT VT = Operand.getValueType(); 12490 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12491 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12492 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12493 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12494 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12495 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12496 12497 // The Newton-Raphson computation with a single constant does not provide 12498 // enough accuracy on some CPUs. 12499 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12500 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12501 } 12502 return SDValue(); 12503 } 12504 12505 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12506 int Enabled, 12507 int &RefinementSteps) const { 12508 EVT VT = Operand.getValueType(); 12509 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12510 (VT == MVT::f64 && Subtarget.hasFRE()) || 12511 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12512 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12513 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12514 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12515 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12516 } 12517 return SDValue(); 12518 } 12519 12520 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12521 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12522 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12523 // enabled for division), this functionality is redundant with the default 12524 // combiner logic (once the division -> reciprocal/multiply transformation 12525 // has taken place). As a result, this matters more for older cores than for 12526 // newer ones. 12527 12528 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12529 // reciprocal if there are two or more FDIVs (for embedded cores with only 12530 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12531 switch (Subtarget.getCPUDirective()) { 12532 default: 12533 return 3; 12534 case PPC::DIR_440: 12535 case PPC::DIR_A2: 12536 case PPC::DIR_E500: 12537 case PPC::DIR_E500mc: 12538 case PPC::DIR_E5500: 12539 return 2; 12540 } 12541 } 12542 12543 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12544 // collapsed, and so we need to look through chains of them. 12545 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12546 int64_t& Offset, SelectionDAG &DAG) { 12547 if (DAG.isBaseWithConstantOffset(Loc)) { 12548 Base = Loc.getOperand(0); 12549 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12550 12551 // The base might itself be a base plus an offset, and if so, accumulate 12552 // that as well. 12553 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12554 } 12555 } 12556 12557 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12558 unsigned Bytes, int Dist, 12559 SelectionDAG &DAG) { 12560 if (VT.getSizeInBits() / 8 != Bytes) 12561 return false; 12562 12563 SDValue BaseLoc = Base->getBasePtr(); 12564 if (Loc.getOpcode() == ISD::FrameIndex) { 12565 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12566 return false; 12567 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12568 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12569 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12570 int FS = MFI.getObjectSize(FI); 12571 int BFS = MFI.getObjectSize(BFI); 12572 if (FS != BFS || FS != (int)Bytes) return false; 12573 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12574 } 12575 12576 SDValue Base1 = Loc, Base2 = BaseLoc; 12577 int64_t Offset1 = 0, Offset2 = 0; 12578 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12579 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12580 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12581 return true; 12582 12583 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12584 const GlobalValue *GV1 = nullptr; 12585 const GlobalValue *GV2 = nullptr; 12586 Offset1 = 0; 12587 Offset2 = 0; 12588 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12589 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12590 if (isGA1 && isGA2 && GV1 == GV2) 12591 return Offset1 == (Offset2 + Dist*Bytes); 12592 return false; 12593 } 12594 12595 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12596 // not enforce equality of the chain operands. 12597 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12598 unsigned Bytes, int Dist, 12599 SelectionDAG &DAG) { 12600 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12601 EVT VT = LS->getMemoryVT(); 12602 SDValue Loc = LS->getBasePtr(); 12603 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12604 } 12605 12606 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12607 EVT VT; 12608 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12609 default: return false; 12610 case Intrinsic::ppc_altivec_lvx: 12611 case Intrinsic::ppc_altivec_lvxl: 12612 case Intrinsic::ppc_vsx_lxvw4x: 12613 case Intrinsic::ppc_vsx_lxvw4x_be: 12614 VT = MVT::v4i32; 12615 break; 12616 case Intrinsic::ppc_vsx_lxvd2x: 12617 case Intrinsic::ppc_vsx_lxvd2x_be: 12618 VT = MVT::v2f64; 12619 break; 12620 case Intrinsic::ppc_altivec_lvebx: 12621 VT = MVT::i8; 12622 break; 12623 case Intrinsic::ppc_altivec_lvehx: 12624 VT = MVT::i16; 12625 break; 12626 case Intrinsic::ppc_altivec_lvewx: 12627 VT = MVT::i32; 12628 break; 12629 } 12630 12631 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12632 } 12633 12634 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12635 EVT VT; 12636 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12637 default: return false; 12638 case Intrinsic::ppc_altivec_stvx: 12639 case Intrinsic::ppc_altivec_stvxl: 12640 case Intrinsic::ppc_vsx_stxvw4x: 12641 VT = MVT::v4i32; 12642 break; 12643 case Intrinsic::ppc_vsx_stxvd2x: 12644 VT = MVT::v2f64; 12645 break; 12646 case Intrinsic::ppc_vsx_stxvw4x_be: 12647 VT = MVT::v4i32; 12648 break; 12649 case Intrinsic::ppc_vsx_stxvd2x_be: 12650 VT = MVT::v2f64; 12651 break; 12652 case Intrinsic::ppc_altivec_stvebx: 12653 VT = MVT::i8; 12654 break; 12655 case Intrinsic::ppc_altivec_stvehx: 12656 VT = MVT::i16; 12657 break; 12658 case Intrinsic::ppc_altivec_stvewx: 12659 VT = MVT::i32; 12660 break; 12661 } 12662 12663 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12664 } 12665 12666 return false; 12667 } 12668 12669 // Return true is there is a nearyby consecutive load to the one provided 12670 // (regardless of alignment). We search up and down the chain, looking though 12671 // token factors and other loads (but nothing else). As a result, a true result 12672 // indicates that it is safe to create a new consecutive load adjacent to the 12673 // load provided. 12674 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12675 SDValue Chain = LD->getChain(); 12676 EVT VT = LD->getMemoryVT(); 12677 12678 SmallSet<SDNode *, 16> LoadRoots; 12679 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12680 SmallSet<SDNode *, 16> Visited; 12681 12682 // First, search up the chain, branching to follow all token-factor operands. 12683 // If we find a consecutive load, then we're done, otherwise, record all 12684 // nodes just above the top-level loads and token factors. 12685 while (!Queue.empty()) { 12686 SDNode *ChainNext = Queue.pop_back_val(); 12687 if (!Visited.insert(ChainNext).second) 12688 continue; 12689 12690 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12691 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12692 return true; 12693 12694 if (!Visited.count(ChainLD->getChain().getNode())) 12695 Queue.push_back(ChainLD->getChain().getNode()); 12696 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12697 for (const SDUse &O : ChainNext->ops()) 12698 if (!Visited.count(O.getNode())) 12699 Queue.push_back(O.getNode()); 12700 } else 12701 LoadRoots.insert(ChainNext); 12702 } 12703 12704 // Second, search down the chain, starting from the top-level nodes recorded 12705 // in the first phase. These top-level nodes are the nodes just above all 12706 // loads and token factors. Starting with their uses, recursively look though 12707 // all loads (just the chain uses) and token factors to find a consecutive 12708 // load. 12709 Visited.clear(); 12710 Queue.clear(); 12711 12712 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12713 IE = LoadRoots.end(); I != IE; ++I) { 12714 Queue.push_back(*I); 12715 12716 while (!Queue.empty()) { 12717 SDNode *LoadRoot = Queue.pop_back_val(); 12718 if (!Visited.insert(LoadRoot).second) 12719 continue; 12720 12721 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12722 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12723 return true; 12724 12725 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12726 UE = LoadRoot->use_end(); UI != UE; ++UI) 12727 if (((isa<MemSDNode>(*UI) && 12728 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12729 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12730 Queue.push_back(*UI); 12731 } 12732 } 12733 12734 return false; 12735 } 12736 12737 /// This function is called when we have proved that a SETCC node can be replaced 12738 /// by subtraction (and other supporting instructions) so that the result of 12739 /// comparison is kept in a GPR instead of CR. This function is purely for 12740 /// codegen purposes and has some flags to guide the codegen process. 12741 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12742 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12743 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12744 12745 // Zero extend the operands to the largest legal integer. Originally, they 12746 // must be of a strictly smaller size. 12747 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12748 DAG.getConstant(Size, DL, MVT::i32)); 12749 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12750 DAG.getConstant(Size, DL, MVT::i32)); 12751 12752 // Swap if needed. Depends on the condition code. 12753 if (Swap) 12754 std::swap(Op0, Op1); 12755 12756 // Subtract extended integers. 12757 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12758 12759 // Move the sign bit to the least significant position and zero out the rest. 12760 // Now the least significant bit carries the result of original comparison. 12761 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12762 DAG.getConstant(Size - 1, DL, MVT::i32)); 12763 auto Final = Shifted; 12764 12765 // Complement the result if needed. Based on the condition code. 12766 if (Complement) 12767 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12768 DAG.getConstant(1, DL, MVT::i64)); 12769 12770 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12771 } 12772 12773 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12774 DAGCombinerInfo &DCI) const { 12775 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12776 12777 SelectionDAG &DAG = DCI.DAG; 12778 SDLoc DL(N); 12779 12780 // Size of integers being compared has a critical role in the following 12781 // analysis, so we prefer to do this when all types are legal. 12782 if (!DCI.isAfterLegalizeDAG()) 12783 return SDValue(); 12784 12785 // If all users of SETCC extend its value to a legal integer type 12786 // then we replace SETCC with a subtraction 12787 for (SDNode::use_iterator UI = N->use_begin(), 12788 UE = N->use_end(); UI != UE; ++UI) { 12789 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12790 return SDValue(); 12791 } 12792 12793 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12794 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12795 12796 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12797 12798 if (OpSize < Size) { 12799 switch (CC) { 12800 default: break; 12801 case ISD::SETULT: 12802 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12803 case ISD::SETULE: 12804 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12805 case ISD::SETUGT: 12806 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12807 case ISD::SETUGE: 12808 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12809 } 12810 } 12811 12812 return SDValue(); 12813 } 12814 12815 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12816 DAGCombinerInfo &DCI) const { 12817 SelectionDAG &DAG = DCI.DAG; 12818 SDLoc dl(N); 12819 12820 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12821 // If we're tracking CR bits, we need to be careful that we don't have: 12822 // trunc(binary-ops(zext(x), zext(y))) 12823 // or 12824 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12825 // such that we're unnecessarily moving things into GPRs when it would be 12826 // better to keep them in CR bits. 12827 12828 // Note that trunc here can be an actual i1 trunc, or can be the effective 12829 // truncation that comes from a setcc or select_cc. 12830 if (N->getOpcode() == ISD::TRUNCATE && 12831 N->getValueType(0) != MVT::i1) 12832 return SDValue(); 12833 12834 if (N->getOperand(0).getValueType() != MVT::i32 && 12835 N->getOperand(0).getValueType() != MVT::i64) 12836 return SDValue(); 12837 12838 if (N->getOpcode() == ISD::SETCC || 12839 N->getOpcode() == ISD::SELECT_CC) { 12840 // If we're looking at a comparison, then we need to make sure that the 12841 // high bits (all except for the first) don't matter the result. 12842 ISD::CondCode CC = 12843 cast<CondCodeSDNode>(N->getOperand( 12844 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12845 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12846 12847 if (ISD::isSignedIntSetCC(CC)) { 12848 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12849 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12850 return SDValue(); 12851 } else if (ISD::isUnsignedIntSetCC(CC)) { 12852 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12853 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12854 !DAG.MaskedValueIsZero(N->getOperand(1), 12855 APInt::getHighBitsSet(OpBits, OpBits-1))) 12856 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12857 : SDValue()); 12858 } else { 12859 // This is neither a signed nor an unsigned comparison, just make sure 12860 // that the high bits are equal. 12861 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12862 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12863 12864 // We don't really care about what is known about the first bit (if 12865 // anything), so clear it in all masks prior to comparing them. 12866 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12867 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12868 12869 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12870 return SDValue(); 12871 } 12872 } 12873 12874 // We now know that the higher-order bits are irrelevant, we just need to 12875 // make sure that all of the intermediate operations are bit operations, and 12876 // all inputs are extensions. 12877 if (N->getOperand(0).getOpcode() != ISD::AND && 12878 N->getOperand(0).getOpcode() != ISD::OR && 12879 N->getOperand(0).getOpcode() != ISD::XOR && 12880 N->getOperand(0).getOpcode() != ISD::SELECT && 12881 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12882 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12883 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12884 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12885 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12886 return SDValue(); 12887 12888 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12889 N->getOperand(1).getOpcode() != ISD::AND && 12890 N->getOperand(1).getOpcode() != ISD::OR && 12891 N->getOperand(1).getOpcode() != ISD::XOR && 12892 N->getOperand(1).getOpcode() != ISD::SELECT && 12893 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12894 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12895 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12896 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12897 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12898 return SDValue(); 12899 12900 SmallVector<SDValue, 4> Inputs; 12901 SmallVector<SDValue, 8> BinOps, PromOps; 12902 SmallPtrSet<SDNode *, 16> Visited; 12903 12904 for (unsigned i = 0; i < 2; ++i) { 12905 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12906 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12907 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12908 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12909 isa<ConstantSDNode>(N->getOperand(i))) 12910 Inputs.push_back(N->getOperand(i)); 12911 else 12912 BinOps.push_back(N->getOperand(i)); 12913 12914 if (N->getOpcode() == ISD::TRUNCATE) 12915 break; 12916 } 12917 12918 // Visit all inputs, collect all binary operations (and, or, xor and 12919 // select) that are all fed by extensions. 12920 while (!BinOps.empty()) { 12921 SDValue BinOp = BinOps.back(); 12922 BinOps.pop_back(); 12923 12924 if (!Visited.insert(BinOp.getNode()).second) 12925 continue; 12926 12927 PromOps.push_back(BinOp); 12928 12929 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12930 // The condition of the select is not promoted. 12931 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12932 continue; 12933 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12934 continue; 12935 12936 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12937 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12938 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12939 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12940 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12941 Inputs.push_back(BinOp.getOperand(i)); 12942 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12943 BinOp.getOperand(i).getOpcode() == ISD::OR || 12944 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12945 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12946 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12947 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12948 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12949 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12950 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12951 BinOps.push_back(BinOp.getOperand(i)); 12952 } else { 12953 // We have an input that is not an extension or another binary 12954 // operation; we'll abort this transformation. 12955 return SDValue(); 12956 } 12957 } 12958 } 12959 12960 // Make sure that this is a self-contained cluster of operations (which 12961 // is not quite the same thing as saying that everything has only one 12962 // use). 12963 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12964 if (isa<ConstantSDNode>(Inputs[i])) 12965 continue; 12966 12967 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12968 UE = Inputs[i].getNode()->use_end(); 12969 UI != UE; ++UI) { 12970 SDNode *User = *UI; 12971 if (User != N && !Visited.count(User)) 12972 return SDValue(); 12973 12974 // Make sure that we're not going to promote the non-output-value 12975 // operand(s) or SELECT or SELECT_CC. 12976 // FIXME: Although we could sometimes handle this, and it does occur in 12977 // practice that one of the condition inputs to the select is also one of 12978 // the outputs, we currently can't deal with this. 12979 if (User->getOpcode() == ISD::SELECT) { 12980 if (User->getOperand(0) == Inputs[i]) 12981 return SDValue(); 12982 } else if (User->getOpcode() == ISD::SELECT_CC) { 12983 if (User->getOperand(0) == Inputs[i] || 12984 User->getOperand(1) == Inputs[i]) 12985 return SDValue(); 12986 } 12987 } 12988 } 12989 12990 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12991 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12992 UE = PromOps[i].getNode()->use_end(); 12993 UI != UE; ++UI) { 12994 SDNode *User = *UI; 12995 if (User != N && !Visited.count(User)) 12996 return SDValue(); 12997 12998 // Make sure that we're not going to promote the non-output-value 12999 // operand(s) or SELECT or SELECT_CC. 13000 // FIXME: Although we could sometimes handle this, and it does occur in 13001 // practice that one of the condition inputs to the select is also one of 13002 // the outputs, we currently can't deal with this. 13003 if (User->getOpcode() == ISD::SELECT) { 13004 if (User->getOperand(0) == PromOps[i]) 13005 return SDValue(); 13006 } else if (User->getOpcode() == ISD::SELECT_CC) { 13007 if (User->getOperand(0) == PromOps[i] || 13008 User->getOperand(1) == PromOps[i]) 13009 return SDValue(); 13010 } 13011 } 13012 } 13013 13014 // Replace all inputs with the extension operand. 13015 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13016 // Constants may have users outside the cluster of to-be-promoted nodes, 13017 // and so we need to replace those as we do the promotions. 13018 if (isa<ConstantSDNode>(Inputs[i])) 13019 continue; 13020 else 13021 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13022 } 13023 13024 std::list<HandleSDNode> PromOpHandles; 13025 for (auto &PromOp : PromOps) 13026 PromOpHandles.emplace_back(PromOp); 13027 13028 // Replace all operations (these are all the same, but have a different 13029 // (i1) return type). DAG.getNode will validate that the types of 13030 // a binary operator match, so go through the list in reverse so that 13031 // we've likely promoted both operands first. Any intermediate truncations or 13032 // extensions disappear. 13033 while (!PromOpHandles.empty()) { 13034 SDValue PromOp = PromOpHandles.back().getValue(); 13035 PromOpHandles.pop_back(); 13036 13037 if (PromOp.getOpcode() == ISD::TRUNCATE || 13038 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13039 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13040 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13041 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13042 PromOp.getOperand(0).getValueType() != MVT::i1) { 13043 // The operand is not yet ready (see comment below). 13044 PromOpHandles.emplace_front(PromOp); 13045 continue; 13046 } 13047 13048 SDValue RepValue = PromOp.getOperand(0); 13049 if (isa<ConstantSDNode>(RepValue)) 13050 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13051 13052 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13053 continue; 13054 } 13055 13056 unsigned C; 13057 switch (PromOp.getOpcode()) { 13058 default: C = 0; break; 13059 case ISD::SELECT: C = 1; break; 13060 case ISD::SELECT_CC: C = 2; break; 13061 } 13062 13063 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13064 PromOp.getOperand(C).getValueType() != MVT::i1) || 13065 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13066 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13067 // The to-be-promoted operands of this node have not yet been 13068 // promoted (this should be rare because we're going through the 13069 // list backward, but if one of the operands has several users in 13070 // this cluster of to-be-promoted nodes, it is possible). 13071 PromOpHandles.emplace_front(PromOp); 13072 continue; 13073 } 13074 13075 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13076 PromOp.getNode()->op_end()); 13077 13078 // If there are any constant inputs, make sure they're replaced now. 13079 for (unsigned i = 0; i < 2; ++i) 13080 if (isa<ConstantSDNode>(Ops[C+i])) 13081 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13082 13083 DAG.ReplaceAllUsesOfValueWith(PromOp, 13084 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13085 } 13086 13087 // Now we're left with the initial truncation itself. 13088 if (N->getOpcode() == ISD::TRUNCATE) 13089 return N->getOperand(0); 13090 13091 // Otherwise, this is a comparison. The operands to be compared have just 13092 // changed type (to i1), but everything else is the same. 13093 return SDValue(N, 0); 13094 } 13095 13096 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13097 DAGCombinerInfo &DCI) const { 13098 SelectionDAG &DAG = DCI.DAG; 13099 SDLoc dl(N); 13100 13101 // If we're tracking CR bits, we need to be careful that we don't have: 13102 // zext(binary-ops(trunc(x), trunc(y))) 13103 // or 13104 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13105 // such that we're unnecessarily moving things into CR bits that can more 13106 // efficiently stay in GPRs. Note that if we're not certain that the high 13107 // bits are set as required by the final extension, we still may need to do 13108 // some masking to get the proper behavior. 13109 13110 // This same functionality is important on PPC64 when dealing with 13111 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13112 // the return values of functions. Because it is so similar, it is handled 13113 // here as well. 13114 13115 if (N->getValueType(0) != MVT::i32 && 13116 N->getValueType(0) != MVT::i64) 13117 return SDValue(); 13118 13119 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13120 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13121 return SDValue(); 13122 13123 if (N->getOperand(0).getOpcode() != ISD::AND && 13124 N->getOperand(0).getOpcode() != ISD::OR && 13125 N->getOperand(0).getOpcode() != ISD::XOR && 13126 N->getOperand(0).getOpcode() != ISD::SELECT && 13127 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13128 return SDValue(); 13129 13130 SmallVector<SDValue, 4> Inputs; 13131 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13132 SmallPtrSet<SDNode *, 16> Visited; 13133 13134 // Visit all inputs, collect all binary operations (and, or, xor and 13135 // select) that are all fed by truncations. 13136 while (!BinOps.empty()) { 13137 SDValue BinOp = BinOps.back(); 13138 BinOps.pop_back(); 13139 13140 if (!Visited.insert(BinOp.getNode()).second) 13141 continue; 13142 13143 PromOps.push_back(BinOp); 13144 13145 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13146 // The condition of the select is not promoted. 13147 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13148 continue; 13149 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13150 continue; 13151 13152 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13153 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13154 Inputs.push_back(BinOp.getOperand(i)); 13155 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13156 BinOp.getOperand(i).getOpcode() == ISD::OR || 13157 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13158 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13159 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13160 BinOps.push_back(BinOp.getOperand(i)); 13161 } else { 13162 // We have an input that is not a truncation or another binary 13163 // operation; we'll abort this transformation. 13164 return SDValue(); 13165 } 13166 } 13167 } 13168 13169 // The operands of a select that must be truncated when the select is 13170 // promoted because the operand is actually part of the to-be-promoted set. 13171 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13172 13173 // Make sure that this is a self-contained cluster of operations (which 13174 // is not quite the same thing as saying that everything has only one 13175 // use). 13176 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13177 if (isa<ConstantSDNode>(Inputs[i])) 13178 continue; 13179 13180 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13181 UE = Inputs[i].getNode()->use_end(); 13182 UI != UE; ++UI) { 13183 SDNode *User = *UI; 13184 if (User != N && !Visited.count(User)) 13185 return SDValue(); 13186 13187 // If we're going to promote the non-output-value operand(s) or SELECT or 13188 // SELECT_CC, record them for truncation. 13189 if (User->getOpcode() == ISD::SELECT) { 13190 if (User->getOperand(0) == Inputs[i]) 13191 SelectTruncOp[0].insert(std::make_pair(User, 13192 User->getOperand(0).getValueType())); 13193 } else if (User->getOpcode() == ISD::SELECT_CC) { 13194 if (User->getOperand(0) == Inputs[i]) 13195 SelectTruncOp[0].insert(std::make_pair(User, 13196 User->getOperand(0).getValueType())); 13197 if (User->getOperand(1) == Inputs[i]) 13198 SelectTruncOp[1].insert(std::make_pair(User, 13199 User->getOperand(1).getValueType())); 13200 } 13201 } 13202 } 13203 13204 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13205 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13206 UE = PromOps[i].getNode()->use_end(); 13207 UI != UE; ++UI) { 13208 SDNode *User = *UI; 13209 if (User != N && !Visited.count(User)) 13210 return SDValue(); 13211 13212 // If we're going to promote the non-output-value operand(s) or SELECT or 13213 // SELECT_CC, record them for truncation. 13214 if (User->getOpcode() == ISD::SELECT) { 13215 if (User->getOperand(0) == PromOps[i]) 13216 SelectTruncOp[0].insert(std::make_pair(User, 13217 User->getOperand(0).getValueType())); 13218 } else if (User->getOpcode() == ISD::SELECT_CC) { 13219 if (User->getOperand(0) == PromOps[i]) 13220 SelectTruncOp[0].insert(std::make_pair(User, 13221 User->getOperand(0).getValueType())); 13222 if (User->getOperand(1) == PromOps[i]) 13223 SelectTruncOp[1].insert(std::make_pair(User, 13224 User->getOperand(1).getValueType())); 13225 } 13226 } 13227 } 13228 13229 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13230 bool ReallyNeedsExt = false; 13231 if (N->getOpcode() != ISD::ANY_EXTEND) { 13232 // If all of the inputs are not already sign/zero extended, then 13233 // we'll still need to do that at the end. 13234 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13235 if (isa<ConstantSDNode>(Inputs[i])) 13236 continue; 13237 13238 unsigned OpBits = 13239 Inputs[i].getOperand(0).getValueSizeInBits(); 13240 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13241 13242 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13243 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13244 APInt::getHighBitsSet(OpBits, 13245 OpBits-PromBits))) || 13246 (N->getOpcode() == ISD::SIGN_EXTEND && 13247 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13248 (OpBits-(PromBits-1)))) { 13249 ReallyNeedsExt = true; 13250 break; 13251 } 13252 } 13253 } 13254 13255 // Replace all inputs, either with the truncation operand, or a 13256 // truncation or extension to the final output type. 13257 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13258 // Constant inputs need to be replaced with the to-be-promoted nodes that 13259 // use them because they might have users outside of the cluster of 13260 // promoted nodes. 13261 if (isa<ConstantSDNode>(Inputs[i])) 13262 continue; 13263 13264 SDValue InSrc = Inputs[i].getOperand(0); 13265 if (Inputs[i].getValueType() == N->getValueType(0)) 13266 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13267 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13268 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13269 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13270 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13271 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13272 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13273 else 13274 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13275 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13276 } 13277 13278 std::list<HandleSDNode> PromOpHandles; 13279 for (auto &PromOp : PromOps) 13280 PromOpHandles.emplace_back(PromOp); 13281 13282 // Replace all operations (these are all the same, but have a different 13283 // (promoted) return type). DAG.getNode will validate that the types of 13284 // a binary operator match, so go through the list in reverse so that 13285 // we've likely promoted both operands first. 13286 while (!PromOpHandles.empty()) { 13287 SDValue PromOp = PromOpHandles.back().getValue(); 13288 PromOpHandles.pop_back(); 13289 13290 unsigned C; 13291 switch (PromOp.getOpcode()) { 13292 default: C = 0; break; 13293 case ISD::SELECT: C = 1; break; 13294 case ISD::SELECT_CC: C = 2; break; 13295 } 13296 13297 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13298 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13299 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13300 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13301 // The to-be-promoted operands of this node have not yet been 13302 // promoted (this should be rare because we're going through the 13303 // list backward, but if one of the operands has several users in 13304 // this cluster of to-be-promoted nodes, it is possible). 13305 PromOpHandles.emplace_front(PromOp); 13306 continue; 13307 } 13308 13309 // For SELECT and SELECT_CC nodes, we do a similar check for any 13310 // to-be-promoted comparison inputs. 13311 if (PromOp.getOpcode() == ISD::SELECT || 13312 PromOp.getOpcode() == ISD::SELECT_CC) { 13313 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13314 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13315 (SelectTruncOp[1].count(PromOp.getNode()) && 13316 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13317 PromOpHandles.emplace_front(PromOp); 13318 continue; 13319 } 13320 } 13321 13322 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13323 PromOp.getNode()->op_end()); 13324 13325 // If this node has constant inputs, then they'll need to be promoted here. 13326 for (unsigned i = 0; i < 2; ++i) { 13327 if (!isa<ConstantSDNode>(Ops[C+i])) 13328 continue; 13329 if (Ops[C+i].getValueType() == N->getValueType(0)) 13330 continue; 13331 13332 if (N->getOpcode() == ISD::SIGN_EXTEND) 13333 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13334 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13335 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13336 else 13337 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13338 } 13339 13340 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13341 // truncate them again to the original value type. 13342 if (PromOp.getOpcode() == ISD::SELECT || 13343 PromOp.getOpcode() == ISD::SELECT_CC) { 13344 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13345 if (SI0 != SelectTruncOp[0].end()) 13346 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13347 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13348 if (SI1 != SelectTruncOp[1].end()) 13349 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13350 } 13351 13352 DAG.ReplaceAllUsesOfValueWith(PromOp, 13353 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13354 } 13355 13356 // Now we're left with the initial extension itself. 13357 if (!ReallyNeedsExt) 13358 return N->getOperand(0); 13359 13360 // To zero extend, just mask off everything except for the first bit (in the 13361 // i1 case). 13362 if (N->getOpcode() == ISD::ZERO_EXTEND) 13363 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13364 DAG.getConstant(APInt::getLowBitsSet( 13365 N->getValueSizeInBits(0), PromBits), 13366 dl, N->getValueType(0))); 13367 13368 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13369 "Invalid extension type"); 13370 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13371 SDValue ShiftCst = 13372 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13373 return DAG.getNode( 13374 ISD::SRA, dl, N->getValueType(0), 13375 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13376 ShiftCst); 13377 } 13378 13379 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13380 DAGCombinerInfo &DCI) const { 13381 assert(N->getOpcode() == ISD::SETCC && 13382 "Should be called with a SETCC node"); 13383 13384 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13385 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13386 SDValue LHS = N->getOperand(0); 13387 SDValue RHS = N->getOperand(1); 13388 13389 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13390 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13391 LHS.hasOneUse()) 13392 std::swap(LHS, RHS); 13393 13394 // x == 0-y --> x+y == 0 13395 // x != 0-y --> x+y != 0 13396 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13397 RHS.hasOneUse()) { 13398 SDLoc DL(N); 13399 SelectionDAG &DAG = DCI.DAG; 13400 EVT VT = N->getValueType(0); 13401 EVT OpVT = LHS.getValueType(); 13402 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13403 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13404 } 13405 } 13406 13407 return DAGCombineTruncBoolExt(N, DCI); 13408 } 13409 13410 // Is this an extending load from an f32 to an f64? 13411 static bool isFPExtLoad(SDValue Op) { 13412 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13413 return LD->getExtensionType() == ISD::EXTLOAD && 13414 Op.getValueType() == MVT::f64; 13415 return false; 13416 } 13417 13418 /// Reduces the number of fp-to-int conversion when building a vector. 13419 /// 13420 /// If this vector is built out of floating to integer conversions, 13421 /// transform it to a vector built out of floating point values followed by a 13422 /// single floating to integer conversion of the vector. 13423 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13424 /// becomes (fptosi (build_vector ($A, $B, ...))) 13425 SDValue PPCTargetLowering:: 13426 combineElementTruncationToVectorTruncation(SDNode *N, 13427 DAGCombinerInfo &DCI) const { 13428 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13429 "Should be called with a BUILD_VECTOR node"); 13430 13431 SelectionDAG &DAG = DCI.DAG; 13432 SDLoc dl(N); 13433 13434 SDValue FirstInput = N->getOperand(0); 13435 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13436 "The input operand must be an fp-to-int conversion."); 13437 13438 // This combine happens after legalization so the fp_to_[su]i nodes are 13439 // already converted to PPCSISD nodes. 13440 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13441 if (FirstConversion == PPCISD::FCTIDZ || 13442 FirstConversion == PPCISD::FCTIDUZ || 13443 FirstConversion == PPCISD::FCTIWZ || 13444 FirstConversion == PPCISD::FCTIWUZ) { 13445 bool IsSplat = true; 13446 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13447 FirstConversion == PPCISD::FCTIWUZ; 13448 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13449 SmallVector<SDValue, 4> Ops; 13450 EVT TargetVT = N->getValueType(0); 13451 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13452 SDValue NextOp = N->getOperand(i); 13453 if (NextOp.getOpcode() != PPCISD::MFVSR) 13454 return SDValue(); 13455 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13456 if (NextConversion != FirstConversion) 13457 return SDValue(); 13458 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13459 // This is not valid if the input was originally double precision. It is 13460 // also not profitable to do unless this is an extending load in which 13461 // case doing this combine will allow us to combine consecutive loads. 13462 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13463 return SDValue(); 13464 if (N->getOperand(i) != FirstInput) 13465 IsSplat = false; 13466 } 13467 13468 // If this is a splat, we leave it as-is since there will be only a single 13469 // fp-to-int conversion followed by a splat of the integer. This is better 13470 // for 32-bit and smaller ints and neutral for 64-bit ints. 13471 if (IsSplat) 13472 return SDValue(); 13473 13474 // Now that we know we have the right type of node, get its operands 13475 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13476 SDValue In = N->getOperand(i).getOperand(0); 13477 if (Is32Bit) { 13478 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13479 // here, we know that all inputs are extending loads so this is safe). 13480 if (In.isUndef()) 13481 Ops.push_back(DAG.getUNDEF(SrcVT)); 13482 else { 13483 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13484 MVT::f32, In.getOperand(0), 13485 DAG.getIntPtrConstant(1, dl)); 13486 Ops.push_back(Trunc); 13487 } 13488 } else 13489 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13490 } 13491 13492 unsigned Opcode; 13493 if (FirstConversion == PPCISD::FCTIDZ || 13494 FirstConversion == PPCISD::FCTIWZ) 13495 Opcode = ISD::FP_TO_SINT; 13496 else 13497 Opcode = ISD::FP_TO_UINT; 13498 13499 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13500 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13501 return DAG.getNode(Opcode, dl, TargetVT, BV); 13502 } 13503 return SDValue(); 13504 } 13505 13506 /// Reduce the number of loads when building a vector. 13507 /// 13508 /// Building a vector out of multiple loads can be converted to a load 13509 /// of the vector type if the loads are consecutive. If the loads are 13510 /// consecutive but in descending order, a shuffle is added at the end 13511 /// to reorder the vector. 13512 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13513 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13514 "Should be called with a BUILD_VECTOR node"); 13515 13516 SDLoc dl(N); 13517 13518 // Return early for non byte-sized type, as they can't be consecutive. 13519 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13520 return SDValue(); 13521 13522 bool InputsAreConsecutiveLoads = true; 13523 bool InputsAreReverseConsecutive = true; 13524 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13525 SDValue FirstInput = N->getOperand(0); 13526 bool IsRoundOfExtLoad = false; 13527 13528 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13529 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13530 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13531 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13532 } 13533 // Not a build vector of (possibly fp_rounded) loads. 13534 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13535 N->getNumOperands() == 1) 13536 return SDValue(); 13537 13538 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13539 // If any inputs are fp_round(extload), they all must be. 13540 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13541 return SDValue(); 13542 13543 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13544 N->getOperand(i); 13545 if (NextInput.getOpcode() != ISD::LOAD) 13546 return SDValue(); 13547 13548 SDValue PreviousInput = 13549 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13550 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13551 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13552 13553 // If any inputs are fp_round(extload), they all must be. 13554 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13555 return SDValue(); 13556 13557 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13558 InputsAreConsecutiveLoads = false; 13559 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13560 InputsAreReverseConsecutive = false; 13561 13562 // Exit early if the loads are neither consecutive nor reverse consecutive. 13563 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13564 return SDValue(); 13565 } 13566 13567 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13568 "The loads cannot be both consecutive and reverse consecutive."); 13569 13570 SDValue FirstLoadOp = 13571 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13572 SDValue LastLoadOp = 13573 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13574 N->getOperand(N->getNumOperands()-1); 13575 13576 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13577 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13578 if (InputsAreConsecutiveLoads) { 13579 assert(LD1 && "Input needs to be a LoadSDNode."); 13580 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13581 LD1->getBasePtr(), LD1->getPointerInfo(), 13582 LD1->getAlignment()); 13583 } 13584 if (InputsAreReverseConsecutive) { 13585 assert(LDL && "Input needs to be a LoadSDNode."); 13586 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13587 LDL->getBasePtr(), LDL->getPointerInfo(), 13588 LDL->getAlignment()); 13589 SmallVector<int, 16> Ops; 13590 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13591 Ops.push_back(i); 13592 13593 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13594 DAG.getUNDEF(N->getValueType(0)), Ops); 13595 } 13596 return SDValue(); 13597 } 13598 13599 // This function adds the required vector_shuffle needed to get 13600 // the elements of the vector extract in the correct position 13601 // as specified by the CorrectElems encoding. 13602 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13603 SDValue Input, uint64_t Elems, 13604 uint64_t CorrectElems) { 13605 SDLoc dl(N); 13606 13607 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13608 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13609 13610 // Knowing the element indices being extracted from the original 13611 // vector and the order in which they're being inserted, just put 13612 // them at element indices required for the instruction. 13613 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13614 if (DAG.getDataLayout().isLittleEndian()) 13615 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13616 else 13617 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13618 CorrectElems = CorrectElems >> 8; 13619 Elems = Elems >> 8; 13620 } 13621 13622 SDValue Shuffle = 13623 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13624 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13625 13626 EVT VT = N->getValueType(0); 13627 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13628 13629 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13630 Input.getValueType().getVectorElementType(), 13631 VT.getVectorNumElements()); 13632 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13633 DAG.getValueType(ExtVT)); 13634 } 13635 13636 // Look for build vector patterns where input operands come from sign 13637 // extended vector_extract elements of specific indices. If the correct indices 13638 // aren't used, add a vector shuffle to fix up the indices and create 13639 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13640 // during instruction selection. 13641 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13642 // This array encodes the indices that the vector sign extend instructions 13643 // extract from when extending from one type to another for both BE and LE. 13644 // The right nibble of each byte corresponds to the LE incides. 13645 // and the left nibble of each byte corresponds to the BE incides. 13646 // For example: 0x3074B8FC byte->word 13647 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13648 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13649 // For example: 0x000070F8 byte->double word 13650 // For LE: the allowed indices are: 0x0,0x8 13651 // For BE: the allowed indices are: 0x7,0xF 13652 uint64_t TargetElems[] = { 13653 0x3074B8FC, // b->w 13654 0x000070F8, // b->d 13655 0x10325476, // h->w 13656 0x00003074, // h->d 13657 0x00001032, // w->d 13658 }; 13659 13660 uint64_t Elems = 0; 13661 int Index; 13662 SDValue Input; 13663 13664 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13665 if (!Op) 13666 return false; 13667 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13668 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13669 return false; 13670 13671 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13672 // of the right width. 13673 SDValue Extract = Op.getOperand(0); 13674 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13675 Extract = Extract.getOperand(0); 13676 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13677 return false; 13678 13679 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13680 if (!ExtOp) 13681 return false; 13682 13683 Index = ExtOp->getZExtValue(); 13684 if (Input && Input != Extract.getOperand(0)) 13685 return false; 13686 13687 if (!Input) 13688 Input = Extract.getOperand(0); 13689 13690 Elems = Elems << 8; 13691 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13692 Elems |= Index; 13693 13694 return true; 13695 }; 13696 13697 // If the build vector operands aren't sign extended vector extracts, 13698 // of the same input vector, then return. 13699 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13700 if (!isSExtOfVecExtract(N->getOperand(i))) { 13701 return SDValue(); 13702 } 13703 } 13704 13705 // If the vector extract indicies are not correct, add the appropriate 13706 // vector_shuffle. 13707 int TgtElemArrayIdx; 13708 int InputSize = Input.getValueType().getScalarSizeInBits(); 13709 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13710 if (InputSize + OutputSize == 40) 13711 TgtElemArrayIdx = 0; 13712 else if (InputSize + OutputSize == 72) 13713 TgtElemArrayIdx = 1; 13714 else if (InputSize + OutputSize == 48) 13715 TgtElemArrayIdx = 2; 13716 else if (InputSize + OutputSize == 80) 13717 TgtElemArrayIdx = 3; 13718 else if (InputSize + OutputSize == 96) 13719 TgtElemArrayIdx = 4; 13720 else 13721 return SDValue(); 13722 13723 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13724 CorrectElems = DAG.getDataLayout().isLittleEndian() 13725 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13726 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13727 if (Elems != CorrectElems) { 13728 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13729 } 13730 13731 // Regular lowering will catch cases where a shuffle is not needed. 13732 return SDValue(); 13733 } 13734 13735 // Look for the pattern of a load from a narrow width to i128, feeding 13736 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13737 // (LXVRZX). This node represents a zero extending load that will be matched 13738 // to the Load VSX Vector Rightmost instructions. 13739 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13740 SDLoc DL(N); 13741 13742 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13743 if (N->getValueType(0) != MVT::v1i128) 13744 return SDValue(); 13745 13746 SDValue Operand = N->getOperand(0); 13747 // Proceed with the transformation if the operand to the BUILD_VECTOR 13748 // is a load instruction. 13749 if (Operand.getOpcode() != ISD::LOAD) 13750 return SDValue(); 13751 13752 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13753 EVT MemoryType = LD->getMemoryVT(); 13754 13755 // This transformation is only valid if the we are loading either a byte, 13756 // halfword, word, or doubleword. 13757 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13758 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13759 13760 // Ensure that the load from the narrow width is being zero extended to i128. 13761 if (!ValidLDType || 13762 (LD->getExtensionType() != ISD::ZEXTLOAD && 13763 LD->getExtensionType() != ISD::EXTLOAD)) 13764 return SDValue(); 13765 13766 SDValue LoadOps[] = { 13767 LD->getChain(), LD->getBasePtr(), 13768 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13769 13770 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13771 DAG.getVTList(MVT::v1i128, MVT::Other), 13772 LoadOps, MemoryType, LD->getMemOperand()); 13773 } 13774 13775 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13776 DAGCombinerInfo &DCI) const { 13777 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13778 "Should be called with a BUILD_VECTOR node"); 13779 13780 SelectionDAG &DAG = DCI.DAG; 13781 SDLoc dl(N); 13782 13783 if (!Subtarget.hasVSX()) 13784 return SDValue(); 13785 13786 // The target independent DAG combiner will leave a build_vector of 13787 // float-to-int conversions intact. We can generate MUCH better code for 13788 // a float-to-int conversion of a vector of floats. 13789 SDValue FirstInput = N->getOperand(0); 13790 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13791 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13792 if (Reduced) 13793 return Reduced; 13794 } 13795 13796 // If we're building a vector out of consecutive loads, just load that 13797 // vector type. 13798 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13799 if (Reduced) 13800 return Reduced; 13801 13802 // If we're building a vector out of extended elements from another vector 13803 // we have P9 vector integer extend instructions. The code assumes legal 13804 // input types (i.e. it can't handle things like v4i16) so do not run before 13805 // legalization. 13806 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13807 Reduced = combineBVOfVecSExt(N, DAG); 13808 if (Reduced) 13809 return Reduced; 13810 } 13811 13812 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13813 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13814 // is a load from <valid narrow width> to i128. 13815 if (Subtarget.isISA3_1()) { 13816 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13817 if (BVOfZLoad) 13818 return BVOfZLoad; 13819 } 13820 13821 if (N->getValueType(0) != MVT::v2f64) 13822 return SDValue(); 13823 13824 // Looking for: 13825 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13826 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13827 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13828 return SDValue(); 13829 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13830 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13831 return SDValue(); 13832 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13833 return SDValue(); 13834 13835 SDValue Ext1 = FirstInput.getOperand(0); 13836 SDValue Ext2 = N->getOperand(1).getOperand(0); 13837 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13838 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13839 return SDValue(); 13840 13841 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13842 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13843 if (!Ext1Op || !Ext2Op) 13844 return SDValue(); 13845 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13846 Ext1.getOperand(0) != Ext2.getOperand(0)) 13847 return SDValue(); 13848 13849 int FirstElem = Ext1Op->getZExtValue(); 13850 int SecondElem = Ext2Op->getZExtValue(); 13851 int SubvecIdx; 13852 if (FirstElem == 0 && SecondElem == 1) 13853 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13854 else if (FirstElem == 2 && SecondElem == 3) 13855 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13856 else 13857 return SDValue(); 13858 13859 SDValue SrcVec = Ext1.getOperand(0); 13860 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13861 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13862 return DAG.getNode(NodeType, dl, MVT::v2f64, 13863 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13864 } 13865 13866 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13867 DAGCombinerInfo &DCI) const { 13868 assert((N->getOpcode() == ISD::SINT_TO_FP || 13869 N->getOpcode() == ISD::UINT_TO_FP) && 13870 "Need an int -> FP conversion node here"); 13871 13872 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13873 return SDValue(); 13874 13875 SelectionDAG &DAG = DCI.DAG; 13876 SDLoc dl(N); 13877 SDValue Op(N, 0); 13878 13879 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13880 // from the hardware. 13881 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13882 return SDValue(); 13883 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13884 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13885 return SDValue(); 13886 13887 SDValue FirstOperand(Op.getOperand(0)); 13888 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13889 (FirstOperand.getValueType() == MVT::i8 || 13890 FirstOperand.getValueType() == MVT::i16); 13891 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13892 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13893 bool DstDouble = Op.getValueType() == MVT::f64; 13894 unsigned ConvOp = Signed ? 13895 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13896 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13897 SDValue WidthConst = 13898 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13899 dl, false); 13900 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13901 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13902 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13903 DAG.getVTList(MVT::f64, MVT::Other), 13904 Ops, MVT::i8, LDN->getMemOperand()); 13905 13906 // For signed conversion, we need to sign-extend the value in the VSR 13907 if (Signed) { 13908 SDValue ExtOps[] = { Ld, WidthConst }; 13909 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13910 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13911 } else 13912 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13913 } 13914 13915 13916 // For i32 intermediate values, unfortunately, the conversion functions 13917 // leave the upper 32 bits of the value are undefined. Within the set of 13918 // scalar instructions, we have no method for zero- or sign-extending the 13919 // value. Thus, we cannot handle i32 intermediate values here. 13920 if (Op.getOperand(0).getValueType() == MVT::i32) 13921 return SDValue(); 13922 13923 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13924 "UINT_TO_FP is supported only with FPCVT"); 13925 13926 // If we have FCFIDS, then use it when converting to single-precision. 13927 // Otherwise, convert to double-precision and then round. 13928 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13929 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13930 : PPCISD::FCFIDS) 13931 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13932 : PPCISD::FCFID); 13933 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13934 ? MVT::f32 13935 : MVT::f64; 13936 13937 // If we're converting from a float, to an int, and back to a float again, 13938 // then we don't need the store/load pair at all. 13939 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13940 Subtarget.hasFPCVT()) || 13941 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13942 SDValue Src = Op.getOperand(0).getOperand(0); 13943 if (Src.getValueType() == MVT::f32) { 13944 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13945 DCI.AddToWorklist(Src.getNode()); 13946 } else if (Src.getValueType() != MVT::f64) { 13947 // Make sure that we don't pick up a ppc_fp128 source value. 13948 return SDValue(); 13949 } 13950 13951 unsigned FCTOp = 13952 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13953 PPCISD::FCTIDUZ; 13954 13955 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13956 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13957 13958 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13959 FP = DAG.getNode(ISD::FP_ROUND, dl, 13960 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13961 DCI.AddToWorklist(FP.getNode()); 13962 } 13963 13964 return FP; 13965 } 13966 13967 return SDValue(); 13968 } 13969 13970 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13971 // builtins) into loads with swaps. 13972 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13973 DAGCombinerInfo &DCI) const { 13974 SelectionDAG &DAG = DCI.DAG; 13975 SDLoc dl(N); 13976 SDValue Chain; 13977 SDValue Base; 13978 MachineMemOperand *MMO; 13979 13980 switch (N->getOpcode()) { 13981 default: 13982 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13983 case ISD::LOAD: { 13984 LoadSDNode *LD = cast<LoadSDNode>(N); 13985 Chain = LD->getChain(); 13986 Base = LD->getBasePtr(); 13987 MMO = LD->getMemOperand(); 13988 // If the MMO suggests this isn't a load of a full vector, leave 13989 // things alone. For a built-in, we have to make the change for 13990 // correctness, so if there is a size problem that will be a bug. 13991 if (MMO->getSize() < 16) 13992 return SDValue(); 13993 break; 13994 } 13995 case ISD::INTRINSIC_W_CHAIN: { 13996 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13997 Chain = Intrin->getChain(); 13998 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13999 // us what we want. Get operand 2 instead. 14000 Base = Intrin->getOperand(2); 14001 MMO = Intrin->getMemOperand(); 14002 break; 14003 } 14004 } 14005 14006 MVT VecTy = N->getValueType(0).getSimpleVT(); 14007 14008 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14009 // aligned and the type is a vector with elements up to 4 bytes 14010 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14011 VecTy.getScalarSizeInBits() <= 32) { 14012 return SDValue(); 14013 } 14014 14015 SDValue LoadOps[] = { Chain, Base }; 14016 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14017 DAG.getVTList(MVT::v2f64, MVT::Other), 14018 LoadOps, MVT::v2f64, MMO); 14019 14020 DCI.AddToWorklist(Load.getNode()); 14021 Chain = Load.getValue(1); 14022 SDValue Swap = DAG.getNode( 14023 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14024 DCI.AddToWorklist(Swap.getNode()); 14025 14026 // Add a bitcast if the resulting load type doesn't match v2f64. 14027 if (VecTy != MVT::v2f64) { 14028 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14029 DCI.AddToWorklist(N.getNode()); 14030 // Package {bitcast value, swap's chain} to match Load's shape. 14031 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14032 N, Swap.getValue(1)); 14033 } 14034 14035 return Swap; 14036 } 14037 14038 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14039 // builtins) into stores with swaps. 14040 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14041 DAGCombinerInfo &DCI) const { 14042 SelectionDAG &DAG = DCI.DAG; 14043 SDLoc dl(N); 14044 SDValue Chain; 14045 SDValue Base; 14046 unsigned SrcOpnd; 14047 MachineMemOperand *MMO; 14048 14049 switch (N->getOpcode()) { 14050 default: 14051 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14052 case ISD::STORE: { 14053 StoreSDNode *ST = cast<StoreSDNode>(N); 14054 Chain = ST->getChain(); 14055 Base = ST->getBasePtr(); 14056 MMO = ST->getMemOperand(); 14057 SrcOpnd = 1; 14058 // If the MMO suggests this isn't a store of a full vector, leave 14059 // things alone. For a built-in, we have to make the change for 14060 // correctness, so if there is a size problem that will be a bug. 14061 if (MMO->getSize() < 16) 14062 return SDValue(); 14063 break; 14064 } 14065 case ISD::INTRINSIC_VOID: { 14066 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14067 Chain = Intrin->getChain(); 14068 // Intrin->getBasePtr() oddly does not get what we want. 14069 Base = Intrin->getOperand(3); 14070 MMO = Intrin->getMemOperand(); 14071 SrcOpnd = 2; 14072 break; 14073 } 14074 } 14075 14076 SDValue Src = N->getOperand(SrcOpnd); 14077 MVT VecTy = Src.getValueType().getSimpleVT(); 14078 14079 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14080 // aligned and the type is a vector with elements up to 4 bytes 14081 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14082 VecTy.getScalarSizeInBits() <= 32) { 14083 return SDValue(); 14084 } 14085 14086 // All stores are done as v2f64 and possible bit cast. 14087 if (VecTy != MVT::v2f64) { 14088 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14089 DCI.AddToWorklist(Src.getNode()); 14090 } 14091 14092 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14093 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14094 DCI.AddToWorklist(Swap.getNode()); 14095 Chain = Swap.getValue(1); 14096 SDValue StoreOps[] = { Chain, Swap, Base }; 14097 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14098 DAG.getVTList(MVT::Other), 14099 StoreOps, VecTy, MMO); 14100 DCI.AddToWorklist(Store.getNode()); 14101 return Store; 14102 } 14103 14104 // Handle DAG combine for STORE (FP_TO_INT F). 14105 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14106 DAGCombinerInfo &DCI) const { 14107 14108 SelectionDAG &DAG = DCI.DAG; 14109 SDLoc dl(N); 14110 unsigned Opcode = N->getOperand(1).getOpcode(); 14111 14112 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14113 && "Not a FP_TO_INT Instruction!"); 14114 14115 SDValue Val = N->getOperand(1).getOperand(0); 14116 EVT Op1VT = N->getOperand(1).getValueType(); 14117 EVT ResVT = Val.getValueType(); 14118 14119 if (!isTypeLegal(ResVT)) 14120 return SDValue(); 14121 14122 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14123 bool ValidTypeForStoreFltAsInt = 14124 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14125 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14126 14127 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14128 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14129 return SDValue(); 14130 14131 // Extend f32 values to f64 14132 if (ResVT.getScalarSizeInBits() == 32) { 14133 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14134 DCI.AddToWorklist(Val.getNode()); 14135 } 14136 14137 // Set signed or unsigned conversion opcode. 14138 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14139 PPCISD::FP_TO_SINT_IN_VSR : 14140 PPCISD::FP_TO_UINT_IN_VSR; 14141 14142 Val = DAG.getNode(ConvOpcode, 14143 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14144 DCI.AddToWorklist(Val.getNode()); 14145 14146 // Set number of bytes being converted. 14147 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14148 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14149 DAG.getIntPtrConstant(ByteSize, dl, false), 14150 DAG.getValueType(Op1VT) }; 14151 14152 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14153 DAG.getVTList(MVT::Other), Ops, 14154 cast<StoreSDNode>(N)->getMemoryVT(), 14155 cast<StoreSDNode>(N)->getMemOperand()); 14156 14157 DCI.AddToWorklist(Val.getNode()); 14158 return Val; 14159 } 14160 14161 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14162 // Check that the source of the element keeps flipping 14163 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14164 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14165 for (int i = 1, e = Mask.size(); i < e; i++) { 14166 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14167 return false; 14168 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14169 return false; 14170 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14171 } 14172 return true; 14173 } 14174 14175 static bool isSplatBV(SDValue Op) { 14176 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14177 return false; 14178 SDValue FirstOp; 14179 14180 // Find first non-undef input. 14181 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14182 FirstOp = Op.getOperand(i); 14183 if (!FirstOp.isUndef()) 14184 break; 14185 } 14186 14187 // All inputs are undef or the same as the first non-undef input. 14188 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14189 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14190 return false; 14191 return true; 14192 } 14193 14194 static SDValue isScalarToVec(SDValue Op) { 14195 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14196 return Op; 14197 if (Op.getOpcode() != ISD::BITCAST) 14198 return SDValue(); 14199 Op = Op.getOperand(0); 14200 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14201 return Op; 14202 return SDValue(); 14203 } 14204 14205 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14206 int LHSMaxIdx, int RHSMinIdx, 14207 int RHSMaxIdx, int HalfVec) { 14208 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14209 int Idx = ShuffV[i]; 14210 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14211 ShuffV[i] += HalfVec; 14212 } 14213 return; 14214 } 14215 14216 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14217 // the original is: 14218 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14219 // In such a case, just change the shuffle mask to extract the element 14220 // from the permuted index. 14221 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14222 SDLoc dl(OrigSToV); 14223 EVT VT = OrigSToV.getValueType(); 14224 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14225 "Expecting a SCALAR_TO_VECTOR here"); 14226 SDValue Input = OrigSToV.getOperand(0); 14227 14228 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14229 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14230 SDValue OrigVector = Input.getOperand(0); 14231 14232 // Can't handle non-const element indices or different vector types 14233 // for the input to the extract and the output of the scalar_to_vector. 14234 if (Idx && VT == OrigVector.getValueType()) { 14235 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14236 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14237 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14238 } 14239 } 14240 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14241 OrigSToV.getOperand(0)); 14242 } 14243 14244 // On little endian subtargets, combine shuffles such as: 14245 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14246 // into: 14247 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14248 // because the latter can be matched to a single instruction merge. 14249 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14250 // to put the value into element zero. Adjust the shuffle mask so that the 14251 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14252 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14253 SelectionDAG &DAG) const { 14254 SDValue LHS = SVN->getOperand(0); 14255 SDValue RHS = SVN->getOperand(1); 14256 auto Mask = SVN->getMask(); 14257 int NumElts = LHS.getValueType().getVectorNumElements(); 14258 SDValue Res(SVN, 0); 14259 SDLoc dl(SVN); 14260 14261 // None of these combines are useful on big endian systems since the ISA 14262 // already has a big endian bias. 14263 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14264 return Res; 14265 14266 // If this is not a shuffle of a shuffle and the first element comes from 14267 // the second vector, canonicalize to the commuted form. This will make it 14268 // more likely to match one of the single instruction patterns. 14269 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14270 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14271 std::swap(LHS, RHS); 14272 Res = DAG.getCommutedVectorShuffle(*SVN); 14273 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14274 } 14275 14276 // Adjust the shuffle mask if either input vector comes from a 14277 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14278 // form (to prevent the need for a swap). 14279 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14280 SDValue SToVLHS = isScalarToVec(LHS); 14281 SDValue SToVRHS = isScalarToVec(RHS); 14282 if (SToVLHS || SToVRHS) { 14283 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14284 : SToVRHS.getValueType().getVectorNumElements(); 14285 int NumEltsOut = ShuffV.size(); 14286 14287 // Initially assume that neither input is permuted. These will be adjusted 14288 // accordingly if either input is. 14289 int LHSMaxIdx = -1; 14290 int RHSMinIdx = -1; 14291 int RHSMaxIdx = -1; 14292 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14293 14294 // Get the permuted scalar to vector nodes for the source(s) that come from 14295 // ISD::SCALAR_TO_VECTOR. 14296 if (SToVLHS) { 14297 // Set up the values for the shuffle vector fixup. 14298 LHSMaxIdx = NumEltsOut / NumEltsIn; 14299 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14300 if (SToVLHS.getValueType() != LHS.getValueType()) 14301 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14302 LHS = SToVLHS; 14303 } 14304 if (SToVRHS) { 14305 RHSMinIdx = NumEltsOut; 14306 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14307 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14308 if (SToVRHS.getValueType() != RHS.getValueType()) 14309 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14310 RHS = SToVRHS; 14311 } 14312 14313 // Fix up the shuffle mask to reflect where the desired element actually is. 14314 // The minimum and maximum indices that correspond to element zero for both 14315 // the LHS and RHS are computed and will control which shuffle mask entries 14316 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14317 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14318 // HalfVec to refer to the corresponding element in the permuted vector. 14319 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14320 HalfVec); 14321 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14322 14323 // We may have simplified away the shuffle. We won't be able to do anything 14324 // further with it here. 14325 if (!isa<ShuffleVectorSDNode>(Res)) 14326 return Res; 14327 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14328 } 14329 14330 // The common case after we commuted the shuffle is that the RHS is a splat 14331 // and we have elements coming in from the splat at indices that are not 14332 // conducive to using a merge. 14333 // Example: 14334 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14335 if (!isSplatBV(RHS)) 14336 return Res; 14337 14338 // We are looking for a mask such that all even elements are from 14339 // one vector and all odd elements from the other. 14340 if (!isAlternatingShuffMask(Mask, NumElts)) 14341 return Res; 14342 14343 // Adjust the mask so we are pulling in the same index from the splat 14344 // as the index from the interesting vector in consecutive elements. 14345 // Example (even elements from first vector): 14346 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14347 if (Mask[0] < NumElts) 14348 for (int i = 1, e = Mask.size(); i < e; i += 2) 14349 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14350 // Example (odd elements from first vector): 14351 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14352 else 14353 for (int i = 0, e = Mask.size(); i < e; i += 2) 14354 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14355 14356 // If the RHS has undefs, we need to remove them since we may have created 14357 // a shuffle that adds those instead of the splat value. 14358 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14359 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14360 14361 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14362 return Res; 14363 } 14364 14365 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14366 LSBaseSDNode *LSBase, 14367 DAGCombinerInfo &DCI) const { 14368 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14369 "Not a reverse memop pattern!"); 14370 14371 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14372 auto Mask = SVN->getMask(); 14373 int i = 0; 14374 auto I = Mask.rbegin(); 14375 auto E = Mask.rend(); 14376 14377 for (; I != E; ++I) { 14378 if (*I != i) 14379 return false; 14380 i++; 14381 } 14382 return true; 14383 }; 14384 14385 SelectionDAG &DAG = DCI.DAG; 14386 EVT VT = SVN->getValueType(0); 14387 14388 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14389 return SDValue(); 14390 14391 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14392 // See comment in PPCVSXSwapRemoval.cpp. 14393 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14394 if (!Subtarget.hasP9Vector()) 14395 return SDValue(); 14396 14397 if(!IsElementReverse(SVN)) 14398 return SDValue(); 14399 14400 if (LSBase->getOpcode() == ISD::LOAD) { 14401 SDLoc dl(SVN); 14402 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14403 return DAG.getMemIntrinsicNode( 14404 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14405 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14406 } 14407 14408 if (LSBase->getOpcode() == ISD::STORE) { 14409 SDLoc dl(LSBase); 14410 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14411 LSBase->getBasePtr()}; 14412 return DAG.getMemIntrinsicNode( 14413 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14414 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14415 } 14416 14417 llvm_unreachable("Expected a load or store node here"); 14418 } 14419 14420 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14421 DAGCombinerInfo &DCI) const { 14422 SelectionDAG &DAG = DCI.DAG; 14423 SDLoc dl(N); 14424 switch (N->getOpcode()) { 14425 default: break; 14426 case ISD::ADD: 14427 return combineADD(N, DCI); 14428 case ISD::SHL: 14429 return combineSHL(N, DCI); 14430 case ISD::SRA: 14431 return combineSRA(N, DCI); 14432 case ISD::SRL: 14433 return combineSRL(N, DCI); 14434 case ISD::MUL: 14435 return combineMUL(N, DCI); 14436 case ISD::FMA: 14437 case PPCISD::FNMSUB: 14438 return combineFMALike(N, DCI); 14439 case PPCISD::SHL: 14440 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14441 return N->getOperand(0); 14442 break; 14443 case PPCISD::SRL: 14444 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14445 return N->getOperand(0); 14446 break; 14447 case PPCISD::SRA: 14448 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14449 if (C->isNullValue() || // 0 >>s V -> 0. 14450 C->isAllOnesValue()) // -1 >>s V -> -1. 14451 return N->getOperand(0); 14452 } 14453 break; 14454 case ISD::SIGN_EXTEND: 14455 case ISD::ZERO_EXTEND: 14456 case ISD::ANY_EXTEND: 14457 return DAGCombineExtBoolTrunc(N, DCI); 14458 case ISD::TRUNCATE: 14459 return combineTRUNCATE(N, DCI); 14460 case ISD::SETCC: 14461 if (SDValue CSCC = combineSetCC(N, DCI)) 14462 return CSCC; 14463 LLVM_FALLTHROUGH; 14464 case ISD::SELECT_CC: 14465 return DAGCombineTruncBoolExt(N, DCI); 14466 case ISD::SINT_TO_FP: 14467 case ISD::UINT_TO_FP: 14468 return combineFPToIntToFP(N, DCI); 14469 case ISD::VECTOR_SHUFFLE: 14470 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14471 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14472 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14473 } 14474 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14475 case ISD::STORE: { 14476 14477 EVT Op1VT = N->getOperand(1).getValueType(); 14478 unsigned Opcode = N->getOperand(1).getOpcode(); 14479 14480 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14481 SDValue Val= combineStoreFPToInt(N, DCI); 14482 if (Val) 14483 return Val; 14484 } 14485 14486 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14487 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14488 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14489 if (Val) 14490 return Val; 14491 } 14492 14493 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14494 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14495 N->getOperand(1).getNode()->hasOneUse() && 14496 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14497 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14498 14499 // STBRX can only handle simple types and it makes no sense to store less 14500 // two bytes in byte-reversed order. 14501 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14502 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14503 break; 14504 14505 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14506 // Do an any-extend to 32-bits if this is a half-word input. 14507 if (BSwapOp.getValueType() == MVT::i16) 14508 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14509 14510 // If the type of BSWAP operand is wider than stored memory width 14511 // it need to be shifted to the right side before STBRX. 14512 if (Op1VT.bitsGT(mVT)) { 14513 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14514 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14515 DAG.getConstant(Shift, dl, MVT::i32)); 14516 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14517 if (Op1VT == MVT::i64) 14518 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14519 } 14520 14521 SDValue Ops[] = { 14522 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14523 }; 14524 return 14525 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14526 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14527 cast<StoreSDNode>(N)->getMemOperand()); 14528 } 14529 14530 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14531 // So it can increase the chance of CSE constant construction. 14532 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14533 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14534 // Need to sign-extended to 64-bits to handle negative values. 14535 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14536 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14537 MemVT.getSizeInBits()); 14538 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14539 14540 // DAG.getTruncStore() can't be used here because it doesn't accept 14541 // the general (base + offset) addressing mode. 14542 // So we use UpdateNodeOperands and setTruncatingStore instead. 14543 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14544 N->getOperand(3)); 14545 cast<StoreSDNode>(N)->setTruncatingStore(true); 14546 return SDValue(N, 0); 14547 } 14548 14549 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14550 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14551 if (Op1VT.isSimple()) { 14552 MVT StoreVT = Op1VT.getSimpleVT(); 14553 if (Subtarget.needsSwapsForVSXMemOps() && 14554 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14555 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14556 return expandVSXStoreForLE(N, DCI); 14557 } 14558 break; 14559 } 14560 case ISD::LOAD: { 14561 LoadSDNode *LD = cast<LoadSDNode>(N); 14562 EVT VT = LD->getValueType(0); 14563 14564 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14565 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14566 if (VT.isSimple()) { 14567 MVT LoadVT = VT.getSimpleVT(); 14568 if (Subtarget.needsSwapsForVSXMemOps() && 14569 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14570 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14571 return expandVSXLoadForLE(N, DCI); 14572 } 14573 14574 // We sometimes end up with a 64-bit integer load, from which we extract 14575 // two single-precision floating-point numbers. This happens with 14576 // std::complex<float>, and other similar structures, because of the way we 14577 // canonicalize structure copies. However, if we lack direct moves, 14578 // then the final bitcasts from the extracted integer values to the 14579 // floating-point numbers turn into store/load pairs. Even with direct moves, 14580 // just loading the two floating-point numbers is likely better. 14581 auto ReplaceTwoFloatLoad = [&]() { 14582 if (VT != MVT::i64) 14583 return false; 14584 14585 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14586 LD->isVolatile()) 14587 return false; 14588 14589 // We're looking for a sequence like this: 14590 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14591 // t16: i64 = srl t13, Constant:i32<32> 14592 // t17: i32 = truncate t16 14593 // t18: f32 = bitcast t17 14594 // t19: i32 = truncate t13 14595 // t20: f32 = bitcast t19 14596 14597 if (!LD->hasNUsesOfValue(2, 0)) 14598 return false; 14599 14600 auto UI = LD->use_begin(); 14601 while (UI.getUse().getResNo() != 0) ++UI; 14602 SDNode *Trunc = *UI++; 14603 while (UI.getUse().getResNo() != 0) ++UI; 14604 SDNode *RightShift = *UI; 14605 if (Trunc->getOpcode() != ISD::TRUNCATE) 14606 std::swap(Trunc, RightShift); 14607 14608 if (Trunc->getOpcode() != ISD::TRUNCATE || 14609 Trunc->getValueType(0) != MVT::i32 || 14610 !Trunc->hasOneUse()) 14611 return false; 14612 if (RightShift->getOpcode() != ISD::SRL || 14613 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14614 RightShift->getConstantOperandVal(1) != 32 || 14615 !RightShift->hasOneUse()) 14616 return false; 14617 14618 SDNode *Trunc2 = *RightShift->use_begin(); 14619 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14620 Trunc2->getValueType(0) != MVT::i32 || 14621 !Trunc2->hasOneUse()) 14622 return false; 14623 14624 SDNode *Bitcast = *Trunc->use_begin(); 14625 SDNode *Bitcast2 = *Trunc2->use_begin(); 14626 14627 if (Bitcast->getOpcode() != ISD::BITCAST || 14628 Bitcast->getValueType(0) != MVT::f32) 14629 return false; 14630 if (Bitcast2->getOpcode() != ISD::BITCAST || 14631 Bitcast2->getValueType(0) != MVT::f32) 14632 return false; 14633 14634 if (Subtarget.isLittleEndian()) 14635 std::swap(Bitcast, Bitcast2); 14636 14637 // Bitcast has the second float (in memory-layout order) and Bitcast2 14638 // has the first one. 14639 14640 SDValue BasePtr = LD->getBasePtr(); 14641 if (LD->isIndexed()) { 14642 assert(LD->getAddressingMode() == ISD::PRE_INC && 14643 "Non-pre-inc AM on PPC?"); 14644 BasePtr = 14645 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14646 LD->getOffset()); 14647 } 14648 14649 auto MMOFlags = 14650 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14651 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14652 LD->getPointerInfo(), LD->getAlignment(), 14653 MMOFlags, LD->getAAInfo()); 14654 SDValue AddPtr = 14655 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14656 BasePtr, DAG.getIntPtrConstant(4, dl)); 14657 SDValue FloatLoad2 = DAG.getLoad( 14658 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14659 LD->getPointerInfo().getWithOffset(4), 14660 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14661 14662 if (LD->isIndexed()) { 14663 // Note that DAGCombine should re-form any pre-increment load(s) from 14664 // what is produced here if that makes sense. 14665 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14666 } 14667 14668 DCI.CombineTo(Bitcast2, FloatLoad); 14669 DCI.CombineTo(Bitcast, FloatLoad2); 14670 14671 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14672 SDValue(FloatLoad2.getNode(), 1)); 14673 return true; 14674 }; 14675 14676 if (ReplaceTwoFloatLoad()) 14677 return SDValue(N, 0); 14678 14679 EVT MemVT = LD->getMemoryVT(); 14680 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14681 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14682 if (LD->isUnindexed() && VT.isVector() && 14683 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14684 // P8 and later hardware should just use LOAD. 14685 !Subtarget.hasP8Vector() && 14686 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14687 VT == MVT::v4f32))) && 14688 LD->getAlign() < ABIAlignment) { 14689 // This is a type-legal unaligned Altivec load. 14690 SDValue Chain = LD->getChain(); 14691 SDValue Ptr = LD->getBasePtr(); 14692 bool isLittleEndian = Subtarget.isLittleEndian(); 14693 14694 // This implements the loading of unaligned vectors as described in 14695 // the venerable Apple Velocity Engine overview. Specifically: 14696 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14697 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14698 // 14699 // The general idea is to expand a sequence of one or more unaligned 14700 // loads into an alignment-based permutation-control instruction (lvsl 14701 // or lvsr), a series of regular vector loads (which always truncate 14702 // their input address to an aligned address), and a series of 14703 // permutations. The results of these permutations are the requested 14704 // loaded values. The trick is that the last "extra" load is not taken 14705 // from the address you might suspect (sizeof(vector) bytes after the 14706 // last requested load), but rather sizeof(vector) - 1 bytes after the 14707 // last requested vector. The point of this is to avoid a page fault if 14708 // the base address happened to be aligned. This works because if the 14709 // base address is aligned, then adding less than a full vector length 14710 // will cause the last vector in the sequence to be (re)loaded. 14711 // Otherwise, the next vector will be fetched as you might suspect was 14712 // necessary. 14713 14714 // We might be able to reuse the permutation generation from 14715 // a different base address offset from this one by an aligned amount. 14716 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14717 // optimization later. 14718 Intrinsic::ID Intr, IntrLD, IntrPerm; 14719 MVT PermCntlTy, PermTy, LDTy; 14720 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14721 : Intrinsic::ppc_altivec_lvsl; 14722 IntrLD = Intrinsic::ppc_altivec_lvx; 14723 IntrPerm = Intrinsic::ppc_altivec_vperm; 14724 PermCntlTy = MVT::v16i8; 14725 PermTy = MVT::v4i32; 14726 LDTy = MVT::v4i32; 14727 14728 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14729 14730 // Create the new MMO for the new base load. It is like the original MMO, 14731 // but represents an area in memory almost twice the vector size centered 14732 // on the original address. If the address is unaligned, we might start 14733 // reading up to (sizeof(vector)-1) bytes below the address of the 14734 // original unaligned load. 14735 MachineFunction &MF = DAG.getMachineFunction(); 14736 MachineMemOperand *BaseMMO = 14737 MF.getMachineMemOperand(LD->getMemOperand(), 14738 -(long)MemVT.getStoreSize()+1, 14739 2*MemVT.getStoreSize()-1); 14740 14741 // Create the new base load. 14742 SDValue LDXIntID = 14743 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14744 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14745 SDValue BaseLoad = 14746 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14747 DAG.getVTList(PermTy, MVT::Other), 14748 BaseLoadOps, LDTy, BaseMMO); 14749 14750 // Note that the value of IncOffset (which is provided to the next 14751 // load's pointer info offset value, and thus used to calculate the 14752 // alignment), and the value of IncValue (which is actually used to 14753 // increment the pointer value) are different! This is because we 14754 // require the next load to appear to be aligned, even though it 14755 // is actually offset from the base pointer by a lesser amount. 14756 int IncOffset = VT.getSizeInBits() / 8; 14757 int IncValue = IncOffset; 14758 14759 // Walk (both up and down) the chain looking for another load at the real 14760 // (aligned) offset (the alignment of the other load does not matter in 14761 // this case). If found, then do not use the offset reduction trick, as 14762 // that will prevent the loads from being later combined (as they would 14763 // otherwise be duplicates). 14764 if (!findConsecutiveLoad(LD, DAG)) 14765 --IncValue; 14766 14767 SDValue Increment = 14768 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14769 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14770 14771 MachineMemOperand *ExtraMMO = 14772 MF.getMachineMemOperand(LD->getMemOperand(), 14773 1, 2*MemVT.getStoreSize()-1); 14774 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14775 SDValue ExtraLoad = 14776 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14777 DAG.getVTList(PermTy, MVT::Other), 14778 ExtraLoadOps, LDTy, ExtraMMO); 14779 14780 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14781 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14782 14783 // Because vperm has a big-endian bias, we must reverse the order 14784 // of the input vectors and complement the permute control vector 14785 // when generating little endian code. We have already handled the 14786 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14787 // and ExtraLoad here. 14788 SDValue Perm; 14789 if (isLittleEndian) 14790 Perm = BuildIntrinsicOp(IntrPerm, 14791 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14792 else 14793 Perm = BuildIntrinsicOp(IntrPerm, 14794 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14795 14796 if (VT != PermTy) 14797 Perm = Subtarget.hasAltivec() 14798 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14799 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14800 DAG.getTargetConstant(1, dl, MVT::i64)); 14801 // second argument is 1 because this rounding 14802 // is always exact. 14803 14804 // The output of the permutation is our loaded result, the TokenFactor is 14805 // our new chain. 14806 DCI.CombineTo(N, Perm, TF); 14807 return SDValue(N, 0); 14808 } 14809 } 14810 break; 14811 case ISD::INTRINSIC_WO_CHAIN: { 14812 bool isLittleEndian = Subtarget.isLittleEndian(); 14813 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14814 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14815 : Intrinsic::ppc_altivec_lvsl); 14816 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14817 SDValue Add = N->getOperand(1); 14818 14819 int Bits = 4 /* 16 byte alignment */; 14820 14821 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14822 APInt::getAllOnesValue(Bits /* alignment */) 14823 .zext(Add.getScalarValueSizeInBits()))) { 14824 SDNode *BasePtr = Add->getOperand(0).getNode(); 14825 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14826 UE = BasePtr->use_end(); 14827 UI != UE; ++UI) { 14828 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14829 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14830 IID) { 14831 // We've found another LVSL/LVSR, and this address is an aligned 14832 // multiple of that one. The results will be the same, so use the 14833 // one we've just found instead. 14834 14835 return SDValue(*UI, 0); 14836 } 14837 } 14838 } 14839 14840 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14841 SDNode *BasePtr = Add->getOperand(0).getNode(); 14842 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14843 UE = BasePtr->use_end(); UI != UE; ++UI) { 14844 if (UI->getOpcode() == ISD::ADD && 14845 isa<ConstantSDNode>(UI->getOperand(1)) && 14846 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14847 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14848 (1ULL << Bits) == 0) { 14849 SDNode *OtherAdd = *UI; 14850 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14851 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14852 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14853 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14854 return SDValue(*VI, 0); 14855 } 14856 } 14857 } 14858 } 14859 } 14860 } 14861 14862 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14863 // Expose the vabsduw/h/b opportunity for down stream 14864 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14865 (IID == Intrinsic::ppc_altivec_vmaxsw || 14866 IID == Intrinsic::ppc_altivec_vmaxsh || 14867 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14868 SDValue V1 = N->getOperand(1); 14869 SDValue V2 = N->getOperand(2); 14870 if ((V1.getSimpleValueType() == MVT::v4i32 || 14871 V1.getSimpleValueType() == MVT::v8i16 || 14872 V1.getSimpleValueType() == MVT::v16i8) && 14873 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14874 // (0-a, a) 14875 if (V1.getOpcode() == ISD::SUB && 14876 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14877 V1.getOperand(1) == V2) { 14878 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14879 } 14880 // (a, 0-a) 14881 if (V2.getOpcode() == ISD::SUB && 14882 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14883 V2.getOperand(1) == V1) { 14884 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14885 } 14886 // (x-y, y-x) 14887 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14888 V1.getOperand(0) == V2.getOperand(1) && 14889 V1.getOperand(1) == V2.getOperand(0)) { 14890 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14891 } 14892 } 14893 } 14894 } 14895 14896 break; 14897 case ISD::INTRINSIC_W_CHAIN: 14898 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14899 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14900 if (Subtarget.needsSwapsForVSXMemOps()) { 14901 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14902 default: 14903 break; 14904 case Intrinsic::ppc_vsx_lxvw4x: 14905 case Intrinsic::ppc_vsx_lxvd2x: 14906 return expandVSXLoadForLE(N, DCI); 14907 } 14908 } 14909 break; 14910 case ISD::INTRINSIC_VOID: 14911 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14912 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14913 if (Subtarget.needsSwapsForVSXMemOps()) { 14914 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14915 default: 14916 break; 14917 case Intrinsic::ppc_vsx_stxvw4x: 14918 case Intrinsic::ppc_vsx_stxvd2x: 14919 return expandVSXStoreForLE(N, DCI); 14920 } 14921 } 14922 break; 14923 case ISD::BSWAP: 14924 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14925 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14926 N->getOperand(0).hasOneUse() && 14927 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14928 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14929 N->getValueType(0) == MVT::i64))) { 14930 SDValue Load = N->getOperand(0); 14931 LoadSDNode *LD = cast<LoadSDNode>(Load); 14932 // Create the byte-swapping load. 14933 SDValue Ops[] = { 14934 LD->getChain(), // Chain 14935 LD->getBasePtr(), // Ptr 14936 DAG.getValueType(N->getValueType(0)) // VT 14937 }; 14938 SDValue BSLoad = 14939 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14940 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14941 MVT::i64 : MVT::i32, MVT::Other), 14942 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14943 14944 // If this is an i16 load, insert the truncate. 14945 SDValue ResVal = BSLoad; 14946 if (N->getValueType(0) == MVT::i16) 14947 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14948 14949 // First, combine the bswap away. This makes the value produced by the 14950 // load dead. 14951 DCI.CombineTo(N, ResVal); 14952 14953 // Next, combine the load away, we give it a bogus result value but a real 14954 // chain result. The result value is dead because the bswap is dead. 14955 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14956 14957 // Return N so it doesn't get rechecked! 14958 return SDValue(N, 0); 14959 } 14960 break; 14961 case PPCISD::VCMP: 14962 // If a VCMPo node already exists with exactly the same operands as this 14963 // node, use its result instead of this node (VCMPo computes both a CR6 and 14964 // a normal output). 14965 // 14966 if (!N->getOperand(0).hasOneUse() && 14967 !N->getOperand(1).hasOneUse() && 14968 !N->getOperand(2).hasOneUse()) { 14969 14970 // Scan all of the users of the LHS, looking for VCMPo's that match. 14971 SDNode *VCMPoNode = nullptr; 14972 14973 SDNode *LHSN = N->getOperand(0).getNode(); 14974 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14975 UI != E; ++UI) 14976 if (UI->getOpcode() == PPCISD::VCMPo && 14977 UI->getOperand(1) == N->getOperand(1) && 14978 UI->getOperand(2) == N->getOperand(2) && 14979 UI->getOperand(0) == N->getOperand(0)) { 14980 VCMPoNode = *UI; 14981 break; 14982 } 14983 14984 // If there is no VCMPo node, or if the flag value has a single use, don't 14985 // transform this. 14986 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14987 break; 14988 14989 // Look at the (necessarily single) use of the flag value. If it has a 14990 // chain, this transformation is more complex. Note that multiple things 14991 // could use the value result, which we should ignore. 14992 SDNode *FlagUser = nullptr; 14993 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14994 FlagUser == nullptr; ++UI) { 14995 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14996 SDNode *User = *UI; 14997 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14998 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14999 FlagUser = User; 15000 break; 15001 } 15002 } 15003 } 15004 15005 // If the user is a MFOCRF instruction, we know this is safe. 15006 // Otherwise we give up for right now. 15007 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15008 return SDValue(VCMPoNode, 0); 15009 } 15010 break; 15011 case ISD::BRCOND: { 15012 SDValue Cond = N->getOperand(1); 15013 SDValue Target = N->getOperand(2); 15014 15015 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15016 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15017 Intrinsic::loop_decrement) { 15018 15019 // We now need to make the intrinsic dead (it cannot be instruction 15020 // selected). 15021 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15022 assert(Cond.getNode()->hasOneUse() && 15023 "Counter decrement has more than one use"); 15024 15025 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15026 N->getOperand(0), Target); 15027 } 15028 } 15029 break; 15030 case ISD::BR_CC: { 15031 // If this is a branch on an altivec predicate comparison, lower this so 15032 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15033 // lowering is done pre-legalize, because the legalizer lowers the predicate 15034 // compare down to code that is difficult to reassemble. 15035 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15036 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15037 15038 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15039 // value. If so, pass-through the AND to get to the intrinsic. 15040 if (LHS.getOpcode() == ISD::AND && 15041 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15042 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15043 Intrinsic::loop_decrement && 15044 isa<ConstantSDNode>(LHS.getOperand(1)) && 15045 !isNullConstant(LHS.getOperand(1))) 15046 LHS = LHS.getOperand(0); 15047 15048 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15049 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15050 Intrinsic::loop_decrement && 15051 isa<ConstantSDNode>(RHS)) { 15052 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15053 "Counter decrement comparison is not EQ or NE"); 15054 15055 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15056 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15057 (CC == ISD::SETNE && !Val); 15058 15059 // We now need to make the intrinsic dead (it cannot be instruction 15060 // selected). 15061 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15062 assert(LHS.getNode()->hasOneUse() && 15063 "Counter decrement has more than one use"); 15064 15065 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15066 N->getOperand(0), N->getOperand(4)); 15067 } 15068 15069 int CompareOpc; 15070 bool isDot; 15071 15072 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15073 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15074 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15075 assert(isDot && "Can't compare against a vector result!"); 15076 15077 // If this is a comparison against something other than 0/1, then we know 15078 // that the condition is never/always true. 15079 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15080 if (Val != 0 && Val != 1) { 15081 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15082 return N->getOperand(0); 15083 // Always !=, turn it into an unconditional branch. 15084 return DAG.getNode(ISD::BR, dl, MVT::Other, 15085 N->getOperand(0), N->getOperand(4)); 15086 } 15087 15088 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15089 15090 // Create the PPCISD altivec 'dot' comparison node. 15091 SDValue Ops[] = { 15092 LHS.getOperand(2), // LHS of compare 15093 LHS.getOperand(3), // RHS of compare 15094 DAG.getConstant(CompareOpc, dl, MVT::i32) 15095 }; 15096 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15097 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15098 15099 // Unpack the result based on how the target uses it. 15100 PPC::Predicate CompOpc; 15101 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15102 default: // Can't happen, don't crash on invalid number though. 15103 case 0: // Branch on the value of the EQ bit of CR6. 15104 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15105 break; 15106 case 1: // Branch on the inverted value of the EQ bit of CR6. 15107 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15108 break; 15109 case 2: // Branch on the value of the LT bit of CR6. 15110 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15111 break; 15112 case 3: // Branch on the inverted value of the LT bit of CR6. 15113 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15114 break; 15115 } 15116 15117 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15118 DAG.getConstant(CompOpc, dl, MVT::i32), 15119 DAG.getRegister(PPC::CR6, MVT::i32), 15120 N->getOperand(4), CompNode.getValue(1)); 15121 } 15122 break; 15123 } 15124 case ISD::BUILD_VECTOR: 15125 return DAGCombineBuildVector(N, DCI); 15126 case ISD::ABS: 15127 return combineABS(N, DCI); 15128 case ISD::VSELECT: 15129 return combineVSelect(N, DCI); 15130 } 15131 15132 return SDValue(); 15133 } 15134 15135 SDValue 15136 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15137 SelectionDAG &DAG, 15138 SmallVectorImpl<SDNode *> &Created) const { 15139 // fold (sdiv X, pow2) 15140 EVT VT = N->getValueType(0); 15141 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15142 return SDValue(); 15143 if ((VT != MVT::i32 && VT != MVT::i64) || 15144 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15145 return SDValue(); 15146 15147 SDLoc DL(N); 15148 SDValue N0 = N->getOperand(0); 15149 15150 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15151 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15152 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15153 15154 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15155 Created.push_back(Op.getNode()); 15156 15157 if (IsNegPow2) { 15158 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15159 Created.push_back(Op.getNode()); 15160 } 15161 15162 return Op; 15163 } 15164 15165 //===----------------------------------------------------------------------===// 15166 // Inline Assembly Support 15167 //===----------------------------------------------------------------------===// 15168 15169 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15170 KnownBits &Known, 15171 const APInt &DemandedElts, 15172 const SelectionDAG &DAG, 15173 unsigned Depth) const { 15174 Known.resetAll(); 15175 switch (Op.getOpcode()) { 15176 default: break; 15177 case PPCISD::LBRX: { 15178 // lhbrx is known to have the top bits cleared out. 15179 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15180 Known.Zero = 0xFFFF0000; 15181 break; 15182 } 15183 case ISD::INTRINSIC_WO_CHAIN: { 15184 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15185 default: break; 15186 case Intrinsic::ppc_altivec_vcmpbfp_p: 15187 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15188 case Intrinsic::ppc_altivec_vcmpequb_p: 15189 case Intrinsic::ppc_altivec_vcmpequh_p: 15190 case Intrinsic::ppc_altivec_vcmpequw_p: 15191 case Intrinsic::ppc_altivec_vcmpequd_p: 15192 case Intrinsic::ppc_altivec_vcmpgefp_p: 15193 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15194 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15195 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15196 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15197 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15198 case Intrinsic::ppc_altivec_vcmpgtub_p: 15199 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15200 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15201 case Intrinsic::ppc_altivec_vcmpgtud_p: 15202 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15203 break; 15204 } 15205 } 15206 } 15207 } 15208 15209 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15210 switch (Subtarget.getCPUDirective()) { 15211 default: break; 15212 case PPC::DIR_970: 15213 case PPC::DIR_PWR4: 15214 case PPC::DIR_PWR5: 15215 case PPC::DIR_PWR5X: 15216 case PPC::DIR_PWR6: 15217 case PPC::DIR_PWR6X: 15218 case PPC::DIR_PWR7: 15219 case PPC::DIR_PWR8: 15220 case PPC::DIR_PWR9: 15221 case PPC::DIR_PWR10: 15222 case PPC::DIR_PWR_FUTURE: { 15223 if (!ML) 15224 break; 15225 15226 if (!DisableInnermostLoopAlign32) { 15227 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15228 // so that we can decrease cache misses and branch-prediction misses. 15229 // Actual alignment of the loop will depend on the hotness check and other 15230 // logic in alignBlocks. 15231 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15232 return Align(32); 15233 } 15234 15235 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15236 15237 // For small loops (between 5 and 8 instructions), align to a 32-byte 15238 // boundary so that the entire loop fits in one instruction-cache line. 15239 uint64_t LoopSize = 0; 15240 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15241 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15242 LoopSize += TII->getInstSizeInBytes(*J); 15243 if (LoopSize > 32) 15244 break; 15245 } 15246 15247 if (LoopSize > 16 && LoopSize <= 32) 15248 return Align(32); 15249 15250 break; 15251 } 15252 } 15253 15254 return TargetLowering::getPrefLoopAlignment(ML); 15255 } 15256 15257 /// getConstraintType - Given a constraint, return the type of 15258 /// constraint it is for this target. 15259 PPCTargetLowering::ConstraintType 15260 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15261 if (Constraint.size() == 1) { 15262 switch (Constraint[0]) { 15263 default: break; 15264 case 'b': 15265 case 'r': 15266 case 'f': 15267 case 'd': 15268 case 'v': 15269 case 'y': 15270 return C_RegisterClass; 15271 case 'Z': 15272 // FIXME: While Z does indicate a memory constraint, it specifically 15273 // indicates an r+r address (used in conjunction with the 'y' modifier 15274 // in the replacement string). Currently, we're forcing the base 15275 // register to be r0 in the asm printer (which is interpreted as zero) 15276 // and forming the complete address in the second register. This is 15277 // suboptimal. 15278 return C_Memory; 15279 } 15280 } else if (Constraint == "wc") { // individual CR bits. 15281 return C_RegisterClass; 15282 } else if (Constraint == "wa" || Constraint == "wd" || 15283 Constraint == "wf" || Constraint == "ws" || 15284 Constraint == "wi" || Constraint == "ww") { 15285 return C_RegisterClass; // VSX registers. 15286 } 15287 return TargetLowering::getConstraintType(Constraint); 15288 } 15289 15290 /// Examine constraint type and operand type and determine a weight value. 15291 /// This object must already have been set up with the operand type 15292 /// and the current alternative constraint selected. 15293 TargetLowering::ConstraintWeight 15294 PPCTargetLowering::getSingleConstraintMatchWeight( 15295 AsmOperandInfo &info, const char *constraint) const { 15296 ConstraintWeight weight = CW_Invalid; 15297 Value *CallOperandVal = info.CallOperandVal; 15298 // If we don't have a value, we can't do a match, 15299 // but allow it at the lowest weight. 15300 if (!CallOperandVal) 15301 return CW_Default; 15302 Type *type = CallOperandVal->getType(); 15303 15304 // Look at the constraint type. 15305 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15306 return CW_Register; // an individual CR bit. 15307 else if ((StringRef(constraint) == "wa" || 15308 StringRef(constraint) == "wd" || 15309 StringRef(constraint) == "wf") && 15310 type->isVectorTy()) 15311 return CW_Register; 15312 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15313 return CW_Register; // just hold 64-bit integers data. 15314 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15315 return CW_Register; 15316 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15317 return CW_Register; 15318 15319 switch (*constraint) { 15320 default: 15321 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15322 break; 15323 case 'b': 15324 if (type->isIntegerTy()) 15325 weight = CW_Register; 15326 break; 15327 case 'f': 15328 if (type->isFloatTy()) 15329 weight = CW_Register; 15330 break; 15331 case 'd': 15332 if (type->isDoubleTy()) 15333 weight = CW_Register; 15334 break; 15335 case 'v': 15336 if (type->isVectorTy()) 15337 weight = CW_Register; 15338 break; 15339 case 'y': 15340 weight = CW_Register; 15341 break; 15342 case 'Z': 15343 weight = CW_Memory; 15344 break; 15345 } 15346 return weight; 15347 } 15348 15349 std::pair<unsigned, const TargetRegisterClass *> 15350 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15351 StringRef Constraint, 15352 MVT VT) const { 15353 if (Constraint.size() == 1) { 15354 // GCC RS6000 Constraint Letters 15355 switch (Constraint[0]) { 15356 case 'b': // R1-R31 15357 if (VT == MVT::i64 && Subtarget.isPPC64()) 15358 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15359 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15360 case 'r': // R0-R31 15361 if (VT == MVT::i64 && Subtarget.isPPC64()) 15362 return std::make_pair(0U, &PPC::G8RCRegClass); 15363 return std::make_pair(0U, &PPC::GPRCRegClass); 15364 // 'd' and 'f' constraints are both defined to be "the floating point 15365 // registers", where one is for 32-bit and the other for 64-bit. We don't 15366 // really care overly much here so just give them all the same reg classes. 15367 case 'd': 15368 case 'f': 15369 if (Subtarget.hasSPE()) { 15370 if (VT == MVT::f32 || VT == MVT::i32) 15371 return std::make_pair(0U, &PPC::GPRCRegClass); 15372 if (VT == MVT::f64 || VT == MVT::i64) 15373 return std::make_pair(0U, &PPC::SPERCRegClass); 15374 } else { 15375 if (VT == MVT::f32 || VT == MVT::i32) 15376 return std::make_pair(0U, &PPC::F4RCRegClass); 15377 if (VT == MVT::f64 || VT == MVT::i64) 15378 return std::make_pair(0U, &PPC::F8RCRegClass); 15379 } 15380 break; 15381 case 'v': 15382 if (Subtarget.hasAltivec()) 15383 return std::make_pair(0U, &PPC::VRRCRegClass); 15384 break; 15385 case 'y': // crrc 15386 return std::make_pair(0U, &PPC::CRRCRegClass); 15387 } 15388 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15389 // An individual CR bit. 15390 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15391 } else if ((Constraint == "wa" || Constraint == "wd" || 15392 Constraint == "wf" || Constraint == "wi") && 15393 Subtarget.hasVSX()) { 15394 return std::make_pair(0U, &PPC::VSRCRegClass); 15395 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15396 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15397 return std::make_pair(0U, &PPC::VSSRCRegClass); 15398 else 15399 return std::make_pair(0U, &PPC::VSFRCRegClass); 15400 } 15401 15402 // If we name a VSX register, we can't defer to the base class because it 15403 // will not recognize the correct register (their names will be VSL{0-31} 15404 // and V{0-31} so they won't match). So we match them here. 15405 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15406 int VSNum = atoi(Constraint.data() + 3); 15407 assert(VSNum >= 0 && VSNum <= 63 && 15408 "Attempted to access a vsr out of range"); 15409 if (VSNum < 32) 15410 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15411 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15412 } 15413 std::pair<unsigned, const TargetRegisterClass *> R = 15414 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15415 15416 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15417 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15418 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15419 // register. 15420 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15421 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15422 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15423 PPC::GPRCRegClass.contains(R.first)) 15424 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15425 PPC::sub_32, &PPC::G8RCRegClass), 15426 &PPC::G8RCRegClass); 15427 15428 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15429 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15430 R.first = PPC::CR0; 15431 R.second = &PPC::CRRCRegClass; 15432 } 15433 15434 return R; 15435 } 15436 15437 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15438 /// vector. If it is invalid, don't add anything to Ops. 15439 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15440 std::string &Constraint, 15441 std::vector<SDValue>&Ops, 15442 SelectionDAG &DAG) const { 15443 SDValue Result; 15444 15445 // Only support length 1 constraints. 15446 if (Constraint.length() > 1) return; 15447 15448 char Letter = Constraint[0]; 15449 switch (Letter) { 15450 default: break; 15451 case 'I': 15452 case 'J': 15453 case 'K': 15454 case 'L': 15455 case 'M': 15456 case 'N': 15457 case 'O': 15458 case 'P': { 15459 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15460 if (!CST) return; // Must be an immediate to match. 15461 SDLoc dl(Op); 15462 int64_t Value = CST->getSExtValue(); 15463 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15464 // numbers are printed as such. 15465 switch (Letter) { 15466 default: llvm_unreachable("Unknown constraint letter!"); 15467 case 'I': // "I" is a signed 16-bit constant. 15468 if (isInt<16>(Value)) 15469 Result = DAG.getTargetConstant(Value, dl, TCVT); 15470 break; 15471 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15472 if (isShiftedUInt<16, 16>(Value)) 15473 Result = DAG.getTargetConstant(Value, dl, TCVT); 15474 break; 15475 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15476 if (isShiftedInt<16, 16>(Value)) 15477 Result = DAG.getTargetConstant(Value, dl, TCVT); 15478 break; 15479 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15480 if (isUInt<16>(Value)) 15481 Result = DAG.getTargetConstant(Value, dl, TCVT); 15482 break; 15483 case 'M': // "M" is a constant that is greater than 31. 15484 if (Value > 31) 15485 Result = DAG.getTargetConstant(Value, dl, TCVT); 15486 break; 15487 case 'N': // "N" is a positive constant that is an exact power of two. 15488 if (Value > 0 && isPowerOf2_64(Value)) 15489 Result = DAG.getTargetConstant(Value, dl, TCVT); 15490 break; 15491 case 'O': // "O" is the constant zero. 15492 if (Value == 0) 15493 Result = DAG.getTargetConstant(Value, dl, TCVT); 15494 break; 15495 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15496 if (isInt<16>(-Value)) 15497 Result = DAG.getTargetConstant(Value, dl, TCVT); 15498 break; 15499 } 15500 break; 15501 } 15502 } 15503 15504 if (Result.getNode()) { 15505 Ops.push_back(Result); 15506 return; 15507 } 15508 15509 // Handle standard constraint letters. 15510 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15511 } 15512 15513 // isLegalAddressingMode - Return true if the addressing mode represented 15514 // by AM is legal for this target, for a load/store of the specified type. 15515 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15516 const AddrMode &AM, Type *Ty, 15517 unsigned AS, 15518 Instruction *I) const { 15519 // Vector type r+i form is supported since power9 as DQ form. We don't check 15520 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15521 // imm form is preferred and the offset can be adjusted to use imm form later 15522 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15523 // max offset to check legal addressing mode, we should be a little aggressive 15524 // to contain other offsets for that LSRUse. 15525 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15526 return false; 15527 15528 // PPC allows a sign-extended 16-bit immediate field. 15529 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15530 return false; 15531 15532 // No global is ever allowed as a base. 15533 if (AM.BaseGV) 15534 return false; 15535 15536 // PPC only support r+r, 15537 switch (AM.Scale) { 15538 case 0: // "r+i" or just "i", depending on HasBaseReg. 15539 break; 15540 case 1: 15541 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15542 return false; 15543 // Otherwise we have r+r or r+i. 15544 break; 15545 case 2: 15546 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15547 return false; 15548 // Allow 2*r as r+r. 15549 break; 15550 default: 15551 // No other scales are supported. 15552 return false; 15553 } 15554 15555 return true; 15556 } 15557 15558 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15559 SelectionDAG &DAG) const { 15560 MachineFunction &MF = DAG.getMachineFunction(); 15561 MachineFrameInfo &MFI = MF.getFrameInfo(); 15562 MFI.setReturnAddressIsTaken(true); 15563 15564 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15565 return SDValue(); 15566 15567 SDLoc dl(Op); 15568 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15569 15570 // Make sure the function does not optimize away the store of the RA to 15571 // the stack. 15572 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15573 FuncInfo->setLRStoreRequired(); 15574 bool isPPC64 = Subtarget.isPPC64(); 15575 auto PtrVT = getPointerTy(MF.getDataLayout()); 15576 15577 if (Depth > 0) { 15578 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15579 SDValue Offset = 15580 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15581 isPPC64 ? MVT::i64 : MVT::i32); 15582 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15583 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15584 MachinePointerInfo()); 15585 } 15586 15587 // Just load the return address off the stack. 15588 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15589 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15590 MachinePointerInfo()); 15591 } 15592 15593 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15594 SelectionDAG &DAG) const { 15595 SDLoc dl(Op); 15596 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15597 15598 MachineFunction &MF = DAG.getMachineFunction(); 15599 MachineFrameInfo &MFI = MF.getFrameInfo(); 15600 MFI.setFrameAddressIsTaken(true); 15601 15602 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15603 bool isPPC64 = PtrVT == MVT::i64; 15604 15605 // Naked functions never have a frame pointer, and so we use r1. For all 15606 // other functions, this decision must be delayed until during PEI. 15607 unsigned FrameReg; 15608 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15609 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15610 else 15611 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15612 15613 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15614 PtrVT); 15615 while (Depth--) 15616 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15617 FrameAddr, MachinePointerInfo()); 15618 return FrameAddr; 15619 } 15620 15621 // FIXME? Maybe this could be a TableGen attribute on some registers and 15622 // this table could be generated automatically from RegInfo. 15623 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15624 const MachineFunction &MF) const { 15625 bool isPPC64 = Subtarget.isPPC64(); 15626 15627 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15628 if (!is64Bit && VT != LLT::scalar(32)) 15629 report_fatal_error("Invalid register global variable type"); 15630 15631 Register Reg = StringSwitch<Register>(RegName) 15632 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15633 .Case("r2", isPPC64 ? Register() : PPC::R2) 15634 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15635 .Default(Register()); 15636 15637 if (Reg) 15638 return Reg; 15639 report_fatal_error("Invalid register name global variable"); 15640 } 15641 15642 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15643 // 32-bit SVR4 ABI access everything as got-indirect. 15644 if (Subtarget.is32BitELFABI()) 15645 return true; 15646 15647 // AIX accesses everything indirectly through the TOC, which is similar to 15648 // the GOT. 15649 if (Subtarget.isAIXABI()) 15650 return true; 15651 15652 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15653 // If it is small or large code model, module locals are accessed 15654 // indirectly by loading their address from .toc/.got. 15655 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15656 return true; 15657 15658 // JumpTable and BlockAddress are accessed as got-indirect. 15659 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15660 return true; 15661 15662 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15663 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15664 15665 return false; 15666 } 15667 15668 bool 15669 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15670 // The PowerPC target isn't yet aware of offsets. 15671 return false; 15672 } 15673 15674 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15675 const CallInst &I, 15676 MachineFunction &MF, 15677 unsigned Intrinsic) const { 15678 switch (Intrinsic) { 15679 case Intrinsic::ppc_altivec_lvx: 15680 case Intrinsic::ppc_altivec_lvxl: 15681 case Intrinsic::ppc_altivec_lvebx: 15682 case Intrinsic::ppc_altivec_lvehx: 15683 case Intrinsic::ppc_altivec_lvewx: 15684 case Intrinsic::ppc_vsx_lxvd2x: 15685 case Intrinsic::ppc_vsx_lxvw4x: { 15686 EVT VT; 15687 switch (Intrinsic) { 15688 case Intrinsic::ppc_altivec_lvebx: 15689 VT = MVT::i8; 15690 break; 15691 case Intrinsic::ppc_altivec_lvehx: 15692 VT = MVT::i16; 15693 break; 15694 case Intrinsic::ppc_altivec_lvewx: 15695 VT = MVT::i32; 15696 break; 15697 case Intrinsic::ppc_vsx_lxvd2x: 15698 VT = MVT::v2f64; 15699 break; 15700 default: 15701 VT = MVT::v4i32; 15702 break; 15703 } 15704 15705 Info.opc = ISD::INTRINSIC_W_CHAIN; 15706 Info.memVT = VT; 15707 Info.ptrVal = I.getArgOperand(0); 15708 Info.offset = -VT.getStoreSize()+1; 15709 Info.size = 2*VT.getStoreSize()-1; 15710 Info.align = Align(1); 15711 Info.flags = MachineMemOperand::MOLoad; 15712 return true; 15713 } 15714 case Intrinsic::ppc_altivec_stvx: 15715 case Intrinsic::ppc_altivec_stvxl: 15716 case Intrinsic::ppc_altivec_stvebx: 15717 case Intrinsic::ppc_altivec_stvehx: 15718 case Intrinsic::ppc_altivec_stvewx: 15719 case Intrinsic::ppc_vsx_stxvd2x: 15720 case Intrinsic::ppc_vsx_stxvw4x: { 15721 EVT VT; 15722 switch (Intrinsic) { 15723 case Intrinsic::ppc_altivec_stvebx: 15724 VT = MVT::i8; 15725 break; 15726 case Intrinsic::ppc_altivec_stvehx: 15727 VT = MVT::i16; 15728 break; 15729 case Intrinsic::ppc_altivec_stvewx: 15730 VT = MVT::i32; 15731 break; 15732 case Intrinsic::ppc_vsx_stxvd2x: 15733 VT = MVT::v2f64; 15734 break; 15735 default: 15736 VT = MVT::v4i32; 15737 break; 15738 } 15739 15740 Info.opc = ISD::INTRINSIC_VOID; 15741 Info.memVT = VT; 15742 Info.ptrVal = I.getArgOperand(1); 15743 Info.offset = -VT.getStoreSize()+1; 15744 Info.size = 2*VT.getStoreSize()-1; 15745 Info.align = Align(1); 15746 Info.flags = MachineMemOperand::MOStore; 15747 return true; 15748 } 15749 default: 15750 break; 15751 } 15752 15753 return false; 15754 } 15755 15756 /// It returns EVT::Other if the type should be determined using generic 15757 /// target-independent logic. 15758 EVT PPCTargetLowering::getOptimalMemOpType( 15759 const MemOp &Op, const AttributeList &FuncAttributes) const { 15760 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15761 // We should use Altivec/VSX loads and stores when available. For unaligned 15762 // addresses, unaligned VSX loads are only fast starting with the P8. 15763 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15764 (Op.isAligned(Align(16)) || 15765 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15766 return MVT::v4i32; 15767 } 15768 15769 if (Subtarget.isPPC64()) { 15770 return MVT::i64; 15771 } 15772 15773 return MVT::i32; 15774 } 15775 15776 /// Returns true if it is beneficial to convert a load of a constant 15777 /// to just the constant itself. 15778 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15779 Type *Ty) const { 15780 assert(Ty->isIntegerTy()); 15781 15782 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15783 return !(BitSize == 0 || BitSize > 64); 15784 } 15785 15786 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15787 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15788 return false; 15789 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15790 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15791 return NumBits1 == 64 && NumBits2 == 32; 15792 } 15793 15794 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15795 if (!VT1.isInteger() || !VT2.isInteger()) 15796 return false; 15797 unsigned NumBits1 = VT1.getSizeInBits(); 15798 unsigned NumBits2 = VT2.getSizeInBits(); 15799 return NumBits1 == 64 && NumBits2 == 32; 15800 } 15801 15802 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15803 // Generally speaking, zexts are not free, but they are free when they can be 15804 // folded with other operations. 15805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15806 EVT MemVT = LD->getMemoryVT(); 15807 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15808 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15809 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15810 LD->getExtensionType() == ISD::ZEXTLOAD)) 15811 return true; 15812 } 15813 15814 // FIXME: Add other cases... 15815 // - 32-bit shifts with a zext to i64 15816 // - zext after ctlz, bswap, etc. 15817 // - zext after and by a constant mask 15818 15819 return TargetLowering::isZExtFree(Val, VT2); 15820 } 15821 15822 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15823 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15824 "invalid fpext types"); 15825 // Extending to float128 is not free. 15826 if (DestVT == MVT::f128) 15827 return false; 15828 return true; 15829 } 15830 15831 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15832 return isInt<16>(Imm) || isUInt<16>(Imm); 15833 } 15834 15835 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15836 return isInt<16>(Imm) || isUInt<16>(Imm); 15837 } 15838 15839 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15840 unsigned, 15841 unsigned, 15842 MachineMemOperand::Flags, 15843 bool *Fast) const { 15844 if (DisablePPCUnaligned) 15845 return false; 15846 15847 // PowerPC supports unaligned memory access for simple non-vector types. 15848 // Although accessing unaligned addresses is not as efficient as accessing 15849 // aligned addresses, it is generally more efficient than manual expansion, 15850 // and generally only traps for software emulation when crossing page 15851 // boundaries. 15852 15853 if (!VT.isSimple()) 15854 return false; 15855 15856 if (VT.isFloatingPoint() && !VT.isVector() && 15857 !Subtarget.allowsUnalignedFPAccess()) 15858 return false; 15859 15860 if (VT.getSimpleVT().isVector()) { 15861 if (Subtarget.hasVSX()) { 15862 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15863 VT != MVT::v4f32 && VT != MVT::v4i32) 15864 return false; 15865 } else { 15866 return false; 15867 } 15868 } 15869 15870 if (VT == MVT::ppcf128) 15871 return false; 15872 15873 if (Fast) 15874 *Fast = true; 15875 15876 return true; 15877 } 15878 15879 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15880 EVT VT) const { 15881 return isFMAFasterThanFMulAndFAdd( 15882 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15883 } 15884 15885 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15886 Type *Ty) const { 15887 switch (Ty->getScalarType()->getTypeID()) { 15888 case Type::FloatTyID: 15889 case Type::DoubleTyID: 15890 return true; 15891 case Type::FP128TyID: 15892 return Subtarget.hasP9Vector(); 15893 default: 15894 return false; 15895 } 15896 } 15897 15898 // FIXME: add more patterns which are not profitable to hoist. 15899 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15900 if (!I->hasOneUse()) 15901 return true; 15902 15903 Instruction *User = I->user_back(); 15904 assert(User && "A single use instruction with no uses."); 15905 15906 switch (I->getOpcode()) { 15907 case Instruction::FMul: { 15908 // Don't break FMA, PowerPC prefers FMA. 15909 if (User->getOpcode() != Instruction::FSub && 15910 User->getOpcode() != Instruction::FAdd) 15911 return true; 15912 15913 const TargetOptions &Options = getTargetMachine().Options; 15914 const Function *F = I->getFunction(); 15915 const DataLayout &DL = F->getParent()->getDataLayout(); 15916 Type *Ty = User->getOperand(0)->getType(); 15917 15918 return !( 15919 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15920 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15921 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15922 } 15923 case Instruction::Load: { 15924 // Don't break "store (load float*)" pattern, this pattern will be combined 15925 // to "store (load int32)" in later InstCombine pass. See function 15926 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15927 // cycles than loading a 32 bit integer. 15928 LoadInst *LI = cast<LoadInst>(I); 15929 // For the loads that combineLoadToOperationType does nothing, like 15930 // ordered load, it should be profitable to hoist them. 15931 // For swifterror load, it can only be used for pointer to pointer type, so 15932 // later type check should get rid of this case. 15933 if (!LI->isUnordered()) 15934 return true; 15935 15936 if (User->getOpcode() != Instruction::Store) 15937 return true; 15938 15939 if (I->getType()->getTypeID() != Type::FloatTyID) 15940 return true; 15941 15942 return false; 15943 } 15944 default: 15945 return true; 15946 } 15947 return true; 15948 } 15949 15950 const MCPhysReg * 15951 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15952 // LR is a callee-save register, but we must treat it as clobbered by any call 15953 // site. Hence we include LR in the scratch registers, which are in turn added 15954 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15955 // to CTR, which is used by any indirect call. 15956 static const MCPhysReg ScratchRegs[] = { 15957 PPC::X12, PPC::LR8, PPC::CTR8, 0 15958 }; 15959 15960 return ScratchRegs; 15961 } 15962 15963 Register PPCTargetLowering::getExceptionPointerRegister( 15964 const Constant *PersonalityFn) const { 15965 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15966 } 15967 15968 Register PPCTargetLowering::getExceptionSelectorRegister( 15969 const Constant *PersonalityFn) const { 15970 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15971 } 15972 15973 bool 15974 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15975 EVT VT , unsigned DefinedValues) const { 15976 if (VT == MVT::v2i64) 15977 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15978 15979 if (Subtarget.hasVSX()) 15980 return true; 15981 15982 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15983 } 15984 15985 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15986 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15987 return TargetLowering::getSchedulingPreference(N); 15988 15989 return Sched::ILP; 15990 } 15991 15992 // Create a fast isel object. 15993 FastISel * 15994 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15995 const TargetLibraryInfo *LibInfo) const { 15996 return PPC::createFastISel(FuncInfo, LibInfo); 15997 } 15998 15999 // 'Inverted' means the FMA opcode after negating one multiplicand. 16000 // For example, (fma -a b c) = (fnmsub a b c) 16001 static unsigned invertFMAOpcode(unsigned Opc) { 16002 switch (Opc) { 16003 default: 16004 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16005 case ISD::FMA: 16006 return PPCISD::FNMSUB; 16007 case PPCISD::FNMSUB: 16008 return ISD::FMA; 16009 } 16010 } 16011 16012 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16013 bool LegalOps, bool OptForSize, 16014 NegatibleCost &Cost, 16015 unsigned Depth) const { 16016 if (Depth > SelectionDAG::MaxRecursionDepth) 16017 return SDValue(); 16018 16019 unsigned Opc = Op.getOpcode(); 16020 EVT VT = Op.getValueType(); 16021 SDNodeFlags Flags = Op.getNode()->getFlags(); 16022 16023 switch (Opc) { 16024 case PPCISD::FNMSUB: 16025 if (!Op.hasOneUse() || !isTypeLegal(VT)) 16026 break; 16027 16028 const TargetOptions &Options = getTargetMachine().Options; 16029 SDValue N0 = Op.getOperand(0); 16030 SDValue N1 = Op.getOperand(1); 16031 SDValue N2 = Op.getOperand(2); 16032 SDLoc Loc(Op); 16033 16034 NegatibleCost N2Cost = NegatibleCost::Expensive; 16035 SDValue NegN2 = 16036 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16037 16038 if (!NegN2) 16039 return SDValue(); 16040 16041 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16042 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16043 // These transformations may change sign of zeroes. For example, 16044 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16045 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16046 // Try and choose the cheaper one to negate. 16047 NegatibleCost N0Cost = NegatibleCost::Expensive; 16048 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16049 N0Cost, Depth + 1); 16050 16051 NegatibleCost N1Cost = NegatibleCost::Expensive; 16052 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16053 N1Cost, Depth + 1); 16054 16055 if (NegN0 && N0Cost <= N1Cost) { 16056 Cost = std::min(N0Cost, N2Cost); 16057 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16058 } else if (NegN1) { 16059 Cost = std::min(N1Cost, N2Cost); 16060 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16061 } 16062 } 16063 16064 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16065 if (isOperationLegal(ISD::FMA, VT)) { 16066 Cost = N2Cost; 16067 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16068 } 16069 16070 break; 16071 } 16072 16073 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16074 Cost, Depth); 16075 } 16076 16077 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16078 bool PPCTargetLowering::useLoadStackGuardNode() const { 16079 if (!Subtarget.isTargetLinux()) 16080 return TargetLowering::useLoadStackGuardNode(); 16081 return true; 16082 } 16083 16084 // Override to disable global variable loading on Linux. 16085 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16086 if (!Subtarget.isTargetLinux()) 16087 return TargetLowering::insertSSPDeclarations(M); 16088 } 16089 16090 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16091 bool ForCodeSize) const { 16092 if (!VT.isSimple() || !Subtarget.hasVSX()) 16093 return false; 16094 16095 switch(VT.getSimpleVT().SimpleTy) { 16096 default: 16097 // For FP types that are currently not supported by PPC backend, return 16098 // false. Examples: f16, f80. 16099 return false; 16100 case MVT::f32: 16101 case MVT::f64: 16102 if (Subtarget.hasPrefixInstrs()) { 16103 // With prefixed instructions, we can materialize anything that can be 16104 // represented with a 32-bit immediate, not just positive zero. 16105 APFloat APFloatOfImm = Imm; 16106 return convertToNonDenormSingle(APFloatOfImm); 16107 } 16108 LLVM_FALLTHROUGH; 16109 case MVT::ppcf128: 16110 return Imm.isPosZero(); 16111 } 16112 } 16113 16114 // For vector shift operation op, fold 16115 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16116 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16117 SelectionDAG &DAG) { 16118 SDValue N0 = N->getOperand(0); 16119 SDValue N1 = N->getOperand(1); 16120 EVT VT = N0.getValueType(); 16121 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16122 unsigned Opcode = N->getOpcode(); 16123 unsigned TargetOpcode; 16124 16125 switch (Opcode) { 16126 default: 16127 llvm_unreachable("Unexpected shift operation"); 16128 case ISD::SHL: 16129 TargetOpcode = PPCISD::SHL; 16130 break; 16131 case ISD::SRL: 16132 TargetOpcode = PPCISD::SRL; 16133 break; 16134 case ISD::SRA: 16135 TargetOpcode = PPCISD::SRA; 16136 break; 16137 } 16138 16139 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16140 N1->getOpcode() == ISD::AND) 16141 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16142 if (Mask->getZExtValue() == OpSizeInBits - 1) 16143 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16144 16145 return SDValue(); 16146 } 16147 16148 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16149 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16150 return Value; 16151 16152 SDValue N0 = N->getOperand(0); 16153 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16154 if (!Subtarget.isISA3_0() || 16155 N0.getOpcode() != ISD::SIGN_EXTEND || 16156 N0.getOperand(0).getValueType() != MVT::i32 || 16157 CN1 == nullptr || N->getValueType(0) != MVT::i64) 16158 return SDValue(); 16159 16160 // We can't save an operation here if the value is already extended, and 16161 // the existing shift is easier to combine. 16162 SDValue ExtsSrc = N0.getOperand(0); 16163 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16164 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16165 return SDValue(); 16166 16167 SDLoc DL(N0); 16168 SDValue ShiftBy = SDValue(CN1, 0); 16169 // We want the shift amount to be i32 on the extswli, but the shift could 16170 // have an i64. 16171 if (ShiftBy.getValueType() == MVT::i64) 16172 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16173 16174 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16175 ShiftBy); 16176 } 16177 16178 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16179 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16180 return Value; 16181 16182 return SDValue(); 16183 } 16184 16185 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16186 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16187 return Value; 16188 16189 return SDValue(); 16190 } 16191 16192 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16193 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16194 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16195 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16196 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16197 const PPCSubtarget &Subtarget) { 16198 if (!Subtarget.isPPC64()) 16199 return SDValue(); 16200 16201 SDValue LHS = N->getOperand(0); 16202 SDValue RHS = N->getOperand(1); 16203 16204 auto isZextOfCompareWithConstant = [](SDValue Op) { 16205 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16206 Op.getValueType() != MVT::i64) 16207 return false; 16208 16209 SDValue Cmp = Op.getOperand(0); 16210 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16211 Cmp.getOperand(0).getValueType() != MVT::i64) 16212 return false; 16213 16214 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16215 int64_t NegConstant = 0 - Constant->getSExtValue(); 16216 // Due to the limitations of the addi instruction, 16217 // -C is required to be [-32768, 32767]. 16218 return isInt<16>(NegConstant); 16219 } 16220 16221 return false; 16222 }; 16223 16224 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16225 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16226 16227 // If there is a pattern, canonicalize a zext operand to the RHS. 16228 if (LHSHasPattern && !RHSHasPattern) 16229 std::swap(LHS, RHS); 16230 else if (!LHSHasPattern && !RHSHasPattern) 16231 return SDValue(); 16232 16233 SDLoc DL(N); 16234 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16235 SDValue Cmp = RHS.getOperand(0); 16236 SDValue Z = Cmp.getOperand(0); 16237 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16238 16239 assert(Constant && "Constant Should not be a null pointer."); 16240 int64_t NegConstant = 0 - Constant->getSExtValue(); 16241 16242 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16243 default: break; 16244 case ISD::SETNE: { 16245 // when C == 0 16246 // --> addze X, (addic Z, -1).carry 16247 // / 16248 // add X, (zext(setne Z, C))-- 16249 // \ when -32768 <= -C <= 32767 && C != 0 16250 // --> addze X, (addic (addi Z, -C), -1).carry 16251 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16252 DAG.getConstant(NegConstant, DL, MVT::i64)); 16253 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16254 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16255 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16256 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16257 SDValue(Addc.getNode(), 1)); 16258 } 16259 case ISD::SETEQ: { 16260 // when C == 0 16261 // --> addze X, (subfic Z, 0).carry 16262 // / 16263 // add X, (zext(sete Z, C))-- 16264 // \ when -32768 <= -C <= 32767 && C != 0 16265 // --> addze X, (subfic (addi Z, -C), 0).carry 16266 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16267 DAG.getConstant(NegConstant, DL, MVT::i64)); 16268 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16269 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16270 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16271 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16272 SDValue(Subc.getNode(), 1)); 16273 } 16274 } 16275 16276 return SDValue(); 16277 } 16278 16279 // Transform 16280 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16281 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16282 // In this case both C1 and C2 must be known constants. 16283 // C1+C2 must fit into a 34 bit signed integer. 16284 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16285 const PPCSubtarget &Subtarget) { 16286 if (!Subtarget.isUsingPCRelativeCalls()) 16287 return SDValue(); 16288 16289 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16290 // If we find that node try to cast the Global Address and the Constant. 16291 SDValue LHS = N->getOperand(0); 16292 SDValue RHS = N->getOperand(1); 16293 16294 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16295 std::swap(LHS, RHS); 16296 16297 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16298 return SDValue(); 16299 16300 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16301 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16302 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16303 16304 // Check that both casts succeeded. 16305 if (!GSDN || !ConstNode) 16306 return SDValue(); 16307 16308 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16309 SDLoc DL(GSDN); 16310 16311 // The signed int offset needs to fit in 34 bits. 16312 if (!isInt<34>(NewOffset)) 16313 return SDValue(); 16314 16315 // The new global address is a copy of the old global address except 16316 // that it has the updated Offset. 16317 SDValue GA = 16318 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16319 NewOffset, GSDN->getTargetFlags()); 16320 SDValue MatPCRel = 16321 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16322 return MatPCRel; 16323 } 16324 16325 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16326 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16327 return Value; 16328 16329 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16330 return Value; 16331 16332 return SDValue(); 16333 } 16334 16335 // Detect TRUNCATE operations on bitcasts of float128 values. 16336 // What we are looking for here is the situtation where we extract a subset 16337 // of bits from a 128 bit float. 16338 // This can be of two forms: 16339 // 1) BITCAST of f128 feeding TRUNCATE 16340 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16341 // The reason this is required is because we do not have a legal i128 type 16342 // and so we want to prevent having to store the f128 and then reload part 16343 // of it. 16344 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16345 DAGCombinerInfo &DCI) const { 16346 // If we are using CRBits then try that first. 16347 if (Subtarget.useCRBits()) { 16348 // Check if CRBits did anything and return that if it did. 16349 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16350 return CRTruncValue; 16351 } 16352 16353 SDLoc dl(N); 16354 SDValue Op0 = N->getOperand(0); 16355 16356 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16357 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16358 EVT VT = N->getValueType(0); 16359 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16360 return SDValue(); 16361 SDValue Sub = Op0.getOperand(0); 16362 if (Sub.getOpcode() == ISD::SUB) { 16363 SDValue SubOp0 = Sub.getOperand(0); 16364 SDValue SubOp1 = Sub.getOperand(1); 16365 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16366 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16367 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16368 SubOp1.getOperand(0), 16369 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16370 } 16371 } 16372 } 16373 16374 // Looking for a truncate of i128 to i64. 16375 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16376 return SDValue(); 16377 16378 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16379 16380 // SRL feeding TRUNCATE. 16381 if (Op0.getOpcode() == ISD::SRL) { 16382 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16383 // The right shift has to be by 64 bits. 16384 if (!ConstNode || ConstNode->getZExtValue() != 64) 16385 return SDValue(); 16386 16387 // Switch the element number to extract. 16388 EltToExtract = EltToExtract ? 0 : 1; 16389 // Update Op0 past the SRL. 16390 Op0 = Op0.getOperand(0); 16391 } 16392 16393 // BITCAST feeding a TRUNCATE possibly via SRL. 16394 if (Op0.getOpcode() == ISD::BITCAST && 16395 Op0.getValueType() == MVT::i128 && 16396 Op0.getOperand(0).getValueType() == MVT::f128) { 16397 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16398 return DCI.DAG.getNode( 16399 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16400 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16401 } 16402 return SDValue(); 16403 } 16404 16405 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16406 SelectionDAG &DAG = DCI.DAG; 16407 16408 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16409 if (!ConstOpOrElement) 16410 return SDValue(); 16411 16412 // An imul is usually smaller than the alternative sequence for legal type. 16413 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16414 isOperationLegal(ISD::MUL, N->getValueType(0))) 16415 return SDValue(); 16416 16417 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16418 switch (this->Subtarget.getCPUDirective()) { 16419 default: 16420 // TODO: enhance the condition for subtarget before pwr8 16421 return false; 16422 case PPC::DIR_PWR8: 16423 // type mul add shl 16424 // scalar 4 1 1 16425 // vector 7 2 2 16426 return true; 16427 case PPC::DIR_PWR9: 16428 case PPC::DIR_PWR10: 16429 case PPC::DIR_PWR_FUTURE: 16430 // type mul add shl 16431 // scalar 5 2 2 16432 // vector 7 2 2 16433 16434 // The cycle RATIO of related operations are showed as a table above. 16435 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16436 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16437 // are 4, it is always profitable; but for 3 instrs patterns 16438 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16439 // So we should only do it for vector type. 16440 return IsAddOne && IsNeg ? VT.isVector() : true; 16441 } 16442 }; 16443 16444 EVT VT = N->getValueType(0); 16445 SDLoc DL(N); 16446 16447 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16448 bool IsNeg = MulAmt.isNegative(); 16449 APInt MulAmtAbs = MulAmt.abs(); 16450 16451 if ((MulAmtAbs - 1).isPowerOf2()) { 16452 // (mul x, 2^N + 1) => (add (shl x, N), x) 16453 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16454 16455 if (!IsProfitable(IsNeg, true, VT)) 16456 return SDValue(); 16457 16458 SDValue Op0 = N->getOperand(0); 16459 SDValue Op1 = 16460 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16461 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16462 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16463 16464 if (!IsNeg) 16465 return Res; 16466 16467 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16468 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16469 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16470 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16471 16472 if (!IsProfitable(IsNeg, false, VT)) 16473 return SDValue(); 16474 16475 SDValue Op0 = N->getOperand(0); 16476 SDValue Op1 = 16477 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16478 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16479 16480 if (!IsNeg) 16481 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16482 else 16483 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16484 16485 } else { 16486 return SDValue(); 16487 } 16488 } 16489 16490 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16491 // in combiner since we need to check SD flags and other subtarget features. 16492 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16493 DAGCombinerInfo &DCI) const { 16494 SDValue N0 = N->getOperand(0); 16495 SDValue N1 = N->getOperand(1); 16496 SDValue N2 = N->getOperand(2); 16497 SDNodeFlags Flags = N->getFlags(); 16498 EVT VT = N->getValueType(0); 16499 SelectionDAG &DAG = DCI.DAG; 16500 const TargetOptions &Options = getTargetMachine().Options; 16501 unsigned Opc = N->getOpcode(); 16502 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16503 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16504 SDLoc Loc(N); 16505 16506 if (!isOperationLegal(ISD::FMA, VT)) 16507 return SDValue(); 16508 16509 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16510 // since (fnmsub a b c)=-0 while c-ab=+0. 16511 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16512 return SDValue(); 16513 16514 // (fma (fneg a) b c) => (fnmsub a b c) 16515 // (fnmsub (fneg a) b c) => (fma a b c) 16516 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16517 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16518 16519 // (fma a (fneg b) c) => (fnmsub a b c) 16520 // (fnmsub a (fneg b) c) => (fma a b c) 16521 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16522 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16523 16524 return SDValue(); 16525 } 16526 16527 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16528 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16529 if (!Subtarget.is64BitELFABI()) 16530 return false; 16531 16532 // If not a tail call then no need to proceed. 16533 if (!CI->isTailCall()) 16534 return false; 16535 16536 // If sibling calls have been disabled and tail-calls aren't guaranteed 16537 // there is no reason to duplicate. 16538 auto &TM = getTargetMachine(); 16539 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16540 return false; 16541 16542 // Can't tail call a function called indirectly, or if it has variadic args. 16543 const Function *Callee = CI->getCalledFunction(); 16544 if (!Callee || Callee->isVarArg()) 16545 return false; 16546 16547 // Make sure the callee and caller calling conventions are eligible for tco. 16548 const Function *Caller = CI->getParent()->getParent(); 16549 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16550 CI->getCallingConv())) 16551 return false; 16552 16553 // If the function is local then we have a good chance at tail-calling it 16554 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16555 } 16556 16557 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16558 if (!Subtarget.hasVSX()) 16559 return false; 16560 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16561 return true; 16562 return VT == MVT::f32 || VT == MVT::f64 || 16563 VT == MVT::v4f32 || VT == MVT::v2f64; 16564 } 16565 16566 bool PPCTargetLowering:: 16567 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16568 const Value *Mask = AndI.getOperand(1); 16569 // If the mask is suitable for andi. or andis. we should sink the and. 16570 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16571 // Can't handle constants wider than 64-bits. 16572 if (CI->getBitWidth() > 64) 16573 return false; 16574 int64_t ConstVal = CI->getZExtValue(); 16575 return isUInt<16>(ConstVal) || 16576 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16577 } 16578 16579 // For non-constant masks, we can always use the record-form and. 16580 return true; 16581 } 16582 16583 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16584 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16585 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16586 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16587 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16588 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16589 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16590 assert(Subtarget.hasP9Altivec() && 16591 "Only combine this when P9 altivec supported!"); 16592 EVT VT = N->getValueType(0); 16593 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16594 return SDValue(); 16595 16596 SelectionDAG &DAG = DCI.DAG; 16597 SDLoc dl(N); 16598 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16599 // Even for signed integers, if it's known to be positive (as signed 16600 // integer) due to zero-extended inputs. 16601 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16602 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16603 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16604 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16605 (SubOpcd1 == ISD::ZERO_EXTEND || 16606 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16607 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16608 N->getOperand(0)->getOperand(0), 16609 N->getOperand(0)->getOperand(1), 16610 DAG.getTargetConstant(0, dl, MVT::i32)); 16611 } 16612 16613 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16614 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16615 N->getOperand(0).hasOneUse()) { 16616 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16617 N->getOperand(0)->getOperand(0), 16618 N->getOperand(0)->getOperand(1), 16619 DAG.getTargetConstant(1, dl, MVT::i32)); 16620 } 16621 } 16622 16623 return SDValue(); 16624 } 16625 16626 // For type v4i32/v8ii16/v16i8, transform 16627 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16628 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16629 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16630 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16631 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16632 DAGCombinerInfo &DCI) const { 16633 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16634 assert(Subtarget.hasP9Altivec() && 16635 "Only combine this when P9 altivec supported!"); 16636 16637 SelectionDAG &DAG = DCI.DAG; 16638 SDLoc dl(N); 16639 SDValue Cond = N->getOperand(0); 16640 SDValue TrueOpnd = N->getOperand(1); 16641 SDValue FalseOpnd = N->getOperand(2); 16642 EVT VT = N->getOperand(1).getValueType(); 16643 16644 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16645 FalseOpnd.getOpcode() != ISD::SUB) 16646 return SDValue(); 16647 16648 // ABSD only available for type v4i32/v8i16/v16i8 16649 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16650 return SDValue(); 16651 16652 // At least to save one more dependent computation 16653 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16654 return SDValue(); 16655 16656 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16657 16658 // Can only handle unsigned comparison here 16659 switch (CC) { 16660 default: 16661 return SDValue(); 16662 case ISD::SETUGT: 16663 case ISD::SETUGE: 16664 break; 16665 case ISD::SETULT: 16666 case ISD::SETULE: 16667 std::swap(TrueOpnd, FalseOpnd); 16668 break; 16669 } 16670 16671 SDValue CmpOpnd1 = Cond.getOperand(0); 16672 SDValue CmpOpnd2 = Cond.getOperand(1); 16673 16674 // SETCC CmpOpnd1 CmpOpnd2 cond 16675 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16676 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16677 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16678 TrueOpnd.getOperand(1) == CmpOpnd2 && 16679 FalseOpnd.getOperand(0) == CmpOpnd2 && 16680 FalseOpnd.getOperand(1) == CmpOpnd1) { 16681 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16682 CmpOpnd1, CmpOpnd2, 16683 DAG.getTargetConstant(0, dl, MVT::i32)); 16684 } 16685 16686 return SDValue(); 16687 } 16688