1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the PPCISelLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCallingConv.h" 17 #include "PPCCCState.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCISelLowering.h" 21 #include "PPCMachineFunctionInfo.h" 22 #include "PPCPerfectShuffle.h" 23 #include "PPCRegisterInfo.h" 24 #include "PPCSubtarget.h" 25 #include "PPCTargetMachine.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/ADT/APInt.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/None.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/STLExtras.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/CodeGen/CallingConvLower.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineLoopInfo.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/MachineValueType.h" 51 #include "llvm/CodeGen/RuntimeLibcalls.h" 52 #include "llvm/CodeGen/SelectionDAG.h" 53 #include "llvm/CodeGen/SelectionDAGNodes.h" 54 #include "llvm/CodeGen/ValueTypes.h" 55 #include "llvm/IR/CallingConv.h" 56 #include "llvm/IR/CallSite.h" 57 #include "llvm/IR/Constant.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/Function.h" 63 #include "llvm/IR/GlobalValue.h" 64 #include "llvm/IR/Instructions.h" 65 #include "llvm/IR/Intrinsics.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Module.h" 68 #include "llvm/IR/Type.h" 69 #include "llvm/IR/Use.h" 70 #include "llvm/IR/Value.h" 71 #include "llvm/MC/MCExpr.h" 72 #include "llvm/MC/MCRegisterInfo.h" 73 #include "llvm/Support/AtomicOrdering.h" 74 #include "llvm/Support/BranchProbability.h" 75 #include "llvm/Support/Casting.h" 76 #include "llvm/Support/CodeGen.h" 77 #include "llvm/Support/CommandLine.h" 78 #include "llvm/Support/Compiler.h" 79 #include "llvm/Support/Debug.h" 80 #include "llvm/Support/ErrorHandling.h" 81 #include "llvm/Support/Format.h" 82 #include "llvm/Support/KnownBits.h" 83 #include "llvm/Support/MathExtras.h" 84 #include "llvm/Support/raw_ostream.h" 85 #include "llvm/Target/TargetInstrInfo.h" 86 #include "llvm/Target/TargetLowering.h" 87 #include "llvm/Target/TargetMachine.h" 88 #include "llvm/Target/TargetOptions.h" 89 #include "llvm/Target/TargetRegisterInfo.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <list> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 100 #define DEBUG_TYPE "ppc-lowering" 101 102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 104 105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisableSCO("disable-ppc-sco", 112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 113 114 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 116 117 // FIXME: Remove this once the bug has been fixed! 118 extern cl::opt<bool> ANDIGlueBug; 119 120 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 121 const PPCSubtarget &STI) 122 : TargetLowering(TM), Subtarget(STI) { 123 // Use _setjmp/_longjmp instead of setjmp/longjmp. 124 setUseUnderscoreSetJmp(true); 125 setUseUnderscoreLongJmp(true); 126 127 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 128 // arguments are at least 4/8 bytes aligned. 129 bool isPPC64 = Subtarget.isPPC64(); 130 setMinStackArgumentAlignment(isPPC64 ? 8:4); 131 132 // Set up the register classes. 133 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 134 if (!useSoftFloat()) { 135 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 136 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 137 } 138 139 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD 140 for (MVT VT : MVT::integer_valuetypes()) { 141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 142 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 143 } 144 145 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 146 147 // PowerPC has pre-inc load and store's. 148 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 149 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 150 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 151 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 152 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 153 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 154 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 155 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 156 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 157 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 158 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 159 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 160 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 161 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 162 163 if (Subtarget.useCRBits()) { 164 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 165 166 if (isPPC64 || Subtarget.hasFPCVT()) { 167 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 168 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 169 isPPC64 ? MVT::i64 : MVT::i32); 170 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 171 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 172 isPPC64 ? MVT::i64 : MVT::i32); 173 } else { 174 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 175 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 176 } 177 178 // PowerPC does not support direct load / store of condition registers 179 setOperationAction(ISD::LOAD, MVT::i1, Custom); 180 setOperationAction(ISD::STORE, MVT::i1, Custom); 181 182 // FIXME: Remove this once the ANDI glue bug is fixed: 183 if (ANDIGlueBug) 184 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 185 186 for (MVT VT : MVT::integer_valuetypes()) { 187 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 188 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 189 setTruncStoreAction(VT, MVT::i1, Expand); 190 } 191 192 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 193 } 194 195 // This is used in the ppcf128->int sequence. Note it has different semantics 196 // from FP_ROUND: that rounds to nearest, this rounds to zero. 197 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 198 199 // We do not currently implement these libm ops for PowerPC. 200 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 201 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 202 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 203 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 204 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 205 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 206 207 // PowerPC has no SREM/UREM instructions 208 setOperationAction(ISD::SREM, MVT::i32, Expand); 209 setOperationAction(ISD::UREM, MVT::i32, Expand); 210 setOperationAction(ISD::SREM, MVT::i64, Expand); 211 setOperationAction(ISD::UREM, MVT::i64, Expand); 212 213 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 214 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 215 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 216 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 217 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 218 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 219 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 220 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 221 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 222 223 // We don't support sin/cos/sqrt/fmod/pow 224 setOperationAction(ISD::FSIN , MVT::f64, Expand); 225 setOperationAction(ISD::FCOS , MVT::f64, Expand); 226 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 227 setOperationAction(ISD::FREM , MVT::f64, Expand); 228 setOperationAction(ISD::FPOW , MVT::f64, Expand); 229 setOperationAction(ISD::FMA , MVT::f64, Legal); 230 setOperationAction(ISD::FSIN , MVT::f32, Expand); 231 setOperationAction(ISD::FCOS , MVT::f32, Expand); 232 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 233 setOperationAction(ISD::FREM , MVT::f32, Expand); 234 setOperationAction(ISD::FPOW , MVT::f32, Expand); 235 setOperationAction(ISD::FMA , MVT::f32, Legal); 236 237 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 238 239 // If we're enabling GP optimizations, use hardware square root 240 if (!Subtarget.hasFSQRT() && 241 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 242 Subtarget.hasFRE())) 243 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 244 245 if (!Subtarget.hasFSQRT() && 246 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 247 Subtarget.hasFRES())) 248 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 249 250 if (Subtarget.hasFCPSGN()) { 251 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 252 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 253 } else { 254 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 255 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 256 } 257 258 if (Subtarget.hasFPRND()) { 259 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 260 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 261 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 262 setOperationAction(ISD::FROUND, MVT::f64, Legal); 263 264 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 265 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 266 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 267 setOperationAction(ISD::FROUND, MVT::f32, Legal); 268 } 269 270 // PowerPC does not have BSWAP 271 // CTPOP or CTTZ were introduced in P8/P9 respectivelly 272 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 273 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 274 if (Subtarget.isISA3_0()) { 275 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 276 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 277 } else { 278 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 279 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 280 } 281 282 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 283 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 284 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 285 } else { 286 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 287 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 288 } 289 290 // PowerPC does not have ROTR 291 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 292 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 293 294 if (!Subtarget.useCRBits()) { 295 // PowerPC does not have Select 296 setOperationAction(ISD::SELECT, MVT::i32, Expand); 297 setOperationAction(ISD::SELECT, MVT::i64, Expand); 298 setOperationAction(ISD::SELECT, MVT::f32, Expand); 299 setOperationAction(ISD::SELECT, MVT::f64, Expand); 300 } 301 302 // PowerPC wants to turn select_cc of FP into fsel when possible. 303 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 304 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 305 306 // PowerPC wants to optimize integer setcc a bit 307 if (!Subtarget.useCRBits()) 308 setOperationAction(ISD::SETCC, MVT::i32, Custom); 309 310 // PowerPC does not have BRCOND which requires SetCC 311 if (!Subtarget.useCRBits()) 312 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 313 314 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 315 316 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 317 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 318 319 // PowerPC does not have [U|S]INT_TO_FP 320 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 321 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 322 323 if (Subtarget.hasDirectMove() && isPPC64) { 324 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 325 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 326 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 327 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 328 } else { 329 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 330 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 331 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 332 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 333 } 334 335 // We cannot sextinreg(i1). Expand to shifts. 336 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 337 338 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 339 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 340 // support continuation, user-level threading, and etc.. As a result, no 341 // other SjLj exception interfaces are implemented and please don't build 342 // your own exception handling based on them. 343 // LLVM/Clang supports zero-cost DWARF exception handling. 344 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 345 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 346 347 // We want to legalize GlobalAddress and ConstantPool nodes into the 348 // appropriate instructions to materialize the address. 349 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 350 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 351 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 352 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 353 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 354 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 355 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 356 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 357 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 358 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 359 360 // TRAP is legal. 361 setOperationAction(ISD::TRAP, MVT::Other, Legal); 362 363 // TRAMPOLINE is custom lowered. 364 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 365 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 366 367 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 368 setOperationAction(ISD::VASTART , MVT::Other, Custom); 369 370 if (Subtarget.isSVR4ABI()) { 371 if (isPPC64) { 372 // VAARG always uses double-word chunks, so promote anything smaller. 373 setOperationAction(ISD::VAARG, MVT::i1, Promote); 374 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 375 setOperationAction(ISD::VAARG, MVT::i8, Promote); 376 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 377 setOperationAction(ISD::VAARG, MVT::i16, Promote); 378 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 379 setOperationAction(ISD::VAARG, MVT::i32, Promote); 380 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 381 setOperationAction(ISD::VAARG, MVT::Other, Expand); 382 } else { 383 // VAARG is custom lowered with the 32-bit SVR4 ABI. 384 setOperationAction(ISD::VAARG, MVT::Other, Custom); 385 setOperationAction(ISD::VAARG, MVT::i64, Custom); 386 } 387 } else 388 setOperationAction(ISD::VAARG, MVT::Other, Expand); 389 390 if (Subtarget.isSVR4ABI() && !isPPC64) 391 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 392 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 393 else 394 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 395 396 // Use the default implementation. 397 setOperationAction(ISD::VAEND , MVT::Other, Expand); 398 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 399 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 400 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 401 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 402 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 403 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 404 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 405 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 406 407 // We want to custom lower some of our intrinsics. 408 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 409 410 // To handle counter-based loop conditions. 411 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 412 413 // Comparisons that require checking two conditions. 414 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 415 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 416 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 417 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 418 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 419 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 420 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 421 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 422 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 423 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 424 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 425 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 426 427 if (Subtarget.has64BitSupport()) { 428 // They also have instructions for converting between i64 and fp. 429 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 430 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 431 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 432 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 433 // This is just the low 32 bits of a (signed) fp->i64 conversion. 434 // We cannot do this with Promote because i64 is not a legal type. 435 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 436 437 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 438 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 439 } else { 440 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 441 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 442 } 443 444 // With the instructions enabled under FPCVT, we can do everything. 445 if (Subtarget.hasFPCVT()) { 446 if (Subtarget.has64BitSupport()) { 447 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 448 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 449 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 450 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 451 } 452 453 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 454 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 455 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 456 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 457 } 458 459 if (Subtarget.use64BitRegs()) { 460 // 64-bit PowerPC implementations can support i64 types directly 461 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 462 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 463 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 464 // 64-bit PowerPC wants to expand i128 shifts itself. 465 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 466 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 467 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 468 } else { 469 // 32-bit PowerPC wants to expand i64 shifts itself. 470 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 471 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 472 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 473 } 474 475 if (Subtarget.hasAltivec()) { 476 // First set operation action for all vector types to expand. Then we 477 // will selectively turn on ones that can be effectively codegen'd. 478 for (MVT VT : MVT::vector_valuetypes()) { 479 // add/sub are legal for all supported vector VT's. 480 setOperationAction(ISD::ADD, VT, Legal); 481 setOperationAction(ISD::SUB, VT, Legal); 482 483 // Vector instructions introduced in P8 484 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 485 setOperationAction(ISD::CTPOP, VT, Legal); 486 setOperationAction(ISD::CTLZ, VT, Legal); 487 } 488 else { 489 setOperationAction(ISD::CTPOP, VT, Expand); 490 setOperationAction(ISD::CTLZ, VT, Expand); 491 } 492 493 // Vector instructions introduced in P9 494 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 495 setOperationAction(ISD::CTTZ, VT, Legal); 496 else 497 setOperationAction(ISD::CTTZ, VT, Expand); 498 499 // We promote all shuffles to v16i8. 500 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 501 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 502 503 // We promote all non-typed operations to v4i32. 504 setOperationAction(ISD::AND , VT, Promote); 505 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 506 setOperationAction(ISD::OR , VT, Promote); 507 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 508 setOperationAction(ISD::XOR , VT, Promote); 509 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 510 setOperationAction(ISD::LOAD , VT, Promote); 511 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 512 setOperationAction(ISD::SELECT, VT, Promote); 513 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 514 setOperationAction(ISD::SELECT_CC, VT, Promote); 515 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 516 setOperationAction(ISD::STORE, VT, Promote); 517 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 518 519 // No other operations are legal. 520 setOperationAction(ISD::MUL , VT, Expand); 521 setOperationAction(ISD::SDIV, VT, Expand); 522 setOperationAction(ISD::SREM, VT, Expand); 523 setOperationAction(ISD::UDIV, VT, Expand); 524 setOperationAction(ISD::UREM, VT, Expand); 525 setOperationAction(ISD::FDIV, VT, Expand); 526 setOperationAction(ISD::FREM, VT, Expand); 527 setOperationAction(ISD::FNEG, VT, Expand); 528 setOperationAction(ISD::FSQRT, VT, Expand); 529 setOperationAction(ISD::FLOG, VT, Expand); 530 setOperationAction(ISD::FLOG10, VT, Expand); 531 setOperationAction(ISD::FLOG2, VT, Expand); 532 setOperationAction(ISD::FEXP, VT, Expand); 533 setOperationAction(ISD::FEXP2, VT, Expand); 534 setOperationAction(ISD::FSIN, VT, Expand); 535 setOperationAction(ISD::FCOS, VT, Expand); 536 setOperationAction(ISD::FABS, VT, Expand); 537 setOperationAction(ISD::FPOWI, VT, Expand); 538 setOperationAction(ISD::FFLOOR, VT, Expand); 539 setOperationAction(ISD::FCEIL, VT, Expand); 540 setOperationAction(ISD::FTRUNC, VT, Expand); 541 setOperationAction(ISD::FRINT, VT, Expand); 542 setOperationAction(ISD::FNEARBYINT, VT, Expand); 543 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 544 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 545 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 546 setOperationAction(ISD::MULHU, VT, Expand); 547 setOperationAction(ISD::MULHS, VT, Expand); 548 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 549 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 550 setOperationAction(ISD::UDIVREM, VT, Expand); 551 setOperationAction(ISD::SDIVREM, VT, Expand); 552 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 553 setOperationAction(ISD::FPOW, VT, Expand); 554 setOperationAction(ISD::BSWAP, VT, Expand); 555 setOperationAction(ISD::VSELECT, VT, Expand); 556 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 557 setOperationAction(ISD::ROTL, VT, Expand); 558 setOperationAction(ISD::ROTR, VT, Expand); 559 560 for (MVT InnerVT : MVT::vector_valuetypes()) { 561 setTruncStoreAction(VT, InnerVT, Expand); 562 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 563 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 564 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 565 } 566 } 567 568 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 569 // with merges, splats, etc. 570 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 571 572 setOperationAction(ISD::AND , MVT::v4i32, Legal); 573 setOperationAction(ISD::OR , MVT::v4i32, Legal); 574 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 575 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 576 setOperationAction(ISD::SELECT, MVT::v4i32, 577 Subtarget.useCRBits() ? Legal : Expand); 578 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 579 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 580 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 581 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 582 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 583 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 584 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 585 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 586 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 587 588 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 589 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 590 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 591 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 592 593 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 594 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 595 596 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 597 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 598 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 599 } 600 601 if (Subtarget.hasP8Altivec()) 602 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 603 else 604 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 605 606 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 607 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 608 609 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 610 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 611 612 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 613 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 614 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 615 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 616 617 // Altivec does not contain unordered floating-point compare instructions 618 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 619 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 620 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 621 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 622 623 if (Subtarget.hasVSX()) { 624 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 625 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 626 if (Subtarget.hasP8Vector()) { 627 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 628 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 629 } 630 if (Subtarget.hasDirectMove() && isPPC64) { 631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 633 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 634 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 635 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 636 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 637 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 638 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 639 } 640 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 641 642 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 643 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 644 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 645 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 646 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 647 648 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 649 650 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 651 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 652 653 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 654 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 655 656 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 657 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 658 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 659 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 660 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 661 662 // Share the Altivec comparison restrictions. 663 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 664 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 665 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 666 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 667 668 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 669 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 670 671 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 672 673 if (Subtarget.hasP8Vector()) 674 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 675 676 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 677 678 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 679 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 680 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 681 682 if (Subtarget.hasP8Altivec()) { 683 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 684 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 685 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 686 687 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 688 } 689 else { 690 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 691 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 692 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 693 694 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 695 696 // VSX v2i64 only supports non-arithmetic operations. 697 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 698 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 699 } 700 701 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 702 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 703 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 704 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 705 706 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 707 708 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 709 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 710 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 711 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 712 713 // Vector operation legalization checks the result type of 714 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 715 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 716 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 717 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 718 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 719 720 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 721 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 722 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 723 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 724 725 if (Subtarget.hasDirectMove()) 726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 727 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 728 729 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 730 } 731 732 if (Subtarget.hasP8Altivec()) { 733 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 734 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 735 } 736 737 if (Subtarget.hasP9Vector()) { 738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 739 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 740 } 741 } 742 743 if (Subtarget.hasQPX()) { 744 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 745 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 746 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 747 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 748 749 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 750 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 751 752 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 753 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 754 755 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 756 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 757 758 if (!Subtarget.useCRBits()) 759 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 760 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 761 762 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 763 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 764 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 765 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 766 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 767 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 768 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 769 770 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 771 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 772 773 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 774 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 775 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 776 777 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 778 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 779 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 780 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 781 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand); 782 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 783 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 784 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 785 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 786 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 787 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 788 789 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 790 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 791 792 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 793 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 794 795 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 796 797 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 798 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 799 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 800 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 801 802 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 803 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 804 805 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 806 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 807 808 if (!Subtarget.useCRBits()) 809 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 810 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 811 812 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 813 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 814 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 815 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 816 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 818 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 819 820 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 821 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 822 823 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 824 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 825 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 826 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 827 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand); 828 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 829 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 830 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 831 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 832 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 833 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 834 835 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 836 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 837 838 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 839 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 840 841 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 842 843 setOperationAction(ISD::AND , MVT::v4i1, Legal); 844 setOperationAction(ISD::OR , MVT::v4i1, Legal); 845 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 846 847 if (!Subtarget.useCRBits()) 848 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 849 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 850 851 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 852 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 853 854 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 855 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 856 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 857 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 858 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 859 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 860 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 861 862 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 863 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 864 865 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 866 867 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 868 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 869 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 870 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 871 872 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 873 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 874 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 875 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 876 877 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 878 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 879 880 // These need to set FE_INEXACT, and so cannot be vectorized here. 881 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 882 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 883 884 if (TM.Options.UnsafeFPMath) { 885 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 886 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 887 888 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 889 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 890 } else { 891 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 892 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 893 894 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 895 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 896 } 897 } 898 899 if (Subtarget.has64BitSupport()) 900 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 901 902 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 903 904 if (!isPPC64) { 905 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 906 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 907 } 908 909 setBooleanContents(ZeroOrOneBooleanContent); 910 911 if (Subtarget.hasAltivec()) { 912 // Altivec instructions set fields to all zeros or all ones. 913 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 914 } 915 916 if (!isPPC64) { 917 // These libcalls are not available in 32-bit. 918 setLibcallName(RTLIB::SHL_I128, nullptr); 919 setLibcallName(RTLIB::SRL_I128, nullptr); 920 setLibcallName(RTLIB::SRA_I128, nullptr); 921 } 922 923 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 924 925 // We have target-specific dag combine patterns for the following nodes: 926 setTargetDAGCombine(ISD::SINT_TO_FP); 927 setTargetDAGCombine(ISD::BUILD_VECTOR); 928 if (Subtarget.hasFPCVT()) 929 setTargetDAGCombine(ISD::UINT_TO_FP); 930 setTargetDAGCombine(ISD::LOAD); 931 setTargetDAGCombine(ISD::STORE); 932 setTargetDAGCombine(ISD::BR_CC); 933 if (Subtarget.useCRBits()) 934 setTargetDAGCombine(ISD::BRCOND); 935 setTargetDAGCombine(ISD::BSWAP); 936 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 937 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 938 setTargetDAGCombine(ISD::INTRINSIC_VOID); 939 940 setTargetDAGCombine(ISD::SIGN_EXTEND); 941 setTargetDAGCombine(ISD::ZERO_EXTEND); 942 setTargetDAGCombine(ISD::ANY_EXTEND); 943 944 if (Subtarget.useCRBits()) { 945 setTargetDAGCombine(ISD::TRUNCATE); 946 setTargetDAGCombine(ISD::SETCC); 947 setTargetDAGCombine(ISD::SELECT_CC); 948 } 949 950 // Use reciprocal estimates. 951 if (TM.Options.UnsafeFPMath) { 952 setTargetDAGCombine(ISD::FDIV); 953 setTargetDAGCombine(ISD::FSQRT); 954 } 955 956 // Darwin long double math library functions have $LDBL128 appended. 957 if (Subtarget.isDarwin()) { 958 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 959 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 960 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 961 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 962 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 963 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 964 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 965 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 966 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 967 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 968 } 969 970 // With 32 condition bits, we don't need to sink (and duplicate) compares 971 // aggressively in CodeGenPrep. 972 if (Subtarget.useCRBits()) { 973 setHasMultipleConditionRegisters(); 974 setJumpIsExpensive(); 975 } 976 977 setMinFunctionAlignment(2); 978 if (Subtarget.isDarwin()) 979 setPrefFunctionAlignment(4); 980 981 switch (Subtarget.getDarwinDirective()) { 982 default: break; 983 case PPC::DIR_970: 984 case PPC::DIR_A2: 985 case PPC::DIR_E500mc: 986 case PPC::DIR_E5500: 987 case PPC::DIR_PWR4: 988 case PPC::DIR_PWR5: 989 case PPC::DIR_PWR5X: 990 case PPC::DIR_PWR6: 991 case PPC::DIR_PWR6X: 992 case PPC::DIR_PWR7: 993 case PPC::DIR_PWR8: 994 case PPC::DIR_PWR9: 995 setPrefFunctionAlignment(4); 996 setPrefLoopAlignment(4); 997 break; 998 } 999 1000 if (Subtarget.enableMachineScheduler()) 1001 setSchedulingPreference(Sched::Source); 1002 else 1003 setSchedulingPreference(Sched::Hybrid); 1004 1005 computeRegisterProperties(STI.getRegisterInfo()); 1006 1007 // The Freescale cores do better with aggressive inlining of memcpy and 1008 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1009 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1010 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1011 MaxStoresPerMemset = 32; 1012 MaxStoresPerMemsetOptSize = 16; 1013 MaxStoresPerMemcpy = 32; 1014 MaxStoresPerMemcpyOptSize = 8; 1015 MaxStoresPerMemmove = 32; 1016 MaxStoresPerMemmoveOptSize = 8; 1017 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1018 // The A2 also benefits from (very) aggressive inlining of memcpy and 1019 // friends. The overhead of a the function call, even when warm, can be 1020 // over one hundred cycles. 1021 MaxStoresPerMemset = 128; 1022 MaxStoresPerMemcpy = 128; 1023 MaxStoresPerMemmove = 128; 1024 } 1025 } 1026 1027 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1028 /// the desired ByVal argument alignment. 1029 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1030 unsigned MaxMaxAlign) { 1031 if (MaxAlign == MaxMaxAlign) 1032 return; 1033 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1034 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1035 MaxAlign = 32; 1036 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1037 MaxAlign = 16; 1038 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1039 unsigned EltAlign = 0; 1040 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1041 if (EltAlign > MaxAlign) 1042 MaxAlign = EltAlign; 1043 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1044 for (auto *EltTy : STy->elements()) { 1045 unsigned EltAlign = 0; 1046 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1047 if (EltAlign > MaxAlign) 1048 MaxAlign = EltAlign; 1049 if (MaxAlign == MaxMaxAlign) 1050 break; 1051 } 1052 } 1053 } 1054 1055 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1056 /// function arguments in the caller parameter area. 1057 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1058 const DataLayout &DL) const { 1059 // Darwin passes everything on 4 byte boundary. 1060 if (Subtarget.isDarwin()) 1061 return 4; 1062 1063 // 16byte and wider vectors are passed on 16byte boundary. 1064 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1065 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1066 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1067 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1068 return Align; 1069 } 1070 1071 bool PPCTargetLowering::useSoftFloat() const { 1072 return Subtarget.useSoftFloat(); 1073 } 1074 1075 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1076 switch ((PPCISD::NodeType)Opcode) { 1077 case PPCISD::FIRST_NUMBER: break; 1078 case PPCISD::FSEL: return "PPCISD::FSEL"; 1079 case PPCISD::FCFID: return "PPCISD::FCFID"; 1080 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1081 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1082 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1083 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1084 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1085 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1086 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1087 case PPCISD::FRE: return "PPCISD::FRE"; 1088 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1089 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1090 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1091 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1092 case PPCISD::VPERM: return "PPCISD::VPERM"; 1093 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1094 case PPCISD::XXINSERT: return "PPCISD::XXINSERT"; 1095 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1096 case PPCISD::CMPB: return "PPCISD::CMPB"; 1097 case PPCISD::Hi: return "PPCISD::Hi"; 1098 case PPCISD::Lo: return "PPCISD::Lo"; 1099 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1100 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1101 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1102 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1103 case PPCISD::SRL: return "PPCISD::SRL"; 1104 case PPCISD::SRA: return "PPCISD::SRA"; 1105 case PPCISD::SHL: return "PPCISD::SHL"; 1106 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1107 case PPCISD::CALL: return "PPCISD::CALL"; 1108 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1109 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1110 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1111 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1112 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1113 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1114 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1115 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1116 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1117 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1118 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1119 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1120 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1121 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1122 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1123 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1124 case PPCISD::VCMP: return "PPCISD::VCMP"; 1125 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1126 case PPCISD::LBRX: return "PPCISD::LBRX"; 1127 case PPCISD::STBRX: return "PPCISD::STBRX"; 1128 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1129 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1130 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1131 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1132 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1133 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1134 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1135 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1136 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1137 case PPCISD::BDZ: return "PPCISD::BDZ"; 1138 case PPCISD::MFFS: return "PPCISD::MFFS"; 1139 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1140 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1141 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1142 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1143 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1144 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1145 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1146 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1147 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1148 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1149 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1150 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1151 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1152 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1153 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1154 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1155 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1156 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1157 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1158 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1159 case PPCISD::SC: return "PPCISD::SC"; 1160 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1161 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1162 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1163 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1164 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1165 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1166 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1167 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1168 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1169 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1170 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1171 } 1172 return nullptr; 1173 } 1174 1175 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1176 EVT VT) const { 1177 if (!VT.isVector()) 1178 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1179 1180 if (Subtarget.hasQPX()) 1181 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1182 1183 return VT.changeVectorElementTypeToInteger(); 1184 } 1185 1186 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1187 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1188 return true; 1189 } 1190 1191 //===----------------------------------------------------------------------===// 1192 // Node matching predicates, for use by the tblgen matching code. 1193 //===----------------------------------------------------------------------===// 1194 1195 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1196 static bool isFloatingPointZero(SDValue Op) { 1197 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1198 return CFP->getValueAPF().isZero(); 1199 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1200 // Maybe this has already been legalized into the constant pool? 1201 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1202 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1203 return CFP->getValueAPF().isZero(); 1204 } 1205 return false; 1206 } 1207 1208 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1209 /// true if Op is undef or if it matches the specified value. 1210 static bool isConstantOrUndef(int Op, int Val) { 1211 return Op < 0 || Op == Val; 1212 } 1213 1214 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1215 /// VPKUHUM instruction. 1216 /// The ShuffleKind distinguishes between big-endian operations with 1217 /// two different inputs (0), either-endian operations with two identical 1218 /// inputs (1), and little-endian operations with two different inputs (2). 1219 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1220 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1221 SelectionDAG &DAG) { 1222 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1223 if (ShuffleKind == 0) { 1224 if (IsLE) 1225 return false; 1226 for (unsigned i = 0; i != 16; ++i) 1227 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1228 return false; 1229 } else if (ShuffleKind == 2) { 1230 if (!IsLE) 1231 return false; 1232 for (unsigned i = 0; i != 16; ++i) 1233 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1234 return false; 1235 } else if (ShuffleKind == 1) { 1236 unsigned j = IsLE ? 0 : 1; 1237 for (unsigned i = 0; i != 8; ++i) 1238 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1239 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1240 return false; 1241 } 1242 return true; 1243 } 1244 1245 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1246 /// VPKUWUM instruction. 1247 /// The ShuffleKind distinguishes between big-endian operations with 1248 /// two different inputs (0), either-endian operations with two identical 1249 /// inputs (1), and little-endian operations with two different inputs (2). 1250 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1251 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1252 SelectionDAG &DAG) { 1253 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1254 if (ShuffleKind == 0) { 1255 if (IsLE) 1256 return false; 1257 for (unsigned i = 0; i != 16; i += 2) 1258 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1259 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1260 return false; 1261 } else if (ShuffleKind == 2) { 1262 if (!IsLE) 1263 return false; 1264 for (unsigned i = 0; i != 16; i += 2) 1265 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1266 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1267 return false; 1268 } else if (ShuffleKind == 1) { 1269 unsigned j = IsLE ? 0 : 2; 1270 for (unsigned i = 0; i != 8; i += 2) 1271 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1272 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1273 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1274 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1275 return false; 1276 } 1277 return true; 1278 } 1279 1280 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1281 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1282 /// current subtarget. 1283 /// 1284 /// The ShuffleKind distinguishes between big-endian operations with 1285 /// two different inputs (0), either-endian operations with two identical 1286 /// inputs (1), and little-endian operations with two different inputs (2). 1287 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1288 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1289 SelectionDAG &DAG) { 1290 const PPCSubtarget& Subtarget = 1291 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1292 if (!Subtarget.hasP8Vector()) 1293 return false; 1294 1295 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1296 if (ShuffleKind == 0) { 1297 if (IsLE) 1298 return false; 1299 for (unsigned i = 0; i != 16; i += 4) 1300 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1301 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1302 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1303 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1304 return false; 1305 } else if (ShuffleKind == 2) { 1306 if (!IsLE) 1307 return false; 1308 for (unsigned i = 0; i != 16; i += 4) 1309 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1310 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1311 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1312 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1313 return false; 1314 } else if (ShuffleKind == 1) { 1315 unsigned j = IsLE ? 0 : 4; 1316 for (unsigned i = 0; i != 8; i += 4) 1317 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1318 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1319 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1320 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1321 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1322 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1323 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1324 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1325 return false; 1326 } 1327 return true; 1328 } 1329 1330 /// isVMerge - Common function, used to match vmrg* shuffles. 1331 /// 1332 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1333 unsigned LHSStart, unsigned RHSStart) { 1334 if (N->getValueType(0) != MVT::v16i8) 1335 return false; 1336 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1337 "Unsupported merge size!"); 1338 1339 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1340 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1341 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1342 LHSStart+j+i*UnitSize) || 1343 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1344 RHSStart+j+i*UnitSize)) 1345 return false; 1346 } 1347 return true; 1348 } 1349 1350 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1351 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1352 /// The ShuffleKind distinguishes between big-endian merges with two 1353 /// different inputs (0), either-endian merges with two identical inputs (1), 1354 /// and little-endian merges with two different inputs (2). For the latter, 1355 /// the input operands are swapped (see PPCInstrAltivec.td). 1356 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1357 unsigned ShuffleKind, SelectionDAG &DAG) { 1358 if (DAG.getDataLayout().isLittleEndian()) { 1359 if (ShuffleKind == 1) // unary 1360 return isVMerge(N, UnitSize, 0, 0); 1361 else if (ShuffleKind == 2) // swapped 1362 return isVMerge(N, UnitSize, 0, 16); 1363 else 1364 return false; 1365 } else { 1366 if (ShuffleKind == 1) // unary 1367 return isVMerge(N, UnitSize, 8, 8); 1368 else if (ShuffleKind == 0) // normal 1369 return isVMerge(N, UnitSize, 8, 24); 1370 else 1371 return false; 1372 } 1373 } 1374 1375 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1376 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1377 /// The ShuffleKind distinguishes between big-endian merges with two 1378 /// different inputs (0), either-endian merges with two identical inputs (1), 1379 /// and little-endian merges with two different inputs (2). For the latter, 1380 /// the input operands are swapped (see PPCInstrAltivec.td). 1381 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1382 unsigned ShuffleKind, SelectionDAG &DAG) { 1383 if (DAG.getDataLayout().isLittleEndian()) { 1384 if (ShuffleKind == 1) // unary 1385 return isVMerge(N, UnitSize, 8, 8); 1386 else if (ShuffleKind == 2) // swapped 1387 return isVMerge(N, UnitSize, 8, 24); 1388 else 1389 return false; 1390 } else { 1391 if (ShuffleKind == 1) // unary 1392 return isVMerge(N, UnitSize, 0, 0); 1393 else if (ShuffleKind == 0) // normal 1394 return isVMerge(N, UnitSize, 0, 16); 1395 else 1396 return false; 1397 } 1398 } 1399 1400 /** 1401 * \brief Common function used to match vmrgew and vmrgow shuffles 1402 * 1403 * The indexOffset determines whether to look for even or odd words in 1404 * the shuffle mask. This is based on the of the endianness of the target 1405 * machine. 1406 * - Little Endian: 1407 * - Use offset of 0 to check for odd elements 1408 * - Use offset of 4 to check for even elements 1409 * - Big Endian: 1410 * - Use offset of 0 to check for even elements 1411 * - Use offset of 4 to check for odd elements 1412 * A detailed description of the vector element ordering for little endian and 1413 * big endian can be found at 1414 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1415 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1416 * compiler differences mean to you 1417 * 1418 * The mask to the shuffle vector instruction specifies the indices of the 1419 * elements from the two input vectors to place in the result. The elements are 1420 * numbered in array-access order, starting with the first vector. These vectors 1421 * are always of type v16i8, thus each vector will contain 16 elements of size 1422 * 8. More info on the shuffle vector can be found in the 1423 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1424 * Language Reference. 1425 * 1426 * The RHSStartValue indicates whether the same input vectors are used (unary) 1427 * or two different input vectors are used, based on the following: 1428 * - If the instruction uses the same vector for both inputs, the range of the 1429 * indices will be 0 to 15. In this case, the RHSStart value passed should 1430 * be 0. 1431 * - If the instruction has two different vectors then the range of the 1432 * indices will be 0 to 31. In this case, the RHSStart value passed should 1433 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1434 * to 31 specify elements in the second vector). 1435 * 1436 * \param[in] N The shuffle vector SD Node to analyze 1437 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1438 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1439 * vector to the shuffle_vector instruction 1440 * \return true iff this shuffle vector represents an even or odd word merge 1441 */ 1442 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1443 unsigned RHSStartValue) { 1444 if (N->getValueType(0) != MVT::v16i8) 1445 return false; 1446 1447 for (unsigned i = 0; i < 2; ++i) 1448 for (unsigned j = 0; j < 4; ++j) 1449 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1450 i*RHSStartValue+j+IndexOffset) || 1451 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1452 i*RHSStartValue+j+IndexOffset+8)) 1453 return false; 1454 return true; 1455 } 1456 1457 /** 1458 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or 1459 * vmrgow instructions. 1460 * 1461 * \param[in] N The shuffle vector SD Node to analyze 1462 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1463 * \param[in] ShuffleKind Identify the type of merge: 1464 * - 0 = big-endian merge with two different inputs; 1465 * - 1 = either-endian merge with two identical inputs; 1466 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1467 * little-endian merges). 1468 * \param[in] DAG The current SelectionDAG 1469 * \return true iff this shuffle mask 1470 */ 1471 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1472 unsigned ShuffleKind, SelectionDAG &DAG) { 1473 if (DAG.getDataLayout().isLittleEndian()) { 1474 unsigned indexOffset = CheckEven ? 4 : 0; 1475 if (ShuffleKind == 1) // Unary 1476 return isVMerge(N, indexOffset, 0); 1477 else if (ShuffleKind == 2) // swapped 1478 return isVMerge(N, indexOffset, 16); 1479 else 1480 return false; 1481 } 1482 else { 1483 unsigned indexOffset = CheckEven ? 0 : 4; 1484 if (ShuffleKind == 1) // Unary 1485 return isVMerge(N, indexOffset, 0); 1486 else if (ShuffleKind == 0) // Normal 1487 return isVMerge(N, indexOffset, 16); 1488 else 1489 return false; 1490 } 1491 return false; 1492 } 1493 1494 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1495 /// amount, otherwise return -1. 1496 /// The ShuffleKind distinguishes between big-endian operations with two 1497 /// different inputs (0), either-endian operations with two identical inputs 1498 /// (1), and little-endian operations with two different inputs (2). For the 1499 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1500 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1501 SelectionDAG &DAG) { 1502 if (N->getValueType(0) != MVT::v16i8) 1503 return -1; 1504 1505 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1506 1507 // Find the first non-undef value in the shuffle mask. 1508 unsigned i; 1509 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1510 /*search*/; 1511 1512 if (i == 16) return -1; // all undef. 1513 1514 // Otherwise, check to see if the rest of the elements are consecutively 1515 // numbered from this value. 1516 unsigned ShiftAmt = SVOp->getMaskElt(i); 1517 if (ShiftAmt < i) return -1; 1518 1519 ShiftAmt -= i; 1520 bool isLE = DAG.getDataLayout().isLittleEndian(); 1521 1522 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1523 // Check the rest of the elements to see if they are consecutive. 1524 for (++i; i != 16; ++i) 1525 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1526 return -1; 1527 } else if (ShuffleKind == 1) { 1528 // Check the rest of the elements to see if they are consecutive. 1529 for (++i; i != 16; ++i) 1530 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1531 return -1; 1532 } else 1533 return -1; 1534 1535 if (isLE) 1536 ShiftAmt = 16 - ShiftAmt; 1537 1538 return ShiftAmt; 1539 } 1540 1541 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1542 /// specifies a splat of a single element that is suitable for input to 1543 /// VSPLTB/VSPLTH/VSPLTW. 1544 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1545 assert(N->getValueType(0) == MVT::v16i8 && 1546 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1547 1548 // The consecutive indices need to specify an element, not part of two 1549 // different elements. So abandon ship early if this isn't the case. 1550 if (N->getMaskElt(0) % EltSize != 0) 1551 return false; 1552 1553 // This is a splat operation if each element of the permute is the same, and 1554 // if the value doesn't reference the second vector. 1555 unsigned ElementBase = N->getMaskElt(0); 1556 1557 // FIXME: Handle UNDEF elements too! 1558 if (ElementBase >= 16) 1559 return false; 1560 1561 // Check that the indices are consecutive, in the case of a multi-byte element 1562 // splatted with a v16i8 mask. 1563 for (unsigned i = 1; i != EltSize; ++i) 1564 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1565 return false; 1566 1567 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1568 if (N->getMaskElt(i) < 0) continue; 1569 for (unsigned j = 0; j != EltSize; ++j) 1570 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1571 return false; 1572 } 1573 return true; 1574 } 1575 1576 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1577 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1578 // Check that the mask is shuffling words 1579 for (unsigned i = 0; i < 4; ++i) { 1580 unsigned B0 = N->getMaskElt(i*4); 1581 unsigned B1 = N->getMaskElt(i*4+1); 1582 unsigned B2 = N->getMaskElt(i*4+2); 1583 unsigned B3 = N->getMaskElt(i*4+3); 1584 if (B0 % 4) 1585 return false; 1586 if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1) 1587 return false; 1588 } 1589 1590 // Now we look at mask elements 0,4,8,12 1591 unsigned M0 = N->getMaskElt(0) / 4; 1592 unsigned M1 = N->getMaskElt(4) / 4; 1593 unsigned M2 = N->getMaskElt(8) / 4; 1594 unsigned M3 = N->getMaskElt(12) / 4; 1595 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1596 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1597 1598 // Below, let H and L be arbitrary elements of the shuffle mask 1599 // where H is in the range [4,7] and L is in the range [0,3]. 1600 // H, 1, 2, 3 or L, 5, 6, 7 1601 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1602 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1603 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1604 InsertAtByte = IsLE ? 12 : 0; 1605 Swap = M0 < 4; 1606 return true; 1607 } 1608 // 0, H, 2, 3 or 4, L, 6, 7 1609 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1610 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1611 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1612 InsertAtByte = IsLE ? 8 : 4; 1613 Swap = M1 < 4; 1614 return true; 1615 } 1616 // 0, 1, H, 3 or 4, 5, L, 7 1617 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1618 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1619 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1620 InsertAtByte = IsLE ? 4 : 8; 1621 Swap = M2 < 4; 1622 return true; 1623 } 1624 // 0, 1, 2, H or 4, 5, 6, L 1625 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1626 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1627 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1628 InsertAtByte = IsLE ? 0 : 12; 1629 Swap = M3 < 4; 1630 return true; 1631 } 1632 1633 // If both vector operands for the shuffle are the same vector, the mask will 1634 // contain only elements from the first one and the second one will be undef. 1635 if (N->getOperand(1).isUndef()) { 1636 ShiftElts = 0; 1637 Swap = true; 1638 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1639 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1640 InsertAtByte = IsLE ? 12 : 0; 1641 return true; 1642 } 1643 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1644 InsertAtByte = IsLE ? 8 : 4; 1645 return true; 1646 } 1647 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1648 InsertAtByte = IsLE ? 4 : 8; 1649 return true; 1650 } 1651 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1652 InsertAtByte = IsLE ? 0 : 12; 1653 return true; 1654 } 1655 } 1656 1657 return false; 1658 } 1659 1660 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1661 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1662 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1663 SelectionDAG &DAG) { 1664 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1665 assert(isSplatShuffleMask(SVOp, EltSize)); 1666 if (DAG.getDataLayout().isLittleEndian()) 1667 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1668 else 1669 return SVOp->getMaskElt(0) / EltSize; 1670 } 1671 1672 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1673 /// by using a vspltis[bhw] instruction of the specified element size, return 1674 /// the constant being splatted. The ByteSize field indicates the number of 1675 /// bytes of each element [124] -> [bhw]. 1676 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1677 SDValue OpVal(nullptr, 0); 1678 1679 // If ByteSize of the splat is bigger than the element size of the 1680 // build_vector, then we have a case where we are checking for a splat where 1681 // multiple elements of the buildvector are folded together into a single 1682 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1683 unsigned EltSize = 16/N->getNumOperands(); 1684 if (EltSize < ByteSize) { 1685 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1686 SDValue UniquedVals[4]; 1687 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1688 1689 // See if all of the elements in the buildvector agree across. 1690 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1691 if (N->getOperand(i).isUndef()) continue; 1692 // If the element isn't a constant, bail fully out. 1693 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1694 1695 if (!UniquedVals[i&(Multiple-1)].getNode()) 1696 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1697 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1698 return SDValue(); // no match. 1699 } 1700 1701 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1702 // either constant or undef values that are identical for each chunk. See 1703 // if these chunks can form into a larger vspltis*. 1704 1705 // Check to see if all of the leading entries are either 0 or -1. If 1706 // neither, then this won't fit into the immediate field. 1707 bool LeadingZero = true; 1708 bool LeadingOnes = true; 1709 for (unsigned i = 0; i != Multiple-1; ++i) { 1710 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1711 1712 LeadingZero &= isNullConstant(UniquedVals[i]); 1713 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 1714 } 1715 // Finally, check the least significant entry. 1716 if (LeadingZero) { 1717 if (!UniquedVals[Multiple-1].getNode()) 1718 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 1719 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1720 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 1721 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1722 } 1723 if (LeadingOnes) { 1724 if (!UniquedVals[Multiple-1].getNode()) 1725 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 1726 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1727 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1728 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1729 } 1730 1731 return SDValue(); 1732 } 1733 1734 // Check to see if this buildvec has a single non-undef value in its elements. 1735 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1736 if (N->getOperand(i).isUndef()) continue; 1737 if (!OpVal.getNode()) 1738 OpVal = N->getOperand(i); 1739 else if (OpVal != N->getOperand(i)) 1740 return SDValue(); 1741 } 1742 1743 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1744 1745 unsigned ValSizeInBytes = EltSize; 1746 uint64_t Value = 0; 1747 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1748 Value = CN->getZExtValue(); 1749 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 1750 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 1751 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 1752 } 1753 1754 // If the splat value is larger than the element value, then we can never do 1755 // this splat. The only case that we could fit the replicated bits into our 1756 // immediate field for would be zero, and we prefer to use vxor for it. 1757 if (ValSizeInBytes < ByteSize) return SDValue(); 1758 1759 // If the element value is larger than the splat value, check if it consists 1760 // of a repeated bit pattern of size ByteSize. 1761 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 1762 return SDValue(); 1763 1764 // Properly sign extend the value. 1765 int MaskVal = SignExtend32(Value, ByteSize * 8); 1766 1767 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 1768 if (MaskVal == 0) return SDValue(); 1769 1770 // Finally, if this value fits in a 5 bit sext field, return it 1771 if (SignExtend32<5>(MaskVal) == MaskVal) 1772 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 1773 return SDValue(); 1774 } 1775 1776 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 1777 /// amount, otherwise return -1. 1778 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 1779 EVT VT = N->getValueType(0); 1780 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 1781 return -1; 1782 1783 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1784 1785 // Find the first non-undef value in the shuffle mask. 1786 unsigned i; 1787 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 1788 /*search*/; 1789 1790 if (i == 4) return -1; // all undef. 1791 1792 // Otherwise, check to see if the rest of the elements are consecutively 1793 // numbered from this value. 1794 unsigned ShiftAmt = SVOp->getMaskElt(i); 1795 if (ShiftAmt < i) return -1; 1796 ShiftAmt -= i; 1797 1798 // Check the rest of the elements to see if they are consecutive. 1799 for (++i; i != 4; ++i) 1800 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1801 return -1; 1802 1803 return ShiftAmt; 1804 } 1805 1806 //===----------------------------------------------------------------------===// 1807 // Addressing Mode Selection 1808 //===----------------------------------------------------------------------===// 1809 1810 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 1811 /// or 64-bit immediate, and if the value can be accurately represented as a 1812 /// sign extension from a 16-bit value. If so, this returns true and the 1813 /// immediate. 1814 static bool isIntS16Immediate(SDNode *N, short &Imm) { 1815 if (!isa<ConstantSDNode>(N)) 1816 return false; 1817 1818 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); 1819 if (N->getValueType(0) == MVT::i32) 1820 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 1821 else 1822 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 1823 } 1824 static bool isIntS16Immediate(SDValue Op, short &Imm) { 1825 return isIntS16Immediate(Op.getNode(), Imm); 1826 } 1827 1828 /// SelectAddressRegReg - Given the specified addressed, check to see if it 1829 /// can be represented as an indexed [r+r] operation. Returns false if it 1830 /// can be more efficiently represented with [r+imm]. 1831 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 1832 SDValue &Index, 1833 SelectionDAG &DAG) const { 1834 short imm = 0; 1835 if (N.getOpcode() == ISD::ADD) { 1836 if (isIntS16Immediate(N.getOperand(1), imm)) 1837 return false; // r+i 1838 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 1839 return false; // r+i 1840 1841 Base = N.getOperand(0); 1842 Index = N.getOperand(1); 1843 return true; 1844 } else if (N.getOpcode() == ISD::OR) { 1845 if (isIntS16Immediate(N.getOperand(1), imm)) 1846 return false; // r+i can fold it if we can. 1847 1848 // If this is an or of disjoint bitfields, we can codegen this as an add 1849 // (for better address arithmetic) if the LHS and RHS of the OR are provably 1850 // disjoint. 1851 KnownBits LHSKnown, RHSKnown; 1852 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 1853 1854 if (LHSKnown.Zero.getBoolValue()) { 1855 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 1856 // If all of the bits are known zero on the LHS or RHS, the add won't 1857 // carry. 1858 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 1859 Base = N.getOperand(0); 1860 Index = N.getOperand(1); 1861 return true; 1862 } 1863 } 1864 } 1865 1866 return false; 1867 } 1868 1869 // If we happen to be doing an i64 load or store into a stack slot that has 1870 // less than a 4-byte alignment, then the frame-index elimination may need to 1871 // use an indexed load or store instruction (because the offset may not be a 1872 // multiple of 4). The extra register needed to hold the offset comes from the 1873 // register scavenger, and it is possible that the scavenger will need to use 1874 // an emergency spill slot. As a result, we need to make sure that a spill slot 1875 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 1876 // stack slot. 1877 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 1878 // FIXME: This does not handle the LWA case. 1879 if (VT != MVT::i64) 1880 return; 1881 1882 // NOTE: We'll exclude negative FIs here, which come from argument 1883 // lowering, because there are no known test cases triggering this problem 1884 // using packed structures (or similar). We can remove this exclusion if 1885 // we find such a test case. The reason why this is so test-case driven is 1886 // because this entire 'fixup' is only to prevent crashes (from the 1887 // register scavenger) on not-really-valid inputs. For example, if we have: 1888 // %a = alloca i1 1889 // %b = bitcast i1* %a to i64* 1890 // store i64* a, i64 b 1891 // then the store should really be marked as 'align 1', but is not. If it 1892 // were marked as 'align 1' then the indexed form would have been 1893 // instruction-selected initially, and the problem this 'fixup' is preventing 1894 // won't happen regardless. 1895 if (FrameIdx < 0) 1896 return; 1897 1898 MachineFunction &MF = DAG.getMachineFunction(); 1899 MachineFrameInfo &MFI = MF.getFrameInfo(); 1900 1901 unsigned Align = MFI.getObjectAlignment(FrameIdx); 1902 if (Align >= 4) 1903 return; 1904 1905 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1906 FuncInfo->setHasNonRISpills(); 1907 } 1908 1909 /// Returns true if the address N can be represented by a base register plus 1910 /// a signed 16-bit displacement [r+imm], and if it is not better 1911 /// represented as reg+reg. If Aligned is true, only accept displacements 1912 /// suitable for STD and friends, i.e. multiples of 4. 1913 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 1914 SDValue &Base, 1915 SelectionDAG &DAG, 1916 bool Aligned) const { 1917 // FIXME dl should come from parent load or store, not from address 1918 SDLoc dl(N); 1919 // If this can be more profitably realized as r+r, fail. 1920 if (SelectAddressRegReg(N, Disp, Base, DAG)) 1921 return false; 1922 1923 if (N.getOpcode() == ISD::ADD) { 1924 short imm = 0; 1925 if (isIntS16Immediate(N.getOperand(1), imm) && 1926 (!Aligned || (imm & 3) == 0)) { 1927 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 1928 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1929 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1930 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1931 } else { 1932 Base = N.getOperand(0); 1933 } 1934 return true; // [r+i] 1935 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 1936 // Match LOAD (ADD (X, Lo(G))). 1937 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 1938 && "Cannot handle constant offsets yet!"); 1939 Disp = N.getOperand(1).getOperand(0); // The global address. 1940 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 1941 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 1942 Disp.getOpcode() == ISD::TargetConstantPool || 1943 Disp.getOpcode() == ISD::TargetJumpTable); 1944 Base = N.getOperand(0); 1945 return true; // [&g+r] 1946 } 1947 } else if (N.getOpcode() == ISD::OR) { 1948 short imm = 0; 1949 if (isIntS16Immediate(N.getOperand(1), imm) && 1950 (!Aligned || (imm & 3) == 0)) { 1951 // If this is an or of disjoint bitfields, we can codegen this as an add 1952 // (for better address arithmetic) if the LHS and RHS of the OR are 1953 // provably disjoint. 1954 KnownBits LHSKnown; 1955 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 1956 1957 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 1958 // If all of the bits are known zero on the LHS or RHS, the add won't 1959 // carry. 1960 if (FrameIndexSDNode *FI = 1961 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1962 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1963 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1964 } else { 1965 Base = N.getOperand(0); 1966 } 1967 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 1968 return true; 1969 } 1970 } 1971 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 1972 // Loading from a constant address. 1973 1974 // If this address fits entirely in a 16-bit sext immediate field, codegen 1975 // this as "d, 0" 1976 short Imm; 1977 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) { 1978 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 1979 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 1980 CN->getValueType(0)); 1981 return true; 1982 } 1983 1984 // Handle 32-bit sext immediates with LIS + addr mode. 1985 if ((CN->getValueType(0) == MVT::i32 || 1986 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 1987 (!Aligned || (CN->getZExtValue() & 3) == 0)) { 1988 int Addr = (int)CN->getZExtValue(); 1989 1990 // Otherwise, break this down into an LIS + disp. 1991 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 1992 1993 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 1994 MVT::i32); 1995 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 1996 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 1997 return true; 1998 } 1999 } 2000 2001 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2002 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2003 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2004 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2005 } else 2006 Base = N; 2007 return true; // [r+0] 2008 } 2009 2010 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2011 /// represented as an indexed [r+r] operation. 2012 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2013 SDValue &Index, 2014 SelectionDAG &DAG) const { 2015 // Check to see if we can easily represent this as an [r+r] address. This 2016 // will fail if it thinks that the address is more profitably represented as 2017 // reg+imm, e.g. where imm = 0. 2018 if (SelectAddressRegReg(N, Base, Index, DAG)) 2019 return true; 2020 2021 // If the operand is an addition, always emit this as [r+r], since this is 2022 // better (for code size, and execution, as the memop does the add for free) 2023 // than emitting an explicit add. 2024 if (N.getOpcode() == ISD::ADD) { 2025 Base = N.getOperand(0); 2026 Index = N.getOperand(1); 2027 return true; 2028 } 2029 2030 // Otherwise, do it the hard way, using R0 as the base register. 2031 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2032 N.getValueType()); 2033 Index = N; 2034 return true; 2035 } 2036 2037 /// getPreIndexedAddressParts - returns true by value, base pointer and 2038 /// offset pointer and addressing mode by reference if the node's address 2039 /// can be legally represented as pre-indexed load / store address. 2040 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2041 SDValue &Offset, 2042 ISD::MemIndexedMode &AM, 2043 SelectionDAG &DAG) const { 2044 if (DisablePPCPreinc) return false; 2045 2046 bool isLoad = true; 2047 SDValue Ptr; 2048 EVT VT; 2049 unsigned Alignment; 2050 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2051 Ptr = LD->getBasePtr(); 2052 VT = LD->getMemoryVT(); 2053 Alignment = LD->getAlignment(); 2054 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2055 Ptr = ST->getBasePtr(); 2056 VT = ST->getMemoryVT(); 2057 Alignment = ST->getAlignment(); 2058 isLoad = false; 2059 } else 2060 return false; 2061 2062 // PowerPC doesn't have preinc load/store instructions for vectors (except 2063 // for QPX, which does have preinc r+r forms). 2064 if (VT.isVector()) { 2065 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2066 return false; 2067 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2068 AM = ISD::PRE_INC; 2069 return true; 2070 } 2071 } 2072 2073 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2074 // Common code will reject creating a pre-inc form if the base pointer 2075 // is a frame index, or if N is a store and the base pointer is either 2076 // the same as or a predecessor of the value being stored. Check for 2077 // those situations here, and try with swapped Base/Offset instead. 2078 bool Swap = false; 2079 2080 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2081 Swap = true; 2082 else if (!isLoad) { 2083 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2084 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2085 Swap = true; 2086 } 2087 2088 if (Swap) 2089 std::swap(Base, Offset); 2090 2091 AM = ISD::PRE_INC; 2092 return true; 2093 } 2094 2095 // LDU/STU can only handle immediates that are a multiple of 4. 2096 if (VT != MVT::i64) { 2097 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false)) 2098 return false; 2099 } else { 2100 // LDU/STU need an address with at least 4-byte alignment. 2101 if (Alignment < 4) 2102 return false; 2103 2104 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true)) 2105 return false; 2106 } 2107 2108 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2109 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2110 // sext i32 to i64 when addr mode is r+i. 2111 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2112 LD->getExtensionType() == ISD::SEXTLOAD && 2113 isa<ConstantSDNode>(Offset)) 2114 return false; 2115 } 2116 2117 AM = ISD::PRE_INC; 2118 return true; 2119 } 2120 2121 //===----------------------------------------------------------------------===// 2122 // LowerOperation implementation 2123 //===----------------------------------------------------------------------===// 2124 2125 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2126 /// and LoOpFlags to the target MO flags. 2127 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2128 unsigned &HiOpFlags, unsigned &LoOpFlags, 2129 const GlobalValue *GV = nullptr) { 2130 HiOpFlags = PPCII::MO_HA; 2131 LoOpFlags = PPCII::MO_LO; 2132 2133 // Don't use the pic base if not in PIC relocation model. 2134 if (IsPIC) { 2135 HiOpFlags |= PPCII::MO_PIC_FLAG; 2136 LoOpFlags |= PPCII::MO_PIC_FLAG; 2137 } 2138 2139 // If this is a reference to a global value that requires a non-lazy-ptr, make 2140 // sure that instruction lowering adds it. 2141 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2142 HiOpFlags |= PPCII::MO_NLP_FLAG; 2143 LoOpFlags |= PPCII::MO_NLP_FLAG; 2144 2145 if (GV->hasHiddenVisibility()) { 2146 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2147 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2148 } 2149 } 2150 } 2151 2152 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2153 SelectionDAG &DAG) { 2154 SDLoc DL(HiPart); 2155 EVT PtrVT = HiPart.getValueType(); 2156 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2157 2158 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2159 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2160 2161 // With PIC, the first instruction is actually "GR+hi(&G)". 2162 if (isPIC) 2163 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2164 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2165 2166 // Generate non-pic code that has direct accesses to the constant pool. 2167 // The address of the global is just (hi(&g)+lo(&g)). 2168 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2169 } 2170 2171 static void setUsesTOCBasePtr(MachineFunction &MF) { 2172 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2173 FuncInfo->setUsesTOCBasePtr(); 2174 } 2175 2176 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2177 setUsesTOCBasePtr(DAG.getMachineFunction()); 2178 } 2179 2180 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2181 SDValue GA) { 2182 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2183 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2184 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2185 2186 SDValue Ops[] = { GA, Reg }; 2187 return DAG.getMemIntrinsicNode( 2188 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2189 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true, 2190 false, 0); 2191 } 2192 2193 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2194 SelectionDAG &DAG) const { 2195 EVT PtrVT = Op.getValueType(); 2196 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2197 const Constant *C = CP->getConstVal(); 2198 2199 // 64-bit SVR4 ABI code is always position-independent. 2200 // The actual address of the GlobalValue is stored in the TOC. 2201 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2202 setUsesTOCBasePtr(DAG); 2203 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2204 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2205 } 2206 2207 unsigned MOHiFlag, MOLoFlag; 2208 bool IsPIC = isPositionIndependent(); 2209 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2210 2211 if (IsPIC && Subtarget.isSVR4ABI()) { 2212 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2213 PPCII::MO_PIC_FLAG); 2214 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2215 } 2216 2217 SDValue CPIHi = 2218 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2219 SDValue CPILo = 2220 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2221 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2222 } 2223 2224 // For 64-bit PowerPC, prefer the more compact relative encodings. 2225 // This trades 32 bits per jump table entry for one or two instructions 2226 // on the jump site. 2227 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2228 if (isJumpTableRelative()) 2229 return MachineJumpTableInfo::EK_LabelDifference32; 2230 2231 return TargetLowering::getJumpTableEncoding(); 2232 } 2233 2234 bool PPCTargetLowering::isJumpTableRelative() const { 2235 if (Subtarget.isPPC64()) 2236 return true; 2237 return TargetLowering::isJumpTableRelative(); 2238 } 2239 2240 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2241 SelectionDAG &DAG) const { 2242 if (!Subtarget.isPPC64()) 2243 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2244 2245 switch (getTargetMachine().getCodeModel()) { 2246 case CodeModel::Default: 2247 case CodeModel::Small: 2248 case CodeModel::Medium: 2249 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2250 default: 2251 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2252 getPointerTy(DAG.getDataLayout())); 2253 } 2254 } 2255 2256 const MCExpr * 2257 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2258 unsigned JTI, 2259 MCContext &Ctx) const { 2260 if (!Subtarget.isPPC64()) 2261 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2262 2263 switch (getTargetMachine().getCodeModel()) { 2264 case CodeModel::Default: 2265 case CodeModel::Small: 2266 case CodeModel::Medium: 2267 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2268 default: 2269 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2270 } 2271 } 2272 2273 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2274 EVT PtrVT = Op.getValueType(); 2275 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2276 2277 // 64-bit SVR4 ABI code is always position-independent. 2278 // The actual address of the GlobalValue is stored in the TOC. 2279 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2280 setUsesTOCBasePtr(DAG); 2281 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2282 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2283 } 2284 2285 unsigned MOHiFlag, MOLoFlag; 2286 bool IsPIC = isPositionIndependent(); 2287 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2288 2289 if (IsPIC && Subtarget.isSVR4ABI()) { 2290 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2291 PPCII::MO_PIC_FLAG); 2292 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2293 } 2294 2295 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2296 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2297 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2298 } 2299 2300 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2301 SelectionDAG &DAG) const { 2302 EVT PtrVT = Op.getValueType(); 2303 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2304 const BlockAddress *BA = BASDN->getBlockAddress(); 2305 2306 // 64-bit SVR4 ABI code is always position-independent. 2307 // The actual BlockAddress is stored in the TOC. 2308 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2309 setUsesTOCBasePtr(DAG); 2310 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2311 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 2312 } 2313 2314 unsigned MOHiFlag, MOLoFlag; 2315 bool IsPIC = isPositionIndependent(); 2316 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2317 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2318 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2319 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2320 } 2321 2322 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2323 SelectionDAG &DAG) const { 2324 // FIXME: TLS addresses currently use medium model code sequences, 2325 // which is the most useful form. Eventually support for small and 2326 // large models could be added if users need it, at the cost of 2327 // additional complexity. 2328 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2329 if (DAG.getTarget().Options.EmulatedTLS) 2330 return LowerToTLSEmulatedModel(GA, DAG); 2331 2332 SDLoc dl(GA); 2333 const GlobalValue *GV = GA->getGlobal(); 2334 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2335 bool is64bit = Subtarget.isPPC64(); 2336 const Module *M = DAG.getMachineFunction().getFunction()->getParent(); 2337 PICLevel::Level picLevel = M->getPICLevel(); 2338 2339 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2340 2341 if (Model == TLSModel::LocalExec) { 2342 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2343 PPCII::MO_TPREL_HA); 2344 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2345 PPCII::MO_TPREL_LO); 2346 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2, 2347 is64bit ? MVT::i64 : MVT::i32); 2348 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2349 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2350 } 2351 2352 if (Model == TLSModel::InitialExec) { 2353 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2354 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2355 PPCII::MO_TLS); 2356 SDValue GOTPtr; 2357 if (is64bit) { 2358 setUsesTOCBasePtr(DAG); 2359 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2360 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2361 PtrVT, GOTReg, TGA); 2362 } else 2363 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2364 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2365 PtrVT, TGA, GOTPtr); 2366 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2367 } 2368 2369 if (Model == TLSModel::GeneralDynamic) { 2370 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2371 SDValue GOTPtr; 2372 if (is64bit) { 2373 setUsesTOCBasePtr(DAG); 2374 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2375 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2376 GOTReg, TGA); 2377 } else { 2378 if (picLevel == PICLevel::SmallPIC) 2379 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2380 else 2381 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2382 } 2383 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2384 GOTPtr, TGA, TGA); 2385 } 2386 2387 if (Model == TLSModel::LocalDynamic) { 2388 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2389 SDValue GOTPtr; 2390 if (is64bit) { 2391 setUsesTOCBasePtr(DAG); 2392 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2393 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2394 GOTReg, TGA); 2395 } else { 2396 if (picLevel == PICLevel::SmallPIC) 2397 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2398 else 2399 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2400 } 2401 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2402 PtrVT, GOTPtr, TGA, TGA); 2403 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2404 PtrVT, TLSAddr, TGA); 2405 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2406 } 2407 2408 llvm_unreachable("Unknown TLS model!"); 2409 } 2410 2411 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2412 SelectionDAG &DAG) const { 2413 EVT PtrVT = Op.getValueType(); 2414 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2415 SDLoc DL(GSDN); 2416 const GlobalValue *GV = GSDN->getGlobal(); 2417 2418 // 64-bit SVR4 ABI code is always position-independent. 2419 // The actual address of the GlobalValue is stored in the TOC. 2420 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2421 setUsesTOCBasePtr(DAG); 2422 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2423 return getTOCEntry(DAG, DL, true, GA); 2424 } 2425 2426 unsigned MOHiFlag, MOLoFlag; 2427 bool IsPIC = isPositionIndependent(); 2428 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2429 2430 if (IsPIC && Subtarget.isSVR4ABI()) { 2431 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2432 GSDN->getOffset(), 2433 PPCII::MO_PIC_FLAG); 2434 return getTOCEntry(DAG, DL, false, GA); 2435 } 2436 2437 SDValue GAHi = 2438 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2439 SDValue GALo = 2440 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2441 2442 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2443 2444 // If the global reference is actually to a non-lazy-pointer, we have to do an 2445 // extra load to get the address of the global. 2446 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2447 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2448 return Ptr; 2449 } 2450 2451 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2452 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2453 SDLoc dl(Op); 2454 2455 if (Op.getValueType() == MVT::v2i64) { 2456 // When the operands themselves are v2i64 values, we need to do something 2457 // special because VSX has no underlying comparison operations for these. 2458 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2459 // Equality can be handled by casting to the legal type for Altivec 2460 // comparisons, everything else needs to be expanded. 2461 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2462 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2463 DAG.getSetCC(dl, MVT::v4i32, 2464 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2465 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2466 CC)); 2467 } 2468 2469 return SDValue(); 2470 } 2471 2472 // We handle most of these in the usual way. 2473 return Op; 2474 } 2475 2476 // If we're comparing for equality to zero, expose the fact that this is 2477 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2478 // fold the new nodes. 2479 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2480 return V; 2481 2482 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2483 // Leave comparisons against 0 and -1 alone for now, since they're usually 2484 // optimized. FIXME: revisit this when we can custom lower all setcc 2485 // optimizations. 2486 if (C->isAllOnesValue() || C->isNullValue()) 2487 return SDValue(); 2488 } 2489 2490 // If we have an integer seteq/setne, turn it into a compare against zero 2491 // by xor'ing the rhs with the lhs, which is faster than setting a 2492 // condition register, reading it back out, and masking the correct bit. The 2493 // normal approach here uses sub to do this instead of xor. Using xor exposes 2494 // the result to other bit-twiddling opportunities. 2495 EVT LHSVT = Op.getOperand(0).getValueType(); 2496 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2497 EVT VT = Op.getValueType(); 2498 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2499 Op.getOperand(1)); 2500 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2501 } 2502 return SDValue(); 2503 } 2504 2505 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2506 SDNode *Node = Op.getNode(); 2507 EVT VT = Node->getValueType(0); 2508 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2509 SDValue InChain = Node->getOperand(0); 2510 SDValue VAListPtr = Node->getOperand(1); 2511 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2512 SDLoc dl(Node); 2513 2514 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2515 2516 // gpr_index 2517 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2518 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2519 InChain = GprIndex.getValue(1); 2520 2521 if (VT == MVT::i64) { 2522 // Check if GprIndex is even 2523 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2524 DAG.getConstant(1, dl, MVT::i32)); 2525 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2526 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2527 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2528 DAG.getConstant(1, dl, MVT::i32)); 2529 // Align GprIndex to be even if it isn't 2530 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2531 GprIndex); 2532 } 2533 2534 // fpr index is 1 byte after gpr 2535 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2536 DAG.getConstant(1, dl, MVT::i32)); 2537 2538 // fpr 2539 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2540 FprPtr, MachinePointerInfo(SV), MVT::i8); 2541 InChain = FprIndex.getValue(1); 2542 2543 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2544 DAG.getConstant(8, dl, MVT::i32)); 2545 2546 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2547 DAG.getConstant(4, dl, MVT::i32)); 2548 2549 // areas 2550 SDValue OverflowArea = 2551 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2552 InChain = OverflowArea.getValue(1); 2553 2554 SDValue RegSaveArea = 2555 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2556 InChain = RegSaveArea.getValue(1); 2557 2558 // select overflow_area if index > 8 2559 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2560 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2561 2562 // adjustment constant gpr_index * 4/8 2563 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2564 VT.isInteger() ? GprIndex : FprIndex, 2565 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2566 MVT::i32)); 2567 2568 // OurReg = RegSaveArea + RegConstant 2569 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2570 RegConstant); 2571 2572 // Floating types are 32 bytes into RegSaveArea 2573 if (VT.isFloatingPoint()) 2574 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2575 DAG.getConstant(32, dl, MVT::i32)); 2576 2577 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2578 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2579 VT.isInteger() ? GprIndex : FprIndex, 2580 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2581 MVT::i32)); 2582 2583 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2584 VT.isInteger() ? VAListPtr : FprPtr, 2585 MachinePointerInfo(SV), MVT::i8); 2586 2587 // determine if we should load from reg_save_area or overflow_area 2588 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2589 2590 // increase overflow_area by 4/8 if gpr/fpr > 8 2591 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2592 DAG.getConstant(VT.isInteger() ? 4 : 8, 2593 dl, MVT::i32)); 2594 2595 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2596 OverflowAreaPlusN); 2597 2598 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2599 MachinePointerInfo(), MVT::i32); 2600 2601 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2602 } 2603 2604 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 2605 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2606 2607 // We have to copy the entire va_list struct: 2608 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2609 return DAG.getMemcpy(Op.getOperand(0), Op, 2610 Op.getOperand(1), Op.getOperand(2), 2611 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 2612 false, MachinePointerInfo(), MachinePointerInfo()); 2613 } 2614 2615 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2616 SelectionDAG &DAG) const { 2617 return Op.getOperand(0); 2618 } 2619 2620 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2621 SelectionDAG &DAG) const { 2622 SDValue Chain = Op.getOperand(0); 2623 SDValue Trmp = Op.getOperand(1); // trampoline 2624 SDValue FPtr = Op.getOperand(2); // nested function 2625 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2626 SDLoc dl(Op); 2627 2628 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2629 bool isPPC64 = (PtrVT == MVT::i64); 2630 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 2631 2632 TargetLowering::ArgListTy Args; 2633 TargetLowering::ArgListEntry Entry; 2634 2635 Entry.Ty = IntPtrTy; 2636 Entry.Node = Trmp; Args.push_back(Entry); 2637 2638 // TrampSize == (isPPC64 ? 48 : 40); 2639 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 2640 isPPC64 ? MVT::i64 : MVT::i32); 2641 Args.push_back(Entry); 2642 2643 Entry.Node = FPtr; Args.push_back(Entry); 2644 Entry.Node = Nest; Args.push_back(Entry); 2645 2646 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2647 TargetLowering::CallLoweringInfo CLI(DAG); 2648 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2649 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2650 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 2651 2652 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2653 return CallResult.second; 2654 } 2655 2656 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2657 MachineFunction &MF = DAG.getMachineFunction(); 2658 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2659 EVT PtrVT = getPointerTy(MF.getDataLayout()); 2660 2661 SDLoc dl(Op); 2662 2663 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2664 // vastart just stores the address of the VarArgsFrameIndex slot into the 2665 // memory location argument. 2666 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2667 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2668 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2669 MachinePointerInfo(SV)); 2670 } 2671 2672 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2673 // We suppose the given va_list is already allocated. 2674 // 2675 // typedef struct { 2676 // char gpr; /* index into the array of 8 GPRs 2677 // * stored in the register save area 2678 // * gpr=0 corresponds to r3, 2679 // * gpr=1 to r4, etc. 2680 // */ 2681 // char fpr; /* index into the array of 8 FPRs 2682 // * stored in the register save area 2683 // * fpr=0 corresponds to f1, 2684 // * fpr=1 to f2, etc. 2685 // */ 2686 // char *overflow_arg_area; 2687 // /* location on stack that holds 2688 // * the next overflow argument 2689 // */ 2690 // char *reg_save_area; 2691 // /* where r3:r10 and f1:f8 (if saved) 2692 // * are stored 2693 // */ 2694 // } va_list[1]; 2695 2696 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 2697 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 2698 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2699 PtrVT); 2700 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2701 PtrVT); 2702 2703 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2704 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 2705 2706 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2707 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 2708 2709 uint64_t FPROffset = 1; 2710 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 2711 2712 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2713 2714 // Store first byte : number of int regs 2715 SDValue firstStore = 2716 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 2717 MachinePointerInfo(SV), MVT::i8); 2718 uint64_t nextOffset = FPROffset; 2719 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2720 ConstFPROffset); 2721 2722 // Store second byte : number of float regs 2723 SDValue secondStore = 2724 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2725 MachinePointerInfo(SV, nextOffset), MVT::i8); 2726 nextOffset += StackOffset; 2727 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2728 2729 // Store second word : arguments given on stack 2730 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2731 MachinePointerInfo(SV, nextOffset)); 2732 nextOffset += FrameOffset; 2733 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2734 2735 // Store third word : arguments given in registers 2736 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2737 MachinePointerInfo(SV, nextOffset)); 2738 } 2739 2740 #include "PPCGenCallingConv.inc" 2741 2742 // Function whose sole purpose is to kill compiler warnings 2743 // stemming from unused functions included from PPCGenCallingConv.inc. 2744 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2745 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 2746 } 2747 2748 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 2749 CCValAssign::LocInfo &LocInfo, 2750 ISD::ArgFlagsTy &ArgFlags, 2751 CCState &State) { 2752 return true; 2753 } 2754 2755 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 2756 MVT &LocVT, 2757 CCValAssign::LocInfo &LocInfo, 2758 ISD::ArgFlagsTy &ArgFlags, 2759 CCState &State) { 2760 static const MCPhysReg ArgRegs[] = { 2761 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2762 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2763 }; 2764 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2765 2766 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2767 2768 // Skip one register if the first unallocated register has an even register 2769 // number and there are still argument registers available which have not been 2770 // allocated yet. RegNum is actually an index into ArgRegs, which means we 2771 // need to skip a register if RegNum is odd. 2772 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 2773 State.AllocateReg(ArgRegs[RegNum]); 2774 } 2775 2776 // Always return false here, as this function only makes sure that the first 2777 // unallocated register has an odd register number and does not actually 2778 // allocate a register for the current argument. 2779 return false; 2780 } 2781 2782 bool 2783 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 2784 MVT &LocVT, 2785 CCValAssign::LocInfo &LocInfo, 2786 ISD::ArgFlagsTy &ArgFlags, 2787 CCState &State) { 2788 static const MCPhysReg ArgRegs[] = { 2789 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2790 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2791 }; 2792 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2793 2794 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2795 int RegsLeft = NumArgRegs - RegNum; 2796 2797 // Skip if there is not enough registers left for long double type (4 gpr regs 2798 // in soft float mode) and put long double argument on the stack. 2799 if (RegNum != NumArgRegs && RegsLeft < 4) { 2800 for (int i = 0; i < RegsLeft; i++) { 2801 State.AllocateReg(ArgRegs[RegNum + i]); 2802 } 2803 } 2804 2805 return false; 2806 } 2807 2808 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 2809 MVT &LocVT, 2810 CCValAssign::LocInfo &LocInfo, 2811 ISD::ArgFlagsTy &ArgFlags, 2812 CCState &State) { 2813 static const MCPhysReg ArgRegs[] = { 2814 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 2815 PPC::F8 2816 }; 2817 2818 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2819 2820 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2821 2822 // If there is only one Floating-point register left we need to put both f64 2823 // values of a split ppc_fp128 value on the stack. 2824 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 2825 State.AllocateReg(ArgRegs[RegNum]); 2826 } 2827 2828 // Always return false here, as this function only makes sure that the two f64 2829 // values a ppc_fp128 value is split into are both passed in registers or both 2830 // passed on the stack and does not actually allocate a register for the 2831 // current argument. 2832 return false; 2833 } 2834 2835 /// FPR - The set of FP registers that should be allocated for arguments, 2836 /// on Darwin. 2837 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 2838 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 2839 PPC::F11, PPC::F12, PPC::F13}; 2840 2841 /// QFPR - The set of QPX registers that should be allocated for arguments. 2842 static const MCPhysReg QFPR[] = { 2843 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 2844 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 2845 2846 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 2847 /// the stack. 2848 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 2849 unsigned PtrByteSize) { 2850 unsigned ArgSize = ArgVT.getStoreSize(); 2851 if (Flags.isByVal()) 2852 ArgSize = Flags.getByValSize(); 2853 2854 // Round up to multiples of the pointer size, except for array members, 2855 // which are always packed. 2856 if (!Flags.isInConsecutiveRegs()) 2857 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2858 2859 return ArgSize; 2860 } 2861 2862 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 2863 /// on the stack. 2864 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 2865 ISD::ArgFlagsTy Flags, 2866 unsigned PtrByteSize) { 2867 unsigned Align = PtrByteSize; 2868 2869 // Altivec parameters are padded to a 16 byte boundary. 2870 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 2871 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 2872 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 2873 ArgVT == MVT::v1i128) 2874 Align = 16; 2875 // QPX vector types stored in double-precision are padded to a 32 byte 2876 // boundary. 2877 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 2878 Align = 32; 2879 2880 // ByVal parameters are aligned as requested. 2881 if (Flags.isByVal()) { 2882 unsigned BVAlign = Flags.getByValAlign(); 2883 if (BVAlign > PtrByteSize) { 2884 if (BVAlign % PtrByteSize != 0) 2885 llvm_unreachable( 2886 "ByVal alignment is not a multiple of the pointer size"); 2887 2888 Align = BVAlign; 2889 } 2890 } 2891 2892 // Array members are always packed to their original alignment. 2893 if (Flags.isInConsecutiveRegs()) { 2894 // If the array member was split into multiple registers, the first 2895 // needs to be aligned to the size of the full type. (Except for 2896 // ppcf128, which is only aligned as its f64 components.) 2897 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 2898 Align = OrigVT.getStoreSize(); 2899 else 2900 Align = ArgVT.getStoreSize(); 2901 } 2902 2903 return Align; 2904 } 2905 2906 /// CalculateStackSlotUsed - Return whether this argument will use its 2907 /// stack slot (instead of being passed in registers). ArgOffset, 2908 /// AvailableFPRs, and AvailableVRs must hold the current argument 2909 /// position, and will be updated to account for this argument. 2910 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 2911 ISD::ArgFlagsTy Flags, 2912 unsigned PtrByteSize, 2913 unsigned LinkageSize, 2914 unsigned ParamAreaSize, 2915 unsigned &ArgOffset, 2916 unsigned &AvailableFPRs, 2917 unsigned &AvailableVRs, bool HasQPX) { 2918 bool UseMemory = false; 2919 2920 // Respect alignment of argument on the stack. 2921 unsigned Align = 2922 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 2923 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 2924 // If there's no space left in the argument save area, we must 2925 // use memory (this check also catches zero-sized arguments). 2926 if (ArgOffset >= LinkageSize + ParamAreaSize) 2927 UseMemory = true; 2928 2929 // Allocate argument on the stack. 2930 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 2931 if (Flags.isInConsecutiveRegsLast()) 2932 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2933 // If we overran the argument save area, we must use memory 2934 // (this check catches arguments passed partially in memory) 2935 if (ArgOffset > LinkageSize + ParamAreaSize) 2936 UseMemory = true; 2937 2938 // However, if the argument is actually passed in an FPR or a VR, 2939 // we don't use memory after all. 2940 if (!Flags.isByVal()) { 2941 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 2942 // QPX registers overlap with the scalar FP registers. 2943 (HasQPX && (ArgVT == MVT::v4f32 || 2944 ArgVT == MVT::v4f64 || 2945 ArgVT == MVT::v4i1))) 2946 if (AvailableFPRs > 0) { 2947 --AvailableFPRs; 2948 return false; 2949 } 2950 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 2951 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 2952 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 2953 ArgVT == MVT::v1i128) 2954 if (AvailableVRs > 0) { 2955 --AvailableVRs; 2956 return false; 2957 } 2958 } 2959 2960 return UseMemory; 2961 } 2962 2963 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 2964 /// ensure minimum alignment required for target. 2965 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 2966 unsigned NumBytes) { 2967 unsigned TargetAlign = Lowering->getStackAlignment(); 2968 unsigned AlignMask = TargetAlign - 1; 2969 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 2970 return NumBytes; 2971 } 2972 2973 SDValue PPCTargetLowering::LowerFormalArguments( 2974 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2975 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2976 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2977 if (Subtarget.isSVR4ABI()) { 2978 if (Subtarget.isPPC64()) 2979 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 2980 dl, DAG, InVals); 2981 else 2982 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 2983 dl, DAG, InVals); 2984 } else { 2985 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 2986 dl, DAG, InVals); 2987 } 2988 } 2989 2990 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 2991 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2992 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2993 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2994 2995 // 32-bit SVR4 ABI Stack Frame Layout: 2996 // +-----------------------------------+ 2997 // +--> | Back chain | 2998 // | +-----------------------------------+ 2999 // | | Floating-point register save area | 3000 // | +-----------------------------------+ 3001 // | | General register save area | 3002 // | +-----------------------------------+ 3003 // | | CR save word | 3004 // | +-----------------------------------+ 3005 // | | VRSAVE save word | 3006 // | +-----------------------------------+ 3007 // | | Alignment padding | 3008 // | +-----------------------------------+ 3009 // | | Vector register save area | 3010 // | +-----------------------------------+ 3011 // | | Local variable space | 3012 // | +-----------------------------------+ 3013 // | | Parameter list area | 3014 // | +-----------------------------------+ 3015 // | | LR save word | 3016 // | +-----------------------------------+ 3017 // SP--> +--- | Back chain | 3018 // +-----------------------------------+ 3019 // 3020 // Specifications: 3021 // System V Application Binary Interface PowerPC Processor Supplement 3022 // AltiVec Technology Programming Interface Manual 3023 3024 MachineFunction &MF = DAG.getMachineFunction(); 3025 MachineFrameInfo &MFI = MF.getFrameInfo(); 3026 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3027 3028 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3029 // Potential tail calls could cause overwriting of argument stack slots. 3030 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3031 (CallConv == CallingConv::Fast)); 3032 unsigned PtrByteSize = 4; 3033 3034 // Assign locations to all of the incoming arguments. 3035 SmallVector<CCValAssign, 16> ArgLocs; 3036 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3037 *DAG.getContext()); 3038 3039 // Reserve space for the linkage area on the stack. 3040 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3041 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3042 if (useSoftFloat()) 3043 CCInfo.PreAnalyzeFormalArguments(Ins); 3044 3045 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3046 CCInfo.clearWasPPCF128(); 3047 3048 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3049 CCValAssign &VA = ArgLocs[i]; 3050 3051 // Arguments stored in registers. 3052 if (VA.isRegLoc()) { 3053 const TargetRegisterClass *RC; 3054 EVT ValVT = VA.getValVT(); 3055 3056 switch (ValVT.getSimpleVT().SimpleTy) { 3057 default: 3058 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3059 case MVT::i1: 3060 case MVT::i32: 3061 RC = &PPC::GPRCRegClass; 3062 break; 3063 case MVT::f32: 3064 if (Subtarget.hasP8Vector()) 3065 RC = &PPC::VSSRCRegClass; 3066 else 3067 RC = &PPC::F4RCRegClass; 3068 break; 3069 case MVT::f64: 3070 if (Subtarget.hasVSX()) 3071 RC = &PPC::VSFRCRegClass; 3072 else 3073 RC = &PPC::F8RCRegClass; 3074 break; 3075 case MVT::v16i8: 3076 case MVT::v8i16: 3077 case MVT::v4i32: 3078 RC = &PPC::VRRCRegClass; 3079 break; 3080 case MVT::v4f32: 3081 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3082 break; 3083 case MVT::v2f64: 3084 case MVT::v2i64: 3085 RC = &PPC::VRRCRegClass; 3086 break; 3087 case MVT::v4f64: 3088 RC = &PPC::QFRCRegClass; 3089 break; 3090 case MVT::v4i1: 3091 RC = &PPC::QBRCRegClass; 3092 break; 3093 } 3094 3095 // Transform the arguments stored in physical registers into virtual ones. 3096 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3097 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3098 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3099 3100 if (ValVT == MVT::i1) 3101 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3102 3103 InVals.push_back(ArgValue); 3104 } else { 3105 // Argument stored in memory. 3106 assert(VA.isMemLoc()); 3107 3108 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3109 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(), 3110 isImmutable); 3111 3112 // Create load nodes to retrieve arguments from the stack. 3113 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3114 InVals.push_back( 3115 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3116 } 3117 } 3118 3119 // Assign locations to all of the incoming aggregate by value arguments. 3120 // Aggregates passed by value are stored in the local variable space of the 3121 // caller's stack frame, right above the parameter list area. 3122 SmallVector<CCValAssign, 16> ByValArgLocs; 3123 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3124 ByValArgLocs, *DAG.getContext()); 3125 3126 // Reserve stack space for the allocations in CCInfo. 3127 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3128 3129 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3130 3131 // Area that is at least reserved in the caller of this function. 3132 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3133 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3134 3135 // Set the size that is at least reserved in caller of this function. Tail 3136 // call optimized function's reserved stack space needs to be aligned so that 3137 // taking the difference between two stack areas will result in an aligned 3138 // stack. 3139 MinReservedArea = 3140 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3141 FuncInfo->setMinReservedArea(MinReservedArea); 3142 3143 SmallVector<SDValue, 8> MemOps; 3144 3145 // If the function takes variable number of arguments, make a frame index for 3146 // the start of the first vararg value... for expansion of llvm.va_start. 3147 if (isVarArg) { 3148 static const MCPhysReg GPArgRegs[] = { 3149 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3150 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3151 }; 3152 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3153 3154 static const MCPhysReg FPArgRegs[] = { 3155 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3156 PPC::F8 3157 }; 3158 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3159 3160 if (useSoftFloat()) 3161 NumFPArgRegs = 0; 3162 3163 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3164 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3165 3166 // Make room for NumGPArgRegs and NumFPArgRegs. 3167 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3168 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3169 3170 FuncInfo->setVarArgsStackOffset( 3171 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3172 CCInfo.getNextStackOffset(), true)); 3173 3174 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3175 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3176 3177 // The fixed integer arguments of a variadic function are stored to the 3178 // VarArgsFrameIndex on the stack so that they may be loaded by 3179 // dereferencing the result of va_next. 3180 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3181 // Get an existing live-in vreg, or add a new one. 3182 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3183 if (!VReg) 3184 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3185 3186 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3187 SDValue Store = 3188 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3189 MemOps.push_back(Store); 3190 // Increment the address by four for the next argument to store 3191 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3192 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3193 } 3194 3195 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3196 // is set. 3197 // The double arguments are stored to the VarArgsFrameIndex 3198 // on the stack. 3199 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3200 // Get an existing live-in vreg, or add a new one. 3201 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3202 if (!VReg) 3203 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3204 3205 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3206 SDValue Store = 3207 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3208 MemOps.push_back(Store); 3209 // Increment the address by eight for the next argument to store 3210 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3211 PtrVT); 3212 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3213 } 3214 } 3215 3216 if (!MemOps.empty()) 3217 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3218 3219 return Chain; 3220 } 3221 3222 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3223 // value to MVT::i64 and then truncate to the correct register size. 3224 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3225 EVT ObjectVT, SelectionDAG &DAG, 3226 SDValue ArgVal, 3227 const SDLoc &dl) const { 3228 if (Flags.isSExt()) 3229 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3230 DAG.getValueType(ObjectVT)); 3231 else if (Flags.isZExt()) 3232 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3233 DAG.getValueType(ObjectVT)); 3234 3235 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3236 } 3237 3238 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3239 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3240 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3241 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3242 // TODO: add description of PPC stack frame format, or at least some docs. 3243 // 3244 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3245 bool isLittleEndian = Subtarget.isLittleEndian(); 3246 MachineFunction &MF = DAG.getMachineFunction(); 3247 MachineFrameInfo &MFI = MF.getFrameInfo(); 3248 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3249 3250 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3251 "fastcc not supported on varargs functions"); 3252 3253 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3254 // Potential tail calls could cause overwriting of argument stack slots. 3255 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3256 (CallConv == CallingConv::Fast)); 3257 unsigned PtrByteSize = 8; 3258 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3259 3260 static const MCPhysReg GPR[] = { 3261 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3262 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3263 }; 3264 static const MCPhysReg VR[] = { 3265 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3266 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3267 }; 3268 3269 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3270 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3271 const unsigned Num_VR_Regs = array_lengthof(VR); 3272 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3273 3274 // Do a first pass over the arguments to determine whether the ABI 3275 // guarantees that our caller has allocated the parameter save area 3276 // on its stack frame. In the ELFv1 ABI, this is always the case; 3277 // in the ELFv2 ABI, it is true if this is a vararg function or if 3278 // any parameter is located in a stack slot. 3279 3280 bool HasParameterArea = !isELFv2ABI || isVarArg; 3281 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3282 unsigned NumBytes = LinkageSize; 3283 unsigned AvailableFPRs = Num_FPR_Regs; 3284 unsigned AvailableVRs = Num_VR_Regs; 3285 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3286 if (Ins[i].Flags.isNest()) 3287 continue; 3288 3289 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3290 PtrByteSize, LinkageSize, ParamAreaSize, 3291 NumBytes, AvailableFPRs, AvailableVRs, 3292 Subtarget.hasQPX())) 3293 HasParameterArea = true; 3294 } 3295 3296 // Add DAG nodes to load the arguments or copy them out of registers. On 3297 // entry to a function on PPC, the arguments start after the linkage area, 3298 // although the first ones are often in registers. 3299 3300 unsigned ArgOffset = LinkageSize; 3301 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3302 unsigned &QFPR_idx = FPR_idx; 3303 SmallVector<SDValue, 8> MemOps; 3304 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3305 unsigned CurArgIdx = 0; 3306 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3307 SDValue ArgVal; 3308 bool needsLoad = false; 3309 EVT ObjectVT = Ins[ArgNo].VT; 3310 EVT OrigVT = Ins[ArgNo].ArgVT; 3311 unsigned ObjSize = ObjectVT.getStoreSize(); 3312 unsigned ArgSize = ObjSize; 3313 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3314 if (Ins[ArgNo].isOrigArg()) { 3315 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3316 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3317 } 3318 // We re-align the argument offset for each argument, except when using the 3319 // fast calling convention, when we need to make sure we do that only when 3320 // we'll actually use a stack slot. 3321 unsigned CurArgOffset, Align; 3322 auto ComputeArgOffset = [&]() { 3323 /* Respect alignment of argument on the stack. */ 3324 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3325 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3326 CurArgOffset = ArgOffset; 3327 }; 3328 3329 if (CallConv != CallingConv::Fast) { 3330 ComputeArgOffset(); 3331 3332 /* Compute GPR index associated with argument offset. */ 3333 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3334 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3335 } 3336 3337 // FIXME the codegen can be much improved in some cases. 3338 // We do not have to keep everything in memory. 3339 if (Flags.isByVal()) { 3340 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3341 3342 if (CallConv == CallingConv::Fast) 3343 ComputeArgOffset(); 3344 3345 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3346 ObjSize = Flags.getByValSize(); 3347 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3348 // Empty aggregate parameters do not take up registers. Examples: 3349 // struct { } a; 3350 // union { } b; 3351 // int c[0]; 3352 // etc. However, we have to provide a place-holder in InVals, so 3353 // pretend we have an 8-byte item at the current address for that 3354 // purpose. 3355 if (!ObjSize) { 3356 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3357 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3358 InVals.push_back(FIN); 3359 continue; 3360 } 3361 3362 // Create a stack object covering all stack doublewords occupied 3363 // by the argument. If the argument is (fully or partially) on 3364 // the stack, or if the argument is fully in registers but the 3365 // caller has allocated the parameter save anyway, we can refer 3366 // directly to the caller's stack frame. Otherwise, create a 3367 // local copy in our own frame. 3368 int FI; 3369 if (HasParameterArea || 3370 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3371 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3372 else 3373 FI = MFI.CreateStackObject(ArgSize, Align, false); 3374 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3375 3376 // Handle aggregates smaller than 8 bytes. 3377 if (ObjSize < PtrByteSize) { 3378 // The value of the object is its address, which differs from the 3379 // address of the enclosing doubleword on big-endian systems. 3380 SDValue Arg = FIN; 3381 if (!isLittleEndian) { 3382 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3383 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3384 } 3385 InVals.push_back(Arg); 3386 3387 if (GPR_idx != Num_GPR_Regs) { 3388 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3389 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3390 SDValue Store; 3391 3392 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3393 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3394 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3395 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3396 MachinePointerInfo(&*FuncArg), ObjType); 3397 } else { 3398 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3399 // store the whole register as-is to the parameter save area 3400 // slot. 3401 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3402 MachinePointerInfo(&*FuncArg)); 3403 } 3404 3405 MemOps.push_back(Store); 3406 } 3407 // Whether we copied from a register or not, advance the offset 3408 // into the parameter save area by a full doubleword. 3409 ArgOffset += PtrByteSize; 3410 continue; 3411 } 3412 3413 // The value of the object is its address, which is the address of 3414 // its first stack doubleword. 3415 InVals.push_back(FIN); 3416 3417 // Store whatever pieces of the object are in registers to memory. 3418 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3419 if (GPR_idx == Num_GPR_Regs) 3420 break; 3421 3422 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3424 SDValue Addr = FIN; 3425 if (j) { 3426 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3427 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3428 } 3429 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3430 MachinePointerInfo(&*FuncArg, j)); 3431 MemOps.push_back(Store); 3432 ++GPR_idx; 3433 } 3434 ArgOffset += ArgSize; 3435 continue; 3436 } 3437 3438 switch (ObjectVT.getSimpleVT().SimpleTy) { 3439 default: llvm_unreachable("Unhandled argument type!"); 3440 case MVT::i1: 3441 case MVT::i32: 3442 case MVT::i64: 3443 if (Flags.isNest()) { 3444 // The 'nest' parameter, if any, is passed in R11. 3445 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3446 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3447 3448 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3449 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3450 3451 break; 3452 } 3453 3454 // These can be scalar arguments or elements of an integer array type 3455 // passed directly. Clang may use those instead of "byval" aggregate 3456 // types to avoid forcing arguments to memory unnecessarily. 3457 if (GPR_idx != Num_GPR_Regs) { 3458 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3459 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3460 3461 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3462 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3463 // value to MVT::i64 and then truncate to the correct register size. 3464 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3465 } else { 3466 if (CallConv == CallingConv::Fast) 3467 ComputeArgOffset(); 3468 3469 needsLoad = true; 3470 ArgSize = PtrByteSize; 3471 } 3472 if (CallConv != CallingConv::Fast || needsLoad) 3473 ArgOffset += 8; 3474 break; 3475 3476 case MVT::f32: 3477 case MVT::f64: 3478 // These can be scalar arguments or elements of a float array type 3479 // passed directly. The latter are used to implement ELFv2 homogenous 3480 // float aggregates. 3481 if (FPR_idx != Num_FPR_Regs) { 3482 unsigned VReg; 3483 3484 if (ObjectVT == MVT::f32) 3485 VReg = MF.addLiveIn(FPR[FPR_idx], 3486 Subtarget.hasP8Vector() 3487 ? &PPC::VSSRCRegClass 3488 : &PPC::F4RCRegClass); 3489 else 3490 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3491 ? &PPC::VSFRCRegClass 3492 : &PPC::F8RCRegClass); 3493 3494 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3495 ++FPR_idx; 3496 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3497 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3498 // once we support fp <-> gpr moves. 3499 3500 // This can only ever happen in the presence of f32 array types, 3501 // since otherwise we never run out of FPRs before running out 3502 // of GPRs. 3503 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3504 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3505 3506 if (ObjectVT == MVT::f32) { 3507 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3508 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3509 DAG.getConstant(32, dl, MVT::i32)); 3510 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3511 } 3512 3513 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3514 } else { 3515 if (CallConv == CallingConv::Fast) 3516 ComputeArgOffset(); 3517 3518 needsLoad = true; 3519 } 3520 3521 // When passing an array of floats, the array occupies consecutive 3522 // space in the argument area; only round up to the next doubleword 3523 // at the end of the array. Otherwise, each float takes 8 bytes. 3524 if (CallConv != CallingConv::Fast || needsLoad) { 3525 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3526 ArgOffset += ArgSize; 3527 if (Flags.isInConsecutiveRegsLast()) 3528 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3529 } 3530 break; 3531 case MVT::v4f32: 3532 case MVT::v4i32: 3533 case MVT::v8i16: 3534 case MVT::v16i8: 3535 case MVT::v2f64: 3536 case MVT::v2i64: 3537 case MVT::v1i128: 3538 if (!Subtarget.hasQPX()) { 3539 // These can be scalar arguments or elements of a vector array type 3540 // passed directly. The latter are used to implement ELFv2 homogenous 3541 // vector aggregates. 3542 if (VR_idx != Num_VR_Regs) { 3543 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3544 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3545 ++VR_idx; 3546 } else { 3547 if (CallConv == CallingConv::Fast) 3548 ComputeArgOffset(); 3549 3550 needsLoad = true; 3551 } 3552 if (CallConv != CallingConv::Fast || needsLoad) 3553 ArgOffset += 16; 3554 break; 3555 } // not QPX 3556 3557 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3558 "Invalid QPX parameter type"); 3559 /* fall through */ 3560 3561 case MVT::v4f64: 3562 case MVT::v4i1: 3563 // QPX vectors are treated like their scalar floating-point subregisters 3564 // (except that they're larger). 3565 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3566 if (QFPR_idx != Num_QFPR_Regs) { 3567 const TargetRegisterClass *RC; 3568 switch (ObjectVT.getSimpleVT().SimpleTy) { 3569 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3570 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3571 default: RC = &PPC::QBRCRegClass; break; 3572 } 3573 3574 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3575 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3576 ++QFPR_idx; 3577 } else { 3578 if (CallConv == CallingConv::Fast) 3579 ComputeArgOffset(); 3580 needsLoad = true; 3581 } 3582 if (CallConv != CallingConv::Fast || needsLoad) 3583 ArgOffset += Sz; 3584 break; 3585 } 3586 3587 // We need to load the argument to a virtual register if we determined 3588 // above that we ran out of physical registers of the appropriate type. 3589 if (needsLoad) { 3590 if (ObjSize < ArgSize && !isLittleEndian) 3591 CurArgOffset += ArgSize - ObjSize; 3592 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3593 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3594 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3595 } 3596 3597 InVals.push_back(ArgVal); 3598 } 3599 3600 // Area that is at least reserved in the caller of this function. 3601 unsigned MinReservedArea; 3602 if (HasParameterArea) 3603 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3604 else 3605 MinReservedArea = LinkageSize; 3606 3607 // Set the size that is at least reserved in caller of this function. Tail 3608 // call optimized functions' reserved stack space needs to be aligned so that 3609 // taking the difference between two stack areas will result in an aligned 3610 // stack. 3611 MinReservedArea = 3612 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3613 FuncInfo->setMinReservedArea(MinReservedArea); 3614 3615 // If the function takes variable number of arguments, make a frame index for 3616 // the start of the first vararg value... for expansion of llvm.va_start. 3617 if (isVarArg) { 3618 int Depth = ArgOffset; 3619 3620 FuncInfo->setVarArgsFrameIndex( 3621 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3622 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3623 3624 // If this function is vararg, store any remaining integer argument regs 3625 // to their spots on the stack so that they may be loaded by dereferencing 3626 // the result of va_next. 3627 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3628 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3629 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3630 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3631 SDValue Store = 3632 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3633 MemOps.push_back(Store); 3634 // Increment the address by four for the next argument to store 3635 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3636 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3637 } 3638 } 3639 3640 if (!MemOps.empty()) 3641 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3642 3643 return Chain; 3644 } 3645 3646 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3647 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3648 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3649 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3650 // TODO: add description of PPC stack frame format, or at least some docs. 3651 // 3652 MachineFunction &MF = DAG.getMachineFunction(); 3653 MachineFrameInfo &MFI = MF.getFrameInfo(); 3654 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3655 3656 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3657 bool isPPC64 = PtrVT == MVT::i64; 3658 // Potential tail calls could cause overwriting of argument stack slots. 3659 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3660 (CallConv == CallingConv::Fast)); 3661 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3662 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3663 unsigned ArgOffset = LinkageSize; 3664 // Area that is at least reserved in caller of this function. 3665 unsigned MinReservedArea = ArgOffset; 3666 3667 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3668 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3669 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3670 }; 3671 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3672 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3673 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3674 }; 3675 static const MCPhysReg VR[] = { 3676 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3677 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3678 }; 3679 3680 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3681 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3682 const unsigned Num_VR_Regs = array_lengthof( VR); 3683 3684 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3685 3686 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3687 3688 // In 32-bit non-varargs functions, the stack space for vectors is after the 3689 // stack space for non-vectors. We do not use this space unless we have 3690 // too many vectors to fit in registers, something that only occurs in 3691 // constructed examples:), but we have to walk the arglist to figure 3692 // that out...for the pathological case, compute VecArgOffset as the 3693 // start of the vector parameter area. Computing VecArgOffset is the 3694 // entire point of the following loop. 3695 unsigned VecArgOffset = ArgOffset; 3696 if (!isVarArg && !isPPC64) { 3697 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3698 ++ArgNo) { 3699 EVT ObjectVT = Ins[ArgNo].VT; 3700 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3701 3702 if (Flags.isByVal()) { 3703 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3704 unsigned ObjSize = Flags.getByValSize(); 3705 unsigned ArgSize = 3706 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3707 VecArgOffset += ArgSize; 3708 continue; 3709 } 3710 3711 switch(ObjectVT.getSimpleVT().SimpleTy) { 3712 default: llvm_unreachable("Unhandled argument type!"); 3713 case MVT::i1: 3714 case MVT::i32: 3715 case MVT::f32: 3716 VecArgOffset += 4; 3717 break; 3718 case MVT::i64: // PPC64 3719 case MVT::f64: 3720 // FIXME: We are guaranteed to be !isPPC64 at this point. 3721 // Does MVT::i64 apply? 3722 VecArgOffset += 8; 3723 break; 3724 case MVT::v4f32: 3725 case MVT::v4i32: 3726 case MVT::v8i16: 3727 case MVT::v16i8: 3728 // Nothing to do, we're only looking at Nonvector args here. 3729 break; 3730 } 3731 } 3732 } 3733 // We've found where the vector parameter area in memory is. Skip the 3734 // first 12 parameters; these don't use that memory. 3735 VecArgOffset = ((VecArgOffset+15)/16)*16; 3736 VecArgOffset += 12*16; 3737 3738 // Add DAG nodes to load the arguments or copy them out of registers. On 3739 // entry to a function on PPC, the arguments start after the linkage area, 3740 // although the first ones are often in registers. 3741 3742 SmallVector<SDValue, 8> MemOps; 3743 unsigned nAltivecParamsAtEnd = 0; 3744 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3745 unsigned CurArgIdx = 0; 3746 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3747 SDValue ArgVal; 3748 bool needsLoad = false; 3749 EVT ObjectVT = Ins[ArgNo].VT; 3750 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 3751 unsigned ArgSize = ObjSize; 3752 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3753 if (Ins[ArgNo].isOrigArg()) { 3754 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3755 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3756 } 3757 unsigned CurArgOffset = ArgOffset; 3758 3759 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 3760 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 3761 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 3762 if (isVarArg || isPPC64) { 3763 MinReservedArea = ((MinReservedArea+15)/16)*16; 3764 MinReservedArea += CalculateStackSlotSize(ObjectVT, 3765 Flags, 3766 PtrByteSize); 3767 } else nAltivecParamsAtEnd++; 3768 } else 3769 // Calculate min reserved area. 3770 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 3771 Flags, 3772 PtrByteSize); 3773 3774 // FIXME the codegen can be much improved in some cases. 3775 // We do not have to keep everything in memory. 3776 if (Flags.isByVal()) { 3777 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3778 3779 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3780 ObjSize = Flags.getByValSize(); 3781 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3782 // Objects of size 1 and 2 are right justified, everything else is 3783 // left justified. This means the memory address is adjusted forwards. 3784 if (ObjSize==1 || ObjSize==2) { 3785 CurArgOffset = CurArgOffset + (4 - ObjSize); 3786 } 3787 // The value of the object is its address. 3788 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 3789 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3790 InVals.push_back(FIN); 3791 if (ObjSize==1 || ObjSize==2) { 3792 if (GPR_idx != Num_GPR_Regs) { 3793 unsigned VReg; 3794 if (isPPC64) 3795 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3796 else 3797 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3798 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3799 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 3800 SDValue Store = 3801 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 3802 MachinePointerInfo(&*FuncArg), ObjType); 3803 MemOps.push_back(Store); 3804 ++GPR_idx; 3805 } 3806 3807 ArgOffset += PtrByteSize; 3808 3809 continue; 3810 } 3811 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3812 // Store whatever pieces of the object are in registers 3813 // to memory. ArgOffset will be the address of the beginning 3814 // of the object. 3815 if (GPR_idx != Num_GPR_Regs) { 3816 unsigned VReg; 3817 if (isPPC64) 3818 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3819 else 3820 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3821 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3822 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3823 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3824 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3825 MachinePointerInfo(&*FuncArg, j)); 3826 MemOps.push_back(Store); 3827 ++GPR_idx; 3828 ArgOffset += PtrByteSize; 3829 } else { 3830 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 3831 break; 3832 } 3833 } 3834 continue; 3835 } 3836 3837 switch (ObjectVT.getSimpleVT().SimpleTy) { 3838 default: llvm_unreachable("Unhandled argument type!"); 3839 case MVT::i1: 3840 case MVT::i32: 3841 if (!isPPC64) { 3842 if (GPR_idx != Num_GPR_Regs) { 3843 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3844 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3845 3846 if (ObjectVT == MVT::i1) 3847 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 3848 3849 ++GPR_idx; 3850 } else { 3851 needsLoad = true; 3852 ArgSize = PtrByteSize; 3853 } 3854 // All int arguments reserve stack space in the Darwin ABI. 3855 ArgOffset += PtrByteSize; 3856 break; 3857 } 3858 LLVM_FALLTHROUGH; 3859 case MVT::i64: // PPC64 3860 if (GPR_idx != Num_GPR_Regs) { 3861 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3862 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3863 3864 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3865 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3866 // value to MVT::i64 and then truncate to the correct register size. 3867 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3868 3869 ++GPR_idx; 3870 } else { 3871 needsLoad = true; 3872 ArgSize = PtrByteSize; 3873 } 3874 // All int arguments reserve stack space in the Darwin ABI. 3875 ArgOffset += 8; 3876 break; 3877 3878 case MVT::f32: 3879 case MVT::f64: 3880 // Every 4 bytes of argument space consumes one of the GPRs available for 3881 // argument passing. 3882 if (GPR_idx != Num_GPR_Regs) { 3883 ++GPR_idx; 3884 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 3885 ++GPR_idx; 3886 } 3887 if (FPR_idx != Num_FPR_Regs) { 3888 unsigned VReg; 3889 3890 if (ObjectVT == MVT::f32) 3891 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 3892 else 3893 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 3894 3895 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3896 ++FPR_idx; 3897 } else { 3898 needsLoad = true; 3899 } 3900 3901 // All FP arguments reserve stack space in the Darwin ABI. 3902 ArgOffset += isPPC64 ? 8 : ObjSize; 3903 break; 3904 case MVT::v4f32: 3905 case MVT::v4i32: 3906 case MVT::v8i16: 3907 case MVT::v16i8: 3908 // Note that vector arguments in registers don't reserve stack space, 3909 // except in varargs functions. 3910 if (VR_idx != Num_VR_Regs) { 3911 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3912 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3913 if (isVarArg) { 3914 while ((ArgOffset % 16) != 0) { 3915 ArgOffset += PtrByteSize; 3916 if (GPR_idx != Num_GPR_Regs) 3917 GPR_idx++; 3918 } 3919 ArgOffset += 16; 3920 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 3921 } 3922 ++VR_idx; 3923 } else { 3924 if (!isVarArg && !isPPC64) { 3925 // Vectors go after all the nonvectors. 3926 CurArgOffset = VecArgOffset; 3927 VecArgOffset += 16; 3928 } else { 3929 // Vectors are aligned. 3930 ArgOffset = ((ArgOffset+15)/16)*16; 3931 CurArgOffset = ArgOffset; 3932 ArgOffset += 16; 3933 } 3934 needsLoad = true; 3935 } 3936 break; 3937 } 3938 3939 // We need to load the argument to a virtual register if we determined above 3940 // that we ran out of physical registers of the appropriate type. 3941 if (needsLoad) { 3942 int FI = MFI.CreateFixedObject(ObjSize, 3943 CurArgOffset + (ArgSize - ObjSize), 3944 isImmutable); 3945 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3946 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3947 } 3948 3949 InVals.push_back(ArgVal); 3950 } 3951 3952 // Allow for Altivec parameters at the end, if needed. 3953 if (nAltivecParamsAtEnd) { 3954 MinReservedArea = ((MinReservedArea+15)/16)*16; 3955 MinReservedArea += 16*nAltivecParamsAtEnd; 3956 } 3957 3958 // Area that is at least reserved in the caller of this function. 3959 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 3960 3961 // Set the size that is at least reserved in caller of this function. Tail 3962 // call optimized functions' reserved stack space needs to be aligned so that 3963 // taking the difference between two stack areas will result in an aligned 3964 // stack. 3965 MinReservedArea = 3966 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3967 FuncInfo->setMinReservedArea(MinReservedArea); 3968 3969 // If the function takes variable number of arguments, make a frame index for 3970 // the start of the first vararg value... for expansion of llvm.va_start. 3971 if (isVarArg) { 3972 int Depth = ArgOffset; 3973 3974 FuncInfo->setVarArgsFrameIndex( 3975 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3976 Depth, true)); 3977 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3978 3979 // If this function is vararg, store any remaining integer argument regs 3980 // to their spots on the stack so that they may be loaded by dereferencing 3981 // the result of va_next. 3982 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 3983 unsigned VReg; 3984 3985 if (isPPC64) 3986 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3987 else 3988 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3989 3990 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3991 SDValue Store = 3992 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3993 MemOps.push_back(Store); 3994 // Increment the address by four for the next argument to store 3995 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3996 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3997 } 3998 } 3999 4000 if (!MemOps.empty()) 4001 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4002 4003 return Chain; 4004 } 4005 4006 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4007 /// adjusted to accommodate the arguments for the tailcall. 4008 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4009 unsigned ParamSize) { 4010 4011 if (!isTailCall) return 0; 4012 4013 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4014 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4015 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4016 // Remember only if the new adjustement is bigger. 4017 if (SPDiff < FI->getTailCallSPDelta()) 4018 FI->setTailCallSPDelta(SPDiff); 4019 4020 return SPDiff; 4021 } 4022 4023 static bool isFunctionGlobalAddress(SDValue Callee); 4024 4025 static bool 4026 resideInSameSection(const Function *Caller, SDValue Callee, 4027 const TargetMachine &TM) { 4028 // If !G, Callee can be an external symbol. 4029 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4030 if (!G) 4031 return false; 4032 4033 const GlobalValue *GV = G->getGlobal(); 4034 if (!GV->isStrongDefinitionForLinker()) 4035 return false; 4036 4037 // Any explicitly-specified sections and section prefixes must also match. 4038 // Also, if we're using -ffunction-sections, then each function is always in 4039 // a different section (the same is true for COMDAT functions). 4040 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4041 GV->getSection() != Caller->getSection()) 4042 return false; 4043 if (const auto *F = dyn_cast<Function>(GV)) { 4044 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4045 return false; 4046 } 4047 4048 // If the callee might be interposed, then we can't assume the ultimate call 4049 // target will be in the same section. Even in cases where we can assume that 4050 // interposition won't happen, in any case where the linker might insert a 4051 // stub to allow for interposition, we must generate code as though 4052 // interposition might occur. To understand why this matters, consider a 4053 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4054 // in the same section, but a is in a different module (i.e. has a different 4055 // TOC base pointer). If the linker allows for interposition between b and c, 4056 // then it will generate a stub for the call edge between b and c which will 4057 // save the TOC pointer into the designated stack slot allocated by b. If we 4058 // return true here, and therefore allow a tail call between b and c, that 4059 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4060 // pointer into the stack slot allocated by a (where the a -> b stub saved 4061 // a's TOC base pointer). If we're not considering a tail call, but rather, 4062 // whether a nop is needed after the call instruction in b, because the linker 4063 // will insert a stub, it might complain about a missing nop if we omit it 4064 // (although many don't complain in this case). 4065 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4066 return false; 4067 4068 return true; 4069 } 4070 4071 static bool 4072 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4073 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4074 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4075 4076 const unsigned PtrByteSize = 8; 4077 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4078 4079 static const MCPhysReg GPR[] = { 4080 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4081 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4082 }; 4083 static const MCPhysReg VR[] = { 4084 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4085 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4086 }; 4087 4088 const unsigned NumGPRs = array_lengthof(GPR); 4089 const unsigned NumFPRs = 13; 4090 const unsigned NumVRs = array_lengthof(VR); 4091 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4092 4093 unsigned NumBytes = LinkageSize; 4094 unsigned AvailableFPRs = NumFPRs; 4095 unsigned AvailableVRs = NumVRs; 4096 4097 for (const ISD::OutputArg& Param : Outs) { 4098 if (Param.Flags.isNest()) continue; 4099 4100 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4101 PtrByteSize, LinkageSize, ParamAreaSize, 4102 NumBytes, AvailableFPRs, AvailableVRs, 4103 Subtarget.hasQPX())) 4104 return true; 4105 } 4106 return false; 4107 } 4108 4109 static bool 4110 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) { 4111 if (CS->arg_size() != CallerFn->arg_size()) 4112 return false; 4113 4114 ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin(); 4115 ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end(); 4116 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4117 4118 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4119 const Value* CalleeArg = *CalleeArgIter; 4120 const Value* CallerArg = &(*CallerArgIter); 4121 if (CalleeArg == CallerArg) 4122 continue; 4123 4124 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4125 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4126 // } 4127 // 1st argument of callee is undef and has the same type as caller. 4128 if (CalleeArg->getType() == CallerArg->getType() && 4129 isa<UndefValue>(CalleeArg)) 4130 continue; 4131 4132 return false; 4133 } 4134 4135 return true; 4136 } 4137 4138 bool 4139 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4140 SDValue Callee, 4141 CallingConv::ID CalleeCC, 4142 ImmutableCallSite *CS, 4143 bool isVarArg, 4144 const SmallVectorImpl<ISD::OutputArg> &Outs, 4145 const SmallVectorImpl<ISD::InputArg> &Ins, 4146 SelectionDAG& DAG) const { 4147 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4148 4149 if (DisableSCO && !TailCallOpt) return false; 4150 4151 // Variadic argument functions are not supported. 4152 if (isVarArg) return false; 4153 4154 MachineFunction &MF = DAG.getMachineFunction(); 4155 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4156 4157 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has 4158 // the same calling convention 4159 if (CallerCC != CalleeCC) return false; 4160 4161 // SCO support C calling convention 4162 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C) 4163 return false; 4164 4165 // Caller contains any byval parameter is not supported. 4166 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4167 return false; 4168 4169 // Callee contains any byval parameter is not supported, too. 4170 // Note: This is a quick work around, because in some cases, e.g. 4171 // caller's stack size > callee's stack size, we are still able to apply 4172 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574 4173 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4174 return false; 4175 4176 // No TCO/SCO on indirect call because Caller have to restore its TOC 4177 if (!isFunctionGlobalAddress(Callee) && 4178 !isa<ExternalSymbolSDNode>(Callee)) 4179 return false; 4180 4181 // Check if Callee resides in the same section, because for now, PPC64 SVR4 4182 // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another 4183 // section. 4184 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4185 if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine())) 4186 return false; 4187 4188 // TCO allows altering callee ABI, so we don't have to check further. 4189 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4190 return true; 4191 4192 if (DisableSCO) return false; 4193 4194 // If callee use the same argument list that caller is using, then we can 4195 // apply SCO on this case. If it is not, then we need to check if callee needs 4196 // stack for passing arguments. 4197 if (!hasSameArgumentList(MF.getFunction(), CS) && 4198 needStackSlotPassParameters(Subtarget, Outs)) { 4199 return false; 4200 } 4201 4202 return true; 4203 } 4204 4205 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4206 /// for tail call optimization. Targets which want to do tail call 4207 /// optimization should implement this function. 4208 bool 4209 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4210 CallingConv::ID CalleeCC, 4211 bool isVarArg, 4212 const SmallVectorImpl<ISD::InputArg> &Ins, 4213 SelectionDAG& DAG) const { 4214 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4215 return false; 4216 4217 // Variable argument functions are not supported. 4218 if (isVarArg) 4219 return false; 4220 4221 MachineFunction &MF = DAG.getMachineFunction(); 4222 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4223 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4224 // Functions containing by val parameters are not supported. 4225 for (unsigned i = 0; i != Ins.size(); i++) { 4226 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4227 if (Flags.isByVal()) return false; 4228 } 4229 4230 // Non-PIC/GOT tail calls are supported. 4231 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4232 return true; 4233 4234 // At the moment we can only do local tail calls (in same module, hidden 4235 // or protected) if we are generating PIC. 4236 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4237 return G->getGlobal()->hasHiddenVisibility() 4238 || G->getGlobal()->hasProtectedVisibility(); 4239 } 4240 4241 return false; 4242 } 4243 4244 /// isCallCompatibleAddress - Return the immediate to use if the specified 4245 /// 32-bit value is representable in the immediate field of a BxA instruction. 4246 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4247 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4248 if (!C) return nullptr; 4249 4250 int Addr = C->getZExtValue(); 4251 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4252 SignExtend32<26>(Addr) != Addr) 4253 return nullptr; // Top 6 bits have to be sext of immediate. 4254 4255 return DAG 4256 .getConstant( 4257 (int)C->getZExtValue() >> 2, SDLoc(Op), 4258 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4259 .getNode(); 4260 } 4261 4262 namespace { 4263 4264 struct TailCallArgumentInfo { 4265 SDValue Arg; 4266 SDValue FrameIdxOp; 4267 int FrameIdx = 0; 4268 4269 TailCallArgumentInfo() = default; 4270 }; 4271 4272 } // end anonymous namespace 4273 4274 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4275 static void StoreTailCallArgumentsToStackSlot( 4276 SelectionDAG &DAG, SDValue Chain, 4277 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4278 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4279 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4280 SDValue Arg = TailCallArgs[i].Arg; 4281 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4282 int FI = TailCallArgs[i].FrameIdx; 4283 // Store relative to framepointer. 4284 MemOpChains.push_back(DAG.getStore( 4285 Chain, dl, Arg, FIN, 4286 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4287 } 4288 } 4289 4290 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4291 /// the appropriate stack slot for the tail call optimized function call. 4292 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4293 SDValue OldRetAddr, SDValue OldFP, 4294 int SPDiff, const SDLoc &dl) { 4295 if (SPDiff) { 4296 // Calculate the new stack slot for the return address. 4297 MachineFunction &MF = DAG.getMachineFunction(); 4298 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4299 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4300 bool isPPC64 = Subtarget.isPPC64(); 4301 int SlotSize = isPPC64 ? 8 : 4; 4302 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4303 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4304 NewRetAddrLoc, true); 4305 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4306 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4307 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4308 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4309 4310 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4311 // slot as the FP is never overwritten. 4312 if (Subtarget.isDarwinABI()) { 4313 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4314 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4315 true); 4316 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4317 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4318 MachinePointerInfo::getFixedStack( 4319 DAG.getMachineFunction(), NewFPIdx)); 4320 } 4321 } 4322 return Chain; 4323 } 4324 4325 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4326 /// the position of the argument. 4327 static void 4328 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4329 SDValue Arg, int SPDiff, unsigned ArgOffset, 4330 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4331 int Offset = ArgOffset + SPDiff; 4332 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4333 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4334 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4335 SDValue FIN = DAG.getFrameIndex(FI, VT); 4336 TailCallArgumentInfo Info; 4337 Info.Arg = Arg; 4338 Info.FrameIdxOp = FIN; 4339 Info.FrameIdx = FI; 4340 TailCallArguments.push_back(Info); 4341 } 4342 4343 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4344 /// stack slot. Returns the chain as result and the loaded frame pointers in 4345 /// LROpOut/FPOpout. Used when tail calling. 4346 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4347 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4348 SDValue &FPOpOut, const SDLoc &dl) const { 4349 if (SPDiff) { 4350 // Load the LR and FP stack slot for later adjusting. 4351 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4352 LROpOut = getReturnAddrFrameIndex(DAG); 4353 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4354 Chain = SDValue(LROpOut.getNode(), 1); 4355 4356 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4357 // slot as the FP is never overwritten. 4358 if (Subtarget.isDarwinABI()) { 4359 FPOpOut = getFramePointerFrameIndex(DAG); 4360 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4361 Chain = SDValue(FPOpOut.getNode(), 1); 4362 } 4363 } 4364 return Chain; 4365 } 4366 4367 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4368 /// by "Src" to address "Dst" of size "Size". Alignment information is 4369 /// specified by the specific parameter attribute. The copy will be passed as 4370 /// a byval function parameter. 4371 /// Sometimes what we are copying is the end of a larger object, the part that 4372 /// does not fit in registers. 4373 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4374 SDValue Chain, ISD::ArgFlagsTy Flags, 4375 SelectionDAG &DAG, const SDLoc &dl) { 4376 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4377 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4378 false, false, false, MachinePointerInfo(), 4379 MachinePointerInfo()); 4380 } 4381 4382 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4383 /// tail calls. 4384 static void LowerMemOpCallTo( 4385 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4386 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4387 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4388 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4389 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4390 if (!isTailCall) { 4391 if (isVector) { 4392 SDValue StackPtr; 4393 if (isPPC64) 4394 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4395 else 4396 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4397 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4398 DAG.getConstant(ArgOffset, dl, PtrVT)); 4399 } 4400 MemOpChains.push_back( 4401 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4402 // Calculate and remember argument location. 4403 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4404 TailCallArguments); 4405 } 4406 4407 static void 4408 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4409 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4410 SDValue FPOp, 4411 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4412 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4413 // might overwrite each other in case of tail call optimization. 4414 SmallVector<SDValue, 8> MemOpChains2; 4415 // Do not flag preceding copytoreg stuff together with the following stuff. 4416 InFlag = SDValue(); 4417 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4418 MemOpChains2, dl); 4419 if (!MemOpChains2.empty()) 4420 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4421 4422 // Store the return address to the appropriate stack slot. 4423 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4424 4425 // Emit callseq_end just before tailcall node. 4426 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4427 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4428 InFlag = Chain.getValue(1); 4429 } 4430 4431 // Is this global address that of a function that can be called by name? (as 4432 // opposed to something that must hold a descriptor for an indirect call). 4433 static bool isFunctionGlobalAddress(SDValue Callee) { 4434 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4435 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4436 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4437 return false; 4438 4439 return G->getGlobal()->getValueType()->isFunctionTy(); 4440 } 4441 4442 return false; 4443 } 4444 4445 static unsigned 4446 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4447 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4448 bool isPatchPoint, bool hasNest, 4449 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4450 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4451 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) { 4452 bool isPPC64 = Subtarget.isPPC64(); 4453 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4454 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4455 4456 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4457 NodeTys.push_back(MVT::Other); // Returns a chain 4458 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4459 4460 unsigned CallOpc = PPCISD::CALL; 4461 4462 bool needIndirectCall = true; 4463 if (!isSVR4ABI || !isPPC64) 4464 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4465 // If this is an absolute destination address, use the munged value. 4466 Callee = SDValue(Dest, 0); 4467 needIndirectCall = false; 4468 } 4469 4470 // PC-relative references to external symbols should go through $stub, unless 4471 // we're building with the leopard linker or later, which automatically 4472 // synthesizes these stubs. 4473 const TargetMachine &TM = DAG.getTarget(); 4474 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent(); 4475 const GlobalValue *GV = nullptr; 4476 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4477 GV = G->getGlobal(); 4478 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4479 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4480 4481 if (isFunctionGlobalAddress(Callee)) { 4482 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4483 // A call to a TLS address is actually an indirect call to a 4484 // thread-specific pointer. 4485 unsigned OpFlags = 0; 4486 if (UsePlt) 4487 OpFlags = PPCII::MO_PLT; 4488 4489 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4490 // every direct call is) turn it into a TargetGlobalAddress / 4491 // TargetExternalSymbol node so that legalize doesn't hack it. 4492 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4493 Callee.getValueType(), 0, OpFlags); 4494 needIndirectCall = false; 4495 } 4496 4497 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4498 unsigned char OpFlags = 0; 4499 4500 if (UsePlt) 4501 OpFlags = PPCII::MO_PLT; 4502 4503 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4504 OpFlags); 4505 needIndirectCall = false; 4506 } 4507 4508 if (isPatchPoint) { 4509 // We'll form an invalid direct call when lowering a patchpoint; the full 4510 // sequence for an indirect call is complicated, and many of the 4511 // instructions introduced might have side effects (and, thus, can't be 4512 // removed later). The call itself will be removed as soon as the 4513 // argument/return lowering is complete, so the fact that it has the wrong 4514 // kind of operands should not really matter. 4515 needIndirectCall = false; 4516 } 4517 4518 if (needIndirectCall) { 4519 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4520 // to do the call, we can't use PPCISD::CALL. 4521 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4522 4523 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4524 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4525 // entry point, but to the function descriptor (the function entry point 4526 // address is part of the function descriptor though). 4527 // The function descriptor is a three doubleword structure with the 4528 // following fields: function entry point, TOC base address and 4529 // environment pointer. 4530 // Thus for a call through a function pointer, the following actions need 4531 // to be performed: 4532 // 1. Save the TOC of the caller in the TOC save area of its stack 4533 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4534 // 2. Load the address of the function entry point from the function 4535 // descriptor. 4536 // 3. Load the TOC of the callee from the function descriptor into r2. 4537 // 4. Load the environment pointer from the function descriptor into 4538 // r11. 4539 // 5. Branch to the function entry point address. 4540 // 6. On return of the callee, the TOC of the caller needs to be 4541 // restored (this is done in FinishCall()). 4542 // 4543 // The loads are scheduled at the beginning of the call sequence, and the 4544 // register copies are flagged together to ensure that no other 4545 // operations can be scheduled in between. E.g. without flagging the 4546 // copies together, a TOC access in the caller could be scheduled between 4547 // the assignment of the callee TOC and the branch to the callee, which 4548 // results in the TOC access going through the TOC of the callee instead 4549 // of going through the TOC of the caller, which leads to incorrect code. 4550 4551 // Load the address of the function entry point from the function 4552 // descriptor. 4553 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4554 if (LDChain.getValueType() == MVT::Glue) 4555 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4556 4557 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4558 ? (MachineMemOperand::MODereferenceable | 4559 MachineMemOperand::MOInvariant) 4560 : MachineMemOperand::MONone; 4561 4562 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr); 4563 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4564 /* Alignment = */ 8, MMOFlags); 4565 4566 // Load environment pointer into r11. 4567 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4568 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4569 SDValue LoadEnvPtr = 4570 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4571 /* Alignment = */ 8, MMOFlags); 4572 4573 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4574 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4575 SDValue TOCPtr = 4576 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4577 /* Alignment = */ 8, MMOFlags); 4578 4579 setUsesTOCBasePtr(DAG); 4580 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4581 InFlag); 4582 Chain = TOCVal.getValue(0); 4583 InFlag = TOCVal.getValue(1); 4584 4585 // If the function call has an explicit 'nest' parameter, it takes the 4586 // place of the environment pointer. 4587 if (!hasNest) { 4588 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4589 InFlag); 4590 4591 Chain = EnvVal.getValue(0); 4592 InFlag = EnvVal.getValue(1); 4593 } 4594 4595 MTCTROps[0] = Chain; 4596 MTCTROps[1] = LoadFuncPtr; 4597 MTCTROps[2] = InFlag; 4598 } 4599 4600 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4601 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4602 InFlag = Chain.getValue(1); 4603 4604 NodeTys.clear(); 4605 NodeTys.push_back(MVT::Other); 4606 NodeTys.push_back(MVT::Glue); 4607 Ops.push_back(Chain); 4608 CallOpc = PPCISD::BCTRL; 4609 Callee.setNode(nullptr); 4610 // Add use of X11 (holding environment pointer) 4611 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4612 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4613 // Add CTR register as callee so a bctr can be emitted later. 4614 if (isTailCall) 4615 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4616 } 4617 4618 // If this is a direct call, pass the chain and the callee. 4619 if (Callee.getNode()) { 4620 Ops.push_back(Chain); 4621 Ops.push_back(Callee); 4622 } 4623 // If this is a tail call add stack pointer delta. 4624 if (isTailCall) 4625 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 4626 4627 // Add argument registers to the end of the list so that they are known live 4628 // into the call. 4629 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4630 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4631 RegsToPass[i].second.getValueType())); 4632 4633 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4634 // into the call. 4635 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 4636 setUsesTOCBasePtr(DAG); 4637 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4638 } 4639 4640 return CallOpc; 4641 } 4642 4643 SDValue PPCTargetLowering::LowerCallResult( 4644 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4645 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4646 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4647 SmallVector<CCValAssign, 16> RVLocs; 4648 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4649 *DAG.getContext()); 4650 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 4651 4652 // Copy all of the result registers out of their specified physreg. 4653 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4654 CCValAssign &VA = RVLocs[i]; 4655 assert(VA.isRegLoc() && "Can only return in registers!"); 4656 4657 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4658 VA.getLocReg(), VA.getLocVT(), InFlag); 4659 Chain = Val.getValue(1); 4660 InFlag = Val.getValue(2); 4661 4662 switch (VA.getLocInfo()) { 4663 default: llvm_unreachable("Unknown loc info!"); 4664 case CCValAssign::Full: break; 4665 case CCValAssign::AExt: 4666 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4667 break; 4668 case CCValAssign::ZExt: 4669 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4670 DAG.getValueType(VA.getValVT())); 4671 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4672 break; 4673 case CCValAssign::SExt: 4674 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4675 DAG.getValueType(VA.getValVT())); 4676 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4677 break; 4678 } 4679 4680 InVals.push_back(Val); 4681 } 4682 4683 return Chain; 4684 } 4685 4686 SDValue PPCTargetLowering::FinishCall( 4687 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 4688 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 4689 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 4690 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 4691 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 4692 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const { 4693 std::vector<EVT> NodeTys; 4694 SmallVector<SDValue, 8> Ops; 4695 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 4696 SPDiff, isTailCall, isPatchPoint, hasNest, 4697 RegsToPass, Ops, NodeTys, CS, Subtarget); 4698 4699 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 4700 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 4701 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 4702 4703 // When performing tail call optimization the callee pops its arguments off 4704 // the stack. Account for this here so these bytes can be pushed back on in 4705 // PPCFrameLowering::eliminateCallFramePseudoInstr. 4706 int BytesCalleePops = 4707 (CallConv == CallingConv::Fast && 4708 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 4709 4710 // Add a register mask operand representing the call-preserved registers. 4711 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4712 const uint32_t *Mask = 4713 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 4714 assert(Mask && "Missing call preserved mask for calling convention"); 4715 Ops.push_back(DAG.getRegisterMask(Mask)); 4716 4717 if (InFlag.getNode()) 4718 Ops.push_back(InFlag); 4719 4720 // Emit tail call. 4721 if (isTailCall) { 4722 assert(((Callee.getOpcode() == ISD::Register && 4723 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 4724 Callee.getOpcode() == ISD::TargetExternalSymbol || 4725 Callee.getOpcode() == ISD::TargetGlobalAddress || 4726 isa<ConstantSDNode>(Callee)) && 4727 "Expecting an global address, external symbol, absolute value or register"); 4728 4729 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 4730 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 4731 } 4732 4733 // Add a NOP immediately after the branch instruction when using the 64-bit 4734 // SVR4 ABI. At link time, if caller and callee are in a different module and 4735 // thus have a different TOC, the call will be replaced with a call to a stub 4736 // function which saves the current TOC, loads the TOC of the callee and 4737 // branches to the callee. The NOP will be replaced with a load instruction 4738 // which restores the TOC of the caller from the TOC save slot of the current 4739 // stack frame. If caller and callee belong to the same module (and have the 4740 // same TOC), the NOP will remain unchanged. 4741 4742 MachineFunction &MF = DAG.getMachineFunction(); 4743 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 4744 !isPatchPoint) { 4745 if (CallOpc == PPCISD::BCTRL) { 4746 // This is a call through a function pointer. 4747 // Restore the caller TOC from the save area into R2. 4748 // See PrepareCall() for more information about calls through function 4749 // pointers in the 64-bit SVR4 ABI. 4750 // We are using a target-specific load with r2 hard coded, because the 4751 // result of a target-independent load would never go directly into r2, 4752 // since r2 is a reserved register (which prevents the register allocator 4753 // from allocating it), resulting in an additional register being 4754 // allocated and an unnecessary move instruction being generated. 4755 CallOpc = PPCISD::BCTRL_LOAD_TOC; 4756 4757 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4758 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 4759 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 4760 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 4761 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 4762 4763 // The address needs to go after the chain input but before the flag (or 4764 // any other variadic arguments). 4765 Ops.insert(std::next(Ops.begin()), AddTOC); 4766 } else if (CallOpc == PPCISD::CALL && 4767 !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) { 4768 // Otherwise insert NOP for non-local calls. 4769 CallOpc = PPCISD::CALL_NOP; 4770 } 4771 } 4772 4773 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 4774 InFlag = Chain.getValue(1); 4775 4776 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4777 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 4778 InFlag, dl); 4779 if (!Ins.empty()) 4780 InFlag = Chain.getValue(1); 4781 4782 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 4783 Ins, dl, DAG, InVals); 4784 } 4785 4786 SDValue 4787 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 4788 SmallVectorImpl<SDValue> &InVals) const { 4789 SelectionDAG &DAG = CLI.DAG; 4790 SDLoc &dl = CLI.DL; 4791 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 4792 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 4793 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 4794 SDValue Chain = CLI.Chain; 4795 SDValue Callee = CLI.Callee; 4796 bool &isTailCall = CLI.IsTailCall; 4797 CallingConv::ID CallConv = CLI.CallConv; 4798 bool isVarArg = CLI.IsVarArg; 4799 bool isPatchPoint = CLI.IsPatchPoint; 4800 ImmutableCallSite *CS = CLI.CS; 4801 4802 if (isTailCall) { 4803 if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall())) 4804 isTailCall = false; 4805 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 4806 isTailCall = 4807 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 4808 isVarArg, Outs, Ins, DAG); 4809 else 4810 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 4811 Ins, DAG); 4812 if (isTailCall) { 4813 ++NumTailCalls; 4814 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4815 ++NumSiblingCalls; 4816 4817 assert(isa<GlobalAddressSDNode>(Callee) && 4818 "Callee should be an llvm::Function object."); 4819 DEBUG( 4820 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 4821 const unsigned Width = 80 - strlen("TCO caller: ") 4822 - strlen(", callee linkage: 0, 0"); 4823 dbgs() << "TCO caller: " 4824 << left_justify(DAG.getMachineFunction().getName(), Width) 4825 << ", callee linkage: " 4826 << GV->getVisibility() << ", " << GV->getLinkage() << "\n" 4827 ); 4828 } 4829 } 4830 4831 if (!isTailCall && CS && CS->isMustTailCall()) 4832 report_fatal_error("failed to perform tail call elimination on a call " 4833 "site marked musttail"); 4834 4835 // When long calls (i.e. indirect calls) are always used, calls are always 4836 // made via function pointer. If we have a function name, first translate it 4837 // into a pointer. 4838 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 4839 !isTailCall) 4840 Callee = LowerGlobalAddress(Callee, DAG); 4841 4842 if (Subtarget.isSVR4ABI()) { 4843 if (Subtarget.isPPC64()) 4844 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 4845 isTailCall, isPatchPoint, Outs, OutVals, Ins, 4846 dl, DAG, InVals, CS); 4847 else 4848 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 4849 isTailCall, isPatchPoint, Outs, OutVals, Ins, 4850 dl, DAG, InVals, CS); 4851 } 4852 4853 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 4854 isTailCall, isPatchPoint, Outs, OutVals, Ins, 4855 dl, DAG, InVals, CS); 4856 } 4857 4858 SDValue PPCTargetLowering::LowerCall_32SVR4( 4859 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 4860 bool isTailCall, bool isPatchPoint, 4861 const SmallVectorImpl<ISD::OutputArg> &Outs, 4862 const SmallVectorImpl<SDValue> &OutVals, 4863 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4864 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 4865 ImmutableCallSite *CS) const { 4866 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 4867 // of the 32-bit SVR4 ABI stack frame layout. 4868 4869 assert((CallConv == CallingConv::C || 4870 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 4871 4872 unsigned PtrByteSize = 4; 4873 4874 MachineFunction &MF = DAG.getMachineFunction(); 4875 4876 // Mark this function as potentially containing a function that contains a 4877 // tail call. As a consequence the frame pointer will be used for dynamicalloc 4878 // and restoring the callers stack pointer in this functions epilog. This is 4879 // done because by tail calling the called function might overwrite the value 4880 // in this function's (MF) stack pointer stack slot 0(SP). 4881 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4882 CallConv == CallingConv::Fast) 4883 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 4884 4885 // Count how many bytes are to be pushed on the stack, including the linkage 4886 // area, parameter list area and the part of the local variable space which 4887 // contains copies of aggregates which are passed by value. 4888 4889 // Assign locations to all of the outgoing arguments. 4890 SmallVector<CCValAssign, 16> ArgLocs; 4891 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 4892 4893 // Reserve space for the linkage area on the stack. 4894 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 4895 PtrByteSize); 4896 if (useSoftFloat()) 4897 CCInfo.PreAnalyzeCallOperands(Outs); 4898 4899 if (isVarArg) { 4900 // Handle fixed and variable vector arguments differently. 4901 // Fixed vector arguments go into registers as long as registers are 4902 // available. Variable vector arguments always go into memory. 4903 unsigned NumArgs = Outs.size(); 4904 4905 for (unsigned i = 0; i != NumArgs; ++i) { 4906 MVT ArgVT = Outs[i].VT; 4907 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4908 bool Result; 4909 4910 if (Outs[i].IsFixed) { 4911 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 4912 CCInfo); 4913 } else { 4914 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 4915 ArgFlags, CCInfo); 4916 } 4917 4918 if (Result) { 4919 #ifndef NDEBUG 4920 errs() << "Call operand #" << i << " has unhandled type " 4921 << EVT(ArgVT).getEVTString() << "\n"; 4922 #endif 4923 llvm_unreachable(nullptr); 4924 } 4925 } 4926 } else { 4927 // All arguments are treated the same. 4928 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 4929 } 4930 CCInfo.clearWasPPCF128(); 4931 4932 // Assign locations to all of the outgoing aggregate by value arguments. 4933 SmallVector<CCValAssign, 16> ByValArgLocs; 4934 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 4935 4936 // Reserve stack space for the allocations in CCInfo. 4937 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 4938 4939 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 4940 4941 // Size of the linkage area, parameter list area and the part of the local 4942 // space variable where copies of aggregates which are passed by value are 4943 // stored. 4944 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 4945 4946 // Calculate by how many bytes the stack has to be adjusted in case of tail 4947 // call optimization. 4948 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 4949 4950 // Adjust the stack pointer for the new arguments... 4951 // These operations are automatically eliminated by the prolog/epilog pass 4952 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 4953 SDValue CallSeqStart = Chain; 4954 4955 // Load the return address and frame pointer so it can be moved somewhere else 4956 // later. 4957 SDValue LROp, FPOp; 4958 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 4959 4960 // Set up a copy of the stack pointer for use loading and storing any 4961 // arguments that may not fit in the registers available for argument 4962 // passing. 4963 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4964 4965 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4966 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 4967 SmallVector<SDValue, 8> MemOpChains; 4968 4969 bool seenFloatArg = false; 4970 // Walk the register/memloc assignments, inserting copies/loads. 4971 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 4972 i != e; 4973 ++i) { 4974 CCValAssign &VA = ArgLocs[i]; 4975 SDValue Arg = OutVals[i]; 4976 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4977 4978 if (Flags.isByVal()) { 4979 // Argument is an aggregate which is passed by value, thus we need to 4980 // create a copy of it in the local variable space of the current stack 4981 // frame (which is the stack frame of the caller) and pass the address of 4982 // this copy to the callee. 4983 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 4984 CCValAssign &ByValVA = ByValArgLocs[j++]; 4985 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 4986 4987 // Memory reserved in the local variable space of the callers stack frame. 4988 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 4989 4990 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 4991 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 4992 StackPtr, PtrOff); 4993 4994 // Create a copy of the argument in the local area of the current 4995 // stack frame. 4996 SDValue MemcpyCall = 4997 CreateCopyOfByValArgument(Arg, PtrOff, 4998 CallSeqStart.getNode()->getOperand(0), 4999 Flags, DAG, dl); 5000 5001 // This must go outside the CALLSEQ_START..END. 5002 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5003 SDLoc(MemcpyCall)); 5004 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5005 NewCallSeqStart.getNode()); 5006 Chain = CallSeqStart = NewCallSeqStart; 5007 5008 // Pass the address of the aggregate copy on the stack either in a 5009 // physical register or in the parameter list area of the current stack 5010 // frame to the callee. 5011 Arg = PtrOff; 5012 } 5013 5014 if (VA.isRegLoc()) { 5015 if (Arg.getValueType() == MVT::i1) 5016 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 5017 5018 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5019 // Put argument in a physical register. 5020 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5021 } else { 5022 // Put argument in the parameter list area of the current stack frame. 5023 assert(VA.isMemLoc()); 5024 unsigned LocMemOffset = VA.getLocMemOffset(); 5025 5026 if (!isTailCall) { 5027 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5028 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5029 StackPtr, PtrOff); 5030 5031 MemOpChains.push_back( 5032 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5033 } else { 5034 // Calculate and remember argument location. 5035 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5036 TailCallArguments); 5037 } 5038 } 5039 } 5040 5041 if (!MemOpChains.empty()) 5042 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5043 5044 // Build a sequence of copy-to-reg nodes chained together with token chain 5045 // and flag operands which copy the outgoing args into the appropriate regs. 5046 SDValue InFlag; 5047 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5048 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5049 RegsToPass[i].second, InFlag); 5050 InFlag = Chain.getValue(1); 5051 } 5052 5053 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5054 // registers. 5055 if (isVarArg) { 5056 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5057 SDValue Ops[] = { Chain, InFlag }; 5058 5059 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5060 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5061 5062 InFlag = Chain.getValue(1); 5063 } 5064 5065 if (isTailCall) 5066 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5067 TailCallArguments); 5068 5069 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5070 /* unused except on PPC64 ELFv1 */ false, DAG, 5071 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5072 NumBytes, Ins, InVals, CS); 5073 } 5074 5075 // Copy an argument into memory, being careful to do this outside the 5076 // call sequence for the call to which the argument belongs. 5077 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5078 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5079 SelectionDAG &DAG, const SDLoc &dl) const { 5080 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5081 CallSeqStart.getNode()->getOperand(0), 5082 Flags, DAG, dl); 5083 // The MEMCPY must go outside the CALLSEQ_START..END. 5084 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5085 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5086 SDLoc(MemcpyCall)); 5087 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5088 NewCallSeqStart.getNode()); 5089 return NewCallSeqStart; 5090 } 5091 5092 SDValue PPCTargetLowering::LowerCall_64SVR4( 5093 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5094 bool isTailCall, bool isPatchPoint, 5095 const SmallVectorImpl<ISD::OutputArg> &Outs, 5096 const SmallVectorImpl<SDValue> &OutVals, 5097 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5098 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5099 ImmutableCallSite *CS) const { 5100 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5101 bool isLittleEndian = Subtarget.isLittleEndian(); 5102 unsigned NumOps = Outs.size(); 5103 bool hasNest = false; 5104 bool IsSibCall = false; 5105 5106 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5107 unsigned PtrByteSize = 8; 5108 5109 MachineFunction &MF = DAG.getMachineFunction(); 5110 5111 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5112 IsSibCall = true; 5113 5114 // Mark this function as potentially containing a function that contains a 5115 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5116 // and restoring the callers stack pointer in this functions epilog. This is 5117 // done because by tail calling the called function might overwrite the value 5118 // in this function's (MF) stack pointer stack slot 0(SP). 5119 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5120 CallConv == CallingConv::Fast) 5121 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5122 5123 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5124 "fastcc not supported on varargs functions"); 5125 5126 // Count how many bytes are to be pushed on the stack, including the linkage 5127 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5128 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5129 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5130 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5131 unsigned NumBytes = LinkageSize; 5132 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5133 unsigned &QFPR_idx = FPR_idx; 5134 5135 static const MCPhysReg GPR[] = { 5136 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5137 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5138 }; 5139 static const MCPhysReg VR[] = { 5140 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5141 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5142 }; 5143 5144 const unsigned NumGPRs = array_lengthof(GPR); 5145 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5146 const unsigned NumVRs = array_lengthof(VR); 5147 const unsigned NumQFPRs = NumFPRs; 5148 5149 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5150 // can be passed to the callee in registers. 5151 // For the fast calling convention, there is another check below. 5152 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5153 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5154 if (!HasParameterArea) { 5155 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5156 unsigned AvailableFPRs = NumFPRs; 5157 unsigned AvailableVRs = NumVRs; 5158 unsigned NumBytesTmp = NumBytes; 5159 for (unsigned i = 0; i != NumOps; ++i) { 5160 if (Outs[i].Flags.isNest()) continue; 5161 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5162 PtrByteSize, LinkageSize, ParamAreaSize, 5163 NumBytesTmp, AvailableFPRs, AvailableVRs, 5164 Subtarget.hasQPX())) 5165 HasParameterArea = true; 5166 } 5167 } 5168 5169 // When using the fast calling convention, we don't provide backing for 5170 // arguments that will be in registers. 5171 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5172 5173 // Add up all the space actually used. 5174 for (unsigned i = 0; i != NumOps; ++i) { 5175 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5176 EVT ArgVT = Outs[i].VT; 5177 EVT OrigVT = Outs[i].ArgVT; 5178 5179 if (Flags.isNest()) 5180 continue; 5181 5182 if (CallConv == CallingConv::Fast) { 5183 if (Flags.isByVal()) 5184 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5185 else 5186 switch (ArgVT.getSimpleVT().SimpleTy) { 5187 default: llvm_unreachable("Unexpected ValueType for argument!"); 5188 case MVT::i1: 5189 case MVT::i32: 5190 case MVT::i64: 5191 if (++NumGPRsUsed <= NumGPRs) 5192 continue; 5193 break; 5194 case MVT::v4i32: 5195 case MVT::v8i16: 5196 case MVT::v16i8: 5197 case MVT::v2f64: 5198 case MVT::v2i64: 5199 case MVT::v1i128: 5200 if (++NumVRsUsed <= NumVRs) 5201 continue; 5202 break; 5203 case MVT::v4f32: 5204 // When using QPX, this is handled like a FP register, otherwise, it 5205 // is an Altivec register. 5206 if (Subtarget.hasQPX()) { 5207 if (++NumFPRsUsed <= NumFPRs) 5208 continue; 5209 } else { 5210 if (++NumVRsUsed <= NumVRs) 5211 continue; 5212 } 5213 break; 5214 case MVT::f32: 5215 case MVT::f64: 5216 case MVT::v4f64: // QPX 5217 case MVT::v4i1: // QPX 5218 if (++NumFPRsUsed <= NumFPRs) 5219 continue; 5220 break; 5221 } 5222 } 5223 5224 /* Respect alignment of argument on the stack. */ 5225 unsigned Align = 5226 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5227 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5228 5229 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5230 if (Flags.isInConsecutiveRegsLast()) 5231 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5232 } 5233 5234 unsigned NumBytesActuallyUsed = NumBytes; 5235 5236 // In the old ELFv1 ABI, 5237 // the prolog code of the callee may store up to 8 GPR argument registers to 5238 // the stack, allowing va_start to index over them in memory if its varargs. 5239 // Because we cannot tell if this is needed on the caller side, we have to 5240 // conservatively assume that it is needed. As such, make sure we have at 5241 // least enough stack space for the caller to store the 8 GPRs. 5242 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5243 // really requires memory operands, e.g. a vararg function. 5244 if (HasParameterArea) 5245 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5246 else 5247 NumBytes = LinkageSize; 5248 5249 // Tail call needs the stack to be aligned. 5250 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5251 CallConv == CallingConv::Fast) 5252 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5253 5254 int SPDiff = 0; 5255 5256 // Calculate by how many bytes the stack has to be adjusted in case of tail 5257 // call optimization. 5258 if (!IsSibCall) 5259 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5260 5261 // To protect arguments on the stack from being clobbered in a tail call, 5262 // force all the loads to happen before doing any other lowering. 5263 if (isTailCall) 5264 Chain = DAG.getStackArgumentTokenFactor(Chain); 5265 5266 // Adjust the stack pointer for the new arguments... 5267 // These operations are automatically eliminated by the prolog/epilog pass 5268 if (!IsSibCall) 5269 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5270 SDValue CallSeqStart = Chain; 5271 5272 // Load the return address and frame pointer so it can be move somewhere else 5273 // later. 5274 SDValue LROp, FPOp; 5275 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5276 5277 // Set up a copy of the stack pointer for use loading and storing any 5278 // arguments that may not fit in the registers available for argument 5279 // passing. 5280 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5281 5282 // Figure out which arguments are going to go in registers, and which in 5283 // memory. Also, if this is a vararg function, floating point operations 5284 // must be stored to our stack, and loaded into integer regs as well, if 5285 // any integer regs are available for argument passing. 5286 unsigned ArgOffset = LinkageSize; 5287 5288 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5289 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5290 5291 SmallVector<SDValue, 8> MemOpChains; 5292 for (unsigned i = 0; i != NumOps; ++i) { 5293 SDValue Arg = OutVals[i]; 5294 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5295 EVT ArgVT = Outs[i].VT; 5296 EVT OrigVT = Outs[i].ArgVT; 5297 5298 // PtrOff will be used to store the current argument to the stack if a 5299 // register cannot be found for it. 5300 SDValue PtrOff; 5301 5302 // We re-align the argument offset for each argument, except when using the 5303 // fast calling convention, when we need to make sure we do that only when 5304 // we'll actually use a stack slot. 5305 auto ComputePtrOff = [&]() { 5306 /* Respect alignment of argument on the stack. */ 5307 unsigned Align = 5308 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5309 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5310 5311 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5312 5313 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5314 }; 5315 5316 if (CallConv != CallingConv::Fast) { 5317 ComputePtrOff(); 5318 5319 /* Compute GPR index associated with argument offset. */ 5320 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5321 GPR_idx = std::min(GPR_idx, NumGPRs); 5322 } 5323 5324 // Promote integers to 64-bit values. 5325 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5326 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5327 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5328 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5329 } 5330 5331 // FIXME memcpy is used way more than necessary. Correctness first. 5332 // Note: "by value" is code for passing a structure by value, not 5333 // basic types. 5334 if (Flags.isByVal()) { 5335 // Note: Size includes alignment padding, so 5336 // struct x { short a; char b; } 5337 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5338 // These are the proper values we need for right-justifying the 5339 // aggregate in a parameter register. 5340 unsigned Size = Flags.getByValSize(); 5341 5342 // An empty aggregate parameter takes up no storage and no 5343 // registers. 5344 if (Size == 0) 5345 continue; 5346 5347 if (CallConv == CallingConv::Fast) 5348 ComputePtrOff(); 5349 5350 // All aggregates smaller than 8 bytes must be passed right-justified. 5351 if (Size==1 || Size==2 || Size==4) { 5352 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5353 if (GPR_idx != NumGPRs) { 5354 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5355 MachinePointerInfo(), VT); 5356 MemOpChains.push_back(Load.getValue(1)); 5357 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5358 5359 ArgOffset += PtrByteSize; 5360 continue; 5361 } 5362 } 5363 5364 if (GPR_idx == NumGPRs && Size < 8) { 5365 SDValue AddPtr = PtrOff; 5366 if (!isLittleEndian) { 5367 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5368 PtrOff.getValueType()); 5369 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5370 } 5371 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5372 CallSeqStart, 5373 Flags, DAG, dl); 5374 ArgOffset += PtrByteSize; 5375 continue; 5376 } 5377 // Copy entire object into memory. There are cases where gcc-generated 5378 // code assumes it is there, even if it could be put entirely into 5379 // registers. (This is not what the doc says.) 5380 5381 // FIXME: The above statement is likely due to a misunderstanding of the 5382 // documents. All arguments must be copied into the parameter area BY 5383 // THE CALLEE in the event that the callee takes the address of any 5384 // formal argument. That has not yet been implemented. However, it is 5385 // reasonable to use the stack area as a staging area for the register 5386 // load. 5387 5388 // Skip this for small aggregates, as we will use the same slot for a 5389 // right-justified copy, below. 5390 if (Size >= 8) 5391 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5392 CallSeqStart, 5393 Flags, DAG, dl); 5394 5395 // When a register is available, pass a small aggregate right-justified. 5396 if (Size < 8 && GPR_idx != NumGPRs) { 5397 // The easiest way to get this right-justified in a register 5398 // is to copy the structure into the rightmost portion of a 5399 // local variable slot, then load the whole slot into the 5400 // register. 5401 // FIXME: The memcpy seems to produce pretty awful code for 5402 // small aggregates, particularly for packed ones. 5403 // FIXME: It would be preferable to use the slot in the 5404 // parameter save area instead of a new local variable. 5405 SDValue AddPtr = PtrOff; 5406 if (!isLittleEndian) { 5407 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5408 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5409 } 5410 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5411 CallSeqStart, 5412 Flags, DAG, dl); 5413 5414 // Load the slot into the register. 5415 SDValue Load = 5416 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5417 MemOpChains.push_back(Load.getValue(1)); 5418 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5419 5420 // Done with this argument. 5421 ArgOffset += PtrByteSize; 5422 continue; 5423 } 5424 5425 // For aggregates larger than PtrByteSize, copy the pieces of the 5426 // object that fit into registers from the parameter save area. 5427 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5428 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5429 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5430 if (GPR_idx != NumGPRs) { 5431 SDValue Load = 5432 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5433 MemOpChains.push_back(Load.getValue(1)); 5434 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5435 ArgOffset += PtrByteSize; 5436 } else { 5437 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5438 break; 5439 } 5440 } 5441 continue; 5442 } 5443 5444 switch (Arg.getSimpleValueType().SimpleTy) { 5445 default: llvm_unreachable("Unexpected ValueType for argument!"); 5446 case MVT::i1: 5447 case MVT::i32: 5448 case MVT::i64: 5449 if (Flags.isNest()) { 5450 // The 'nest' parameter, if any, is passed in R11. 5451 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5452 hasNest = true; 5453 break; 5454 } 5455 5456 // These can be scalar arguments or elements of an integer array type 5457 // passed directly. Clang may use those instead of "byval" aggregate 5458 // types to avoid forcing arguments to memory unnecessarily. 5459 if (GPR_idx != NumGPRs) { 5460 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5461 } else { 5462 if (CallConv == CallingConv::Fast) 5463 ComputePtrOff(); 5464 5465 assert(HasParameterArea && 5466 "Parameter area must exist to pass an argument in memory."); 5467 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5468 true, isTailCall, false, MemOpChains, 5469 TailCallArguments, dl); 5470 if (CallConv == CallingConv::Fast) 5471 ArgOffset += PtrByteSize; 5472 } 5473 if (CallConv != CallingConv::Fast) 5474 ArgOffset += PtrByteSize; 5475 break; 5476 case MVT::f32: 5477 case MVT::f64: { 5478 // These can be scalar arguments or elements of a float array type 5479 // passed directly. The latter are used to implement ELFv2 homogenous 5480 // float aggregates. 5481 5482 // Named arguments go into FPRs first, and once they overflow, the 5483 // remaining arguments go into GPRs and then the parameter save area. 5484 // Unnamed arguments for vararg functions always go to GPRs and 5485 // then the parameter save area. For now, put all arguments to vararg 5486 // routines always in both locations (FPR *and* GPR or stack slot). 5487 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5488 bool NeededLoad = false; 5489 5490 // First load the argument into the next available FPR. 5491 if (FPR_idx != NumFPRs) 5492 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5493 5494 // Next, load the argument into GPR or stack slot if needed. 5495 if (!NeedGPROrStack) 5496 ; 5497 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5498 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5499 // once we support fp <-> gpr moves. 5500 5501 // In the non-vararg case, this can only ever happen in the 5502 // presence of f32 array types, since otherwise we never run 5503 // out of FPRs before running out of GPRs. 5504 SDValue ArgVal; 5505 5506 // Double values are always passed in a single GPR. 5507 if (Arg.getValueType() != MVT::f32) { 5508 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5509 5510 // Non-array float values are extended and passed in a GPR. 5511 } else if (!Flags.isInConsecutiveRegs()) { 5512 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5513 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5514 5515 // If we have an array of floats, we collect every odd element 5516 // together with its predecessor into one GPR. 5517 } else if (ArgOffset % PtrByteSize != 0) { 5518 SDValue Lo, Hi; 5519 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5520 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5521 if (!isLittleEndian) 5522 std::swap(Lo, Hi); 5523 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5524 5525 // The final element, if even, goes into the first half of a GPR. 5526 } else if (Flags.isInConsecutiveRegsLast()) { 5527 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5528 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5529 if (!isLittleEndian) 5530 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5531 DAG.getConstant(32, dl, MVT::i32)); 5532 5533 // Non-final even elements are skipped; they will be handled 5534 // together the with subsequent argument on the next go-around. 5535 } else 5536 ArgVal = SDValue(); 5537 5538 if (ArgVal.getNode()) 5539 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5540 } else { 5541 if (CallConv == CallingConv::Fast) 5542 ComputePtrOff(); 5543 5544 // Single-precision floating-point values are mapped to the 5545 // second (rightmost) word of the stack doubleword. 5546 if (Arg.getValueType() == MVT::f32 && 5547 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5548 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5549 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5550 } 5551 5552 assert(HasParameterArea && 5553 "Parameter area must exist to pass an argument in memory."); 5554 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5555 true, isTailCall, false, MemOpChains, 5556 TailCallArguments, dl); 5557 5558 NeededLoad = true; 5559 } 5560 // When passing an array of floats, the array occupies consecutive 5561 // space in the argument area; only round up to the next doubleword 5562 // at the end of the array. Otherwise, each float takes 8 bytes. 5563 if (CallConv != CallingConv::Fast || NeededLoad) { 5564 ArgOffset += (Arg.getValueType() == MVT::f32 && 5565 Flags.isInConsecutiveRegs()) ? 4 : 8; 5566 if (Flags.isInConsecutiveRegsLast()) 5567 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5568 } 5569 break; 5570 } 5571 case MVT::v4f32: 5572 case MVT::v4i32: 5573 case MVT::v8i16: 5574 case MVT::v16i8: 5575 case MVT::v2f64: 5576 case MVT::v2i64: 5577 case MVT::v1i128: 5578 if (!Subtarget.hasQPX()) { 5579 // These can be scalar arguments or elements of a vector array type 5580 // passed directly. The latter are used to implement ELFv2 homogenous 5581 // vector aggregates. 5582 5583 // For a varargs call, named arguments go into VRs or on the stack as 5584 // usual; unnamed arguments always go to the stack or the corresponding 5585 // GPRs when within range. For now, we always put the value in both 5586 // locations (or even all three). 5587 if (isVarArg) { 5588 assert(HasParameterArea && 5589 "Parameter area must exist if we have a varargs call."); 5590 // We could elide this store in the case where the object fits 5591 // entirely in R registers. Maybe later. 5592 SDValue Store = 5593 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5594 MemOpChains.push_back(Store); 5595 if (VR_idx != NumVRs) { 5596 SDValue Load = 5597 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 5598 MemOpChains.push_back(Load.getValue(1)); 5599 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5600 } 5601 ArgOffset += 16; 5602 for (unsigned i=0; i<16; i+=PtrByteSize) { 5603 if (GPR_idx == NumGPRs) 5604 break; 5605 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5606 DAG.getConstant(i, dl, PtrVT)); 5607 SDValue Load = 5608 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5609 MemOpChains.push_back(Load.getValue(1)); 5610 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5611 } 5612 break; 5613 } 5614 5615 // Non-varargs Altivec params go into VRs or on the stack. 5616 if (VR_idx != NumVRs) { 5617 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5618 } else { 5619 if (CallConv == CallingConv::Fast) 5620 ComputePtrOff(); 5621 5622 assert(HasParameterArea && 5623 "Parameter area must exist to pass an argument in memory."); 5624 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5625 true, isTailCall, true, MemOpChains, 5626 TailCallArguments, dl); 5627 if (CallConv == CallingConv::Fast) 5628 ArgOffset += 16; 5629 } 5630 5631 if (CallConv != CallingConv::Fast) 5632 ArgOffset += 16; 5633 break; 5634 } // not QPX 5635 5636 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5637 "Invalid QPX parameter type"); 5638 5639 /* fall through */ 5640 case MVT::v4f64: 5641 case MVT::v4i1: { 5642 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5643 if (isVarArg) { 5644 assert(HasParameterArea && 5645 "Parameter area must exist if we have a varargs call."); 5646 // We could elide this store in the case where the object fits 5647 // entirely in R registers. Maybe later. 5648 SDValue Store = 5649 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5650 MemOpChains.push_back(Store); 5651 if (QFPR_idx != NumQFPRs) { 5652 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 5653 PtrOff, MachinePointerInfo()); 5654 MemOpChains.push_back(Load.getValue(1)); 5655 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5656 } 5657 ArgOffset += (IsF32 ? 16 : 32); 5658 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5659 if (GPR_idx == NumGPRs) 5660 break; 5661 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5662 DAG.getConstant(i, dl, PtrVT)); 5663 SDValue Load = 5664 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5665 MemOpChains.push_back(Load.getValue(1)); 5666 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5667 } 5668 break; 5669 } 5670 5671 // Non-varargs QPX params go into registers or on the stack. 5672 if (QFPR_idx != NumQFPRs) { 5673 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5674 } else { 5675 if (CallConv == CallingConv::Fast) 5676 ComputePtrOff(); 5677 5678 assert(HasParameterArea && 5679 "Parameter area must exist to pass an argument in memory."); 5680 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5681 true, isTailCall, true, MemOpChains, 5682 TailCallArguments, dl); 5683 if (CallConv == CallingConv::Fast) 5684 ArgOffset += (IsF32 ? 16 : 32); 5685 } 5686 5687 if (CallConv != CallingConv::Fast) 5688 ArgOffset += (IsF32 ? 16 : 32); 5689 break; 5690 } 5691 } 5692 } 5693 5694 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 5695 "mismatch in size of parameter area"); 5696 (void)NumBytesActuallyUsed; 5697 5698 if (!MemOpChains.empty()) 5699 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5700 5701 // Check if this is an indirect call (MTCTR/BCTRL). 5702 // See PrepareCall() for more information about calls through function 5703 // pointers in the 64-bit SVR4 ABI. 5704 if (!isTailCall && !isPatchPoint && 5705 !isFunctionGlobalAddress(Callee) && 5706 !isa<ExternalSymbolSDNode>(Callee)) { 5707 // Load r2 into a virtual register and store it to the TOC save area. 5708 setUsesTOCBasePtr(DAG); 5709 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 5710 // TOC save area offset. 5711 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5712 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5713 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5714 Chain = DAG.getStore( 5715 Val.getValue(1), dl, Val, AddPtr, 5716 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 5717 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 5718 // This does not mean the MTCTR instruction must use R12; it's easier 5719 // to model this as an extra parameter, so do that. 5720 if (isELFv2ABI && !isPatchPoint) 5721 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 5722 } 5723 5724 // Build a sequence of copy-to-reg nodes chained together with token chain 5725 // and flag operands which copy the outgoing args into the appropriate regs. 5726 SDValue InFlag; 5727 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5728 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5729 RegsToPass[i].second, InFlag); 5730 InFlag = Chain.getValue(1); 5731 } 5732 5733 if (isTailCall && !IsSibCall) 5734 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5735 TailCallArguments); 5736 5737 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 5738 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 5739 SPDiff, NumBytes, Ins, InVals, CS); 5740 } 5741 5742 SDValue PPCTargetLowering::LowerCall_Darwin( 5743 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5744 bool isTailCall, bool isPatchPoint, 5745 const SmallVectorImpl<ISD::OutputArg> &Outs, 5746 const SmallVectorImpl<SDValue> &OutVals, 5747 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5748 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5749 ImmutableCallSite *CS) const { 5750 unsigned NumOps = Outs.size(); 5751 5752 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5753 bool isPPC64 = PtrVT == MVT::i64; 5754 unsigned PtrByteSize = isPPC64 ? 8 : 4; 5755 5756 MachineFunction &MF = DAG.getMachineFunction(); 5757 5758 // Mark this function as potentially containing a function that contains a 5759 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5760 // and restoring the callers stack pointer in this functions epilog. This is 5761 // done because by tail calling the called function might overwrite the value 5762 // in this function's (MF) stack pointer stack slot 0(SP). 5763 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5764 CallConv == CallingConv::Fast) 5765 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5766 5767 // Count how many bytes are to be pushed on the stack, including the linkage 5768 // area, and parameter passing area. We start with 24/48 bytes, which is 5769 // prereserved space for [SP][CR][LR][3 x unused]. 5770 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5771 unsigned NumBytes = LinkageSize; 5772 5773 // Add up all the space actually used. 5774 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 5775 // they all go in registers, but we must reserve stack space for them for 5776 // possible use by the caller. In varargs or 64-bit calls, parameters are 5777 // assigned stack space in order, with padding so Altivec parameters are 5778 // 16-byte aligned. 5779 unsigned nAltivecParamsAtEnd = 0; 5780 for (unsigned i = 0; i != NumOps; ++i) { 5781 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5782 EVT ArgVT = Outs[i].VT; 5783 // Varargs Altivec parameters are padded to a 16 byte boundary. 5784 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 5785 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 5786 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 5787 if (!isVarArg && !isPPC64) { 5788 // Non-varargs Altivec parameters go after all the non-Altivec 5789 // parameters; handle those later so we know how much padding we need. 5790 nAltivecParamsAtEnd++; 5791 continue; 5792 } 5793 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 5794 NumBytes = ((NumBytes+15)/16)*16; 5795 } 5796 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5797 } 5798 5799 // Allow for Altivec parameters at the end, if needed. 5800 if (nAltivecParamsAtEnd) { 5801 NumBytes = ((NumBytes+15)/16)*16; 5802 NumBytes += 16*nAltivecParamsAtEnd; 5803 } 5804 5805 // The prolog code of the callee may store up to 8 GPR argument registers to 5806 // the stack, allowing va_start to index over them in memory if its varargs. 5807 // Because we cannot tell if this is needed on the caller side, we have to 5808 // conservatively assume that it is needed. As such, make sure we have at 5809 // least enough stack space for the caller to store the 8 GPRs. 5810 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5811 5812 // Tail call needs the stack to be aligned. 5813 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5814 CallConv == CallingConv::Fast) 5815 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5816 5817 // Calculate by how many bytes the stack has to be adjusted in case of tail 5818 // call optimization. 5819 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5820 5821 // To protect arguments on the stack from being clobbered in a tail call, 5822 // force all the loads to happen before doing any other lowering. 5823 if (isTailCall) 5824 Chain = DAG.getStackArgumentTokenFactor(Chain); 5825 5826 // Adjust the stack pointer for the new arguments... 5827 // These operations are automatically eliminated by the prolog/epilog pass 5828 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5829 SDValue CallSeqStart = Chain; 5830 5831 // Load the return address and frame pointer so it can be move somewhere else 5832 // later. 5833 SDValue LROp, FPOp; 5834 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5835 5836 // Set up a copy of the stack pointer for use loading and storing any 5837 // arguments that may not fit in the registers available for argument 5838 // passing. 5839 SDValue StackPtr; 5840 if (isPPC64) 5841 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5842 else 5843 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5844 5845 // Figure out which arguments are going to go in registers, and which in 5846 // memory. Also, if this is a vararg function, floating point operations 5847 // must be stored to our stack, and loaded into integer regs as well, if 5848 // any integer regs are available for argument passing. 5849 unsigned ArgOffset = LinkageSize; 5850 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5851 5852 static const MCPhysReg GPR_32[] = { // 32-bit registers. 5853 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 5854 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 5855 }; 5856 static const MCPhysReg GPR_64[] = { // 64-bit registers. 5857 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5858 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5859 }; 5860 static const MCPhysReg VR[] = { 5861 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5862 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5863 }; 5864 const unsigned NumGPRs = array_lengthof(GPR_32); 5865 const unsigned NumFPRs = 13; 5866 const unsigned NumVRs = array_lengthof(VR); 5867 5868 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 5869 5870 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5871 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5872 5873 SmallVector<SDValue, 8> MemOpChains; 5874 for (unsigned i = 0; i != NumOps; ++i) { 5875 SDValue Arg = OutVals[i]; 5876 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5877 5878 // PtrOff will be used to store the current argument to the stack if a 5879 // register cannot be found for it. 5880 SDValue PtrOff; 5881 5882 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5883 5884 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5885 5886 // On PPC64, promote integers to 64-bit values. 5887 if (isPPC64 && Arg.getValueType() == MVT::i32) { 5888 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5889 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5890 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5891 } 5892 5893 // FIXME memcpy is used way more than necessary. Correctness first. 5894 // Note: "by value" is code for passing a structure by value, not 5895 // basic types. 5896 if (Flags.isByVal()) { 5897 unsigned Size = Flags.getByValSize(); 5898 // Very small objects are passed right-justified. Everything else is 5899 // passed left-justified. 5900 if (Size==1 || Size==2) { 5901 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 5902 if (GPR_idx != NumGPRs) { 5903 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5904 MachinePointerInfo(), VT); 5905 MemOpChains.push_back(Load.getValue(1)); 5906 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5907 5908 ArgOffset += PtrByteSize; 5909 } else { 5910 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5911 PtrOff.getValueType()); 5912 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5913 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5914 CallSeqStart, 5915 Flags, DAG, dl); 5916 ArgOffset += PtrByteSize; 5917 } 5918 continue; 5919 } 5920 // Copy entire object into memory. There are cases where gcc-generated 5921 // code assumes it is there, even if it could be put entirely into 5922 // registers. (This is not what the doc says.) 5923 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5924 CallSeqStart, 5925 Flags, DAG, dl); 5926 5927 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 5928 // copy the pieces of the object that fit into registers from the 5929 // parameter save area. 5930 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5931 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5932 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5933 if (GPR_idx != NumGPRs) { 5934 SDValue Load = 5935 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5936 MemOpChains.push_back(Load.getValue(1)); 5937 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5938 ArgOffset += PtrByteSize; 5939 } else { 5940 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5941 break; 5942 } 5943 } 5944 continue; 5945 } 5946 5947 switch (Arg.getSimpleValueType().SimpleTy) { 5948 default: llvm_unreachable("Unexpected ValueType for argument!"); 5949 case MVT::i1: 5950 case MVT::i32: 5951 case MVT::i64: 5952 if (GPR_idx != NumGPRs) { 5953 if (Arg.getValueType() == MVT::i1) 5954 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 5955 5956 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5957 } else { 5958 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5959 isPPC64, isTailCall, false, MemOpChains, 5960 TailCallArguments, dl); 5961 } 5962 ArgOffset += PtrByteSize; 5963 break; 5964 case MVT::f32: 5965 case MVT::f64: 5966 if (FPR_idx != NumFPRs) { 5967 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5968 5969 if (isVarArg) { 5970 SDValue Store = 5971 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5972 MemOpChains.push_back(Store); 5973 5974 // Float varargs are always shadowed in available integer registers 5975 if (GPR_idx != NumGPRs) { 5976 SDValue Load = 5977 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 5978 MemOpChains.push_back(Load.getValue(1)); 5979 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5980 } 5981 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 5982 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5983 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5984 SDValue Load = 5985 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 5986 MemOpChains.push_back(Load.getValue(1)); 5987 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5988 } 5989 } else { 5990 // If we have any FPRs remaining, we may also have GPRs remaining. 5991 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 5992 // GPRs. 5993 if (GPR_idx != NumGPRs) 5994 ++GPR_idx; 5995 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 5996 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 5997 ++GPR_idx; 5998 } 5999 } else 6000 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6001 isPPC64, isTailCall, false, MemOpChains, 6002 TailCallArguments, dl); 6003 if (isPPC64) 6004 ArgOffset += 8; 6005 else 6006 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6007 break; 6008 case MVT::v4f32: 6009 case MVT::v4i32: 6010 case MVT::v8i16: 6011 case MVT::v16i8: 6012 if (isVarArg) { 6013 // These go aligned on the stack, or in the corresponding R registers 6014 // when within range. The Darwin PPC ABI doc claims they also go in 6015 // V registers; in fact gcc does this only for arguments that are 6016 // prototyped, not for those that match the ... We do it for all 6017 // arguments, seems to work. 6018 while (ArgOffset % 16 !=0) { 6019 ArgOffset += PtrByteSize; 6020 if (GPR_idx != NumGPRs) 6021 GPR_idx++; 6022 } 6023 // We could elide this store in the case where the object fits 6024 // entirely in R registers. Maybe later. 6025 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6026 DAG.getConstant(ArgOffset, dl, PtrVT)); 6027 SDValue Store = 6028 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6029 MemOpChains.push_back(Store); 6030 if (VR_idx != NumVRs) { 6031 SDValue Load = 6032 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6033 MemOpChains.push_back(Load.getValue(1)); 6034 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6035 } 6036 ArgOffset += 16; 6037 for (unsigned i=0; i<16; i+=PtrByteSize) { 6038 if (GPR_idx == NumGPRs) 6039 break; 6040 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6041 DAG.getConstant(i, dl, PtrVT)); 6042 SDValue Load = 6043 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6044 MemOpChains.push_back(Load.getValue(1)); 6045 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6046 } 6047 break; 6048 } 6049 6050 // Non-varargs Altivec params generally go in registers, but have 6051 // stack space allocated at the end. 6052 if (VR_idx != NumVRs) { 6053 // Doesn't have GPR space allocated. 6054 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6055 } else if (nAltivecParamsAtEnd==0) { 6056 // We are emitting Altivec params in order. 6057 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6058 isPPC64, isTailCall, true, MemOpChains, 6059 TailCallArguments, dl); 6060 ArgOffset += 16; 6061 } 6062 break; 6063 } 6064 } 6065 // If all Altivec parameters fit in registers, as they usually do, 6066 // they get stack space following the non-Altivec parameters. We 6067 // don't track this here because nobody below needs it. 6068 // If there are more Altivec parameters than fit in registers emit 6069 // the stores here. 6070 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6071 unsigned j = 0; 6072 // Offset is aligned; skip 1st 12 params which go in V registers. 6073 ArgOffset = ((ArgOffset+15)/16)*16; 6074 ArgOffset += 12*16; 6075 for (unsigned i = 0; i != NumOps; ++i) { 6076 SDValue Arg = OutVals[i]; 6077 EVT ArgType = Outs[i].VT; 6078 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6079 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6080 if (++j > NumVRs) { 6081 SDValue PtrOff; 6082 // We are emitting Altivec params in order. 6083 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6084 isPPC64, isTailCall, true, MemOpChains, 6085 TailCallArguments, dl); 6086 ArgOffset += 16; 6087 } 6088 } 6089 } 6090 } 6091 6092 if (!MemOpChains.empty()) 6093 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6094 6095 // On Darwin, R12 must contain the address of an indirect callee. This does 6096 // not mean the MTCTR instruction must use R12; it's easier to model this as 6097 // an extra parameter, so do that. 6098 if (!isTailCall && 6099 !isFunctionGlobalAddress(Callee) && 6100 !isa<ExternalSymbolSDNode>(Callee) && 6101 !isBLACompatibleAddress(Callee, DAG)) 6102 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6103 PPC::R12), Callee)); 6104 6105 // Build a sequence of copy-to-reg nodes chained together with token chain 6106 // and flag operands which copy the outgoing args into the appropriate regs. 6107 SDValue InFlag; 6108 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6109 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6110 RegsToPass[i].second, InFlag); 6111 InFlag = Chain.getValue(1); 6112 } 6113 6114 if (isTailCall) 6115 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6116 TailCallArguments); 6117 6118 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6119 /* unused except on PPC64 ELFv1 */ false, DAG, 6120 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6121 NumBytes, Ins, InVals, CS); 6122 } 6123 6124 bool 6125 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6126 MachineFunction &MF, bool isVarArg, 6127 const SmallVectorImpl<ISD::OutputArg> &Outs, 6128 LLVMContext &Context) const { 6129 SmallVector<CCValAssign, 16> RVLocs; 6130 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6131 return CCInfo.CheckReturn(Outs, RetCC_PPC); 6132 } 6133 6134 SDValue 6135 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6136 bool isVarArg, 6137 const SmallVectorImpl<ISD::OutputArg> &Outs, 6138 const SmallVectorImpl<SDValue> &OutVals, 6139 const SDLoc &dl, SelectionDAG &DAG) const { 6140 SmallVector<CCValAssign, 16> RVLocs; 6141 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6142 *DAG.getContext()); 6143 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 6144 6145 SDValue Flag; 6146 SmallVector<SDValue, 4> RetOps(1, Chain); 6147 6148 // Copy the result values into the output registers. 6149 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6150 CCValAssign &VA = RVLocs[i]; 6151 assert(VA.isRegLoc() && "Can only return in registers!"); 6152 6153 SDValue Arg = OutVals[i]; 6154 6155 switch (VA.getLocInfo()) { 6156 default: llvm_unreachable("Unknown loc info!"); 6157 case CCValAssign::Full: break; 6158 case CCValAssign::AExt: 6159 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6160 break; 6161 case CCValAssign::ZExt: 6162 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6163 break; 6164 case CCValAssign::SExt: 6165 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6166 break; 6167 } 6168 6169 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6170 Flag = Chain.getValue(1); 6171 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6172 } 6173 6174 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6175 const MCPhysReg *I = 6176 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6177 if (I) { 6178 for (; *I; ++I) { 6179 6180 if (PPC::G8RCRegClass.contains(*I)) 6181 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6182 else if (PPC::F8RCRegClass.contains(*I)) 6183 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6184 else if (PPC::CRRCRegClass.contains(*I)) 6185 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6186 else if (PPC::VRRCRegClass.contains(*I)) 6187 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6188 else 6189 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6190 } 6191 } 6192 6193 RetOps[0] = Chain; // Update chain. 6194 6195 // Add the flag if we have it. 6196 if (Flag.getNode()) 6197 RetOps.push_back(Flag); 6198 6199 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6200 } 6201 6202 SDValue 6203 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6204 SelectionDAG &DAG) const { 6205 SDLoc dl(Op); 6206 6207 // Get the corect type for integers. 6208 EVT IntVT = Op.getValueType(); 6209 6210 // Get the inputs. 6211 SDValue Chain = Op.getOperand(0); 6212 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6213 // Build a DYNAREAOFFSET node. 6214 SDValue Ops[2] = {Chain, FPSIdx}; 6215 SDVTList VTs = DAG.getVTList(IntVT); 6216 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6217 } 6218 6219 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6220 SelectionDAG &DAG) const { 6221 // When we pop the dynamic allocation we need to restore the SP link. 6222 SDLoc dl(Op); 6223 6224 // Get the corect type for pointers. 6225 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6226 6227 // Construct the stack pointer operand. 6228 bool isPPC64 = Subtarget.isPPC64(); 6229 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6230 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6231 6232 // Get the operands for the STACKRESTORE. 6233 SDValue Chain = Op.getOperand(0); 6234 SDValue SaveSP = Op.getOperand(1); 6235 6236 // Load the old link SP. 6237 SDValue LoadLinkSP = 6238 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6239 6240 // Restore the stack pointer. 6241 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6242 6243 // Store the old link SP. 6244 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6245 } 6246 6247 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6248 MachineFunction &MF = DAG.getMachineFunction(); 6249 bool isPPC64 = Subtarget.isPPC64(); 6250 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6251 6252 // Get current frame pointer save index. The users of this index will be 6253 // primarily DYNALLOC instructions. 6254 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6255 int RASI = FI->getReturnAddrSaveIndex(); 6256 6257 // If the frame pointer save index hasn't been defined yet. 6258 if (!RASI) { 6259 // Find out what the fix offset of the frame pointer save area. 6260 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6261 // Allocate the frame index for frame pointer save area. 6262 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6263 // Save the result. 6264 FI->setReturnAddrSaveIndex(RASI); 6265 } 6266 return DAG.getFrameIndex(RASI, PtrVT); 6267 } 6268 6269 SDValue 6270 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6271 MachineFunction &MF = DAG.getMachineFunction(); 6272 bool isPPC64 = Subtarget.isPPC64(); 6273 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6274 6275 // Get current frame pointer save index. The users of this index will be 6276 // primarily DYNALLOC instructions. 6277 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6278 int FPSI = FI->getFramePointerSaveIndex(); 6279 6280 // If the frame pointer save index hasn't been defined yet. 6281 if (!FPSI) { 6282 // Find out what the fix offset of the frame pointer save area. 6283 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6284 // Allocate the frame index for frame pointer save area. 6285 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6286 // Save the result. 6287 FI->setFramePointerSaveIndex(FPSI); 6288 } 6289 return DAG.getFrameIndex(FPSI, PtrVT); 6290 } 6291 6292 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6293 SelectionDAG &DAG) const { 6294 // Get the inputs. 6295 SDValue Chain = Op.getOperand(0); 6296 SDValue Size = Op.getOperand(1); 6297 SDLoc dl(Op); 6298 6299 // Get the corect type for pointers. 6300 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6301 // Negate the size. 6302 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6303 DAG.getConstant(0, dl, PtrVT), Size); 6304 // Construct a node for the frame pointer save index. 6305 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6306 // Build a DYNALLOC node. 6307 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6308 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6309 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6310 } 6311 6312 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6313 SelectionDAG &DAG) const { 6314 MachineFunction &MF = DAG.getMachineFunction(); 6315 6316 bool isPPC64 = Subtarget.isPPC64(); 6317 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6318 6319 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6320 return DAG.getFrameIndex(FI, PtrVT); 6321 } 6322 6323 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6324 SelectionDAG &DAG) const { 6325 SDLoc DL(Op); 6326 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6327 DAG.getVTList(MVT::i32, MVT::Other), 6328 Op.getOperand(0), Op.getOperand(1)); 6329 } 6330 6331 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6332 SelectionDAG &DAG) const { 6333 SDLoc DL(Op); 6334 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6335 Op.getOperand(0), Op.getOperand(1)); 6336 } 6337 6338 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6339 if (Op.getValueType().isVector()) 6340 return LowerVectorLoad(Op, DAG); 6341 6342 assert(Op.getValueType() == MVT::i1 && 6343 "Custom lowering only for i1 loads"); 6344 6345 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6346 6347 SDLoc dl(Op); 6348 LoadSDNode *LD = cast<LoadSDNode>(Op); 6349 6350 SDValue Chain = LD->getChain(); 6351 SDValue BasePtr = LD->getBasePtr(); 6352 MachineMemOperand *MMO = LD->getMemOperand(); 6353 6354 SDValue NewLD = 6355 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6356 BasePtr, MVT::i8, MMO); 6357 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6358 6359 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6360 return DAG.getMergeValues(Ops, dl); 6361 } 6362 6363 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6364 if (Op.getOperand(1).getValueType().isVector()) 6365 return LowerVectorStore(Op, DAG); 6366 6367 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6368 "Custom lowering only for i1 stores"); 6369 6370 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6371 6372 SDLoc dl(Op); 6373 StoreSDNode *ST = cast<StoreSDNode>(Op); 6374 6375 SDValue Chain = ST->getChain(); 6376 SDValue BasePtr = ST->getBasePtr(); 6377 SDValue Value = ST->getValue(); 6378 MachineMemOperand *MMO = ST->getMemOperand(); 6379 6380 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6381 Value); 6382 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6383 } 6384 6385 // FIXME: Remove this once the ANDI glue bug is fixed: 6386 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6387 assert(Op.getValueType() == MVT::i1 && 6388 "Custom lowering only for i1 results"); 6389 6390 SDLoc DL(Op); 6391 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6392 Op.getOperand(0)); 6393 } 6394 6395 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6396 /// possible. 6397 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6398 // Not FP? Not a fsel. 6399 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6400 !Op.getOperand(2).getValueType().isFloatingPoint()) 6401 return Op; 6402 6403 // We might be able to do better than this under some circumstances, but in 6404 // general, fsel-based lowering of select is a finite-math-only optimization. 6405 // For more information, see section F.3 of the 2.06 ISA specification. 6406 if (!DAG.getTarget().Options.NoInfsFPMath || 6407 !DAG.getTarget().Options.NoNaNsFPMath) 6408 return Op; 6409 // TODO: Propagate flags from the select rather than global settings. 6410 SDNodeFlags Flags; 6411 Flags.setNoInfs(true); 6412 Flags.setNoNaNs(true); 6413 6414 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6415 6416 EVT ResVT = Op.getValueType(); 6417 EVT CmpVT = Op.getOperand(0).getValueType(); 6418 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6419 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6420 SDLoc dl(Op); 6421 6422 // If the RHS of the comparison is a 0.0, we don't need to do the 6423 // subtraction at all. 6424 SDValue Sel1; 6425 if (isFloatingPointZero(RHS)) 6426 switch (CC) { 6427 default: break; // SETUO etc aren't handled by fsel. 6428 case ISD::SETNE: 6429 std::swap(TV, FV); 6430 case ISD::SETEQ: 6431 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6432 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6433 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6434 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6435 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6436 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6437 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6438 case ISD::SETULT: 6439 case ISD::SETLT: 6440 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6441 case ISD::SETOGE: 6442 case ISD::SETGE: 6443 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6444 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6445 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6446 case ISD::SETUGT: 6447 case ISD::SETGT: 6448 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6449 case ISD::SETOLE: 6450 case ISD::SETLE: 6451 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6452 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6453 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6454 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6455 } 6456 6457 SDValue Cmp; 6458 switch (CC) { 6459 default: break; // SETUO etc aren't handled by fsel. 6460 case ISD::SETNE: 6461 std::swap(TV, FV); 6462 case ISD::SETEQ: 6463 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6464 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6465 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6466 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6467 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6468 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6469 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6470 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6471 case ISD::SETULT: 6472 case ISD::SETLT: 6473 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6474 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6475 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6476 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6477 case ISD::SETOGE: 6478 case ISD::SETGE: 6479 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6480 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6481 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6482 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6483 case ISD::SETUGT: 6484 case ISD::SETGT: 6485 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6486 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6487 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6488 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6489 case ISD::SETOLE: 6490 case ISD::SETLE: 6491 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6492 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6493 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6494 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6495 } 6496 return Op; 6497 } 6498 6499 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6500 SelectionDAG &DAG, 6501 const SDLoc &dl) const { 6502 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6503 SDValue Src = Op.getOperand(0); 6504 if (Src.getValueType() == MVT::f32) 6505 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6506 6507 SDValue Tmp; 6508 switch (Op.getSimpleValueType().SimpleTy) { 6509 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6510 case MVT::i32: 6511 Tmp = DAG.getNode( 6512 Op.getOpcode() == ISD::FP_TO_SINT 6513 ? PPCISD::FCTIWZ 6514 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6515 dl, MVT::f64, Src); 6516 break; 6517 case MVT::i64: 6518 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6519 "i64 FP_TO_UINT is supported only with FPCVT"); 6520 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6521 PPCISD::FCTIDUZ, 6522 dl, MVT::f64, Src); 6523 break; 6524 } 6525 6526 // Convert the FP value to an int value through memory. 6527 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 6528 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 6529 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 6530 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 6531 MachinePointerInfo MPI = 6532 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 6533 6534 // Emit a store to the stack slot. 6535 SDValue Chain; 6536 if (i32Stack) { 6537 MachineFunction &MF = DAG.getMachineFunction(); 6538 MachineMemOperand *MMO = 6539 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 6540 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 6541 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 6542 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 6543 } else 6544 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 6545 6546 // Result is a load from the stack slot. If loading 4 bytes, make sure to 6547 // add in a bias on big endian. 6548 if (Op.getValueType() == MVT::i32 && !i32Stack) { 6549 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 6550 DAG.getConstant(4, dl, FIPtr.getValueType())); 6551 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 6552 } 6553 6554 RLI.Chain = Chain; 6555 RLI.Ptr = FIPtr; 6556 RLI.MPI = MPI; 6557 } 6558 6559 /// \brief Custom lowers floating point to integer conversions to use 6560 /// the direct move instructions available in ISA 2.07 to avoid the 6561 /// need for load/store combinations. 6562 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 6563 SelectionDAG &DAG, 6564 const SDLoc &dl) const { 6565 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6566 SDValue Src = Op.getOperand(0); 6567 6568 if (Src.getValueType() == MVT::f32) 6569 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6570 6571 SDValue Tmp; 6572 switch (Op.getSimpleValueType().SimpleTy) { 6573 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6574 case MVT::i32: 6575 Tmp = DAG.getNode( 6576 Op.getOpcode() == ISD::FP_TO_SINT 6577 ? PPCISD::FCTIWZ 6578 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6579 dl, MVT::f64, Src); 6580 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 6581 break; 6582 case MVT::i64: 6583 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6584 "i64 FP_TO_UINT is supported only with FPCVT"); 6585 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6586 PPCISD::FCTIDUZ, 6587 dl, MVT::f64, Src); 6588 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 6589 break; 6590 } 6591 return Tmp; 6592 } 6593 6594 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 6595 const SDLoc &dl) const { 6596 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 6597 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 6598 6599 ReuseLoadInfo RLI; 6600 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6601 6602 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6603 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6604 } 6605 6606 // We're trying to insert a regular store, S, and then a load, L. If the 6607 // incoming value, O, is a load, we might just be able to have our load use the 6608 // address used by O. However, we don't know if anything else will store to 6609 // that address before we can load from it. To prevent this situation, we need 6610 // to insert our load, L, into the chain as a peer of O. To do this, we give L 6611 // the same chain operand as O, we create a token factor from the chain results 6612 // of O and L, and we replace all uses of O's chain result with that token 6613 // factor (see spliceIntoChain below for this last part). 6614 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 6615 ReuseLoadInfo &RLI, 6616 SelectionDAG &DAG, 6617 ISD::LoadExtType ET) const { 6618 SDLoc dl(Op); 6619 if (ET == ISD::NON_EXTLOAD && 6620 (Op.getOpcode() == ISD::FP_TO_UINT || 6621 Op.getOpcode() == ISD::FP_TO_SINT) && 6622 isOperationLegalOrCustom(Op.getOpcode(), 6623 Op.getOperand(0).getValueType())) { 6624 6625 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6626 return true; 6627 } 6628 6629 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 6630 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 6631 LD->isNonTemporal()) 6632 return false; 6633 if (LD->getMemoryVT() != MemVT) 6634 return false; 6635 6636 RLI.Ptr = LD->getBasePtr(); 6637 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 6638 assert(LD->getAddressingMode() == ISD::PRE_INC && 6639 "Non-pre-inc AM on PPC?"); 6640 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 6641 LD->getOffset()); 6642 } 6643 6644 RLI.Chain = LD->getChain(); 6645 RLI.MPI = LD->getPointerInfo(); 6646 RLI.IsDereferenceable = LD->isDereferenceable(); 6647 RLI.IsInvariant = LD->isInvariant(); 6648 RLI.Alignment = LD->getAlignment(); 6649 RLI.AAInfo = LD->getAAInfo(); 6650 RLI.Ranges = LD->getRanges(); 6651 6652 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 6653 return true; 6654 } 6655 6656 // Given the head of the old chain, ResChain, insert a token factor containing 6657 // it and NewResChain, and make users of ResChain now be users of that token 6658 // factor. 6659 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 6660 SDValue NewResChain, 6661 SelectionDAG &DAG) const { 6662 if (!ResChain) 6663 return; 6664 6665 SDLoc dl(NewResChain); 6666 6667 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6668 NewResChain, DAG.getUNDEF(MVT::Other)); 6669 assert(TF.getNode() != NewResChain.getNode() && 6670 "A new TF really is required here"); 6671 6672 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 6673 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 6674 } 6675 6676 /// \brief Analyze profitability of direct move 6677 /// prefer float load to int load plus direct move 6678 /// when there is no integer use of int load 6679 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 6680 SDNode *Origin = Op.getOperand(0).getNode(); 6681 if (Origin->getOpcode() != ISD::LOAD) 6682 return true; 6683 6684 // If there is no LXSIBZX/LXSIHZX, like Power8, 6685 // prefer direct move if the memory size is 1 or 2 bytes. 6686 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 6687 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 6688 return true; 6689 6690 for (SDNode::use_iterator UI = Origin->use_begin(), 6691 UE = Origin->use_end(); 6692 UI != UE; ++UI) { 6693 6694 // Only look at the users of the loaded value. 6695 if (UI.getUse().get().getResNo() != 0) 6696 continue; 6697 6698 if (UI->getOpcode() != ISD::SINT_TO_FP && 6699 UI->getOpcode() != ISD::UINT_TO_FP) 6700 return true; 6701 } 6702 6703 return false; 6704 } 6705 6706 /// \brief Custom lowers integer to floating point conversions to use 6707 /// the direct move instructions available in ISA 2.07 to avoid the 6708 /// need for load/store combinations. 6709 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 6710 SelectionDAG &DAG, 6711 const SDLoc &dl) const { 6712 assert((Op.getValueType() == MVT::f32 || 6713 Op.getValueType() == MVT::f64) && 6714 "Invalid floating point type as target of conversion"); 6715 assert(Subtarget.hasFPCVT() && 6716 "Int to FP conversions with direct moves require FPCVT"); 6717 SDValue FP; 6718 SDValue Src = Op.getOperand(0); 6719 bool SinglePrec = Op.getValueType() == MVT::f32; 6720 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 6721 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 6722 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 6723 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 6724 6725 if (WordInt) { 6726 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 6727 dl, MVT::f64, Src); 6728 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6729 } 6730 else { 6731 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 6732 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6733 } 6734 6735 return FP; 6736 } 6737 6738 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 6739 SelectionDAG &DAG) const { 6740 SDLoc dl(Op); 6741 6742 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 6743 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 6744 return SDValue(); 6745 6746 SDValue Value = Op.getOperand(0); 6747 // The values are now known to be -1 (false) or 1 (true). To convert this 6748 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 6749 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 6750 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 6751 6752 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 6753 6754 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 6755 6756 if (Op.getValueType() != MVT::v4f64) 6757 Value = DAG.getNode(ISD::FP_ROUND, dl, 6758 Op.getValueType(), Value, 6759 DAG.getIntPtrConstant(1, dl)); 6760 return Value; 6761 } 6762 6763 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 6764 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 6765 return SDValue(); 6766 6767 if (Op.getOperand(0).getValueType() == MVT::i1) 6768 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 6769 DAG.getConstantFP(1.0, dl, Op.getValueType()), 6770 DAG.getConstantFP(0.0, dl, Op.getValueType())); 6771 6772 // If we have direct moves, we can do all the conversion, skip the store/load 6773 // however, without FPCVT we can't do most conversions. 6774 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 6775 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 6776 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 6777 6778 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 6779 "UINT_TO_FP is supported only with FPCVT"); 6780 6781 // If we have FCFIDS, then use it when converting to single-precision. 6782 // Otherwise, convert to double-precision and then round. 6783 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 6784 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 6785 : PPCISD::FCFIDS) 6786 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 6787 : PPCISD::FCFID); 6788 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 6789 ? MVT::f32 6790 : MVT::f64; 6791 6792 if (Op.getOperand(0).getValueType() == MVT::i64) { 6793 SDValue SINT = Op.getOperand(0); 6794 // When converting to single-precision, we actually need to convert 6795 // to double-precision first and then round to single-precision. 6796 // To avoid double-rounding effects during that operation, we have 6797 // to prepare the input operand. Bits that might be truncated when 6798 // converting to double-precision are replaced by a bit that won't 6799 // be lost at this stage, but is below the single-precision rounding 6800 // position. 6801 // 6802 // However, if -enable-unsafe-fp-math is in effect, accept double 6803 // rounding to avoid the extra overhead. 6804 if (Op.getValueType() == MVT::f32 && 6805 !Subtarget.hasFPCVT() && 6806 !DAG.getTarget().Options.UnsafeFPMath) { 6807 6808 // Twiddle input to make sure the low 11 bits are zero. (If this 6809 // is the case, we are guaranteed the value will fit into the 53 bit 6810 // mantissa of an IEEE double-precision value without rounding.) 6811 // If any of those low 11 bits were not zero originally, make sure 6812 // bit 12 (value 2048) is set instead, so that the final rounding 6813 // to single-precision gets the correct result. 6814 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 6815 SINT, DAG.getConstant(2047, dl, MVT::i64)); 6816 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 6817 Round, DAG.getConstant(2047, dl, MVT::i64)); 6818 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 6819 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 6820 Round, DAG.getConstant(-2048, dl, MVT::i64)); 6821 6822 // However, we cannot use that value unconditionally: if the magnitude 6823 // of the input value is small, the bit-twiddling we did above might 6824 // end up visibly changing the output. Fortunately, in that case, we 6825 // don't need to twiddle bits since the original input will convert 6826 // exactly to double-precision floating-point already. Therefore, 6827 // construct a conditional to use the original value if the top 11 6828 // bits are all sign-bit copies, and use the rounded value computed 6829 // above otherwise. 6830 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 6831 SINT, DAG.getConstant(53, dl, MVT::i32)); 6832 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 6833 Cond, DAG.getConstant(1, dl, MVT::i64)); 6834 Cond = DAG.getSetCC(dl, MVT::i32, 6835 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 6836 6837 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 6838 } 6839 6840 ReuseLoadInfo RLI; 6841 SDValue Bits; 6842 6843 MachineFunction &MF = DAG.getMachineFunction(); 6844 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 6845 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6846 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6847 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6848 } else if (Subtarget.hasLFIWAX() && 6849 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 6850 MachineMemOperand *MMO = 6851 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6852 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6853 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6854 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 6855 DAG.getVTList(MVT::f64, MVT::Other), 6856 Ops, MVT::i32, MMO); 6857 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6858 } else if (Subtarget.hasFPCVT() && 6859 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 6860 MachineMemOperand *MMO = 6861 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6862 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6863 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6864 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 6865 DAG.getVTList(MVT::f64, MVT::Other), 6866 Ops, MVT::i32, MMO); 6867 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6868 } else if (((Subtarget.hasLFIWAX() && 6869 SINT.getOpcode() == ISD::SIGN_EXTEND) || 6870 (Subtarget.hasFPCVT() && 6871 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 6872 SINT.getOperand(0).getValueType() == MVT::i32) { 6873 MachineFrameInfo &MFI = MF.getFrameInfo(); 6874 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6875 6876 int FrameIdx = MFI.CreateStackObject(4, 4, false); 6877 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6878 6879 SDValue Store = 6880 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 6881 MachinePointerInfo::getFixedStack( 6882 DAG.getMachineFunction(), FrameIdx)); 6883 6884 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 6885 "Expected an i32 store"); 6886 6887 RLI.Ptr = FIdx; 6888 RLI.Chain = Store; 6889 RLI.MPI = 6890 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 6891 RLI.Alignment = 4; 6892 6893 MachineMemOperand *MMO = 6894 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6895 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6896 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6897 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 6898 PPCISD::LFIWZX : PPCISD::LFIWAX, 6899 dl, DAG.getVTList(MVT::f64, MVT::Other), 6900 Ops, MVT::i32, MMO); 6901 } else 6902 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 6903 6904 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 6905 6906 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 6907 FP = DAG.getNode(ISD::FP_ROUND, dl, 6908 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 6909 return FP; 6910 } 6911 6912 assert(Op.getOperand(0).getValueType() == MVT::i32 && 6913 "Unhandled INT_TO_FP type in custom expander!"); 6914 // Since we only generate this in 64-bit mode, we can take advantage of 6915 // 64-bit registers. In particular, sign extend the input value into the 6916 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 6917 // then lfd it and fcfid it. 6918 MachineFunction &MF = DAG.getMachineFunction(); 6919 MachineFrameInfo &MFI = MF.getFrameInfo(); 6920 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6921 6922 SDValue Ld; 6923 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 6924 ReuseLoadInfo RLI; 6925 bool ReusingLoad; 6926 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 6927 DAG))) { 6928 int FrameIdx = MFI.CreateStackObject(4, 4, false); 6929 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6930 6931 SDValue Store = 6932 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 6933 MachinePointerInfo::getFixedStack( 6934 DAG.getMachineFunction(), FrameIdx)); 6935 6936 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 6937 "Expected an i32 store"); 6938 6939 RLI.Ptr = FIdx; 6940 RLI.Chain = Store; 6941 RLI.MPI = 6942 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 6943 RLI.Alignment = 4; 6944 } 6945 6946 MachineMemOperand *MMO = 6947 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6948 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6949 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6950 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 6951 PPCISD::LFIWZX : PPCISD::LFIWAX, 6952 dl, DAG.getVTList(MVT::f64, MVT::Other), 6953 Ops, MVT::i32, MMO); 6954 if (ReusingLoad) 6955 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 6956 } else { 6957 assert(Subtarget.isPPC64() && 6958 "i32->FP without LFIWAX supported only on PPC64"); 6959 6960 int FrameIdx = MFI.CreateStackObject(8, 8, false); 6961 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6962 6963 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 6964 Op.getOperand(0)); 6965 6966 // STD the extended value into the stack slot. 6967 SDValue Store = DAG.getStore( 6968 DAG.getEntryNode(), dl, Ext64, FIdx, 6969 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 6970 6971 // Load the value as a double. 6972 Ld = DAG.getLoad( 6973 MVT::f64, dl, Store, FIdx, 6974 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 6975 } 6976 6977 // FCFID it and return it. 6978 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 6979 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 6980 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 6981 DAG.getIntPtrConstant(0, dl)); 6982 return FP; 6983 } 6984 6985 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 6986 SelectionDAG &DAG) const { 6987 SDLoc dl(Op); 6988 /* 6989 The rounding mode is in bits 30:31 of FPSR, and has the following 6990 settings: 6991 00 Round to nearest 6992 01 Round to 0 6993 10 Round to +inf 6994 11 Round to -inf 6995 6996 FLT_ROUNDS, on the other hand, expects the following: 6997 -1 Undefined 6998 0 Round to 0 6999 1 Round to nearest 7000 2 Round to +inf 7001 3 Round to -inf 7002 7003 To perform the conversion, we do: 7004 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7005 */ 7006 7007 MachineFunction &MF = DAG.getMachineFunction(); 7008 EVT VT = Op.getValueType(); 7009 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7010 7011 // Save FP Control Word to register 7012 EVT NodeTys[] = { 7013 MVT::f64, // return register 7014 MVT::Glue // unused in this context 7015 }; 7016 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7017 7018 // Save FP register to stack slot 7019 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7020 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7021 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7022 MachinePointerInfo()); 7023 7024 // Load FP Control Word from low 32 bits of stack slot. 7025 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7026 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7027 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7028 7029 // Transform as necessary 7030 SDValue CWD1 = 7031 DAG.getNode(ISD::AND, dl, MVT::i32, 7032 CWD, DAG.getConstant(3, dl, MVT::i32)); 7033 SDValue CWD2 = 7034 DAG.getNode(ISD::SRL, dl, MVT::i32, 7035 DAG.getNode(ISD::AND, dl, MVT::i32, 7036 DAG.getNode(ISD::XOR, dl, MVT::i32, 7037 CWD, DAG.getConstant(3, dl, MVT::i32)), 7038 DAG.getConstant(3, dl, MVT::i32)), 7039 DAG.getConstant(1, dl, MVT::i32)); 7040 7041 SDValue RetVal = 7042 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7043 7044 return DAG.getNode((VT.getSizeInBits() < 16 ? 7045 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7046 } 7047 7048 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7049 EVT VT = Op.getValueType(); 7050 unsigned BitWidth = VT.getSizeInBits(); 7051 SDLoc dl(Op); 7052 assert(Op.getNumOperands() == 3 && 7053 VT == Op.getOperand(1).getValueType() && 7054 "Unexpected SHL!"); 7055 7056 // Expand into a bunch of logical ops. Note that these ops 7057 // depend on the PPC behavior for oversized shift amounts. 7058 SDValue Lo = Op.getOperand(0); 7059 SDValue Hi = Op.getOperand(1); 7060 SDValue Amt = Op.getOperand(2); 7061 EVT AmtVT = Amt.getValueType(); 7062 7063 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7064 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7065 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7066 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7067 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7068 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7069 DAG.getConstant(-BitWidth, dl, AmtVT)); 7070 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7071 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7072 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7073 SDValue OutOps[] = { OutLo, OutHi }; 7074 return DAG.getMergeValues(OutOps, dl); 7075 } 7076 7077 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7078 EVT VT = Op.getValueType(); 7079 SDLoc dl(Op); 7080 unsigned BitWidth = VT.getSizeInBits(); 7081 assert(Op.getNumOperands() == 3 && 7082 VT == Op.getOperand(1).getValueType() && 7083 "Unexpected SRL!"); 7084 7085 // Expand into a bunch of logical ops. Note that these ops 7086 // depend on the PPC behavior for oversized shift amounts. 7087 SDValue Lo = Op.getOperand(0); 7088 SDValue Hi = Op.getOperand(1); 7089 SDValue Amt = Op.getOperand(2); 7090 EVT AmtVT = Amt.getValueType(); 7091 7092 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7093 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7094 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7095 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7096 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7097 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7098 DAG.getConstant(-BitWidth, dl, AmtVT)); 7099 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7100 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7101 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7102 SDValue OutOps[] = { OutLo, OutHi }; 7103 return DAG.getMergeValues(OutOps, dl); 7104 } 7105 7106 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7107 SDLoc dl(Op); 7108 EVT VT = Op.getValueType(); 7109 unsigned BitWidth = VT.getSizeInBits(); 7110 assert(Op.getNumOperands() == 3 && 7111 VT == Op.getOperand(1).getValueType() && 7112 "Unexpected SRA!"); 7113 7114 // Expand into a bunch of logical ops, followed by a select_cc. 7115 SDValue Lo = Op.getOperand(0); 7116 SDValue Hi = Op.getOperand(1); 7117 SDValue Amt = Op.getOperand(2); 7118 EVT AmtVT = Amt.getValueType(); 7119 7120 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7121 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7122 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7123 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7124 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7125 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7126 DAG.getConstant(-BitWidth, dl, AmtVT)); 7127 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7128 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7129 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7130 Tmp4, Tmp6, ISD::SETLE); 7131 SDValue OutOps[] = { OutLo, OutHi }; 7132 return DAG.getMergeValues(OutOps, dl); 7133 } 7134 7135 //===----------------------------------------------------------------------===// 7136 // Vector related lowering. 7137 // 7138 7139 /// BuildSplatI - Build a canonical splati of Val with an element size of 7140 /// SplatSize. Cast the result to VT. 7141 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7142 SelectionDAG &DAG, const SDLoc &dl) { 7143 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7144 7145 static const MVT VTys[] = { // canonical VT to use for each size. 7146 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7147 }; 7148 7149 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7150 7151 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7152 if (Val == -1) 7153 SplatSize = 1; 7154 7155 EVT CanonicalVT = VTys[SplatSize-1]; 7156 7157 // Build a canonical splat for this value. 7158 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7159 } 7160 7161 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7162 /// specified intrinsic ID. 7163 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7164 const SDLoc &dl, EVT DestVT = MVT::Other) { 7165 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7166 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7167 DAG.getConstant(IID, dl, MVT::i32), Op); 7168 } 7169 7170 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7171 /// specified intrinsic ID. 7172 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7173 SelectionDAG &DAG, const SDLoc &dl, 7174 EVT DestVT = MVT::Other) { 7175 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7176 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7177 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7178 } 7179 7180 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7181 /// specified intrinsic ID. 7182 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7183 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7184 EVT DestVT = MVT::Other) { 7185 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7186 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7187 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7188 } 7189 7190 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7191 /// amount. The result has the specified value type. 7192 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7193 SelectionDAG &DAG, const SDLoc &dl) { 7194 // Force LHS/RHS to be the right type. 7195 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7196 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7197 7198 int Ops[16]; 7199 for (unsigned i = 0; i != 16; ++i) 7200 Ops[i] = i + Amt; 7201 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7202 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7203 } 7204 7205 /// Do we have an efficient pattern in a .td file for this node? 7206 /// 7207 /// \param V - pointer to the BuildVectorSDNode being matched 7208 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7209 /// 7210 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7211 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7212 /// the opposite is true (expansion is beneficial) are: 7213 /// - The node builds a vector out of integers that are not 32 or 64-bits 7214 /// - The node builds a vector out of constants 7215 /// - The node is a "load-and-splat" 7216 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7217 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7218 bool HasDirectMove) { 7219 EVT VecVT = V->getValueType(0); 7220 bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 || 7221 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7222 if (!RightType) 7223 return false; 7224 7225 bool IsSplat = true; 7226 bool IsLoad = false; 7227 SDValue Op0 = V->getOperand(0); 7228 7229 // This function is called in a block that confirms the node is not a constant 7230 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7231 // different constants. 7232 if (V->isConstant()) 7233 return false; 7234 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7235 if (V->getOperand(i).isUndef()) 7236 return false; 7237 // We want to expand nodes that represent load-and-splat even if the 7238 // loaded value is a floating point truncation or conversion to int. 7239 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7240 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7241 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7242 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7243 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7244 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7245 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7246 IsLoad = true; 7247 // If the operands are different or the input is not a load and has more 7248 // uses than just this BV node, then it isn't a splat. 7249 if (V->getOperand(i) != Op0 || 7250 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7251 IsSplat = false; 7252 } 7253 return !(IsSplat && IsLoad); 7254 } 7255 7256 // If this is a case we can't handle, return null and let the default 7257 // expansion code take care of it. If we CAN select this case, and if it 7258 // selects to a single instruction, return Op. Otherwise, if we can codegen 7259 // this case more efficiently than a constant pool load, lower it to the 7260 // sequence of ops that should be used. 7261 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7262 SelectionDAG &DAG) const { 7263 SDLoc dl(Op); 7264 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7265 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7266 7267 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7268 // We first build an i32 vector, load it into a QPX register, 7269 // then convert it to a floating-point vector and compare it 7270 // to a zero vector to get the boolean result. 7271 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7272 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7273 MachinePointerInfo PtrInfo = 7274 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7275 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7276 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7277 7278 assert(BVN->getNumOperands() == 4 && 7279 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7280 7281 bool IsConst = true; 7282 for (unsigned i = 0; i < 4; ++i) { 7283 if (BVN->getOperand(i).isUndef()) continue; 7284 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7285 IsConst = false; 7286 break; 7287 } 7288 } 7289 7290 if (IsConst) { 7291 Constant *One = 7292 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7293 Constant *NegOne = 7294 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7295 7296 Constant *CV[4]; 7297 for (unsigned i = 0; i < 4; ++i) { 7298 if (BVN->getOperand(i).isUndef()) 7299 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7300 else if (isNullConstant(BVN->getOperand(i))) 7301 CV[i] = NegOne; 7302 else 7303 CV[i] = One; 7304 } 7305 7306 Constant *CP = ConstantVector::get(CV); 7307 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7308 16 /* alignment */); 7309 7310 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7311 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7312 return DAG.getMemIntrinsicNode( 7313 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7314 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7315 } 7316 7317 SmallVector<SDValue, 4> Stores; 7318 for (unsigned i = 0; i < 4; ++i) { 7319 if (BVN->getOperand(i).isUndef()) continue; 7320 7321 unsigned Offset = 4*i; 7322 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7323 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7324 7325 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7326 if (StoreSize > 4) { 7327 Stores.push_back( 7328 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7329 PtrInfo.getWithOffset(Offset), MVT::i32)); 7330 } else { 7331 SDValue StoreValue = BVN->getOperand(i); 7332 if (StoreSize < 4) 7333 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7334 7335 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7336 PtrInfo.getWithOffset(Offset))); 7337 } 7338 } 7339 7340 SDValue StoreChain; 7341 if (!Stores.empty()) 7342 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7343 else 7344 StoreChain = DAG.getEntryNode(); 7345 7346 // Now load from v4i32 into the QPX register; this will extend it to 7347 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7348 // is typed as v4f64 because the QPX register integer states are not 7349 // explicitly represented. 7350 7351 SDValue Ops[] = {StoreChain, 7352 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7353 FIdx}; 7354 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7355 7356 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7357 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7358 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7359 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7360 LoadedVect); 7361 7362 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7363 7364 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7365 } 7366 7367 // All other QPX vectors are handled by generic code. 7368 if (Subtarget.hasQPX()) 7369 return SDValue(); 7370 7371 // Check if this is a splat of a constant value. 7372 APInt APSplatBits, APSplatUndef; 7373 unsigned SplatBitSize; 7374 bool HasAnyUndefs; 7375 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7376 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7377 SplatBitSize > 32) { 7378 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7379 // lowered to VSX instructions under certain conditions. 7380 // Without VSX, there is no pattern more efficient than expanding the node. 7381 if (Subtarget.hasVSX() && 7382 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove())) 7383 return Op; 7384 return SDValue(); 7385 } 7386 7387 unsigned SplatBits = APSplatBits.getZExtValue(); 7388 unsigned SplatUndef = APSplatUndef.getZExtValue(); 7389 unsigned SplatSize = SplatBitSize / 8; 7390 7391 // First, handle single instruction cases. 7392 7393 // All zeros? 7394 if (SplatBits == 0) { 7395 // Canonicalize all zero vectors to be v4i32. 7396 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 7397 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 7398 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 7399 } 7400 return Op; 7401 } 7402 7403 // We have XXSPLTIB for constant splats one byte wide 7404 if (Subtarget.hasP9Vector() && SplatSize == 1) { 7405 // This is a splat of 1-byte elements with some elements potentially undef. 7406 // Rather than trying to match undef in the SDAG patterns, ensure that all 7407 // elements are the same constant. 7408 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 7409 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 7410 dl, MVT::i32)); 7411 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 7412 if (Op.getValueType() != MVT::v16i8) 7413 return DAG.getBitcast(Op.getValueType(), NewBV); 7414 return NewBV; 7415 } 7416 return Op; 7417 } 7418 7419 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 7420 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 7421 (32-SplatBitSize)); 7422 if (SextVal >= -16 && SextVal <= 15) 7423 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 7424 7425 // Two instruction sequences. 7426 7427 // If this value is in the range [-32,30] and is even, use: 7428 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 7429 // If this value is in the range [17,31] and is odd, use: 7430 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 7431 // If this value is in the range [-31,-17] and is odd, use: 7432 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 7433 // Note the last two are three-instruction sequences. 7434 if (SextVal >= -32 && SextVal <= 31) { 7435 // To avoid having these optimizations undone by constant folding, 7436 // we convert to a pseudo that will be expanded later into one of 7437 // the above forms. 7438 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 7439 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 7440 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 7441 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 7442 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 7443 if (VT == Op.getValueType()) 7444 return RetVal; 7445 else 7446 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 7447 } 7448 7449 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 7450 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 7451 // for fneg/fabs. 7452 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 7453 // Make -1 and vspltisw -1: 7454 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 7455 7456 // Make the VSLW intrinsic, computing 0x8000_0000. 7457 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 7458 OnesV, DAG, dl); 7459 7460 // xor by OnesV to invert it. 7461 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 7462 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7463 } 7464 7465 // Check to see if this is a wide variety of vsplti*, binop self cases. 7466 static const signed char SplatCsts[] = { 7467 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 7468 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 7469 }; 7470 7471 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 7472 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 7473 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 7474 int i = SplatCsts[idx]; 7475 7476 // Figure out what shift amount will be used by altivec if shifted by i in 7477 // this splat size. 7478 unsigned TypeShiftAmt = i & (SplatBitSize-1); 7479 7480 // vsplti + shl self. 7481 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 7482 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7483 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7484 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 7485 Intrinsic::ppc_altivec_vslw 7486 }; 7487 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7488 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7489 } 7490 7491 // vsplti + srl self. 7492 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7493 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7494 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7495 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 7496 Intrinsic::ppc_altivec_vsrw 7497 }; 7498 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7499 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7500 } 7501 7502 // vsplti + sra self. 7503 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7504 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7505 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7506 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 7507 Intrinsic::ppc_altivec_vsraw 7508 }; 7509 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7510 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7511 } 7512 7513 // vsplti + rol self. 7514 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 7515 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 7516 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7517 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7518 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 7519 Intrinsic::ppc_altivec_vrlw 7520 }; 7521 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7522 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7523 } 7524 7525 // t = vsplti c, result = vsldoi t, t, 1 7526 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 7527 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7528 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 7529 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7530 } 7531 // t = vsplti c, result = vsldoi t, t, 2 7532 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 7533 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7534 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 7535 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7536 } 7537 // t = vsplti c, result = vsldoi t, t, 3 7538 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 7539 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7540 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 7541 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7542 } 7543 } 7544 7545 return SDValue(); 7546 } 7547 7548 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7549 /// the specified operations to build the shuffle. 7550 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7551 SDValue RHS, SelectionDAG &DAG, 7552 const SDLoc &dl) { 7553 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7554 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7555 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7556 7557 enum { 7558 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7559 OP_VMRGHW, 7560 OP_VMRGLW, 7561 OP_VSPLTISW0, 7562 OP_VSPLTISW1, 7563 OP_VSPLTISW2, 7564 OP_VSPLTISW3, 7565 OP_VSLDOI4, 7566 OP_VSLDOI8, 7567 OP_VSLDOI12 7568 }; 7569 7570 if (OpNum == OP_COPY) { 7571 if (LHSID == (1*9+2)*9+3) return LHS; 7572 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7573 return RHS; 7574 } 7575 7576 SDValue OpLHS, OpRHS; 7577 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7578 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7579 7580 int ShufIdxs[16]; 7581 switch (OpNum) { 7582 default: llvm_unreachable("Unknown i32 permute!"); 7583 case OP_VMRGHW: 7584 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 7585 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 7586 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 7587 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 7588 break; 7589 case OP_VMRGLW: 7590 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 7591 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 7592 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 7593 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 7594 break; 7595 case OP_VSPLTISW0: 7596 for (unsigned i = 0; i != 16; ++i) 7597 ShufIdxs[i] = (i&3)+0; 7598 break; 7599 case OP_VSPLTISW1: 7600 for (unsigned i = 0; i != 16; ++i) 7601 ShufIdxs[i] = (i&3)+4; 7602 break; 7603 case OP_VSPLTISW2: 7604 for (unsigned i = 0; i != 16; ++i) 7605 ShufIdxs[i] = (i&3)+8; 7606 break; 7607 case OP_VSPLTISW3: 7608 for (unsigned i = 0; i != 16; ++i) 7609 ShufIdxs[i] = (i&3)+12; 7610 break; 7611 case OP_VSLDOI4: 7612 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 7613 case OP_VSLDOI8: 7614 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 7615 case OP_VSLDOI12: 7616 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 7617 } 7618 EVT VT = OpLHS.getValueType(); 7619 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 7620 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 7621 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 7622 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7623 } 7624 7625 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 7626 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 7627 /// return the code it can be lowered into. Worst case, it can always be 7628 /// lowered into a vperm. 7629 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 7630 SelectionDAG &DAG) const { 7631 SDLoc dl(Op); 7632 SDValue V1 = Op.getOperand(0); 7633 SDValue V2 = Op.getOperand(1); 7634 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 7635 EVT VT = Op.getValueType(); 7636 bool isLittleEndian = Subtarget.isLittleEndian(); 7637 7638 unsigned ShiftElts, InsertAtByte; 7639 bool Swap; 7640 if (Subtarget.hasP9Vector() && 7641 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 7642 isLittleEndian)) { 7643 if (Swap) 7644 std::swap(V1, V2); 7645 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7646 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 7647 if (ShiftElts) { 7648 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 7649 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7650 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl, 7651 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7652 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 7653 } 7654 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2, 7655 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7656 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 7657 } 7658 7659 if (Subtarget.hasVSX()) { 7660 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 7661 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 7662 7663 // If the source for the shuffle is a scalar_to_vector that came from a 7664 // 32-bit load, it will have used LXVWSX so we don't need to splat again. 7665 if (Subtarget.hasP9Vector() && 7666 ((isLittleEndian && SplatIdx == 3) || 7667 (!isLittleEndian && SplatIdx == 0))) { 7668 SDValue Src = V1.getOperand(0); 7669 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR && 7670 Src.getOperand(0).getOpcode() == ISD::LOAD && 7671 Src.getOperand(0).hasOneUse()) 7672 return V1; 7673 } 7674 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7675 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 7676 DAG.getConstant(SplatIdx, dl, MVT::i32)); 7677 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 7678 } 7679 7680 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 7681 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 7682 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 7683 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 7684 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 7685 } 7686 } 7687 7688 if (Subtarget.hasQPX()) { 7689 if (VT.getVectorNumElements() != 4) 7690 return SDValue(); 7691 7692 if (V2.isUndef()) V2 = V1; 7693 7694 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 7695 if (AlignIdx != -1) { 7696 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 7697 DAG.getConstant(AlignIdx, dl, MVT::i32)); 7698 } else if (SVOp->isSplat()) { 7699 int SplatIdx = SVOp->getSplatIndex(); 7700 if (SplatIdx >= 4) { 7701 std::swap(V1, V2); 7702 SplatIdx -= 4; 7703 } 7704 7705 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 7706 DAG.getConstant(SplatIdx, dl, MVT::i32)); 7707 } 7708 7709 // Lower this into a qvgpci/qvfperm pair. 7710 7711 // Compute the qvgpci literal 7712 unsigned idx = 0; 7713 for (unsigned i = 0; i < 4; ++i) { 7714 int m = SVOp->getMaskElt(i); 7715 unsigned mm = m >= 0 ? (unsigned) m : i; 7716 idx |= mm << (3-i)*3; 7717 } 7718 7719 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 7720 DAG.getConstant(idx, dl, MVT::i32)); 7721 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 7722 } 7723 7724 // Cases that are handled by instructions that take permute immediates 7725 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 7726 // selected by the instruction selector. 7727 if (V2.isUndef()) { 7728 if (PPC::isSplatShuffleMask(SVOp, 1) || 7729 PPC::isSplatShuffleMask(SVOp, 2) || 7730 PPC::isSplatShuffleMask(SVOp, 4) || 7731 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 7732 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 7733 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 7734 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 7735 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 7736 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 7737 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 7738 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 7739 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 7740 (Subtarget.hasP8Altivec() && ( 7741 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 7742 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 7743 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 7744 return Op; 7745 } 7746 } 7747 7748 // Altivec has a variety of "shuffle immediates" that take two vector inputs 7749 // and produce a fixed permutation. If any of these match, do not lower to 7750 // VPERM. 7751 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 7752 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 7753 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 7754 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 7755 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 7756 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 7757 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 7758 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 7759 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 7760 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 7761 (Subtarget.hasP8Altivec() && ( 7762 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 7763 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 7764 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 7765 return Op; 7766 7767 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 7768 // perfect shuffle table to emit an optimal matching sequence. 7769 ArrayRef<int> PermMask = SVOp->getMask(); 7770 7771 unsigned PFIndexes[4]; 7772 bool isFourElementShuffle = true; 7773 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 7774 unsigned EltNo = 8; // Start out undef. 7775 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 7776 if (PermMask[i*4+j] < 0) 7777 continue; // Undef, ignore it. 7778 7779 unsigned ByteSource = PermMask[i*4+j]; 7780 if ((ByteSource & 3) != j) { 7781 isFourElementShuffle = false; 7782 break; 7783 } 7784 7785 if (EltNo == 8) { 7786 EltNo = ByteSource/4; 7787 } else if (EltNo != ByteSource/4) { 7788 isFourElementShuffle = false; 7789 break; 7790 } 7791 } 7792 PFIndexes[i] = EltNo; 7793 } 7794 7795 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 7796 // perfect shuffle vector to determine if it is cost effective to do this as 7797 // discrete instructions, or whether we should use a vperm. 7798 // For now, we skip this for little endian until such time as we have a 7799 // little-endian perfect shuffle table. 7800 if (isFourElementShuffle && !isLittleEndian) { 7801 // Compute the index in the perfect shuffle table. 7802 unsigned PFTableIndex = 7803 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7804 7805 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7806 unsigned Cost = (PFEntry >> 30); 7807 7808 // Determining when to avoid vperm is tricky. Many things affect the cost 7809 // of vperm, particularly how many times the perm mask needs to be computed. 7810 // For example, if the perm mask can be hoisted out of a loop or is already 7811 // used (perhaps because there are multiple permutes with the same shuffle 7812 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 7813 // the loop requires an extra register. 7814 // 7815 // As a compromise, we only emit discrete instructions if the shuffle can be 7816 // generated in 3 or fewer operations. When we have loop information 7817 // available, if this block is within a loop, we should avoid using vperm 7818 // for 3-operation perms and use a constant pool load instead. 7819 if (Cost < 3) 7820 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7821 } 7822 7823 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 7824 // vector that will get spilled to the constant pool. 7825 if (V2.isUndef()) V2 = V1; 7826 7827 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 7828 // that it is in input element units, not in bytes. Convert now. 7829 7830 // For little endian, the order of the input vectors is reversed, and 7831 // the permutation mask is complemented with respect to 31. This is 7832 // necessary to produce proper semantics with the big-endian-biased vperm 7833 // instruction. 7834 EVT EltVT = V1.getValueType().getVectorElementType(); 7835 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 7836 7837 SmallVector<SDValue, 16> ResultMask; 7838 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 7839 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 7840 7841 for (unsigned j = 0; j != BytesPerElement; ++j) 7842 if (isLittleEndian) 7843 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 7844 dl, MVT::i32)); 7845 else 7846 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 7847 MVT::i32)); 7848 } 7849 7850 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 7851 if (isLittleEndian) 7852 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 7853 V2, V1, VPermMask); 7854 else 7855 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 7856 V1, V2, VPermMask); 7857 } 7858 7859 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 7860 /// vector comparison. If it is, return true and fill in Opc/isDot with 7861 /// information about the intrinsic. 7862 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 7863 bool &isDot, const PPCSubtarget &Subtarget) { 7864 unsigned IntrinsicID = 7865 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 7866 CompareOpc = -1; 7867 isDot = false; 7868 switch (IntrinsicID) { 7869 default: 7870 return false; 7871 // Comparison predicates. 7872 case Intrinsic::ppc_altivec_vcmpbfp_p: 7873 CompareOpc = 966; 7874 isDot = true; 7875 break; 7876 case Intrinsic::ppc_altivec_vcmpeqfp_p: 7877 CompareOpc = 198; 7878 isDot = true; 7879 break; 7880 case Intrinsic::ppc_altivec_vcmpequb_p: 7881 CompareOpc = 6; 7882 isDot = true; 7883 break; 7884 case Intrinsic::ppc_altivec_vcmpequh_p: 7885 CompareOpc = 70; 7886 isDot = true; 7887 break; 7888 case Intrinsic::ppc_altivec_vcmpequw_p: 7889 CompareOpc = 134; 7890 isDot = true; 7891 break; 7892 case Intrinsic::ppc_altivec_vcmpequd_p: 7893 if (Subtarget.hasP8Altivec()) { 7894 CompareOpc = 199; 7895 isDot = true; 7896 } else 7897 return false; 7898 break; 7899 case Intrinsic::ppc_altivec_vcmpneb_p: 7900 case Intrinsic::ppc_altivec_vcmpneh_p: 7901 case Intrinsic::ppc_altivec_vcmpnew_p: 7902 case Intrinsic::ppc_altivec_vcmpnezb_p: 7903 case Intrinsic::ppc_altivec_vcmpnezh_p: 7904 case Intrinsic::ppc_altivec_vcmpnezw_p: 7905 if (Subtarget.hasP9Altivec()) { 7906 switch (IntrinsicID) { 7907 default: 7908 llvm_unreachable("Unknown comparison intrinsic."); 7909 case Intrinsic::ppc_altivec_vcmpneb_p: 7910 CompareOpc = 7; 7911 break; 7912 case Intrinsic::ppc_altivec_vcmpneh_p: 7913 CompareOpc = 71; 7914 break; 7915 case Intrinsic::ppc_altivec_vcmpnew_p: 7916 CompareOpc = 135; 7917 break; 7918 case Intrinsic::ppc_altivec_vcmpnezb_p: 7919 CompareOpc = 263; 7920 break; 7921 case Intrinsic::ppc_altivec_vcmpnezh_p: 7922 CompareOpc = 327; 7923 break; 7924 case Intrinsic::ppc_altivec_vcmpnezw_p: 7925 CompareOpc = 391; 7926 break; 7927 } 7928 isDot = true; 7929 } else 7930 return false; 7931 break; 7932 case Intrinsic::ppc_altivec_vcmpgefp_p: 7933 CompareOpc = 454; 7934 isDot = true; 7935 break; 7936 case Intrinsic::ppc_altivec_vcmpgtfp_p: 7937 CompareOpc = 710; 7938 isDot = true; 7939 break; 7940 case Intrinsic::ppc_altivec_vcmpgtsb_p: 7941 CompareOpc = 774; 7942 isDot = true; 7943 break; 7944 case Intrinsic::ppc_altivec_vcmpgtsh_p: 7945 CompareOpc = 838; 7946 isDot = true; 7947 break; 7948 case Intrinsic::ppc_altivec_vcmpgtsw_p: 7949 CompareOpc = 902; 7950 isDot = true; 7951 break; 7952 case Intrinsic::ppc_altivec_vcmpgtsd_p: 7953 if (Subtarget.hasP8Altivec()) { 7954 CompareOpc = 967; 7955 isDot = true; 7956 } else 7957 return false; 7958 break; 7959 case Intrinsic::ppc_altivec_vcmpgtub_p: 7960 CompareOpc = 518; 7961 isDot = true; 7962 break; 7963 case Intrinsic::ppc_altivec_vcmpgtuh_p: 7964 CompareOpc = 582; 7965 isDot = true; 7966 break; 7967 case Intrinsic::ppc_altivec_vcmpgtuw_p: 7968 CompareOpc = 646; 7969 isDot = true; 7970 break; 7971 case Intrinsic::ppc_altivec_vcmpgtud_p: 7972 if (Subtarget.hasP8Altivec()) { 7973 CompareOpc = 711; 7974 isDot = true; 7975 } else 7976 return false; 7977 break; 7978 7979 // VSX predicate comparisons use the same infrastructure 7980 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 7981 case Intrinsic::ppc_vsx_xvcmpgedp_p: 7982 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 7983 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 7984 case Intrinsic::ppc_vsx_xvcmpgesp_p: 7985 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 7986 if (Subtarget.hasVSX()) { 7987 switch (IntrinsicID) { 7988 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 7989 CompareOpc = 99; 7990 break; 7991 case Intrinsic::ppc_vsx_xvcmpgedp_p: 7992 CompareOpc = 115; 7993 break; 7994 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 7995 CompareOpc = 107; 7996 break; 7997 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 7998 CompareOpc = 67; 7999 break; 8000 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8001 CompareOpc = 83; 8002 break; 8003 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8004 CompareOpc = 75; 8005 break; 8006 } 8007 isDot = true; 8008 } else 8009 return false; 8010 break; 8011 8012 // Normal Comparisons. 8013 case Intrinsic::ppc_altivec_vcmpbfp: 8014 CompareOpc = 966; 8015 break; 8016 case Intrinsic::ppc_altivec_vcmpeqfp: 8017 CompareOpc = 198; 8018 break; 8019 case Intrinsic::ppc_altivec_vcmpequb: 8020 CompareOpc = 6; 8021 break; 8022 case Intrinsic::ppc_altivec_vcmpequh: 8023 CompareOpc = 70; 8024 break; 8025 case Intrinsic::ppc_altivec_vcmpequw: 8026 CompareOpc = 134; 8027 break; 8028 case Intrinsic::ppc_altivec_vcmpequd: 8029 if (Subtarget.hasP8Altivec()) 8030 CompareOpc = 199; 8031 else 8032 return false; 8033 break; 8034 case Intrinsic::ppc_altivec_vcmpneb: 8035 case Intrinsic::ppc_altivec_vcmpneh: 8036 case Intrinsic::ppc_altivec_vcmpnew: 8037 case Intrinsic::ppc_altivec_vcmpnezb: 8038 case Intrinsic::ppc_altivec_vcmpnezh: 8039 case Intrinsic::ppc_altivec_vcmpnezw: 8040 if (Subtarget.hasP9Altivec()) 8041 switch (IntrinsicID) { 8042 default: 8043 llvm_unreachable("Unknown comparison intrinsic."); 8044 case Intrinsic::ppc_altivec_vcmpneb: 8045 CompareOpc = 7; 8046 break; 8047 case Intrinsic::ppc_altivec_vcmpneh: 8048 CompareOpc = 71; 8049 break; 8050 case Intrinsic::ppc_altivec_vcmpnew: 8051 CompareOpc = 135; 8052 break; 8053 case Intrinsic::ppc_altivec_vcmpnezb: 8054 CompareOpc = 263; 8055 break; 8056 case Intrinsic::ppc_altivec_vcmpnezh: 8057 CompareOpc = 327; 8058 break; 8059 case Intrinsic::ppc_altivec_vcmpnezw: 8060 CompareOpc = 391; 8061 break; 8062 } 8063 else 8064 return false; 8065 break; 8066 case Intrinsic::ppc_altivec_vcmpgefp: 8067 CompareOpc = 454; 8068 break; 8069 case Intrinsic::ppc_altivec_vcmpgtfp: 8070 CompareOpc = 710; 8071 break; 8072 case Intrinsic::ppc_altivec_vcmpgtsb: 8073 CompareOpc = 774; 8074 break; 8075 case Intrinsic::ppc_altivec_vcmpgtsh: 8076 CompareOpc = 838; 8077 break; 8078 case Intrinsic::ppc_altivec_vcmpgtsw: 8079 CompareOpc = 902; 8080 break; 8081 case Intrinsic::ppc_altivec_vcmpgtsd: 8082 if (Subtarget.hasP8Altivec()) 8083 CompareOpc = 967; 8084 else 8085 return false; 8086 break; 8087 case Intrinsic::ppc_altivec_vcmpgtub: 8088 CompareOpc = 518; 8089 break; 8090 case Intrinsic::ppc_altivec_vcmpgtuh: 8091 CompareOpc = 582; 8092 break; 8093 case Intrinsic::ppc_altivec_vcmpgtuw: 8094 CompareOpc = 646; 8095 break; 8096 case Intrinsic::ppc_altivec_vcmpgtud: 8097 if (Subtarget.hasP8Altivec()) 8098 CompareOpc = 711; 8099 else 8100 return false; 8101 break; 8102 } 8103 return true; 8104 } 8105 8106 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8107 /// lower, do it, otherwise return null. 8108 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8109 SelectionDAG &DAG) const { 8110 unsigned IntrinsicID = 8111 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8112 8113 if (IntrinsicID == Intrinsic::thread_pointer) { 8114 // Reads the thread pointer register, used for __builtin_thread_pointer. 8115 bool is64bit = Subtarget.isPPC64(); 8116 return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2, 8117 is64bit ? MVT::i64 : MVT::i32); 8118 } 8119 8120 // If this is a lowered altivec predicate compare, CompareOpc is set to the 8121 // opcode number of the comparison. 8122 SDLoc dl(Op); 8123 int CompareOpc; 8124 bool isDot; 8125 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 8126 return SDValue(); // Don't custom lower most intrinsics. 8127 8128 // If this is a non-dot comparison, make the VCMP node and we are done. 8129 if (!isDot) { 8130 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 8131 Op.getOperand(1), Op.getOperand(2), 8132 DAG.getConstant(CompareOpc, dl, MVT::i32)); 8133 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 8134 } 8135 8136 // Create the PPCISD altivec 'dot' comparison node. 8137 SDValue Ops[] = { 8138 Op.getOperand(2), // LHS 8139 Op.getOperand(3), // RHS 8140 DAG.getConstant(CompareOpc, dl, MVT::i32) 8141 }; 8142 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 8143 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8144 8145 // Now that we have the comparison, emit a copy from the CR to a GPR. 8146 // This is flagged to the above dot comparison. 8147 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 8148 DAG.getRegister(PPC::CR6, MVT::i32), 8149 CompNode.getValue(1)); 8150 8151 // Unpack the result based on how the target uses it. 8152 unsigned BitNo; // Bit # of CR6. 8153 bool InvertBit; // Invert result? 8154 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 8155 default: // Can't happen, don't crash on invalid number though. 8156 case 0: // Return the value of the EQ bit of CR6. 8157 BitNo = 0; InvertBit = false; 8158 break; 8159 case 1: // Return the inverted value of the EQ bit of CR6. 8160 BitNo = 0; InvertBit = true; 8161 break; 8162 case 2: // Return the value of the LT bit of CR6. 8163 BitNo = 2; InvertBit = false; 8164 break; 8165 case 3: // Return the inverted value of the LT bit of CR6. 8166 BitNo = 2; InvertBit = true; 8167 break; 8168 } 8169 8170 // Shift the bit into the low position. 8171 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 8172 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 8173 // Isolate the bit. 8174 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 8175 DAG.getConstant(1, dl, MVT::i32)); 8176 8177 // If we are supposed to, toggle the bit. 8178 if (InvertBit) 8179 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 8180 DAG.getConstant(1, dl, MVT::i32)); 8181 return Flags; 8182 } 8183 8184 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 8185 SelectionDAG &DAG) const { 8186 SDLoc dl(Op); 8187 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 8188 // instructions), but for smaller types, we need to first extend up to v2i32 8189 // before doing going farther. 8190 if (Op.getValueType() == MVT::v2i64) { 8191 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 8192 if (ExtVT != MVT::v2i32) { 8193 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 8194 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 8195 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 8196 ExtVT.getVectorElementType(), 4))); 8197 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 8198 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 8199 DAG.getValueType(MVT::v2i32)); 8200 } 8201 8202 return Op; 8203 } 8204 8205 return SDValue(); 8206 } 8207 8208 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 8209 SelectionDAG &DAG) const { 8210 SDLoc dl(Op); 8211 // Create a stack slot that is 16-byte aligned. 8212 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8213 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8214 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8215 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8216 8217 // Store the input value into Value#0 of the stack slot. 8218 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8219 MachinePointerInfo()); 8220 // Load it out. 8221 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 8222 } 8223 8224 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8225 SelectionDAG &DAG) const { 8226 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 8227 "Should only be called for ISD::INSERT_VECTOR_ELT"); 8228 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8229 // We have legal lowering for constant indices but not for variable ones. 8230 if (C) 8231 return Op; 8232 return SDValue(); 8233 } 8234 8235 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8236 SelectionDAG &DAG) const { 8237 SDLoc dl(Op); 8238 SDNode *N = Op.getNode(); 8239 8240 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 8241 "Unknown extract_vector_elt type"); 8242 8243 SDValue Value = N->getOperand(0); 8244 8245 // The first part of this is like the store lowering except that we don't 8246 // need to track the chain. 8247 8248 // The values are now known to be -1 (false) or 1 (true). To convert this 8249 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8250 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8251 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8252 8253 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8254 // understand how to form the extending load. 8255 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8256 8257 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8258 8259 // Now convert to an integer and store. 8260 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8261 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8262 Value); 8263 8264 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8265 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8266 MachinePointerInfo PtrInfo = 8267 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8268 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8269 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8270 8271 SDValue StoreChain = DAG.getEntryNode(); 8272 SDValue Ops[] = {StoreChain, 8273 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8274 Value, FIdx}; 8275 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8276 8277 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8278 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8279 8280 // Extract the value requested. 8281 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 8282 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8283 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8284 8285 SDValue IntVal = 8286 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 8287 8288 if (!Subtarget.useCRBits()) 8289 return IntVal; 8290 8291 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 8292 } 8293 8294 /// Lowering for QPX v4i1 loads 8295 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 8296 SelectionDAG &DAG) const { 8297 SDLoc dl(Op); 8298 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 8299 SDValue LoadChain = LN->getChain(); 8300 SDValue BasePtr = LN->getBasePtr(); 8301 8302 if (Op.getValueType() == MVT::v4f64 || 8303 Op.getValueType() == MVT::v4f32) { 8304 EVT MemVT = LN->getMemoryVT(); 8305 unsigned Alignment = LN->getAlignment(); 8306 8307 // If this load is properly aligned, then it is legal. 8308 if (Alignment >= MemVT.getStoreSize()) 8309 return Op; 8310 8311 EVT ScalarVT = Op.getValueType().getScalarType(), 8312 ScalarMemVT = MemVT.getScalarType(); 8313 unsigned Stride = ScalarMemVT.getStoreSize(); 8314 8315 SDValue Vals[4], LoadChains[4]; 8316 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8317 SDValue Load; 8318 if (ScalarVT != ScalarMemVT) 8319 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 8320 BasePtr, 8321 LN->getPointerInfo().getWithOffset(Idx * Stride), 8322 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8323 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8324 else 8325 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 8326 LN->getPointerInfo().getWithOffset(Idx * Stride), 8327 MinAlign(Alignment, Idx * Stride), 8328 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8329 8330 if (Idx == 0 && LN->isIndexed()) { 8331 assert(LN->getAddressingMode() == ISD::PRE_INC && 8332 "Unknown addressing mode on vector load"); 8333 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 8334 LN->getAddressingMode()); 8335 } 8336 8337 Vals[Idx] = Load; 8338 LoadChains[Idx] = Load.getValue(1); 8339 8340 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8341 DAG.getConstant(Stride, dl, 8342 BasePtr.getValueType())); 8343 } 8344 8345 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8346 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 8347 8348 if (LN->isIndexed()) { 8349 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 8350 return DAG.getMergeValues(RetOps, dl); 8351 } 8352 8353 SDValue RetOps[] = { Value, TF }; 8354 return DAG.getMergeValues(RetOps, dl); 8355 } 8356 8357 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 8358 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 8359 8360 // To lower v4i1 from a byte array, we load the byte elements of the 8361 // vector and then reuse the BUILD_VECTOR logic. 8362 8363 SDValue VectElmts[4], VectElmtChains[4]; 8364 for (unsigned i = 0; i < 4; ++i) { 8365 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 8366 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 8367 8368 VectElmts[i] = DAG.getExtLoad( 8369 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 8370 LN->getPointerInfo().getWithOffset(i), MVT::i8, 8371 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8372 VectElmtChains[i] = VectElmts[i].getValue(1); 8373 } 8374 8375 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 8376 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 8377 8378 SDValue RVals[] = { Value, LoadChain }; 8379 return DAG.getMergeValues(RVals, dl); 8380 } 8381 8382 /// Lowering for QPX v4i1 stores 8383 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 8384 SelectionDAG &DAG) const { 8385 SDLoc dl(Op); 8386 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 8387 SDValue StoreChain = SN->getChain(); 8388 SDValue BasePtr = SN->getBasePtr(); 8389 SDValue Value = SN->getValue(); 8390 8391 if (Value.getValueType() == MVT::v4f64 || 8392 Value.getValueType() == MVT::v4f32) { 8393 EVT MemVT = SN->getMemoryVT(); 8394 unsigned Alignment = SN->getAlignment(); 8395 8396 // If this store is properly aligned, then it is legal. 8397 if (Alignment >= MemVT.getStoreSize()) 8398 return Op; 8399 8400 EVT ScalarVT = Value.getValueType().getScalarType(), 8401 ScalarMemVT = MemVT.getScalarType(); 8402 unsigned Stride = ScalarMemVT.getStoreSize(); 8403 8404 SDValue Stores[4]; 8405 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8406 SDValue Ex = DAG.getNode( 8407 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 8408 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 8409 SDValue Store; 8410 if (ScalarVT != ScalarMemVT) 8411 Store = 8412 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 8413 SN->getPointerInfo().getWithOffset(Idx * Stride), 8414 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8415 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 8416 else 8417 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 8418 SN->getPointerInfo().getWithOffset(Idx * Stride), 8419 MinAlign(Alignment, Idx * Stride), 8420 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 8421 8422 if (Idx == 0 && SN->isIndexed()) { 8423 assert(SN->getAddressingMode() == ISD::PRE_INC && 8424 "Unknown addressing mode on vector store"); 8425 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 8426 SN->getAddressingMode()); 8427 } 8428 8429 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8430 DAG.getConstant(Stride, dl, 8431 BasePtr.getValueType())); 8432 Stores[Idx] = Store; 8433 } 8434 8435 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8436 8437 if (SN->isIndexed()) { 8438 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 8439 return DAG.getMergeValues(RetOps, dl); 8440 } 8441 8442 return TF; 8443 } 8444 8445 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 8446 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 8447 8448 // The values are now known to be -1 (false) or 1 (true). To convert this 8449 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8450 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8451 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8452 8453 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8454 // understand how to form the extending load. 8455 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8456 8457 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8458 8459 // Now convert to an integer and store. 8460 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8461 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8462 Value); 8463 8464 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8465 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8466 MachinePointerInfo PtrInfo = 8467 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8468 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8469 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8470 8471 SDValue Ops[] = {StoreChain, 8472 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8473 Value, FIdx}; 8474 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8475 8476 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8477 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8478 8479 // Move data into the byte array. 8480 SDValue Loads[4], LoadChains[4]; 8481 for (unsigned i = 0; i < 4; ++i) { 8482 unsigned Offset = 4*i; 8483 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8484 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8485 8486 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 8487 PtrInfo.getWithOffset(Offset)); 8488 LoadChains[i] = Loads[i].getValue(1); 8489 } 8490 8491 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8492 8493 SDValue Stores[4]; 8494 for (unsigned i = 0; i < 4; ++i) { 8495 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 8496 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 8497 8498 Stores[i] = DAG.getTruncStore( 8499 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 8500 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 8501 SN->getAAInfo()); 8502 } 8503 8504 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8505 8506 return StoreChain; 8507 } 8508 8509 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 8510 SDLoc dl(Op); 8511 if (Op.getValueType() == MVT::v4i32) { 8512 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8513 8514 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 8515 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 8516 8517 SDValue RHSSwap = // = vrlw RHS, 16 8518 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 8519 8520 // Shrinkify inputs to v8i16. 8521 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 8522 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 8523 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 8524 8525 // Low parts multiplied together, generating 32-bit results (we ignore the 8526 // top parts). 8527 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 8528 LHS, RHS, DAG, dl, MVT::v4i32); 8529 8530 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 8531 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 8532 // Shift the high parts up 16 bits. 8533 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 8534 Neg16, DAG, dl); 8535 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 8536 } else if (Op.getValueType() == MVT::v8i16) { 8537 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8538 8539 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 8540 8541 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 8542 LHS, RHS, Zero, DAG, dl); 8543 } else if (Op.getValueType() == MVT::v16i8) { 8544 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8545 bool isLittleEndian = Subtarget.isLittleEndian(); 8546 8547 // Multiply the even 8-bit parts, producing 16-bit sums. 8548 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 8549 LHS, RHS, DAG, dl, MVT::v8i16); 8550 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 8551 8552 // Multiply the odd 8-bit parts, producing 16-bit sums. 8553 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 8554 LHS, RHS, DAG, dl, MVT::v8i16); 8555 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 8556 8557 // Merge the results together. Because vmuleub and vmuloub are 8558 // instructions with a big-endian bias, we must reverse the 8559 // element numbering and reverse the meaning of "odd" and "even" 8560 // when generating little endian code. 8561 int Ops[16]; 8562 for (unsigned i = 0; i != 8; ++i) { 8563 if (isLittleEndian) { 8564 Ops[i*2 ] = 2*i; 8565 Ops[i*2+1] = 2*i+16; 8566 } else { 8567 Ops[i*2 ] = 2*i+1; 8568 Ops[i*2+1] = 2*i+1+16; 8569 } 8570 } 8571 if (isLittleEndian) 8572 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 8573 else 8574 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 8575 } else { 8576 llvm_unreachable("Unknown mul to lower!"); 8577 } 8578 } 8579 8580 /// LowerOperation - Provide custom lowering hooks for some operations. 8581 /// 8582 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8583 switch (Op.getOpcode()) { 8584 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 8585 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8586 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8587 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8588 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8589 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 8590 case ISD::SETCC: return LowerSETCC(Op, DAG); 8591 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 8592 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 8593 case ISD::VASTART: 8594 return LowerVASTART(Op, DAG); 8595 8596 case ISD::VAARG: 8597 return LowerVAARG(Op, DAG); 8598 8599 case ISD::VACOPY: 8600 return LowerVACOPY(Op, DAG); 8601 8602 case ISD::STACKRESTORE: 8603 return LowerSTACKRESTORE(Op, DAG); 8604 8605 case ISD::DYNAMIC_STACKALLOC: 8606 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8607 8608 case ISD::GET_DYNAMIC_AREA_OFFSET: 8609 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 8610 8611 case ISD::EH_DWARF_CFA: 8612 return LowerEH_DWARF_CFA(Op, DAG); 8613 8614 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 8615 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 8616 8617 case ISD::LOAD: return LowerLOAD(Op, DAG); 8618 case ISD::STORE: return LowerSTORE(Op, DAG); 8619 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 8620 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8621 case ISD::FP_TO_UINT: 8622 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 8623 SDLoc(Op)); 8624 case ISD::UINT_TO_FP: 8625 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8626 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8627 8628 // Lower 64-bit shifts. 8629 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 8630 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 8631 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 8632 8633 // Vector-related lowering. 8634 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 8635 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8636 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 8637 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 8638 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 8639 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8640 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8641 case ISD::MUL: return LowerMUL(Op, DAG); 8642 8643 // For counter-based loop handling. 8644 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 8645 8646 // Frame & Return address. 8647 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8648 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8649 } 8650 } 8651 8652 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 8653 SmallVectorImpl<SDValue>&Results, 8654 SelectionDAG &DAG) const { 8655 SDLoc dl(N); 8656 switch (N->getOpcode()) { 8657 default: 8658 llvm_unreachable("Do not know how to custom type legalize this operation!"); 8659 case ISD::READCYCLECOUNTER: { 8660 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 8661 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 8662 8663 Results.push_back(RTB); 8664 Results.push_back(RTB.getValue(1)); 8665 Results.push_back(RTB.getValue(2)); 8666 break; 8667 } 8668 case ISD::INTRINSIC_W_CHAIN: { 8669 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 8670 Intrinsic::ppc_is_decremented_ctr_nonzero) 8671 break; 8672 8673 assert(N->getValueType(0) == MVT::i1 && 8674 "Unexpected result type for CTR decrement intrinsic"); 8675 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 8676 N->getValueType(0)); 8677 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 8678 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 8679 N->getOperand(1)); 8680 8681 Results.push_back(NewInt); 8682 Results.push_back(NewInt.getValue(1)); 8683 break; 8684 } 8685 case ISD::VAARG: { 8686 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 8687 return; 8688 8689 EVT VT = N->getValueType(0); 8690 8691 if (VT == MVT::i64) { 8692 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 8693 8694 Results.push_back(NewNode); 8695 Results.push_back(NewNode.getValue(1)); 8696 } 8697 return; 8698 } 8699 case ISD::FP_ROUND_INREG: { 8700 assert(N->getValueType(0) == MVT::ppcf128); 8701 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 8702 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8703 MVT::f64, N->getOperand(0), 8704 DAG.getIntPtrConstant(0, dl)); 8705 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8706 MVT::f64, N->getOperand(0), 8707 DAG.getIntPtrConstant(1, dl)); 8708 8709 // Add the two halves of the long double in round-to-zero mode. 8710 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8711 8712 // We know the low half is about to be thrown away, so just use something 8713 // convenient. 8714 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 8715 FPreg, FPreg)); 8716 return; 8717 } 8718 case ISD::FP_TO_SINT: 8719 case ISD::FP_TO_UINT: 8720 // LowerFP_TO_INT() can only handle f32 and f64. 8721 if (N->getOperand(0).getValueType() == MVT::ppcf128) 8722 return; 8723 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 8724 return; 8725 } 8726 } 8727 8728 //===----------------------------------------------------------------------===// 8729 // Other Lowering Code 8730 //===----------------------------------------------------------------------===// 8731 8732 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 8733 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 8734 Function *Func = Intrinsic::getDeclaration(M, Id); 8735 return Builder.CreateCall(Func, {}); 8736 } 8737 8738 // The mappings for emitLeading/TrailingFence is taken from 8739 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 8740 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 8741 Instruction *Inst, 8742 AtomicOrdering Ord) const { 8743 if (Ord == AtomicOrdering::SequentiallyConsistent) 8744 return callIntrinsic(Builder, Intrinsic::ppc_sync); 8745 if (isReleaseOrStronger(Ord)) 8746 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 8747 return nullptr; 8748 } 8749 8750 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 8751 Instruction *Inst, 8752 AtomicOrdering Ord) const { 8753 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) 8754 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 8755 // FIXME: this is too conservative, a dependent branch + isync is enough. 8756 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 8757 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 8758 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 8759 return nullptr; 8760 } 8761 8762 MachineBasicBlock * 8763 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 8764 unsigned AtomicSize, 8765 unsigned BinOpcode, 8766 unsigned CmpOpcode, 8767 unsigned CmpPred) const { 8768 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 8769 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 8770 8771 auto LoadMnemonic = PPC::LDARX; 8772 auto StoreMnemonic = PPC::STDCX; 8773 switch (AtomicSize) { 8774 default: 8775 llvm_unreachable("Unexpected size of atomic entity"); 8776 case 1: 8777 LoadMnemonic = PPC::LBARX; 8778 StoreMnemonic = PPC::STBCX; 8779 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 8780 break; 8781 case 2: 8782 LoadMnemonic = PPC::LHARX; 8783 StoreMnemonic = PPC::STHCX; 8784 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 8785 break; 8786 case 4: 8787 LoadMnemonic = PPC::LWARX; 8788 StoreMnemonic = PPC::STWCX; 8789 break; 8790 case 8: 8791 LoadMnemonic = PPC::LDARX; 8792 StoreMnemonic = PPC::STDCX; 8793 break; 8794 } 8795 8796 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8797 MachineFunction *F = BB->getParent(); 8798 MachineFunction::iterator It = ++BB->getIterator(); 8799 8800 unsigned dest = MI.getOperand(0).getReg(); 8801 unsigned ptrA = MI.getOperand(1).getReg(); 8802 unsigned ptrB = MI.getOperand(2).getReg(); 8803 unsigned incr = MI.getOperand(3).getReg(); 8804 DebugLoc dl = MI.getDebugLoc(); 8805 8806 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 8807 MachineBasicBlock *loop2MBB = 8808 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 8809 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 8810 F->insert(It, loopMBB); 8811 if (CmpOpcode) 8812 F->insert(It, loop2MBB); 8813 F->insert(It, exitMBB); 8814 exitMBB->splice(exitMBB->begin(), BB, 8815 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8816 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8817 8818 MachineRegisterInfo &RegInfo = F->getRegInfo(); 8819 unsigned TmpReg = (!BinOpcode) ? incr : 8820 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 8821 : &PPC::GPRCRegClass); 8822 8823 // thisMBB: 8824 // ... 8825 // fallthrough --> loopMBB 8826 BB->addSuccessor(loopMBB); 8827 8828 // loopMBB: 8829 // l[wd]arx dest, ptr 8830 // add r0, dest, incr 8831 // st[wd]cx. r0, ptr 8832 // bne- loopMBB 8833 // fallthrough --> exitMBB 8834 8835 // For max/min... 8836 // loopMBB: 8837 // l[wd]arx dest, ptr 8838 // cmpl?[wd] incr, dest 8839 // bgt exitMBB 8840 // loop2MBB: 8841 // st[wd]cx. dest, ptr 8842 // bne- loopMBB 8843 // fallthrough --> exitMBB 8844 8845 BB = loopMBB; 8846 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 8847 .addReg(ptrA).addReg(ptrB); 8848 if (BinOpcode) 8849 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 8850 if (CmpOpcode) { 8851 // Signed comparisons of byte or halfword values must be sign-extended. 8852 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 8853 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 8854 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 8855 ExtReg).addReg(dest); 8856 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 8857 .addReg(incr).addReg(ExtReg); 8858 } else 8859 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 8860 .addReg(incr).addReg(dest); 8861 8862 BuildMI(BB, dl, TII->get(PPC::BCC)) 8863 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 8864 BB->addSuccessor(loop2MBB); 8865 BB->addSuccessor(exitMBB); 8866 BB = loop2MBB; 8867 } 8868 BuildMI(BB, dl, TII->get(StoreMnemonic)) 8869 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 8870 BuildMI(BB, dl, TII->get(PPC::BCC)) 8871 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 8872 BB->addSuccessor(loopMBB); 8873 BB->addSuccessor(exitMBB); 8874 8875 // exitMBB: 8876 // ... 8877 BB = exitMBB; 8878 return BB; 8879 } 8880 8881 MachineBasicBlock * 8882 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 8883 MachineBasicBlock *BB, 8884 bool is8bit, // operation 8885 unsigned BinOpcode, 8886 unsigned CmpOpcode, 8887 unsigned CmpPred) const { 8888 // If we support part-word atomic mnemonics, just use them 8889 if (Subtarget.hasPartwordAtomics()) 8890 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 8891 CmpOpcode, CmpPred); 8892 8893 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 8894 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 8895 // In 64 bit mode we have to use 64 bits for addresses, even though the 8896 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 8897 // registers without caring whether they're 32 or 64, but here we're 8898 // doing actual arithmetic on the addresses. 8899 bool is64bit = Subtarget.isPPC64(); 8900 bool isLittleEndian = Subtarget.isLittleEndian(); 8901 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 8902 8903 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8904 MachineFunction *F = BB->getParent(); 8905 MachineFunction::iterator It = ++BB->getIterator(); 8906 8907 unsigned dest = MI.getOperand(0).getReg(); 8908 unsigned ptrA = MI.getOperand(1).getReg(); 8909 unsigned ptrB = MI.getOperand(2).getReg(); 8910 unsigned incr = MI.getOperand(3).getReg(); 8911 DebugLoc dl = MI.getDebugLoc(); 8912 8913 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 8914 MachineBasicBlock *loop2MBB = 8915 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 8916 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 8917 F->insert(It, loopMBB); 8918 if (CmpOpcode) 8919 F->insert(It, loop2MBB); 8920 F->insert(It, exitMBB); 8921 exitMBB->splice(exitMBB->begin(), BB, 8922 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8923 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8924 8925 MachineRegisterInfo &RegInfo = F->getRegInfo(); 8926 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 8927 : &PPC::GPRCRegClass; 8928 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 8929 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 8930 unsigned ShiftReg = 8931 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 8932 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 8933 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 8934 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 8935 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 8936 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 8937 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 8938 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 8939 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 8940 unsigned Ptr1Reg; 8941 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 8942 8943 // thisMBB: 8944 // ... 8945 // fallthrough --> loopMBB 8946 BB->addSuccessor(loopMBB); 8947 8948 // The 4-byte load must be aligned, while a char or short may be 8949 // anywhere in the word. Hence all this nasty bookkeeping code. 8950 // add ptr1, ptrA, ptrB [copy if ptrA==0] 8951 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 8952 // xori shift, shift1, 24 [16] 8953 // rlwinm ptr, ptr1, 0, 0, 29 8954 // slw incr2, incr, shift 8955 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 8956 // slw mask, mask2, shift 8957 // loopMBB: 8958 // lwarx tmpDest, ptr 8959 // add tmp, tmpDest, incr2 8960 // andc tmp2, tmpDest, mask 8961 // and tmp3, tmp, mask 8962 // or tmp4, tmp3, tmp2 8963 // stwcx. tmp4, ptr 8964 // bne- loopMBB 8965 // fallthrough --> exitMBB 8966 // srw dest, tmpDest, shift 8967 if (ptrA != ZeroReg) { 8968 Ptr1Reg = RegInfo.createVirtualRegister(RC); 8969 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 8970 .addReg(ptrA).addReg(ptrB); 8971 } else { 8972 Ptr1Reg = ptrB; 8973 } 8974 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 8975 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 8976 if (!isLittleEndian) 8977 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 8978 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 8979 if (is64bit) 8980 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 8981 .addReg(Ptr1Reg).addImm(0).addImm(61); 8982 else 8983 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 8984 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 8985 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 8986 .addReg(incr).addReg(ShiftReg); 8987 if (is8bit) 8988 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 8989 else { 8990 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 8991 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 8992 } 8993 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 8994 .addReg(Mask2Reg).addReg(ShiftReg); 8995 8996 BB = loopMBB; 8997 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 8998 .addReg(ZeroReg).addReg(PtrReg); 8999 if (BinOpcode) 9000 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9001 .addReg(Incr2Reg).addReg(TmpDestReg); 9002 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9003 .addReg(TmpDestReg).addReg(MaskReg); 9004 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9005 .addReg(TmpReg).addReg(MaskReg); 9006 if (CmpOpcode) { 9007 // For unsigned comparisons, we can directly compare the shifted values. 9008 // For signed comparisons we shift and sign extend. 9009 unsigned SReg = RegInfo.createVirtualRegister(RC); 9010 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 9011 .addReg(TmpDestReg).addReg(MaskReg); 9012 unsigned ValueReg = SReg; 9013 unsigned CmpReg = Incr2Reg; 9014 if (CmpOpcode == PPC::CMPW) { 9015 ValueReg = RegInfo.createVirtualRegister(RC); 9016 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 9017 .addReg(SReg).addReg(ShiftReg); 9018 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 9019 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 9020 .addReg(ValueReg); 9021 ValueReg = ValueSReg; 9022 CmpReg = incr; 9023 } 9024 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9025 .addReg(CmpReg).addReg(ValueReg); 9026 BuildMI(BB, dl, TII->get(PPC::BCC)) 9027 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9028 BB->addSuccessor(loop2MBB); 9029 BB->addSuccessor(exitMBB); 9030 BB = loop2MBB; 9031 } 9032 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 9033 .addReg(Tmp3Reg).addReg(Tmp2Reg); 9034 BuildMI(BB, dl, TII->get(PPC::STWCX)) 9035 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 9036 BuildMI(BB, dl, TII->get(PPC::BCC)) 9037 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9038 BB->addSuccessor(loopMBB); 9039 BB->addSuccessor(exitMBB); 9040 9041 // exitMBB: 9042 // ... 9043 BB = exitMBB; 9044 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 9045 .addReg(ShiftReg); 9046 return BB; 9047 } 9048 9049 llvm::MachineBasicBlock * 9050 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 9051 MachineBasicBlock *MBB) const { 9052 DebugLoc DL = MI.getDebugLoc(); 9053 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9054 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9055 9056 MachineFunction *MF = MBB->getParent(); 9057 MachineRegisterInfo &MRI = MF->getRegInfo(); 9058 9059 const BasicBlock *BB = MBB->getBasicBlock(); 9060 MachineFunction::iterator I = ++MBB->getIterator(); 9061 9062 // Memory Reference 9063 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9064 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9065 9066 unsigned DstReg = MI.getOperand(0).getReg(); 9067 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 9068 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 9069 unsigned mainDstReg = MRI.createVirtualRegister(RC); 9070 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 9071 9072 MVT PVT = getPointerTy(MF->getDataLayout()); 9073 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9074 "Invalid Pointer Size!"); 9075 // For v = setjmp(buf), we generate 9076 // 9077 // thisMBB: 9078 // SjLjSetup mainMBB 9079 // bl mainMBB 9080 // v_restore = 1 9081 // b sinkMBB 9082 // 9083 // mainMBB: 9084 // buf[LabelOffset] = LR 9085 // v_main = 0 9086 // 9087 // sinkMBB: 9088 // v = phi(main, restore) 9089 // 9090 9091 MachineBasicBlock *thisMBB = MBB; 9092 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 9093 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 9094 MF->insert(I, mainMBB); 9095 MF->insert(I, sinkMBB); 9096 9097 MachineInstrBuilder MIB; 9098 9099 // Transfer the remainder of BB and its successor edges to sinkMBB. 9100 sinkMBB->splice(sinkMBB->begin(), MBB, 9101 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9102 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 9103 9104 // Note that the structure of the jmp_buf used here is not compatible 9105 // with that used by libc, and is not designed to be. Specifically, it 9106 // stores only those 'reserved' registers that LLVM does not otherwise 9107 // understand how to spill. Also, by convention, by the time this 9108 // intrinsic is called, Clang has already stored the frame address in the 9109 // first slot of the buffer and stack address in the third. Following the 9110 // X86 target code, we'll store the jump address in the second slot. We also 9111 // need to save the TOC pointer (R2) to handle jumps between shared 9112 // libraries, and that will be stored in the fourth slot. The thread 9113 // identifier (R13) is not affected. 9114 9115 // thisMBB: 9116 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9117 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9118 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9119 9120 // Prepare IP either in reg. 9121 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 9122 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 9123 unsigned BufReg = MI.getOperand(1).getReg(); 9124 9125 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 9126 setUsesTOCBasePtr(*MBB->getParent()); 9127 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 9128 .addReg(PPC::X2) 9129 .addImm(TOCOffset) 9130 .addReg(BufReg); 9131 MIB.setMemRefs(MMOBegin, MMOEnd); 9132 } 9133 9134 // Naked functions never have a base pointer, and so we use r1. For all 9135 // other functions, this decision must be delayed until during PEI. 9136 unsigned BaseReg; 9137 if (MF->getFunction()->hasFnAttribute(Attribute::Naked)) 9138 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 9139 else 9140 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 9141 9142 MIB = BuildMI(*thisMBB, MI, DL, 9143 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 9144 .addReg(BaseReg) 9145 .addImm(BPOffset) 9146 .addReg(BufReg); 9147 MIB.setMemRefs(MMOBegin, MMOEnd); 9148 9149 // Setup 9150 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 9151 MIB.addRegMask(TRI->getNoPreservedMask()); 9152 9153 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 9154 9155 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 9156 .addMBB(mainMBB); 9157 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 9158 9159 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 9160 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 9161 9162 // mainMBB: 9163 // mainDstReg = 0 9164 MIB = 9165 BuildMI(mainMBB, DL, 9166 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 9167 9168 // Store IP 9169 if (Subtarget.isPPC64()) { 9170 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 9171 .addReg(LabelReg) 9172 .addImm(LabelOffset) 9173 .addReg(BufReg); 9174 } else { 9175 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 9176 .addReg(LabelReg) 9177 .addImm(LabelOffset) 9178 .addReg(BufReg); 9179 } 9180 9181 MIB.setMemRefs(MMOBegin, MMOEnd); 9182 9183 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 9184 mainMBB->addSuccessor(sinkMBB); 9185 9186 // sinkMBB: 9187 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 9188 TII->get(PPC::PHI), DstReg) 9189 .addReg(mainDstReg).addMBB(mainMBB) 9190 .addReg(restoreDstReg).addMBB(thisMBB); 9191 9192 MI.eraseFromParent(); 9193 return sinkMBB; 9194 } 9195 9196 MachineBasicBlock * 9197 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 9198 MachineBasicBlock *MBB) const { 9199 DebugLoc DL = MI.getDebugLoc(); 9200 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9201 9202 MachineFunction *MF = MBB->getParent(); 9203 MachineRegisterInfo &MRI = MF->getRegInfo(); 9204 9205 // Memory Reference 9206 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9207 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9208 9209 MVT PVT = getPointerTy(MF->getDataLayout()); 9210 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9211 "Invalid Pointer Size!"); 9212 9213 const TargetRegisterClass *RC = 9214 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9215 unsigned Tmp = MRI.createVirtualRegister(RC); 9216 // Since FP is only updated here but NOT referenced, it's treated as GPR. 9217 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 9218 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 9219 unsigned BP = 9220 (PVT == MVT::i64) 9221 ? PPC::X30 9222 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 9223 : PPC::R30); 9224 9225 MachineInstrBuilder MIB; 9226 9227 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9228 const int64_t SPOffset = 2 * PVT.getStoreSize(); 9229 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9230 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9231 9232 unsigned BufReg = MI.getOperand(0).getReg(); 9233 9234 // Reload FP (the jumped-to function may not have had a 9235 // frame pointer, and if so, then its r31 will be restored 9236 // as necessary). 9237 if (PVT == MVT::i64) { 9238 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 9239 .addImm(0) 9240 .addReg(BufReg); 9241 } else { 9242 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 9243 .addImm(0) 9244 .addReg(BufReg); 9245 } 9246 MIB.setMemRefs(MMOBegin, MMOEnd); 9247 9248 // Reload IP 9249 if (PVT == MVT::i64) { 9250 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 9251 .addImm(LabelOffset) 9252 .addReg(BufReg); 9253 } else { 9254 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 9255 .addImm(LabelOffset) 9256 .addReg(BufReg); 9257 } 9258 MIB.setMemRefs(MMOBegin, MMOEnd); 9259 9260 // Reload SP 9261 if (PVT == MVT::i64) { 9262 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 9263 .addImm(SPOffset) 9264 .addReg(BufReg); 9265 } else { 9266 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 9267 .addImm(SPOffset) 9268 .addReg(BufReg); 9269 } 9270 MIB.setMemRefs(MMOBegin, MMOEnd); 9271 9272 // Reload BP 9273 if (PVT == MVT::i64) { 9274 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 9275 .addImm(BPOffset) 9276 .addReg(BufReg); 9277 } else { 9278 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 9279 .addImm(BPOffset) 9280 .addReg(BufReg); 9281 } 9282 MIB.setMemRefs(MMOBegin, MMOEnd); 9283 9284 // Reload TOC 9285 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 9286 setUsesTOCBasePtr(*MBB->getParent()); 9287 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 9288 .addImm(TOCOffset) 9289 .addReg(BufReg); 9290 9291 MIB.setMemRefs(MMOBegin, MMOEnd); 9292 } 9293 9294 // Jump 9295 BuildMI(*MBB, MI, DL, 9296 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 9297 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 9298 9299 MI.eraseFromParent(); 9300 return MBB; 9301 } 9302 9303 MachineBasicBlock * 9304 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9305 MachineBasicBlock *BB) const { 9306 if (MI.getOpcode() == TargetOpcode::STACKMAP || 9307 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9308 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 9309 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9310 // Call lowering should have added an r2 operand to indicate a dependence 9311 // on the TOC base pointer value. It can't however, because there is no 9312 // way to mark the dependence as implicit there, and so the stackmap code 9313 // will confuse it with a regular operand. Instead, add the dependence 9314 // here. 9315 setUsesTOCBasePtr(*BB->getParent()); 9316 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 9317 } 9318 9319 return emitPatchPoint(MI, BB); 9320 } 9321 9322 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 9323 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 9324 return emitEHSjLjSetJmp(MI, BB); 9325 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 9326 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 9327 return emitEHSjLjLongJmp(MI, BB); 9328 } 9329 9330 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9331 9332 // To "insert" these instructions we actually have to insert their 9333 // control-flow patterns. 9334 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9335 MachineFunction::iterator It = ++BB->getIterator(); 9336 9337 MachineFunction *F = BB->getParent(); 9338 9339 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9340 MI.getOpcode() == PPC::SELECT_CC_I8 || 9341 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 9342 SmallVector<MachineOperand, 2> Cond; 9343 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9344 MI.getOpcode() == PPC::SELECT_CC_I8) 9345 Cond.push_back(MI.getOperand(4)); 9346 else 9347 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 9348 Cond.push_back(MI.getOperand(1)); 9349 9350 DebugLoc dl = MI.getDebugLoc(); 9351 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 9352 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 9353 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9354 MI.getOpcode() == PPC::SELECT_CC_I8 || 9355 MI.getOpcode() == PPC::SELECT_CC_F4 || 9356 MI.getOpcode() == PPC::SELECT_CC_F8 || 9357 MI.getOpcode() == PPC::SELECT_CC_QFRC || 9358 MI.getOpcode() == PPC::SELECT_CC_QSRC || 9359 MI.getOpcode() == PPC::SELECT_CC_QBRC || 9360 MI.getOpcode() == PPC::SELECT_CC_VRRC || 9361 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 9362 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 9363 MI.getOpcode() == PPC::SELECT_CC_VSRC || 9364 MI.getOpcode() == PPC::SELECT_I4 || 9365 MI.getOpcode() == PPC::SELECT_I8 || 9366 MI.getOpcode() == PPC::SELECT_F4 || 9367 MI.getOpcode() == PPC::SELECT_F8 || 9368 MI.getOpcode() == PPC::SELECT_QFRC || 9369 MI.getOpcode() == PPC::SELECT_QSRC || 9370 MI.getOpcode() == PPC::SELECT_QBRC || 9371 MI.getOpcode() == PPC::SELECT_VRRC || 9372 MI.getOpcode() == PPC::SELECT_VSFRC || 9373 MI.getOpcode() == PPC::SELECT_VSSRC || 9374 MI.getOpcode() == PPC::SELECT_VSRC) { 9375 // The incoming instruction knows the destination vreg to set, the 9376 // condition code register to branch on, the true/false values to 9377 // select between, and a branch opcode to use. 9378 9379 // thisMBB: 9380 // ... 9381 // TrueVal = ... 9382 // cmpTY ccX, r1, r2 9383 // bCC copy1MBB 9384 // fallthrough --> copy0MBB 9385 MachineBasicBlock *thisMBB = BB; 9386 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9387 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9388 DebugLoc dl = MI.getDebugLoc(); 9389 F->insert(It, copy0MBB); 9390 F->insert(It, sinkMBB); 9391 9392 // Transfer the remainder of BB and its successor edges to sinkMBB. 9393 sinkMBB->splice(sinkMBB->begin(), BB, 9394 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9395 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9396 9397 // Next, add the true and fallthrough blocks as its successors. 9398 BB->addSuccessor(copy0MBB); 9399 BB->addSuccessor(sinkMBB); 9400 9401 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 9402 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 9403 MI.getOpcode() == PPC::SELECT_QFRC || 9404 MI.getOpcode() == PPC::SELECT_QSRC || 9405 MI.getOpcode() == PPC::SELECT_QBRC || 9406 MI.getOpcode() == PPC::SELECT_VRRC || 9407 MI.getOpcode() == PPC::SELECT_VSFRC || 9408 MI.getOpcode() == PPC::SELECT_VSSRC || 9409 MI.getOpcode() == PPC::SELECT_VSRC) { 9410 BuildMI(BB, dl, TII->get(PPC::BC)) 9411 .addReg(MI.getOperand(1).getReg()) 9412 .addMBB(sinkMBB); 9413 } else { 9414 unsigned SelectPred = MI.getOperand(4).getImm(); 9415 BuildMI(BB, dl, TII->get(PPC::BCC)) 9416 .addImm(SelectPred) 9417 .addReg(MI.getOperand(1).getReg()) 9418 .addMBB(sinkMBB); 9419 } 9420 9421 // copy0MBB: 9422 // %FalseValue = ... 9423 // # fallthrough to sinkMBB 9424 BB = copy0MBB; 9425 9426 // Update machine-CFG edges 9427 BB->addSuccessor(sinkMBB); 9428 9429 // sinkMBB: 9430 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9431 // ... 9432 BB = sinkMBB; 9433 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 9434 .addReg(MI.getOperand(3).getReg()) 9435 .addMBB(copy0MBB) 9436 .addReg(MI.getOperand(2).getReg()) 9437 .addMBB(thisMBB); 9438 } else if (MI.getOpcode() == PPC::ReadTB) { 9439 // To read the 64-bit time-base register on a 32-bit target, we read the 9440 // two halves. Should the counter have wrapped while it was being read, we 9441 // need to try again. 9442 // ... 9443 // readLoop: 9444 // mfspr Rx,TBU # load from TBU 9445 // mfspr Ry,TB # load from TB 9446 // mfspr Rz,TBU # load from TBU 9447 // cmpw crX,Rx,Rz # check if 'old'='new' 9448 // bne readLoop # branch if they're not equal 9449 // ... 9450 9451 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 9452 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9453 DebugLoc dl = MI.getDebugLoc(); 9454 F->insert(It, readMBB); 9455 F->insert(It, sinkMBB); 9456 9457 // Transfer the remainder of BB and its successor edges to sinkMBB. 9458 sinkMBB->splice(sinkMBB->begin(), BB, 9459 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9460 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9461 9462 BB->addSuccessor(readMBB); 9463 BB = readMBB; 9464 9465 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9466 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9467 unsigned LoReg = MI.getOperand(0).getReg(); 9468 unsigned HiReg = MI.getOperand(1).getReg(); 9469 9470 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 9471 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 9472 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 9473 9474 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 9475 9476 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 9477 .addReg(HiReg).addReg(ReadAgainReg); 9478 BuildMI(BB, dl, TII->get(PPC::BCC)) 9479 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 9480 9481 BB->addSuccessor(readMBB); 9482 BB->addSuccessor(sinkMBB); 9483 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 9484 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 9485 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 9486 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 9487 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 9488 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 9489 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 9490 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 9491 9492 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 9493 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 9494 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 9495 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 9496 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 9497 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 9498 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 9499 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 9500 9501 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 9502 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 9503 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 9504 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 9505 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 9506 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 9507 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 9508 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 9509 9510 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 9511 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 9512 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 9513 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 9514 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 9515 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 9516 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 9517 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 9518 9519 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 9520 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 9521 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 9522 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 9523 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 9524 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 9525 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 9526 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 9527 9528 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 9529 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 9530 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 9531 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 9532 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 9533 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 9534 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 9535 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 9536 9537 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 9538 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 9539 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 9540 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 9541 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 9542 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 9543 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 9544 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 9545 9546 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 9547 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 9548 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 9549 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 9550 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 9551 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 9552 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 9553 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 9554 9555 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 9556 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 9557 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 9558 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 9559 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 9560 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 9561 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 9562 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 9563 9564 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 9565 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 9566 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 9567 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 9568 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 9569 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 9570 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 9571 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 9572 9573 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 9574 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 9575 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 9576 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 9577 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 9578 BB = EmitAtomicBinary(MI, BB, 4, 0); 9579 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 9580 BB = EmitAtomicBinary(MI, BB, 8, 0); 9581 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 9582 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 9583 (Subtarget.hasPartwordAtomics() && 9584 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 9585 (Subtarget.hasPartwordAtomics() && 9586 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 9587 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 9588 9589 auto LoadMnemonic = PPC::LDARX; 9590 auto StoreMnemonic = PPC::STDCX; 9591 switch (MI.getOpcode()) { 9592 default: 9593 llvm_unreachable("Compare and swap of unknown size"); 9594 case PPC::ATOMIC_CMP_SWAP_I8: 9595 LoadMnemonic = PPC::LBARX; 9596 StoreMnemonic = PPC::STBCX; 9597 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 9598 break; 9599 case PPC::ATOMIC_CMP_SWAP_I16: 9600 LoadMnemonic = PPC::LHARX; 9601 StoreMnemonic = PPC::STHCX; 9602 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 9603 break; 9604 case PPC::ATOMIC_CMP_SWAP_I32: 9605 LoadMnemonic = PPC::LWARX; 9606 StoreMnemonic = PPC::STWCX; 9607 break; 9608 case PPC::ATOMIC_CMP_SWAP_I64: 9609 LoadMnemonic = PPC::LDARX; 9610 StoreMnemonic = PPC::STDCX; 9611 break; 9612 } 9613 unsigned dest = MI.getOperand(0).getReg(); 9614 unsigned ptrA = MI.getOperand(1).getReg(); 9615 unsigned ptrB = MI.getOperand(2).getReg(); 9616 unsigned oldval = MI.getOperand(3).getReg(); 9617 unsigned newval = MI.getOperand(4).getReg(); 9618 DebugLoc dl = MI.getDebugLoc(); 9619 9620 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 9621 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 9622 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 9623 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9624 F->insert(It, loop1MBB); 9625 F->insert(It, loop2MBB); 9626 F->insert(It, midMBB); 9627 F->insert(It, exitMBB); 9628 exitMBB->splice(exitMBB->begin(), BB, 9629 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9630 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9631 9632 // thisMBB: 9633 // ... 9634 // fallthrough --> loopMBB 9635 BB->addSuccessor(loop1MBB); 9636 9637 // loop1MBB: 9638 // l[bhwd]arx dest, ptr 9639 // cmp[wd] dest, oldval 9640 // bne- midMBB 9641 // loop2MBB: 9642 // st[bhwd]cx. newval, ptr 9643 // bne- loopMBB 9644 // b exitBB 9645 // midMBB: 9646 // st[bhwd]cx. dest, ptr 9647 // exitBB: 9648 BB = loop1MBB; 9649 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9650 .addReg(ptrA).addReg(ptrB); 9651 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 9652 .addReg(oldval).addReg(dest); 9653 BuildMI(BB, dl, TII->get(PPC::BCC)) 9654 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 9655 BB->addSuccessor(loop2MBB); 9656 BB->addSuccessor(midMBB); 9657 9658 BB = loop2MBB; 9659 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9660 .addReg(newval).addReg(ptrA).addReg(ptrB); 9661 BuildMI(BB, dl, TII->get(PPC::BCC)) 9662 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 9663 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 9664 BB->addSuccessor(loop1MBB); 9665 BB->addSuccessor(exitMBB); 9666 9667 BB = midMBB; 9668 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9669 .addReg(dest).addReg(ptrA).addReg(ptrB); 9670 BB->addSuccessor(exitMBB); 9671 9672 // exitMBB: 9673 // ... 9674 BB = exitMBB; 9675 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 9676 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 9677 // We must use 64-bit registers for addresses when targeting 64-bit, 9678 // since we're actually doing arithmetic on them. Other registers 9679 // can be 32-bit. 9680 bool is64bit = Subtarget.isPPC64(); 9681 bool isLittleEndian = Subtarget.isLittleEndian(); 9682 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 9683 9684 unsigned dest = MI.getOperand(0).getReg(); 9685 unsigned ptrA = MI.getOperand(1).getReg(); 9686 unsigned ptrB = MI.getOperand(2).getReg(); 9687 unsigned oldval = MI.getOperand(3).getReg(); 9688 unsigned newval = MI.getOperand(4).getReg(); 9689 DebugLoc dl = MI.getDebugLoc(); 9690 9691 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 9692 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 9693 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 9694 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9695 F->insert(It, loop1MBB); 9696 F->insert(It, loop2MBB); 9697 F->insert(It, midMBB); 9698 F->insert(It, exitMBB); 9699 exitMBB->splice(exitMBB->begin(), BB, 9700 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9701 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9702 9703 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9704 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9705 : &PPC::GPRCRegClass; 9706 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9707 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9708 unsigned ShiftReg = 9709 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9710 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 9711 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 9712 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 9713 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 9714 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9715 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9716 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9717 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9718 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9719 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9720 unsigned Ptr1Reg; 9721 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 9722 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9723 // thisMBB: 9724 // ... 9725 // fallthrough --> loopMBB 9726 BB->addSuccessor(loop1MBB); 9727 9728 // The 4-byte load must be aligned, while a char or short may be 9729 // anywhere in the word. Hence all this nasty bookkeeping code. 9730 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9731 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9732 // xori shift, shift1, 24 [16] 9733 // rlwinm ptr, ptr1, 0, 0, 29 9734 // slw newval2, newval, shift 9735 // slw oldval2, oldval,shift 9736 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9737 // slw mask, mask2, shift 9738 // and newval3, newval2, mask 9739 // and oldval3, oldval2, mask 9740 // loop1MBB: 9741 // lwarx tmpDest, ptr 9742 // and tmp, tmpDest, mask 9743 // cmpw tmp, oldval3 9744 // bne- midMBB 9745 // loop2MBB: 9746 // andc tmp2, tmpDest, mask 9747 // or tmp4, tmp2, newval3 9748 // stwcx. tmp4, ptr 9749 // bne- loop1MBB 9750 // b exitBB 9751 // midMBB: 9752 // stwcx. tmpDest, ptr 9753 // exitBB: 9754 // srw dest, tmpDest, shift 9755 if (ptrA != ZeroReg) { 9756 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9757 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9758 .addReg(ptrA).addReg(ptrB); 9759 } else { 9760 Ptr1Reg = ptrB; 9761 } 9762 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9763 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9764 if (!isLittleEndian) 9765 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9766 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9767 if (is64bit) 9768 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9769 .addReg(Ptr1Reg).addImm(0).addImm(61); 9770 else 9771 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9772 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9773 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 9774 .addReg(newval).addReg(ShiftReg); 9775 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 9776 .addReg(oldval).addReg(ShiftReg); 9777 if (is8bit) 9778 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9779 else { 9780 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9781 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 9782 .addReg(Mask3Reg).addImm(65535); 9783 } 9784 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9785 .addReg(Mask2Reg).addReg(ShiftReg); 9786 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 9787 .addReg(NewVal2Reg).addReg(MaskReg); 9788 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 9789 .addReg(OldVal2Reg).addReg(MaskReg); 9790 9791 BB = loop1MBB; 9792 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9793 .addReg(ZeroReg).addReg(PtrReg); 9794 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 9795 .addReg(TmpDestReg).addReg(MaskReg); 9796 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 9797 .addReg(TmpReg).addReg(OldVal3Reg); 9798 BuildMI(BB, dl, TII->get(PPC::BCC)) 9799 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 9800 BB->addSuccessor(loop2MBB); 9801 BB->addSuccessor(midMBB); 9802 9803 BB = loop2MBB; 9804 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 9805 .addReg(TmpDestReg).addReg(MaskReg); 9806 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 9807 .addReg(Tmp2Reg).addReg(NewVal3Reg); 9808 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 9809 .addReg(ZeroReg).addReg(PtrReg); 9810 BuildMI(BB, dl, TII->get(PPC::BCC)) 9811 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 9812 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 9813 BB->addSuccessor(loop1MBB); 9814 BB->addSuccessor(exitMBB); 9815 9816 BB = midMBB; 9817 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 9818 .addReg(ZeroReg).addReg(PtrReg); 9819 BB->addSuccessor(exitMBB); 9820 9821 // exitMBB: 9822 // ... 9823 BB = exitMBB; 9824 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 9825 .addReg(ShiftReg); 9826 } else if (MI.getOpcode() == PPC::FADDrtz) { 9827 // This pseudo performs an FADD with rounding mode temporarily forced 9828 // to round-to-zero. We emit this via custom inserter since the FPSCR 9829 // is not modeled at the SelectionDAG level. 9830 unsigned Dest = MI.getOperand(0).getReg(); 9831 unsigned Src1 = MI.getOperand(1).getReg(); 9832 unsigned Src2 = MI.getOperand(2).getReg(); 9833 DebugLoc dl = MI.getDebugLoc(); 9834 9835 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9836 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 9837 9838 // Save FPSCR value. 9839 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 9840 9841 // Set rounding mode to round-to-zero. 9842 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 9843 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 9844 9845 // Perform addition. 9846 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 9847 9848 // Restore FPSCR value. 9849 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 9850 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 9851 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 9852 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 9853 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 9854 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 9855 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 9856 ? PPC::ANDIo8 9857 : PPC::ANDIo; 9858 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 9859 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 9860 9861 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9862 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 9863 &PPC::GPRCRegClass : 9864 &PPC::G8RCRegClass); 9865 9866 DebugLoc dl = MI.getDebugLoc(); 9867 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 9868 .addReg(MI.getOperand(1).getReg()) 9869 .addImm(1); 9870 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 9871 MI.getOperand(0).getReg()) 9872 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 9873 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 9874 DebugLoc Dl = MI.getDebugLoc(); 9875 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9876 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 9877 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 9878 return BB; 9879 } else { 9880 llvm_unreachable("Unexpected instr type to insert"); 9881 } 9882 9883 MI.eraseFromParent(); // The pseudo instruction is gone now. 9884 return BB; 9885 } 9886 9887 //===----------------------------------------------------------------------===// 9888 // Target Optimization Hooks 9889 //===----------------------------------------------------------------------===// 9890 9891 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 9892 // For the estimates, convergence is quadratic, so we essentially double the 9893 // number of digits correct after every iteration. For both FRE and FRSQRTE, 9894 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 9895 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 9896 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 9897 if (VT.getScalarType() == MVT::f64) 9898 RefinementSteps++; 9899 return RefinementSteps; 9900 } 9901 9902 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 9903 int Enabled, int &RefinementSteps, 9904 bool &UseOneConstNR, 9905 bool Reciprocal) const { 9906 EVT VT = Operand.getValueType(); 9907 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 9908 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 9909 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 9910 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 9911 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 9912 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 9913 if (RefinementSteps == ReciprocalEstimate::Unspecified) 9914 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 9915 9916 UseOneConstNR = true; 9917 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 9918 } 9919 return SDValue(); 9920 } 9921 9922 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 9923 int Enabled, 9924 int &RefinementSteps) const { 9925 EVT VT = Operand.getValueType(); 9926 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 9927 (VT == MVT::f64 && Subtarget.hasFRE()) || 9928 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 9929 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 9930 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 9931 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 9932 if (RefinementSteps == ReciprocalEstimate::Unspecified) 9933 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 9934 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 9935 } 9936 return SDValue(); 9937 } 9938 9939 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 9940 // Note: This functionality is used only when unsafe-fp-math is enabled, and 9941 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 9942 // enabled for division), this functionality is redundant with the default 9943 // combiner logic (once the division -> reciprocal/multiply transformation 9944 // has taken place). As a result, this matters more for older cores than for 9945 // newer ones. 9946 9947 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 9948 // reciprocal if there are two or more FDIVs (for embedded cores with only 9949 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 9950 switch (Subtarget.getDarwinDirective()) { 9951 default: 9952 return 3; 9953 case PPC::DIR_440: 9954 case PPC::DIR_A2: 9955 case PPC::DIR_E500mc: 9956 case PPC::DIR_E5500: 9957 return 2; 9958 } 9959 } 9960 9961 // isConsecutiveLSLoc needs to work even if all adds have not yet been 9962 // collapsed, and so we need to look through chains of them. 9963 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 9964 int64_t& Offset, SelectionDAG &DAG) { 9965 if (DAG.isBaseWithConstantOffset(Loc)) { 9966 Base = Loc.getOperand(0); 9967 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 9968 9969 // The base might itself be a base plus an offset, and if so, accumulate 9970 // that as well. 9971 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 9972 } 9973 } 9974 9975 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 9976 unsigned Bytes, int Dist, 9977 SelectionDAG &DAG) { 9978 if (VT.getSizeInBits() / 8 != Bytes) 9979 return false; 9980 9981 SDValue BaseLoc = Base->getBasePtr(); 9982 if (Loc.getOpcode() == ISD::FrameIndex) { 9983 if (BaseLoc.getOpcode() != ISD::FrameIndex) 9984 return false; 9985 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9986 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 9987 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 9988 int FS = MFI.getObjectSize(FI); 9989 int BFS = MFI.getObjectSize(BFI); 9990 if (FS != BFS || FS != (int)Bytes) return false; 9991 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 9992 } 9993 9994 SDValue Base1 = Loc, Base2 = BaseLoc; 9995 int64_t Offset1 = 0, Offset2 = 0; 9996 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 9997 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 9998 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 9999 return true; 10000 10001 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10002 const GlobalValue *GV1 = nullptr; 10003 const GlobalValue *GV2 = nullptr; 10004 Offset1 = 0; 10005 Offset2 = 0; 10006 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10007 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 10008 if (isGA1 && isGA2 && GV1 == GV2) 10009 return Offset1 == (Offset2 + Dist*Bytes); 10010 return false; 10011 } 10012 10013 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 10014 // not enforce equality of the chain operands. 10015 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 10016 unsigned Bytes, int Dist, 10017 SelectionDAG &DAG) { 10018 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 10019 EVT VT = LS->getMemoryVT(); 10020 SDValue Loc = LS->getBasePtr(); 10021 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 10022 } 10023 10024 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 10025 EVT VT; 10026 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10027 default: return false; 10028 case Intrinsic::ppc_qpx_qvlfd: 10029 case Intrinsic::ppc_qpx_qvlfda: 10030 VT = MVT::v4f64; 10031 break; 10032 case Intrinsic::ppc_qpx_qvlfs: 10033 case Intrinsic::ppc_qpx_qvlfsa: 10034 VT = MVT::v4f32; 10035 break; 10036 case Intrinsic::ppc_qpx_qvlfcd: 10037 case Intrinsic::ppc_qpx_qvlfcda: 10038 VT = MVT::v2f64; 10039 break; 10040 case Intrinsic::ppc_qpx_qvlfcs: 10041 case Intrinsic::ppc_qpx_qvlfcsa: 10042 VT = MVT::v2f32; 10043 break; 10044 case Intrinsic::ppc_qpx_qvlfiwa: 10045 case Intrinsic::ppc_qpx_qvlfiwz: 10046 case Intrinsic::ppc_altivec_lvx: 10047 case Intrinsic::ppc_altivec_lvxl: 10048 case Intrinsic::ppc_vsx_lxvw4x: 10049 case Intrinsic::ppc_vsx_lxvw4x_be: 10050 VT = MVT::v4i32; 10051 break; 10052 case Intrinsic::ppc_vsx_lxvd2x: 10053 case Intrinsic::ppc_vsx_lxvd2x_be: 10054 VT = MVT::v2f64; 10055 break; 10056 case Intrinsic::ppc_altivec_lvebx: 10057 VT = MVT::i8; 10058 break; 10059 case Intrinsic::ppc_altivec_lvehx: 10060 VT = MVT::i16; 10061 break; 10062 case Intrinsic::ppc_altivec_lvewx: 10063 VT = MVT::i32; 10064 break; 10065 } 10066 10067 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 10068 } 10069 10070 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 10071 EVT VT; 10072 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10073 default: return false; 10074 case Intrinsic::ppc_qpx_qvstfd: 10075 case Intrinsic::ppc_qpx_qvstfda: 10076 VT = MVT::v4f64; 10077 break; 10078 case Intrinsic::ppc_qpx_qvstfs: 10079 case Intrinsic::ppc_qpx_qvstfsa: 10080 VT = MVT::v4f32; 10081 break; 10082 case Intrinsic::ppc_qpx_qvstfcd: 10083 case Intrinsic::ppc_qpx_qvstfcda: 10084 VT = MVT::v2f64; 10085 break; 10086 case Intrinsic::ppc_qpx_qvstfcs: 10087 case Intrinsic::ppc_qpx_qvstfcsa: 10088 VT = MVT::v2f32; 10089 break; 10090 case Intrinsic::ppc_qpx_qvstfiw: 10091 case Intrinsic::ppc_qpx_qvstfiwa: 10092 case Intrinsic::ppc_altivec_stvx: 10093 case Intrinsic::ppc_altivec_stvxl: 10094 case Intrinsic::ppc_vsx_stxvw4x: 10095 VT = MVT::v4i32; 10096 break; 10097 case Intrinsic::ppc_vsx_stxvd2x: 10098 VT = MVT::v2f64; 10099 break; 10100 case Intrinsic::ppc_vsx_stxvw4x_be: 10101 VT = MVT::v4i32; 10102 break; 10103 case Intrinsic::ppc_vsx_stxvd2x_be: 10104 VT = MVT::v2f64; 10105 break; 10106 case Intrinsic::ppc_altivec_stvebx: 10107 VT = MVT::i8; 10108 break; 10109 case Intrinsic::ppc_altivec_stvehx: 10110 VT = MVT::i16; 10111 break; 10112 case Intrinsic::ppc_altivec_stvewx: 10113 VT = MVT::i32; 10114 break; 10115 } 10116 10117 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 10118 } 10119 10120 return false; 10121 } 10122 10123 // Return true is there is a nearyby consecutive load to the one provided 10124 // (regardless of alignment). We search up and down the chain, looking though 10125 // token factors and other loads (but nothing else). As a result, a true result 10126 // indicates that it is safe to create a new consecutive load adjacent to the 10127 // load provided. 10128 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 10129 SDValue Chain = LD->getChain(); 10130 EVT VT = LD->getMemoryVT(); 10131 10132 SmallSet<SDNode *, 16> LoadRoots; 10133 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 10134 SmallSet<SDNode *, 16> Visited; 10135 10136 // First, search up the chain, branching to follow all token-factor operands. 10137 // If we find a consecutive load, then we're done, otherwise, record all 10138 // nodes just above the top-level loads and token factors. 10139 while (!Queue.empty()) { 10140 SDNode *ChainNext = Queue.pop_back_val(); 10141 if (!Visited.insert(ChainNext).second) 10142 continue; 10143 10144 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 10145 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10146 return true; 10147 10148 if (!Visited.count(ChainLD->getChain().getNode())) 10149 Queue.push_back(ChainLD->getChain().getNode()); 10150 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 10151 for (const SDUse &O : ChainNext->ops()) 10152 if (!Visited.count(O.getNode())) 10153 Queue.push_back(O.getNode()); 10154 } else 10155 LoadRoots.insert(ChainNext); 10156 } 10157 10158 // Second, search down the chain, starting from the top-level nodes recorded 10159 // in the first phase. These top-level nodes are the nodes just above all 10160 // loads and token factors. Starting with their uses, recursively look though 10161 // all loads (just the chain uses) and token factors to find a consecutive 10162 // load. 10163 Visited.clear(); 10164 Queue.clear(); 10165 10166 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 10167 IE = LoadRoots.end(); I != IE; ++I) { 10168 Queue.push_back(*I); 10169 10170 while (!Queue.empty()) { 10171 SDNode *LoadRoot = Queue.pop_back_val(); 10172 if (!Visited.insert(LoadRoot).second) 10173 continue; 10174 10175 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 10176 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10177 return true; 10178 10179 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 10180 UE = LoadRoot->use_end(); UI != UE; ++UI) 10181 if (((isa<MemSDNode>(*UI) && 10182 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 10183 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 10184 Queue.push_back(*UI); 10185 } 10186 } 10187 10188 return false; 10189 } 10190 10191 /// This function is called when we have proved that a SETCC node can be replaced 10192 /// by subtraction (and other supporting instructions) so that the result of 10193 /// comparison is kept in a GPR instead of CR. This function is purely for 10194 /// codegen purposes and has some flags to guide the codegen process. 10195 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 10196 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 10197 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10198 10199 // Zero extend the operands to the largest legal integer. Originally, they 10200 // must be of a strictly smaller size. 10201 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 10202 DAG.getConstant(Size, DL, MVT::i32)); 10203 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 10204 DAG.getConstant(Size, DL, MVT::i32)); 10205 10206 // Swap if needed. Depends on the condition code. 10207 if (Swap) 10208 std::swap(Op0, Op1); 10209 10210 // Subtract extended integers. 10211 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 10212 10213 // Move the sign bit to the least significant position and zero out the rest. 10214 // Now the least significant bit carries the result of original comparison. 10215 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 10216 DAG.getConstant(Size - 1, DL, MVT::i32)); 10217 auto Final = Shifted; 10218 10219 // Complement the result if needed. Based on the condition code. 10220 if (Complement) 10221 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 10222 DAG.getConstant(1, DL, MVT::i64)); 10223 10224 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 10225 } 10226 10227 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 10228 DAGCombinerInfo &DCI) const { 10229 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10230 10231 SelectionDAG &DAG = DCI.DAG; 10232 SDLoc DL(N); 10233 10234 // Size of integers being compared has a critical role in the following 10235 // analysis, so we prefer to do this when all types are legal. 10236 if (!DCI.isAfterLegalizeVectorOps()) 10237 return SDValue(); 10238 10239 // If all users of SETCC extend its value to a legal integer type 10240 // then we replace SETCC with a subtraction 10241 for (SDNode::use_iterator UI = N->use_begin(), 10242 UE = N->use_end(); UI != UE; ++UI) { 10243 if (UI->getOpcode() != ISD::ZERO_EXTEND) 10244 return SDValue(); 10245 } 10246 10247 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10248 auto OpSize = N->getOperand(0).getValueSizeInBits(); 10249 10250 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 10251 10252 if (OpSize < Size) { 10253 switch (CC) { 10254 default: break; 10255 case ISD::SETULT: 10256 return generateEquivalentSub(N, Size, false, false, DL, DAG); 10257 case ISD::SETULE: 10258 return generateEquivalentSub(N, Size, true, true, DL, DAG); 10259 case ISD::SETUGT: 10260 return generateEquivalentSub(N, Size, false, true, DL, DAG); 10261 case ISD::SETUGE: 10262 return generateEquivalentSub(N, Size, true, false, DL, DAG); 10263 } 10264 } 10265 10266 return SDValue(); 10267 } 10268 10269 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 10270 DAGCombinerInfo &DCI) const { 10271 SelectionDAG &DAG = DCI.DAG; 10272 SDLoc dl(N); 10273 10274 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 10275 // If we're tracking CR bits, we need to be careful that we don't have: 10276 // trunc(binary-ops(zext(x), zext(y))) 10277 // or 10278 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 10279 // such that we're unnecessarily moving things into GPRs when it would be 10280 // better to keep them in CR bits. 10281 10282 // Note that trunc here can be an actual i1 trunc, or can be the effective 10283 // truncation that comes from a setcc or select_cc. 10284 if (N->getOpcode() == ISD::TRUNCATE && 10285 N->getValueType(0) != MVT::i1) 10286 return SDValue(); 10287 10288 if (N->getOperand(0).getValueType() != MVT::i32 && 10289 N->getOperand(0).getValueType() != MVT::i64) 10290 return SDValue(); 10291 10292 if (N->getOpcode() == ISD::SETCC || 10293 N->getOpcode() == ISD::SELECT_CC) { 10294 // If we're looking at a comparison, then we need to make sure that the 10295 // high bits (all except for the first) don't matter the result. 10296 ISD::CondCode CC = 10297 cast<CondCodeSDNode>(N->getOperand( 10298 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 10299 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 10300 10301 if (ISD::isSignedIntSetCC(CC)) { 10302 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 10303 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 10304 return SDValue(); 10305 } else if (ISD::isUnsignedIntSetCC(CC)) { 10306 if (!DAG.MaskedValueIsZero(N->getOperand(0), 10307 APInt::getHighBitsSet(OpBits, OpBits-1)) || 10308 !DAG.MaskedValueIsZero(N->getOperand(1), 10309 APInt::getHighBitsSet(OpBits, OpBits-1))) 10310 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 10311 : SDValue()); 10312 } else { 10313 // This is neither a signed nor an unsigned comparison, just make sure 10314 // that the high bits are equal. 10315 KnownBits Op1Known, Op2Known; 10316 DAG.computeKnownBits(N->getOperand(0), Op1Known); 10317 DAG.computeKnownBits(N->getOperand(1), Op2Known); 10318 10319 // We don't really care about what is known about the first bit (if 10320 // anything), so clear it in all masks prior to comparing them. 10321 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 10322 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 10323 10324 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 10325 return SDValue(); 10326 } 10327 } 10328 10329 // We now know that the higher-order bits are irrelevant, we just need to 10330 // make sure that all of the intermediate operations are bit operations, and 10331 // all inputs are extensions. 10332 if (N->getOperand(0).getOpcode() != ISD::AND && 10333 N->getOperand(0).getOpcode() != ISD::OR && 10334 N->getOperand(0).getOpcode() != ISD::XOR && 10335 N->getOperand(0).getOpcode() != ISD::SELECT && 10336 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 10337 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 10338 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 10339 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 10340 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 10341 return SDValue(); 10342 10343 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 10344 N->getOperand(1).getOpcode() != ISD::AND && 10345 N->getOperand(1).getOpcode() != ISD::OR && 10346 N->getOperand(1).getOpcode() != ISD::XOR && 10347 N->getOperand(1).getOpcode() != ISD::SELECT && 10348 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 10349 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 10350 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 10351 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 10352 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 10353 return SDValue(); 10354 10355 SmallVector<SDValue, 4> Inputs; 10356 SmallVector<SDValue, 8> BinOps, PromOps; 10357 SmallPtrSet<SDNode *, 16> Visited; 10358 10359 for (unsigned i = 0; i < 2; ++i) { 10360 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10361 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10362 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 10363 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 10364 isa<ConstantSDNode>(N->getOperand(i))) 10365 Inputs.push_back(N->getOperand(i)); 10366 else 10367 BinOps.push_back(N->getOperand(i)); 10368 10369 if (N->getOpcode() == ISD::TRUNCATE) 10370 break; 10371 } 10372 10373 // Visit all inputs, collect all binary operations (and, or, xor and 10374 // select) that are all fed by extensions. 10375 while (!BinOps.empty()) { 10376 SDValue BinOp = BinOps.back(); 10377 BinOps.pop_back(); 10378 10379 if (!Visited.insert(BinOp.getNode()).second) 10380 continue; 10381 10382 PromOps.push_back(BinOp); 10383 10384 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 10385 // The condition of the select is not promoted. 10386 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 10387 continue; 10388 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 10389 continue; 10390 10391 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10392 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10393 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 10394 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 10395 isa<ConstantSDNode>(BinOp.getOperand(i))) { 10396 Inputs.push_back(BinOp.getOperand(i)); 10397 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 10398 BinOp.getOperand(i).getOpcode() == ISD::OR || 10399 BinOp.getOperand(i).getOpcode() == ISD::XOR || 10400 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 10401 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 10402 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 10403 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10404 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10405 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 10406 BinOps.push_back(BinOp.getOperand(i)); 10407 } else { 10408 // We have an input that is not an extension or another binary 10409 // operation; we'll abort this transformation. 10410 return SDValue(); 10411 } 10412 } 10413 } 10414 10415 // Make sure that this is a self-contained cluster of operations (which 10416 // is not quite the same thing as saying that everything has only one 10417 // use). 10418 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10419 if (isa<ConstantSDNode>(Inputs[i])) 10420 continue; 10421 10422 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 10423 UE = Inputs[i].getNode()->use_end(); 10424 UI != UE; ++UI) { 10425 SDNode *User = *UI; 10426 if (User != N && !Visited.count(User)) 10427 return SDValue(); 10428 10429 // Make sure that we're not going to promote the non-output-value 10430 // operand(s) or SELECT or SELECT_CC. 10431 // FIXME: Although we could sometimes handle this, and it does occur in 10432 // practice that one of the condition inputs to the select is also one of 10433 // the outputs, we currently can't deal with this. 10434 if (User->getOpcode() == ISD::SELECT) { 10435 if (User->getOperand(0) == Inputs[i]) 10436 return SDValue(); 10437 } else if (User->getOpcode() == ISD::SELECT_CC) { 10438 if (User->getOperand(0) == Inputs[i] || 10439 User->getOperand(1) == Inputs[i]) 10440 return SDValue(); 10441 } 10442 } 10443 } 10444 10445 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 10446 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 10447 UE = PromOps[i].getNode()->use_end(); 10448 UI != UE; ++UI) { 10449 SDNode *User = *UI; 10450 if (User != N && !Visited.count(User)) 10451 return SDValue(); 10452 10453 // Make sure that we're not going to promote the non-output-value 10454 // operand(s) or SELECT or SELECT_CC. 10455 // FIXME: Although we could sometimes handle this, and it does occur in 10456 // practice that one of the condition inputs to the select is also one of 10457 // the outputs, we currently can't deal with this. 10458 if (User->getOpcode() == ISD::SELECT) { 10459 if (User->getOperand(0) == PromOps[i]) 10460 return SDValue(); 10461 } else if (User->getOpcode() == ISD::SELECT_CC) { 10462 if (User->getOperand(0) == PromOps[i] || 10463 User->getOperand(1) == PromOps[i]) 10464 return SDValue(); 10465 } 10466 } 10467 } 10468 10469 // Replace all inputs with the extension operand. 10470 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10471 // Constants may have users outside the cluster of to-be-promoted nodes, 10472 // and so we need to replace those as we do the promotions. 10473 if (isa<ConstantSDNode>(Inputs[i])) 10474 continue; 10475 else 10476 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 10477 } 10478 10479 std::list<HandleSDNode> PromOpHandles; 10480 for (auto &PromOp : PromOps) 10481 PromOpHandles.emplace_back(PromOp); 10482 10483 // Replace all operations (these are all the same, but have a different 10484 // (i1) return type). DAG.getNode will validate that the types of 10485 // a binary operator match, so go through the list in reverse so that 10486 // we've likely promoted both operands first. Any intermediate truncations or 10487 // extensions disappear. 10488 while (!PromOpHandles.empty()) { 10489 SDValue PromOp = PromOpHandles.back().getValue(); 10490 PromOpHandles.pop_back(); 10491 10492 if (PromOp.getOpcode() == ISD::TRUNCATE || 10493 PromOp.getOpcode() == ISD::SIGN_EXTEND || 10494 PromOp.getOpcode() == ISD::ZERO_EXTEND || 10495 PromOp.getOpcode() == ISD::ANY_EXTEND) { 10496 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 10497 PromOp.getOperand(0).getValueType() != MVT::i1) { 10498 // The operand is not yet ready (see comment below). 10499 PromOpHandles.emplace_front(PromOp); 10500 continue; 10501 } 10502 10503 SDValue RepValue = PromOp.getOperand(0); 10504 if (isa<ConstantSDNode>(RepValue)) 10505 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 10506 10507 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 10508 continue; 10509 } 10510 10511 unsigned C; 10512 switch (PromOp.getOpcode()) { 10513 default: C = 0; break; 10514 case ISD::SELECT: C = 1; break; 10515 case ISD::SELECT_CC: C = 2; break; 10516 } 10517 10518 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 10519 PromOp.getOperand(C).getValueType() != MVT::i1) || 10520 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 10521 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 10522 // The to-be-promoted operands of this node have not yet been 10523 // promoted (this should be rare because we're going through the 10524 // list backward, but if one of the operands has several users in 10525 // this cluster of to-be-promoted nodes, it is possible). 10526 PromOpHandles.emplace_front(PromOp); 10527 continue; 10528 } 10529 10530 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 10531 PromOp.getNode()->op_end()); 10532 10533 // If there are any constant inputs, make sure they're replaced now. 10534 for (unsigned i = 0; i < 2; ++i) 10535 if (isa<ConstantSDNode>(Ops[C+i])) 10536 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 10537 10538 DAG.ReplaceAllUsesOfValueWith(PromOp, 10539 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 10540 } 10541 10542 // Now we're left with the initial truncation itself. 10543 if (N->getOpcode() == ISD::TRUNCATE) 10544 return N->getOperand(0); 10545 10546 // Otherwise, this is a comparison. The operands to be compared have just 10547 // changed type (to i1), but everything else is the same. 10548 return SDValue(N, 0); 10549 } 10550 10551 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 10552 DAGCombinerInfo &DCI) const { 10553 SelectionDAG &DAG = DCI.DAG; 10554 SDLoc dl(N); 10555 10556 // If we're tracking CR bits, we need to be careful that we don't have: 10557 // zext(binary-ops(trunc(x), trunc(y))) 10558 // or 10559 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 10560 // such that we're unnecessarily moving things into CR bits that can more 10561 // efficiently stay in GPRs. Note that if we're not certain that the high 10562 // bits are set as required by the final extension, we still may need to do 10563 // some masking to get the proper behavior. 10564 10565 // This same functionality is important on PPC64 when dealing with 10566 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 10567 // the return values of functions. Because it is so similar, it is handled 10568 // here as well. 10569 10570 if (N->getValueType(0) != MVT::i32 && 10571 N->getValueType(0) != MVT::i64) 10572 return SDValue(); 10573 10574 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 10575 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 10576 return SDValue(); 10577 10578 if (N->getOperand(0).getOpcode() != ISD::AND && 10579 N->getOperand(0).getOpcode() != ISD::OR && 10580 N->getOperand(0).getOpcode() != ISD::XOR && 10581 N->getOperand(0).getOpcode() != ISD::SELECT && 10582 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 10583 return SDValue(); 10584 10585 SmallVector<SDValue, 4> Inputs; 10586 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 10587 SmallPtrSet<SDNode *, 16> Visited; 10588 10589 // Visit all inputs, collect all binary operations (and, or, xor and 10590 // select) that are all fed by truncations. 10591 while (!BinOps.empty()) { 10592 SDValue BinOp = BinOps.back(); 10593 BinOps.pop_back(); 10594 10595 if (!Visited.insert(BinOp.getNode()).second) 10596 continue; 10597 10598 PromOps.push_back(BinOp); 10599 10600 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 10601 // The condition of the select is not promoted. 10602 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 10603 continue; 10604 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 10605 continue; 10606 10607 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 10608 isa<ConstantSDNode>(BinOp.getOperand(i))) { 10609 Inputs.push_back(BinOp.getOperand(i)); 10610 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 10611 BinOp.getOperand(i).getOpcode() == ISD::OR || 10612 BinOp.getOperand(i).getOpcode() == ISD::XOR || 10613 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 10614 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 10615 BinOps.push_back(BinOp.getOperand(i)); 10616 } else { 10617 // We have an input that is not a truncation or another binary 10618 // operation; we'll abort this transformation. 10619 return SDValue(); 10620 } 10621 } 10622 } 10623 10624 // The operands of a select that must be truncated when the select is 10625 // promoted because the operand is actually part of the to-be-promoted set. 10626 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 10627 10628 // Make sure that this is a self-contained cluster of operations (which 10629 // is not quite the same thing as saying that everything has only one 10630 // use). 10631 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10632 if (isa<ConstantSDNode>(Inputs[i])) 10633 continue; 10634 10635 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 10636 UE = Inputs[i].getNode()->use_end(); 10637 UI != UE; ++UI) { 10638 SDNode *User = *UI; 10639 if (User != N && !Visited.count(User)) 10640 return SDValue(); 10641 10642 // If we're going to promote the non-output-value operand(s) or SELECT or 10643 // SELECT_CC, record them for truncation. 10644 if (User->getOpcode() == ISD::SELECT) { 10645 if (User->getOperand(0) == Inputs[i]) 10646 SelectTruncOp[0].insert(std::make_pair(User, 10647 User->getOperand(0).getValueType())); 10648 } else if (User->getOpcode() == ISD::SELECT_CC) { 10649 if (User->getOperand(0) == Inputs[i]) 10650 SelectTruncOp[0].insert(std::make_pair(User, 10651 User->getOperand(0).getValueType())); 10652 if (User->getOperand(1) == Inputs[i]) 10653 SelectTruncOp[1].insert(std::make_pair(User, 10654 User->getOperand(1).getValueType())); 10655 } 10656 } 10657 } 10658 10659 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 10660 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 10661 UE = PromOps[i].getNode()->use_end(); 10662 UI != UE; ++UI) { 10663 SDNode *User = *UI; 10664 if (User != N && !Visited.count(User)) 10665 return SDValue(); 10666 10667 // If we're going to promote the non-output-value operand(s) or SELECT or 10668 // SELECT_CC, record them for truncation. 10669 if (User->getOpcode() == ISD::SELECT) { 10670 if (User->getOperand(0) == PromOps[i]) 10671 SelectTruncOp[0].insert(std::make_pair(User, 10672 User->getOperand(0).getValueType())); 10673 } else if (User->getOpcode() == ISD::SELECT_CC) { 10674 if (User->getOperand(0) == PromOps[i]) 10675 SelectTruncOp[0].insert(std::make_pair(User, 10676 User->getOperand(0).getValueType())); 10677 if (User->getOperand(1) == PromOps[i]) 10678 SelectTruncOp[1].insert(std::make_pair(User, 10679 User->getOperand(1).getValueType())); 10680 } 10681 } 10682 } 10683 10684 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 10685 bool ReallyNeedsExt = false; 10686 if (N->getOpcode() != ISD::ANY_EXTEND) { 10687 // If all of the inputs are not already sign/zero extended, then 10688 // we'll still need to do that at the end. 10689 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10690 if (isa<ConstantSDNode>(Inputs[i])) 10691 continue; 10692 10693 unsigned OpBits = 10694 Inputs[i].getOperand(0).getValueSizeInBits(); 10695 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 10696 10697 if ((N->getOpcode() == ISD::ZERO_EXTEND && 10698 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 10699 APInt::getHighBitsSet(OpBits, 10700 OpBits-PromBits))) || 10701 (N->getOpcode() == ISD::SIGN_EXTEND && 10702 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 10703 (OpBits-(PromBits-1)))) { 10704 ReallyNeedsExt = true; 10705 break; 10706 } 10707 } 10708 } 10709 10710 // Replace all inputs, either with the truncation operand, or a 10711 // truncation or extension to the final output type. 10712 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10713 // Constant inputs need to be replaced with the to-be-promoted nodes that 10714 // use them because they might have users outside of the cluster of 10715 // promoted nodes. 10716 if (isa<ConstantSDNode>(Inputs[i])) 10717 continue; 10718 10719 SDValue InSrc = Inputs[i].getOperand(0); 10720 if (Inputs[i].getValueType() == N->getValueType(0)) 10721 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 10722 else if (N->getOpcode() == ISD::SIGN_EXTEND) 10723 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 10724 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 10725 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10726 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 10727 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 10728 else 10729 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 10730 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 10731 } 10732 10733 std::list<HandleSDNode> PromOpHandles; 10734 for (auto &PromOp : PromOps) 10735 PromOpHandles.emplace_back(PromOp); 10736 10737 // Replace all operations (these are all the same, but have a different 10738 // (promoted) return type). DAG.getNode will validate that the types of 10739 // a binary operator match, so go through the list in reverse so that 10740 // we've likely promoted both operands first. 10741 while (!PromOpHandles.empty()) { 10742 SDValue PromOp = PromOpHandles.back().getValue(); 10743 PromOpHandles.pop_back(); 10744 10745 unsigned C; 10746 switch (PromOp.getOpcode()) { 10747 default: C = 0; break; 10748 case ISD::SELECT: C = 1; break; 10749 case ISD::SELECT_CC: C = 2; break; 10750 } 10751 10752 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 10753 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 10754 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 10755 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 10756 // The to-be-promoted operands of this node have not yet been 10757 // promoted (this should be rare because we're going through the 10758 // list backward, but if one of the operands has several users in 10759 // this cluster of to-be-promoted nodes, it is possible). 10760 PromOpHandles.emplace_front(PromOp); 10761 continue; 10762 } 10763 10764 // For SELECT and SELECT_CC nodes, we do a similar check for any 10765 // to-be-promoted comparison inputs. 10766 if (PromOp.getOpcode() == ISD::SELECT || 10767 PromOp.getOpcode() == ISD::SELECT_CC) { 10768 if ((SelectTruncOp[0].count(PromOp.getNode()) && 10769 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 10770 (SelectTruncOp[1].count(PromOp.getNode()) && 10771 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 10772 PromOpHandles.emplace_front(PromOp); 10773 continue; 10774 } 10775 } 10776 10777 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 10778 PromOp.getNode()->op_end()); 10779 10780 // If this node has constant inputs, then they'll need to be promoted here. 10781 for (unsigned i = 0; i < 2; ++i) { 10782 if (!isa<ConstantSDNode>(Ops[C+i])) 10783 continue; 10784 if (Ops[C+i].getValueType() == N->getValueType(0)) 10785 continue; 10786 10787 if (N->getOpcode() == ISD::SIGN_EXTEND) 10788 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 10789 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10790 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 10791 else 10792 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 10793 } 10794 10795 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 10796 // truncate them again to the original value type. 10797 if (PromOp.getOpcode() == ISD::SELECT || 10798 PromOp.getOpcode() == ISD::SELECT_CC) { 10799 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 10800 if (SI0 != SelectTruncOp[0].end()) 10801 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 10802 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 10803 if (SI1 != SelectTruncOp[1].end()) 10804 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 10805 } 10806 10807 DAG.ReplaceAllUsesOfValueWith(PromOp, 10808 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 10809 } 10810 10811 // Now we're left with the initial extension itself. 10812 if (!ReallyNeedsExt) 10813 return N->getOperand(0); 10814 10815 // To zero extend, just mask off everything except for the first bit (in the 10816 // i1 case). 10817 if (N->getOpcode() == ISD::ZERO_EXTEND) 10818 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 10819 DAG.getConstant(APInt::getLowBitsSet( 10820 N->getValueSizeInBits(0), PromBits), 10821 dl, N->getValueType(0))); 10822 10823 assert(N->getOpcode() == ISD::SIGN_EXTEND && 10824 "Invalid extension type"); 10825 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 10826 SDValue ShiftCst = 10827 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 10828 return DAG.getNode( 10829 ISD::SRA, dl, N->getValueType(0), 10830 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 10831 ShiftCst); 10832 } 10833 10834 /// \brief Reduces the number of fp-to-int conversion when building a vector. 10835 /// 10836 /// If this vector is built out of floating to integer conversions, 10837 /// transform it to a vector built out of floating point values followed by a 10838 /// single floating to integer conversion of the vector. 10839 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 10840 /// becomes (fptosi (build_vector ($A, $B, ...))) 10841 SDValue PPCTargetLowering:: 10842 combineElementTruncationToVectorTruncation(SDNode *N, 10843 DAGCombinerInfo &DCI) const { 10844 assert(N->getOpcode() == ISD::BUILD_VECTOR && 10845 "Should be called with a BUILD_VECTOR node"); 10846 10847 SelectionDAG &DAG = DCI.DAG; 10848 SDLoc dl(N); 10849 10850 SDValue FirstInput = N->getOperand(0); 10851 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 10852 "The input operand must be an fp-to-int conversion."); 10853 10854 // This combine happens after legalization so the fp_to_[su]i nodes are 10855 // already converted to PPCSISD nodes. 10856 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 10857 if (FirstConversion == PPCISD::FCTIDZ || 10858 FirstConversion == PPCISD::FCTIDUZ || 10859 FirstConversion == PPCISD::FCTIWZ || 10860 FirstConversion == PPCISD::FCTIWUZ) { 10861 bool IsSplat = true; 10862 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 10863 FirstConversion == PPCISD::FCTIWUZ; 10864 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 10865 SmallVector<SDValue, 4> Ops; 10866 EVT TargetVT = N->getValueType(0); 10867 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 10868 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR) 10869 return SDValue(); 10870 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode(); 10871 if (NextConversion != FirstConversion) 10872 return SDValue(); 10873 if (N->getOperand(i) != FirstInput) 10874 IsSplat = false; 10875 } 10876 10877 // If this is a splat, we leave it as-is since there will be only a single 10878 // fp-to-int conversion followed by a splat of the integer. This is better 10879 // for 32-bit and smaller ints and neutral for 64-bit ints. 10880 if (IsSplat) 10881 return SDValue(); 10882 10883 // Now that we know we have the right type of node, get its operands 10884 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 10885 SDValue In = N->getOperand(i).getOperand(0); 10886 // For 32-bit values, we need to add an FP_ROUND node. 10887 if (Is32Bit) { 10888 if (In.isUndef()) 10889 Ops.push_back(DAG.getUNDEF(SrcVT)); 10890 else { 10891 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 10892 MVT::f32, In.getOperand(0), 10893 DAG.getIntPtrConstant(1, dl)); 10894 Ops.push_back(Trunc); 10895 } 10896 } else 10897 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 10898 } 10899 10900 unsigned Opcode; 10901 if (FirstConversion == PPCISD::FCTIDZ || 10902 FirstConversion == PPCISD::FCTIWZ) 10903 Opcode = ISD::FP_TO_SINT; 10904 else 10905 Opcode = ISD::FP_TO_UINT; 10906 10907 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 10908 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 10909 return DAG.getNode(Opcode, dl, TargetVT, BV); 10910 } 10911 return SDValue(); 10912 } 10913 10914 /// \brief Reduce the number of loads when building a vector. 10915 /// 10916 /// Building a vector out of multiple loads can be converted to a load 10917 /// of the vector type if the loads are consecutive. If the loads are 10918 /// consecutive but in descending order, a shuffle is added at the end 10919 /// to reorder the vector. 10920 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 10921 assert(N->getOpcode() == ISD::BUILD_VECTOR && 10922 "Should be called with a BUILD_VECTOR node"); 10923 10924 SDLoc dl(N); 10925 bool InputsAreConsecutiveLoads = true; 10926 bool InputsAreReverseConsecutive = true; 10927 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 10928 SDValue FirstInput = N->getOperand(0); 10929 bool IsRoundOfExtLoad = false; 10930 10931 if (FirstInput.getOpcode() == ISD::FP_ROUND && 10932 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 10933 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 10934 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 10935 } 10936 // Not a build vector of (possibly fp_rounded) loads. 10937 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) 10938 return SDValue(); 10939 10940 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 10941 // If any inputs are fp_round(extload), they all must be. 10942 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 10943 return SDValue(); 10944 10945 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 10946 N->getOperand(i); 10947 if (NextInput.getOpcode() != ISD::LOAD) 10948 return SDValue(); 10949 10950 SDValue PreviousInput = 10951 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 10952 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 10953 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 10954 10955 // If any inputs are fp_round(extload), they all must be. 10956 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 10957 return SDValue(); 10958 10959 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 10960 InputsAreConsecutiveLoads = false; 10961 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 10962 InputsAreReverseConsecutive = false; 10963 10964 // Exit early if the loads are neither consecutive nor reverse consecutive. 10965 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 10966 return SDValue(); 10967 } 10968 10969 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 10970 "The loads cannot be both consecutive and reverse consecutive."); 10971 10972 SDValue FirstLoadOp = 10973 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 10974 SDValue LastLoadOp = 10975 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 10976 N->getOperand(N->getNumOperands()-1); 10977 10978 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 10979 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 10980 if (InputsAreConsecutiveLoads) { 10981 assert(LD1 && "Input needs to be a LoadSDNode."); 10982 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 10983 LD1->getBasePtr(), LD1->getPointerInfo(), 10984 LD1->getAlignment()); 10985 } 10986 if (InputsAreReverseConsecutive) { 10987 assert(LDL && "Input needs to be a LoadSDNode."); 10988 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 10989 LDL->getBasePtr(), LDL->getPointerInfo(), 10990 LDL->getAlignment()); 10991 SmallVector<int, 16> Ops; 10992 for (int i = N->getNumOperands() - 1; i >= 0; i--) 10993 Ops.push_back(i); 10994 10995 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 10996 DAG.getUNDEF(N->getValueType(0)), Ops); 10997 } 10998 return SDValue(); 10999 } 11000 11001 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 11002 DAGCombinerInfo &DCI) const { 11003 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11004 "Should be called with a BUILD_VECTOR node"); 11005 11006 SelectionDAG &DAG = DCI.DAG; 11007 SDLoc dl(N); 11008 11009 if (!Subtarget.hasVSX()) 11010 return SDValue(); 11011 11012 // The target independent DAG combiner will leave a build_vector of 11013 // float-to-int conversions intact. We can generate MUCH better code for 11014 // a float-to-int conversion of a vector of floats. 11015 SDValue FirstInput = N->getOperand(0); 11016 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 11017 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 11018 if (Reduced) 11019 return Reduced; 11020 } 11021 11022 // If we're building a vector out of consecutive loads, just load that 11023 // vector type. 11024 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 11025 if (Reduced) 11026 return Reduced; 11027 11028 if (N->getValueType(0) != MVT::v2f64) 11029 return SDValue(); 11030 11031 // Looking for: 11032 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 11033 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 11034 FirstInput.getOpcode() != ISD::UINT_TO_FP) 11035 return SDValue(); 11036 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 11037 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 11038 return SDValue(); 11039 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 11040 return SDValue(); 11041 11042 SDValue Ext1 = FirstInput.getOperand(0); 11043 SDValue Ext2 = N->getOperand(1).getOperand(0); 11044 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11045 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11046 return SDValue(); 11047 11048 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 11049 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 11050 if (!Ext1Op || !Ext2Op) 11051 return SDValue(); 11052 if (Ext1.getValueType() != MVT::i32 || 11053 Ext2.getValueType() != MVT::i32) 11054 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 11055 return SDValue(); 11056 11057 int FirstElem = Ext1Op->getZExtValue(); 11058 int SecondElem = Ext2Op->getZExtValue(); 11059 int SubvecIdx; 11060 if (FirstElem == 0 && SecondElem == 1) 11061 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 11062 else if (FirstElem == 2 && SecondElem == 3) 11063 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 11064 else 11065 return SDValue(); 11066 11067 SDValue SrcVec = Ext1.getOperand(0); 11068 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 11069 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 11070 return DAG.getNode(NodeType, dl, MVT::v2f64, 11071 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 11072 } 11073 11074 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 11075 DAGCombinerInfo &DCI) const { 11076 assert((N->getOpcode() == ISD::SINT_TO_FP || 11077 N->getOpcode() == ISD::UINT_TO_FP) && 11078 "Need an int -> FP conversion node here"); 11079 11080 if (useSoftFloat() || !Subtarget.has64BitSupport()) 11081 return SDValue(); 11082 11083 SelectionDAG &DAG = DCI.DAG; 11084 SDLoc dl(N); 11085 SDValue Op(N, 0); 11086 11087 SDValue FirstOperand(Op.getOperand(0)); 11088 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 11089 (FirstOperand.getValueType() == MVT::i8 || 11090 FirstOperand.getValueType() == MVT::i16); 11091 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 11092 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 11093 bool DstDouble = Op.getValueType() == MVT::f64; 11094 unsigned ConvOp = Signed ? 11095 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 11096 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 11097 SDValue WidthConst = 11098 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 11099 dl, false); 11100 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 11101 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 11102 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 11103 DAG.getVTList(MVT::f64, MVT::Other), 11104 Ops, MVT::i8, LDN->getMemOperand()); 11105 11106 // For signed conversion, we need to sign-extend the value in the VSR 11107 if (Signed) { 11108 SDValue ExtOps[] = { Ld, WidthConst }; 11109 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 11110 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 11111 } else 11112 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 11113 } 11114 11115 // Don't handle ppc_fp128 here or i1 conversions. 11116 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 11117 return SDValue(); 11118 if (Op.getOperand(0).getValueType() == MVT::i1) 11119 return SDValue(); 11120 11121 // For i32 intermediate values, unfortunately, the conversion functions 11122 // leave the upper 32 bits of the value are undefined. Within the set of 11123 // scalar instructions, we have no method for zero- or sign-extending the 11124 // value. Thus, we cannot handle i32 intermediate values here. 11125 if (Op.getOperand(0).getValueType() == MVT::i32) 11126 return SDValue(); 11127 11128 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 11129 "UINT_TO_FP is supported only with FPCVT"); 11130 11131 // If we have FCFIDS, then use it when converting to single-precision. 11132 // Otherwise, convert to double-precision and then round. 11133 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11134 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 11135 : PPCISD::FCFIDS) 11136 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 11137 : PPCISD::FCFID); 11138 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11139 ? MVT::f32 11140 : MVT::f64; 11141 11142 // If we're converting from a float, to an int, and back to a float again, 11143 // then we don't need the store/load pair at all. 11144 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 11145 Subtarget.hasFPCVT()) || 11146 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 11147 SDValue Src = Op.getOperand(0).getOperand(0); 11148 if (Src.getValueType() == MVT::f32) { 11149 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 11150 DCI.AddToWorklist(Src.getNode()); 11151 } else if (Src.getValueType() != MVT::f64) { 11152 // Make sure that we don't pick up a ppc_fp128 source value. 11153 return SDValue(); 11154 } 11155 11156 unsigned FCTOp = 11157 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 11158 PPCISD::FCTIDUZ; 11159 11160 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 11161 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 11162 11163 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 11164 FP = DAG.getNode(ISD::FP_ROUND, dl, 11165 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 11166 DCI.AddToWorklist(FP.getNode()); 11167 } 11168 11169 return FP; 11170 } 11171 11172 return SDValue(); 11173 } 11174 11175 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 11176 // builtins) into loads with swaps. 11177 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 11178 DAGCombinerInfo &DCI) const { 11179 SelectionDAG &DAG = DCI.DAG; 11180 SDLoc dl(N); 11181 SDValue Chain; 11182 SDValue Base; 11183 MachineMemOperand *MMO; 11184 11185 switch (N->getOpcode()) { 11186 default: 11187 llvm_unreachable("Unexpected opcode for little endian VSX load"); 11188 case ISD::LOAD: { 11189 LoadSDNode *LD = cast<LoadSDNode>(N); 11190 Chain = LD->getChain(); 11191 Base = LD->getBasePtr(); 11192 MMO = LD->getMemOperand(); 11193 // If the MMO suggests this isn't a load of a full vector, leave 11194 // things alone. For a built-in, we have to make the change for 11195 // correctness, so if there is a size problem that will be a bug. 11196 if (MMO->getSize() < 16) 11197 return SDValue(); 11198 break; 11199 } 11200 case ISD::INTRINSIC_W_CHAIN: { 11201 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11202 Chain = Intrin->getChain(); 11203 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 11204 // us what we want. Get operand 2 instead. 11205 Base = Intrin->getOperand(2); 11206 MMO = Intrin->getMemOperand(); 11207 break; 11208 } 11209 } 11210 11211 MVT VecTy = N->getValueType(0).getSimpleVT(); 11212 11213 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 11214 // aligned and the type is a vector with elements up to 4 bytes 11215 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 11216 && VecTy.getScalarSizeInBits() <= 32 ) { 11217 return SDValue(); 11218 } 11219 11220 SDValue LoadOps[] = { Chain, Base }; 11221 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 11222 DAG.getVTList(MVT::v2f64, MVT::Other), 11223 LoadOps, MVT::v2f64, MMO); 11224 11225 DCI.AddToWorklist(Load.getNode()); 11226 Chain = Load.getValue(1); 11227 SDValue Swap = DAG.getNode( 11228 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 11229 DCI.AddToWorklist(Swap.getNode()); 11230 11231 // Add a bitcast if the resulting load type doesn't match v2f64. 11232 if (VecTy != MVT::v2f64) { 11233 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 11234 DCI.AddToWorklist(N.getNode()); 11235 // Package {bitcast value, swap's chain} to match Load's shape. 11236 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 11237 N, Swap.getValue(1)); 11238 } 11239 11240 return Swap; 11241 } 11242 11243 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 11244 // builtins) into stores with swaps. 11245 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 11246 DAGCombinerInfo &DCI) const { 11247 SelectionDAG &DAG = DCI.DAG; 11248 SDLoc dl(N); 11249 SDValue Chain; 11250 SDValue Base; 11251 unsigned SrcOpnd; 11252 MachineMemOperand *MMO; 11253 11254 switch (N->getOpcode()) { 11255 default: 11256 llvm_unreachable("Unexpected opcode for little endian VSX store"); 11257 case ISD::STORE: { 11258 StoreSDNode *ST = cast<StoreSDNode>(N); 11259 Chain = ST->getChain(); 11260 Base = ST->getBasePtr(); 11261 MMO = ST->getMemOperand(); 11262 SrcOpnd = 1; 11263 // If the MMO suggests this isn't a store of a full vector, leave 11264 // things alone. For a built-in, we have to make the change for 11265 // correctness, so if there is a size problem that will be a bug. 11266 if (MMO->getSize() < 16) 11267 return SDValue(); 11268 break; 11269 } 11270 case ISD::INTRINSIC_VOID: { 11271 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11272 Chain = Intrin->getChain(); 11273 // Intrin->getBasePtr() oddly does not get what we want. 11274 Base = Intrin->getOperand(3); 11275 MMO = Intrin->getMemOperand(); 11276 SrcOpnd = 2; 11277 break; 11278 } 11279 } 11280 11281 SDValue Src = N->getOperand(SrcOpnd); 11282 MVT VecTy = Src.getValueType().getSimpleVT(); 11283 11284 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 11285 // aligned and the type is a vector with elements up to 4 bytes 11286 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 11287 && VecTy.getScalarSizeInBits() <= 32 ) { 11288 return SDValue(); 11289 } 11290 11291 // All stores are done as v2f64 and possible bit cast. 11292 if (VecTy != MVT::v2f64) { 11293 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 11294 DCI.AddToWorklist(Src.getNode()); 11295 } 11296 11297 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 11298 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 11299 DCI.AddToWorklist(Swap.getNode()); 11300 Chain = Swap.getValue(1); 11301 SDValue StoreOps[] = { Chain, Swap, Base }; 11302 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 11303 DAG.getVTList(MVT::Other), 11304 StoreOps, VecTy, MMO); 11305 DCI.AddToWorklist(Store.getNode()); 11306 return Store; 11307 } 11308 11309 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 11310 DAGCombinerInfo &DCI) const { 11311 SelectionDAG &DAG = DCI.DAG; 11312 SDLoc dl(N); 11313 switch (N->getOpcode()) { 11314 default: break; 11315 case PPCISD::SHL: 11316 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 11317 return N->getOperand(0); 11318 break; 11319 case PPCISD::SRL: 11320 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 11321 return N->getOperand(0); 11322 break; 11323 case PPCISD::SRA: 11324 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11325 if (C->isNullValue() || // 0 >>s V -> 0. 11326 C->isAllOnesValue()) // -1 >>s V -> -1. 11327 return N->getOperand(0); 11328 } 11329 break; 11330 case ISD::SIGN_EXTEND: 11331 case ISD::ZERO_EXTEND: 11332 case ISD::ANY_EXTEND: 11333 return DAGCombineExtBoolTrunc(N, DCI); 11334 case ISD::TRUNCATE: 11335 case ISD::SETCC: 11336 case ISD::SELECT_CC: 11337 return DAGCombineTruncBoolExt(N, DCI); 11338 case ISD::SINT_TO_FP: 11339 case ISD::UINT_TO_FP: 11340 return combineFPToIntToFP(N, DCI); 11341 case ISD::STORE: { 11342 EVT Op1VT = N->getOperand(1).getValueType(); 11343 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) || 11344 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16)); 11345 11346 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 11347 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 11348 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 11349 ValidTypeForStoreFltAsInt && 11350 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 11351 SDValue Val = N->getOperand(1).getOperand(0); 11352 if (Val.getValueType() == MVT::f32) { 11353 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 11354 DCI.AddToWorklist(Val.getNode()); 11355 } 11356 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 11357 DCI.AddToWorklist(Val.getNode()); 11358 11359 if (Op1VT == MVT::i32) { 11360 SDValue Ops[] = { 11361 N->getOperand(0), Val, N->getOperand(2), 11362 DAG.getValueType(N->getOperand(1).getValueType()) 11363 }; 11364 11365 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 11366 DAG.getVTList(MVT::Other), Ops, 11367 cast<StoreSDNode>(N)->getMemoryVT(), 11368 cast<StoreSDNode>(N)->getMemOperand()); 11369 } else { 11370 unsigned WidthInBytes = 11371 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2; 11372 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false); 11373 11374 SDValue Ops[] = { 11375 N->getOperand(0), Val, N->getOperand(2), WidthConst, 11376 DAG.getValueType(N->getOperand(1).getValueType()) 11377 }; 11378 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl, 11379 DAG.getVTList(MVT::Other), Ops, 11380 cast<StoreSDNode>(N)->getMemoryVT(), 11381 cast<StoreSDNode>(N)->getMemOperand()); 11382 } 11383 11384 DCI.AddToWorklist(Val.getNode()); 11385 return Val; 11386 } 11387 11388 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 11389 if (cast<StoreSDNode>(N)->isUnindexed() && 11390 N->getOperand(1).getOpcode() == ISD::BSWAP && 11391 N->getOperand(1).getNode()->hasOneUse() && 11392 (N->getOperand(1).getValueType() == MVT::i32 || 11393 N->getOperand(1).getValueType() == MVT::i16 || 11394 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 11395 N->getOperand(1).getValueType() == MVT::i64))) { 11396 SDValue BSwapOp = N->getOperand(1).getOperand(0); 11397 // Do an any-extend to 32-bits if this is a half-word input. 11398 if (BSwapOp.getValueType() == MVT::i16) 11399 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 11400 11401 // If the type of BSWAP operand is wider than stored memory width 11402 // it need to be shifted to the right side before STBRX. 11403 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 11404 if (Op1VT.bitsGT(mVT)) { 11405 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 11406 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 11407 DAG.getConstant(Shift, dl, MVT::i32)); 11408 // Need to truncate if this is a bswap of i64 stored as i32/i16. 11409 if (Op1VT == MVT::i64) 11410 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 11411 } 11412 11413 SDValue Ops[] = { 11414 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 11415 }; 11416 return 11417 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 11418 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 11419 cast<StoreSDNode>(N)->getMemOperand()); 11420 } 11421 11422 // For little endian, VSX stores require generating xxswapd/lxvd2x. 11423 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 11424 EVT VT = N->getOperand(1).getValueType(); 11425 if (VT.isSimple()) { 11426 MVT StoreVT = VT.getSimpleVT(); 11427 if (Subtarget.needsSwapsForVSXMemOps() && 11428 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 11429 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 11430 return expandVSXStoreForLE(N, DCI); 11431 } 11432 break; 11433 } 11434 case ISD::LOAD: { 11435 LoadSDNode *LD = cast<LoadSDNode>(N); 11436 EVT VT = LD->getValueType(0); 11437 11438 // For little endian, VSX loads require generating lxvd2x/xxswapd. 11439 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 11440 if (VT.isSimple()) { 11441 MVT LoadVT = VT.getSimpleVT(); 11442 if (Subtarget.needsSwapsForVSXMemOps() && 11443 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 11444 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 11445 return expandVSXLoadForLE(N, DCI); 11446 } 11447 11448 // We sometimes end up with a 64-bit integer load, from which we extract 11449 // two single-precision floating-point numbers. This happens with 11450 // std::complex<float>, and other similar structures, because of the way we 11451 // canonicalize structure copies. However, if we lack direct moves, 11452 // then the final bitcasts from the extracted integer values to the 11453 // floating-point numbers turn into store/load pairs. Even with direct moves, 11454 // just loading the two floating-point numbers is likely better. 11455 auto ReplaceTwoFloatLoad = [&]() { 11456 if (VT != MVT::i64) 11457 return false; 11458 11459 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 11460 LD->isVolatile()) 11461 return false; 11462 11463 // We're looking for a sequence like this: 11464 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 11465 // t16: i64 = srl t13, Constant:i32<32> 11466 // t17: i32 = truncate t16 11467 // t18: f32 = bitcast t17 11468 // t19: i32 = truncate t13 11469 // t20: f32 = bitcast t19 11470 11471 if (!LD->hasNUsesOfValue(2, 0)) 11472 return false; 11473 11474 auto UI = LD->use_begin(); 11475 while (UI.getUse().getResNo() != 0) ++UI; 11476 SDNode *Trunc = *UI++; 11477 while (UI.getUse().getResNo() != 0) ++UI; 11478 SDNode *RightShift = *UI; 11479 if (Trunc->getOpcode() != ISD::TRUNCATE) 11480 std::swap(Trunc, RightShift); 11481 11482 if (Trunc->getOpcode() != ISD::TRUNCATE || 11483 Trunc->getValueType(0) != MVT::i32 || 11484 !Trunc->hasOneUse()) 11485 return false; 11486 if (RightShift->getOpcode() != ISD::SRL || 11487 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 11488 RightShift->getConstantOperandVal(1) != 32 || 11489 !RightShift->hasOneUse()) 11490 return false; 11491 11492 SDNode *Trunc2 = *RightShift->use_begin(); 11493 if (Trunc2->getOpcode() != ISD::TRUNCATE || 11494 Trunc2->getValueType(0) != MVT::i32 || 11495 !Trunc2->hasOneUse()) 11496 return false; 11497 11498 SDNode *Bitcast = *Trunc->use_begin(); 11499 SDNode *Bitcast2 = *Trunc2->use_begin(); 11500 11501 if (Bitcast->getOpcode() != ISD::BITCAST || 11502 Bitcast->getValueType(0) != MVT::f32) 11503 return false; 11504 if (Bitcast2->getOpcode() != ISD::BITCAST || 11505 Bitcast2->getValueType(0) != MVT::f32) 11506 return false; 11507 11508 if (Subtarget.isLittleEndian()) 11509 std::swap(Bitcast, Bitcast2); 11510 11511 // Bitcast has the second float (in memory-layout order) and Bitcast2 11512 // has the first one. 11513 11514 SDValue BasePtr = LD->getBasePtr(); 11515 if (LD->isIndexed()) { 11516 assert(LD->getAddressingMode() == ISD::PRE_INC && 11517 "Non-pre-inc AM on PPC?"); 11518 BasePtr = 11519 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 11520 LD->getOffset()); 11521 } 11522 11523 auto MMOFlags = 11524 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 11525 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 11526 LD->getPointerInfo(), LD->getAlignment(), 11527 MMOFlags, LD->getAAInfo()); 11528 SDValue AddPtr = 11529 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 11530 BasePtr, DAG.getIntPtrConstant(4, dl)); 11531 SDValue FloatLoad2 = DAG.getLoad( 11532 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 11533 LD->getPointerInfo().getWithOffset(4), 11534 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 11535 11536 if (LD->isIndexed()) { 11537 // Note that DAGCombine should re-form any pre-increment load(s) from 11538 // what is produced here if that makes sense. 11539 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 11540 } 11541 11542 DCI.CombineTo(Bitcast2, FloatLoad); 11543 DCI.CombineTo(Bitcast, FloatLoad2); 11544 11545 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 11546 SDValue(FloatLoad2.getNode(), 1)); 11547 return true; 11548 }; 11549 11550 if (ReplaceTwoFloatLoad()) 11551 return SDValue(N, 0); 11552 11553 EVT MemVT = LD->getMemoryVT(); 11554 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 11555 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 11556 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 11557 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 11558 if (LD->isUnindexed() && VT.isVector() && 11559 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 11560 // P8 and later hardware should just use LOAD. 11561 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 11562 VT == MVT::v4i32 || VT == MVT::v4f32)) || 11563 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 11564 LD->getAlignment() >= ScalarABIAlignment)) && 11565 LD->getAlignment() < ABIAlignment) { 11566 // This is a type-legal unaligned Altivec or QPX load. 11567 SDValue Chain = LD->getChain(); 11568 SDValue Ptr = LD->getBasePtr(); 11569 bool isLittleEndian = Subtarget.isLittleEndian(); 11570 11571 // This implements the loading of unaligned vectors as described in 11572 // the venerable Apple Velocity Engine overview. Specifically: 11573 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 11574 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 11575 // 11576 // The general idea is to expand a sequence of one or more unaligned 11577 // loads into an alignment-based permutation-control instruction (lvsl 11578 // or lvsr), a series of regular vector loads (which always truncate 11579 // their input address to an aligned address), and a series of 11580 // permutations. The results of these permutations are the requested 11581 // loaded values. The trick is that the last "extra" load is not taken 11582 // from the address you might suspect (sizeof(vector) bytes after the 11583 // last requested load), but rather sizeof(vector) - 1 bytes after the 11584 // last requested vector. The point of this is to avoid a page fault if 11585 // the base address happened to be aligned. This works because if the 11586 // base address is aligned, then adding less than a full vector length 11587 // will cause the last vector in the sequence to be (re)loaded. 11588 // Otherwise, the next vector will be fetched as you might suspect was 11589 // necessary. 11590 11591 // We might be able to reuse the permutation generation from 11592 // a different base address offset from this one by an aligned amount. 11593 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 11594 // optimization later. 11595 Intrinsic::ID Intr, IntrLD, IntrPerm; 11596 MVT PermCntlTy, PermTy, LDTy; 11597 if (Subtarget.hasAltivec()) { 11598 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 11599 Intrinsic::ppc_altivec_lvsl; 11600 IntrLD = Intrinsic::ppc_altivec_lvx; 11601 IntrPerm = Intrinsic::ppc_altivec_vperm; 11602 PermCntlTy = MVT::v16i8; 11603 PermTy = MVT::v4i32; 11604 LDTy = MVT::v4i32; 11605 } else { 11606 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 11607 Intrinsic::ppc_qpx_qvlpcls; 11608 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 11609 Intrinsic::ppc_qpx_qvlfs; 11610 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 11611 PermCntlTy = MVT::v4f64; 11612 PermTy = MVT::v4f64; 11613 LDTy = MemVT.getSimpleVT(); 11614 } 11615 11616 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 11617 11618 // Create the new MMO for the new base load. It is like the original MMO, 11619 // but represents an area in memory almost twice the vector size centered 11620 // on the original address. If the address is unaligned, we might start 11621 // reading up to (sizeof(vector)-1) bytes below the address of the 11622 // original unaligned load. 11623 MachineFunction &MF = DAG.getMachineFunction(); 11624 MachineMemOperand *BaseMMO = 11625 MF.getMachineMemOperand(LD->getMemOperand(), 11626 -(long)MemVT.getStoreSize()+1, 11627 2*MemVT.getStoreSize()-1); 11628 11629 // Create the new base load. 11630 SDValue LDXIntID = 11631 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 11632 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 11633 SDValue BaseLoad = 11634 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 11635 DAG.getVTList(PermTy, MVT::Other), 11636 BaseLoadOps, LDTy, BaseMMO); 11637 11638 // Note that the value of IncOffset (which is provided to the next 11639 // load's pointer info offset value, and thus used to calculate the 11640 // alignment), and the value of IncValue (which is actually used to 11641 // increment the pointer value) are different! This is because we 11642 // require the next load to appear to be aligned, even though it 11643 // is actually offset from the base pointer by a lesser amount. 11644 int IncOffset = VT.getSizeInBits() / 8; 11645 int IncValue = IncOffset; 11646 11647 // Walk (both up and down) the chain looking for another load at the real 11648 // (aligned) offset (the alignment of the other load does not matter in 11649 // this case). If found, then do not use the offset reduction trick, as 11650 // that will prevent the loads from being later combined (as they would 11651 // otherwise be duplicates). 11652 if (!findConsecutiveLoad(LD, DAG)) 11653 --IncValue; 11654 11655 SDValue Increment = 11656 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 11657 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 11658 11659 MachineMemOperand *ExtraMMO = 11660 MF.getMachineMemOperand(LD->getMemOperand(), 11661 1, 2*MemVT.getStoreSize()-1); 11662 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 11663 SDValue ExtraLoad = 11664 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 11665 DAG.getVTList(PermTy, MVT::Other), 11666 ExtraLoadOps, LDTy, ExtraMMO); 11667 11668 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 11669 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 11670 11671 // Because vperm has a big-endian bias, we must reverse the order 11672 // of the input vectors and complement the permute control vector 11673 // when generating little endian code. We have already handled the 11674 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 11675 // and ExtraLoad here. 11676 SDValue Perm; 11677 if (isLittleEndian) 11678 Perm = BuildIntrinsicOp(IntrPerm, 11679 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 11680 else 11681 Perm = BuildIntrinsicOp(IntrPerm, 11682 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 11683 11684 if (VT != PermTy) 11685 Perm = Subtarget.hasAltivec() ? 11686 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 11687 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 11688 DAG.getTargetConstant(1, dl, MVT::i64)); 11689 // second argument is 1 because this rounding 11690 // is always exact. 11691 11692 // The output of the permutation is our loaded result, the TokenFactor is 11693 // our new chain. 11694 DCI.CombineTo(N, Perm, TF); 11695 return SDValue(N, 0); 11696 } 11697 } 11698 break; 11699 case ISD::INTRINSIC_WO_CHAIN: { 11700 bool isLittleEndian = Subtarget.isLittleEndian(); 11701 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11702 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 11703 : Intrinsic::ppc_altivec_lvsl); 11704 if ((IID == Intr || 11705 IID == Intrinsic::ppc_qpx_qvlpcld || 11706 IID == Intrinsic::ppc_qpx_qvlpcls) && 11707 N->getOperand(1)->getOpcode() == ISD::ADD) { 11708 SDValue Add = N->getOperand(1); 11709 11710 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 11711 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 11712 11713 if (DAG.MaskedValueIsZero(Add->getOperand(1), 11714 APInt::getAllOnesValue(Bits /* alignment */) 11715 .zext(Add.getScalarValueSizeInBits()))) { 11716 SDNode *BasePtr = Add->getOperand(0).getNode(); 11717 for (SDNode::use_iterator UI = BasePtr->use_begin(), 11718 UE = BasePtr->use_end(); 11719 UI != UE; ++UI) { 11720 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 11721 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 11722 // We've found another LVSL/LVSR, and this address is an aligned 11723 // multiple of that one. The results will be the same, so use the 11724 // one we've just found instead. 11725 11726 return SDValue(*UI, 0); 11727 } 11728 } 11729 } 11730 11731 if (isa<ConstantSDNode>(Add->getOperand(1))) { 11732 SDNode *BasePtr = Add->getOperand(0).getNode(); 11733 for (SDNode::use_iterator UI = BasePtr->use_begin(), 11734 UE = BasePtr->use_end(); UI != UE; ++UI) { 11735 if (UI->getOpcode() == ISD::ADD && 11736 isa<ConstantSDNode>(UI->getOperand(1)) && 11737 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 11738 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 11739 (1ULL << Bits) == 0) { 11740 SDNode *OtherAdd = *UI; 11741 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 11742 VE = OtherAdd->use_end(); VI != VE; ++VI) { 11743 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 11744 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 11745 return SDValue(*VI, 0); 11746 } 11747 } 11748 } 11749 } 11750 } 11751 } 11752 } 11753 11754 break; 11755 case ISD::INTRINSIC_W_CHAIN: 11756 // For little endian, VSX loads require generating lxvd2x/xxswapd. 11757 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 11758 if (Subtarget.needsSwapsForVSXMemOps()) { 11759 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11760 default: 11761 break; 11762 case Intrinsic::ppc_vsx_lxvw4x: 11763 case Intrinsic::ppc_vsx_lxvd2x: 11764 return expandVSXLoadForLE(N, DCI); 11765 } 11766 } 11767 break; 11768 case ISD::INTRINSIC_VOID: 11769 // For little endian, VSX stores require generating xxswapd/stxvd2x. 11770 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 11771 if (Subtarget.needsSwapsForVSXMemOps()) { 11772 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11773 default: 11774 break; 11775 case Intrinsic::ppc_vsx_stxvw4x: 11776 case Intrinsic::ppc_vsx_stxvd2x: 11777 return expandVSXStoreForLE(N, DCI); 11778 } 11779 } 11780 break; 11781 case ISD::BSWAP: 11782 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 11783 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 11784 N->getOperand(0).hasOneUse() && 11785 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 11786 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 11787 N->getValueType(0) == MVT::i64))) { 11788 SDValue Load = N->getOperand(0); 11789 LoadSDNode *LD = cast<LoadSDNode>(Load); 11790 // Create the byte-swapping load. 11791 SDValue Ops[] = { 11792 LD->getChain(), // Chain 11793 LD->getBasePtr(), // Ptr 11794 DAG.getValueType(N->getValueType(0)) // VT 11795 }; 11796 SDValue BSLoad = 11797 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 11798 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 11799 MVT::i64 : MVT::i32, MVT::Other), 11800 Ops, LD->getMemoryVT(), LD->getMemOperand()); 11801 11802 // If this is an i16 load, insert the truncate. 11803 SDValue ResVal = BSLoad; 11804 if (N->getValueType(0) == MVT::i16) 11805 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 11806 11807 // First, combine the bswap away. This makes the value produced by the 11808 // load dead. 11809 DCI.CombineTo(N, ResVal); 11810 11811 // Next, combine the load away, we give it a bogus result value but a real 11812 // chain result. The result value is dead because the bswap is dead. 11813 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 11814 11815 // Return N so it doesn't get rechecked! 11816 return SDValue(N, 0); 11817 } 11818 break; 11819 case PPCISD::VCMP: 11820 // If a VCMPo node already exists with exactly the same operands as this 11821 // node, use its result instead of this node (VCMPo computes both a CR6 and 11822 // a normal output). 11823 // 11824 if (!N->getOperand(0).hasOneUse() && 11825 !N->getOperand(1).hasOneUse() && 11826 !N->getOperand(2).hasOneUse()) { 11827 11828 // Scan all of the users of the LHS, looking for VCMPo's that match. 11829 SDNode *VCMPoNode = nullptr; 11830 11831 SDNode *LHSN = N->getOperand(0).getNode(); 11832 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 11833 UI != E; ++UI) 11834 if (UI->getOpcode() == PPCISD::VCMPo && 11835 UI->getOperand(1) == N->getOperand(1) && 11836 UI->getOperand(2) == N->getOperand(2) && 11837 UI->getOperand(0) == N->getOperand(0)) { 11838 VCMPoNode = *UI; 11839 break; 11840 } 11841 11842 // If there is no VCMPo node, or if the flag value has a single use, don't 11843 // transform this. 11844 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 11845 break; 11846 11847 // Look at the (necessarily single) use of the flag value. If it has a 11848 // chain, this transformation is more complex. Note that multiple things 11849 // could use the value result, which we should ignore. 11850 SDNode *FlagUser = nullptr; 11851 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 11852 FlagUser == nullptr; ++UI) { 11853 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 11854 SDNode *User = *UI; 11855 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 11856 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 11857 FlagUser = User; 11858 break; 11859 } 11860 } 11861 } 11862 11863 // If the user is a MFOCRF instruction, we know this is safe. 11864 // Otherwise we give up for right now. 11865 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 11866 return SDValue(VCMPoNode, 0); 11867 } 11868 break; 11869 case ISD::BRCOND: { 11870 SDValue Cond = N->getOperand(1); 11871 SDValue Target = N->getOperand(2); 11872 11873 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 11874 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 11875 Intrinsic::ppc_is_decremented_ctr_nonzero) { 11876 11877 // We now need to make the intrinsic dead (it cannot be instruction 11878 // selected). 11879 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 11880 assert(Cond.getNode()->hasOneUse() && 11881 "Counter decrement has more than one use"); 11882 11883 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 11884 N->getOperand(0), Target); 11885 } 11886 } 11887 break; 11888 case ISD::BR_CC: { 11889 // If this is a branch on an altivec predicate comparison, lower this so 11890 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 11891 // lowering is done pre-legalize, because the legalizer lowers the predicate 11892 // compare down to code that is difficult to reassemble. 11893 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 11894 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 11895 11896 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 11897 // value. If so, pass-through the AND to get to the intrinsic. 11898 if (LHS.getOpcode() == ISD::AND && 11899 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 11900 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 11901 Intrinsic::ppc_is_decremented_ctr_nonzero && 11902 isa<ConstantSDNode>(LHS.getOperand(1)) && 11903 !isNullConstant(LHS.getOperand(1))) 11904 LHS = LHS.getOperand(0); 11905 11906 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 11907 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 11908 Intrinsic::ppc_is_decremented_ctr_nonzero && 11909 isa<ConstantSDNode>(RHS)) { 11910 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 11911 "Counter decrement comparison is not EQ or NE"); 11912 11913 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 11914 bool isBDNZ = (CC == ISD::SETEQ && Val) || 11915 (CC == ISD::SETNE && !Val); 11916 11917 // We now need to make the intrinsic dead (it cannot be instruction 11918 // selected). 11919 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 11920 assert(LHS.getNode()->hasOneUse() && 11921 "Counter decrement has more than one use"); 11922 11923 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 11924 N->getOperand(0), N->getOperand(4)); 11925 } 11926 11927 int CompareOpc; 11928 bool isDot; 11929 11930 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 11931 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 11932 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 11933 assert(isDot && "Can't compare against a vector result!"); 11934 11935 // If this is a comparison against something other than 0/1, then we know 11936 // that the condition is never/always true. 11937 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 11938 if (Val != 0 && Val != 1) { 11939 if (CC == ISD::SETEQ) // Cond never true, remove branch. 11940 return N->getOperand(0); 11941 // Always !=, turn it into an unconditional branch. 11942 return DAG.getNode(ISD::BR, dl, MVT::Other, 11943 N->getOperand(0), N->getOperand(4)); 11944 } 11945 11946 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 11947 11948 // Create the PPCISD altivec 'dot' comparison node. 11949 SDValue Ops[] = { 11950 LHS.getOperand(2), // LHS of compare 11951 LHS.getOperand(3), // RHS of compare 11952 DAG.getConstant(CompareOpc, dl, MVT::i32) 11953 }; 11954 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 11955 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 11956 11957 // Unpack the result based on how the target uses it. 11958 PPC::Predicate CompOpc; 11959 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 11960 default: // Can't happen, don't crash on invalid number though. 11961 case 0: // Branch on the value of the EQ bit of CR6. 11962 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 11963 break; 11964 case 1: // Branch on the inverted value of the EQ bit of CR6. 11965 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 11966 break; 11967 case 2: // Branch on the value of the LT bit of CR6. 11968 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 11969 break; 11970 case 3: // Branch on the inverted value of the LT bit of CR6. 11971 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 11972 break; 11973 } 11974 11975 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 11976 DAG.getConstant(CompOpc, dl, MVT::i32), 11977 DAG.getRegister(PPC::CR6, MVT::i32), 11978 N->getOperand(4), CompNode.getValue(1)); 11979 } 11980 break; 11981 } 11982 case ISD::BUILD_VECTOR: 11983 return DAGCombineBuildVector(N, DCI); 11984 } 11985 11986 return SDValue(); 11987 } 11988 11989 SDValue 11990 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11991 SelectionDAG &DAG, 11992 std::vector<SDNode *> *Created) const { 11993 // fold (sdiv X, pow2) 11994 EVT VT = N->getValueType(0); 11995 if (VT == MVT::i64 && !Subtarget.isPPC64()) 11996 return SDValue(); 11997 if ((VT != MVT::i32 && VT != MVT::i64) || 11998 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 11999 return SDValue(); 12000 12001 SDLoc DL(N); 12002 SDValue N0 = N->getOperand(0); 12003 12004 bool IsNegPow2 = (-Divisor).isPowerOf2(); 12005 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 12006 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 12007 12008 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 12009 if (Created) 12010 Created->push_back(Op.getNode()); 12011 12012 if (IsNegPow2) { 12013 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 12014 if (Created) 12015 Created->push_back(Op.getNode()); 12016 } 12017 12018 return Op; 12019 } 12020 12021 //===----------------------------------------------------------------------===// 12022 // Inline Assembly Support 12023 //===----------------------------------------------------------------------===// 12024 12025 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12026 KnownBits &Known, 12027 const APInt &DemandedElts, 12028 const SelectionDAG &DAG, 12029 unsigned Depth) const { 12030 Known.resetAll(); 12031 switch (Op.getOpcode()) { 12032 default: break; 12033 case PPCISD::LBRX: { 12034 // lhbrx is known to have the top bits cleared out. 12035 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 12036 Known.Zero = 0xFFFF0000; 12037 break; 12038 } 12039 case ISD::INTRINSIC_WO_CHAIN: { 12040 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 12041 default: break; 12042 case Intrinsic::ppc_altivec_vcmpbfp_p: 12043 case Intrinsic::ppc_altivec_vcmpeqfp_p: 12044 case Intrinsic::ppc_altivec_vcmpequb_p: 12045 case Intrinsic::ppc_altivec_vcmpequh_p: 12046 case Intrinsic::ppc_altivec_vcmpequw_p: 12047 case Intrinsic::ppc_altivec_vcmpequd_p: 12048 case Intrinsic::ppc_altivec_vcmpgefp_p: 12049 case Intrinsic::ppc_altivec_vcmpgtfp_p: 12050 case Intrinsic::ppc_altivec_vcmpgtsb_p: 12051 case Intrinsic::ppc_altivec_vcmpgtsh_p: 12052 case Intrinsic::ppc_altivec_vcmpgtsw_p: 12053 case Intrinsic::ppc_altivec_vcmpgtsd_p: 12054 case Intrinsic::ppc_altivec_vcmpgtub_p: 12055 case Intrinsic::ppc_altivec_vcmpgtuh_p: 12056 case Intrinsic::ppc_altivec_vcmpgtuw_p: 12057 case Intrinsic::ppc_altivec_vcmpgtud_p: 12058 Known.Zero = ~1U; // All bits but the low one are known to be zero. 12059 break; 12060 } 12061 } 12062 } 12063 } 12064 12065 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12066 switch (Subtarget.getDarwinDirective()) { 12067 default: break; 12068 case PPC::DIR_970: 12069 case PPC::DIR_PWR4: 12070 case PPC::DIR_PWR5: 12071 case PPC::DIR_PWR5X: 12072 case PPC::DIR_PWR6: 12073 case PPC::DIR_PWR6X: 12074 case PPC::DIR_PWR7: 12075 case PPC::DIR_PWR8: 12076 case PPC::DIR_PWR9: { 12077 if (!ML) 12078 break; 12079 12080 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 12081 12082 // For small loops (between 5 and 8 instructions), align to a 32-byte 12083 // boundary so that the entire loop fits in one instruction-cache line. 12084 uint64_t LoopSize = 0; 12085 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 12086 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 12087 LoopSize += TII->getInstSizeInBytes(*J); 12088 if (LoopSize > 32) 12089 break; 12090 } 12091 12092 if (LoopSize > 16 && LoopSize <= 32) 12093 return 5; 12094 12095 break; 12096 } 12097 } 12098 12099 return TargetLowering::getPrefLoopAlignment(ML); 12100 } 12101 12102 /// getConstraintType - Given a constraint, return the type of 12103 /// constraint it is for this target. 12104 PPCTargetLowering::ConstraintType 12105 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 12106 if (Constraint.size() == 1) { 12107 switch (Constraint[0]) { 12108 default: break; 12109 case 'b': 12110 case 'r': 12111 case 'f': 12112 case 'd': 12113 case 'v': 12114 case 'y': 12115 return C_RegisterClass; 12116 case 'Z': 12117 // FIXME: While Z does indicate a memory constraint, it specifically 12118 // indicates an r+r address (used in conjunction with the 'y' modifier 12119 // in the replacement string). Currently, we're forcing the base 12120 // register to be r0 in the asm printer (which is interpreted as zero) 12121 // and forming the complete address in the second register. This is 12122 // suboptimal. 12123 return C_Memory; 12124 } 12125 } else if (Constraint == "wc") { // individual CR bits. 12126 return C_RegisterClass; 12127 } else if (Constraint == "wa" || Constraint == "wd" || 12128 Constraint == "wf" || Constraint == "ws") { 12129 return C_RegisterClass; // VSX registers. 12130 } 12131 return TargetLowering::getConstraintType(Constraint); 12132 } 12133 12134 /// Examine constraint type and operand type and determine a weight value. 12135 /// This object must already have been set up with the operand type 12136 /// and the current alternative constraint selected. 12137 TargetLowering::ConstraintWeight 12138 PPCTargetLowering::getSingleConstraintMatchWeight( 12139 AsmOperandInfo &info, const char *constraint) const { 12140 ConstraintWeight weight = CW_Invalid; 12141 Value *CallOperandVal = info.CallOperandVal; 12142 // If we don't have a value, we can't do a match, 12143 // but allow it at the lowest weight. 12144 if (!CallOperandVal) 12145 return CW_Default; 12146 Type *type = CallOperandVal->getType(); 12147 12148 // Look at the constraint type. 12149 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 12150 return CW_Register; // an individual CR bit. 12151 else if ((StringRef(constraint) == "wa" || 12152 StringRef(constraint) == "wd" || 12153 StringRef(constraint) == "wf") && 12154 type->isVectorTy()) 12155 return CW_Register; 12156 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 12157 return CW_Register; 12158 12159 switch (*constraint) { 12160 default: 12161 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12162 break; 12163 case 'b': 12164 if (type->isIntegerTy()) 12165 weight = CW_Register; 12166 break; 12167 case 'f': 12168 if (type->isFloatTy()) 12169 weight = CW_Register; 12170 break; 12171 case 'd': 12172 if (type->isDoubleTy()) 12173 weight = CW_Register; 12174 break; 12175 case 'v': 12176 if (type->isVectorTy()) 12177 weight = CW_Register; 12178 break; 12179 case 'y': 12180 weight = CW_Register; 12181 break; 12182 case 'Z': 12183 weight = CW_Memory; 12184 break; 12185 } 12186 return weight; 12187 } 12188 12189 std::pair<unsigned, const TargetRegisterClass *> 12190 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 12191 StringRef Constraint, 12192 MVT VT) const { 12193 if (Constraint.size() == 1) { 12194 // GCC RS6000 Constraint Letters 12195 switch (Constraint[0]) { 12196 case 'b': // R1-R31 12197 if (VT == MVT::i64 && Subtarget.isPPC64()) 12198 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 12199 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 12200 case 'r': // R0-R31 12201 if (VT == MVT::i64 && Subtarget.isPPC64()) 12202 return std::make_pair(0U, &PPC::G8RCRegClass); 12203 return std::make_pair(0U, &PPC::GPRCRegClass); 12204 // 'd' and 'f' constraints are both defined to be "the floating point 12205 // registers", where one is for 32-bit and the other for 64-bit. We don't 12206 // really care overly much here so just give them all the same reg classes. 12207 case 'd': 12208 case 'f': 12209 if (VT == MVT::f32 || VT == MVT::i32) 12210 return std::make_pair(0U, &PPC::F4RCRegClass); 12211 if (VT == MVT::f64 || VT == MVT::i64) 12212 return std::make_pair(0U, &PPC::F8RCRegClass); 12213 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 12214 return std::make_pair(0U, &PPC::QFRCRegClass); 12215 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 12216 return std::make_pair(0U, &PPC::QSRCRegClass); 12217 break; 12218 case 'v': 12219 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 12220 return std::make_pair(0U, &PPC::QFRCRegClass); 12221 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 12222 return std::make_pair(0U, &PPC::QSRCRegClass); 12223 if (Subtarget.hasAltivec()) 12224 return std::make_pair(0U, &PPC::VRRCRegClass); 12225 case 'y': // crrc 12226 return std::make_pair(0U, &PPC::CRRCRegClass); 12227 } 12228 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 12229 // An individual CR bit. 12230 return std::make_pair(0U, &PPC::CRBITRCRegClass); 12231 } else if ((Constraint == "wa" || Constraint == "wd" || 12232 Constraint == "wf") && Subtarget.hasVSX()) { 12233 return std::make_pair(0U, &PPC::VSRCRegClass); 12234 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 12235 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 12236 return std::make_pair(0U, &PPC::VSSRCRegClass); 12237 else 12238 return std::make_pair(0U, &PPC::VSFRCRegClass); 12239 } 12240 12241 std::pair<unsigned, const TargetRegisterClass *> R = 12242 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12243 12244 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 12245 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 12246 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 12247 // register. 12248 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 12249 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 12250 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 12251 PPC::GPRCRegClass.contains(R.first)) 12252 return std::make_pair(TRI->getMatchingSuperReg(R.first, 12253 PPC::sub_32, &PPC::G8RCRegClass), 12254 &PPC::G8RCRegClass); 12255 12256 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 12257 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 12258 R.first = PPC::CR0; 12259 R.second = &PPC::CRRCRegClass; 12260 } 12261 12262 return R; 12263 } 12264 12265 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12266 /// vector. If it is invalid, don't add anything to Ops. 12267 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12268 std::string &Constraint, 12269 std::vector<SDValue>&Ops, 12270 SelectionDAG &DAG) const { 12271 SDValue Result; 12272 12273 // Only support length 1 constraints. 12274 if (Constraint.length() > 1) return; 12275 12276 char Letter = Constraint[0]; 12277 switch (Letter) { 12278 default: break; 12279 case 'I': 12280 case 'J': 12281 case 'K': 12282 case 'L': 12283 case 'M': 12284 case 'N': 12285 case 'O': 12286 case 'P': { 12287 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 12288 if (!CST) return; // Must be an immediate to match. 12289 SDLoc dl(Op); 12290 int64_t Value = CST->getSExtValue(); 12291 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 12292 // numbers are printed as such. 12293 switch (Letter) { 12294 default: llvm_unreachable("Unknown constraint letter!"); 12295 case 'I': // "I" is a signed 16-bit constant. 12296 if (isInt<16>(Value)) 12297 Result = DAG.getTargetConstant(Value, dl, TCVT); 12298 break; 12299 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 12300 if (isShiftedUInt<16, 16>(Value)) 12301 Result = DAG.getTargetConstant(Value, dl, TCVT); 12302 break; 12303 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 12304 if (isShiftedInt<16, 16>(Value)) 12305 Result = DAG.getTargetConstant(Value, dl, TCVT); 12306 break; 12307 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 12308 if (isUInt<16>(Value)) 12309 Result = DAG.getTargetConstant(Value, dl, TCVT); 12310 break; 12311 case 'M': // "M" is a constant that is greater than 31. 12312 if (Value > 31) 12313 Result = DAG.getTargetConstant(Value, dl, TCVT); 12314 break; 12315 case 'N': // "N" is a positive constant that is an exact power of two. 12316 if (Value > 0 && isPowerOf2_64(Value)) 12317 Result = DAG.getTargetConstant(Value, dl, TCVT); 12318 break; 12319 case 'O': // "O" is the constant zero. 12320 if (Value == 0) 12321 Result = DAG.getTargetConstant(Value, dl, TCVT); 12322 break; 12323 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 12324 if (isInt<16>(-Value)) 12325 Result = DAG.getTargetConstant(Value, dl, TCVT); 12326 break; 12327 } 12328 break; 12329 } 12330 } 12331 12332 if (Result.getNode()) { 12333 Ops.push_back(Result); 12334 return; 12335 } 12336 12337 // Handle standard constraint letters. 12338 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12339 } 12340 12341 // isLegalAddressingMode - Return true if the addressing mode represented 12342 // by AM is legal for this target, for a load/store of the specified type. 12343 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12344 const AddrMode &AM, Type *Ty, 12345 unsigned AS) const { 12346 // PPC does not allow r+i addressing modes for vectors! 12347 if (Ty->isVectorTy() && AM.BaseOffs != 0) 12348 return false; 12349 12350 // PPC allows a sign-extended 16-bit immediate field. 12351 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 12352 return false; 12353 12354 // No global is ever allowed as a base. 12355 if (AM.BaseGV) 12356 return false; 12357 12358 // PPC only support r+r, 12359 switch (AM.Scale) { 12360 case 0: // "r+i" or just "i", depending on HasBaseReg. 12361 break; 12362 case 1: 12363 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 12364 return false; 12365 // Otherwise we have r+r or r+i. 12366 break; 12367 case 2: 12368 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 12369 return false; 12370 // Allow 2*r as r+r. 12371 break; 12372 default: 12373 // No other scales are supported. 12374 return false; 12375 } 12376 12377 return true; 12378 } 12379 12380 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 12381 SelectionDAG &DAG) const { 12382 MachineFunction &MF = DAG.getMachineFunction(); 12383 MachineFrameInfo &MFI = MF.getFrameInfo(); 12384 MFI.setReturnAddressIsTaken(true); 12385 12386 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 12387 return SDValue(); 12388 12389 SDLoc dl(Op); 12390 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12391 12392 // Make sure the function does not optimize away the store of the RA to 12393 // the stack. 12394 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 12395 FuncInfo->setLRStoreRequired(); 12396 bool isPPC64 = Subtarget.isPPC64(); 12397 auto PtrVT = getPointerTy(MF.getDataLayout()); 12398 12399 if (Depth > 0) { 12400 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 12401 SDValue Offset = 12402 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 12403 isPPC64 ? MVT::i64 : MVT::i32); 12404 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 12405 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 12406 MachinePointerInfo()); 12407 } 12408 12409 // Just load the return address off the stack. 12410 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 12411 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 12412 MachinePointerInfo()); 12413 } 12414 12415 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 12416 SelectionDAG &DAG) const { 12417 SDLoc dl(Op); 12418 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12419 12420 MachineFunction &MF = DAG.getMachineFunction(); 12421 MachineFrameInfo &MFI = MF.getFrameInfo(); 12422 MFI.setFrameAddressIsTaken(true); 12423 12424 EVT PtrVT = getPointerTy(MF.getDataLayout()); 12425 bool isPPC64 = PtrVT == MVT::i64; 12426 12427 // Naked functions never have a frame pointer, and so we use r1. For all 12428 // other functions, this decision must be delayed until during PEI. 12429 unsigned FrameReg; 12430 if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) 12431 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 12432 else 12433 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 12434 12435 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 12436 PtrVT); 12437 while (Depth--) 12438 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 12439 FrameAddr, MachinePointerInfo()); 12440 return FrameAddr; 12441 } 12442 12443 // FIXME? Maybe this could be a TableGen attribute on some registers and 12444 // this table could be generated automatically from RegInfo. 12445 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 12446 SelectionDAG &DAG) const { 12447 bool isPPC64 = Subtarget.isPPC64(); 12448 bool isDarwinABI = Subtarget.isDarwinABI(); 12449 12450 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 12451 (!isPPC64 && VT != MVT::i32)) 12452 report_fatal_error("Invalid register global variable type"); 12453 12454 bool is64Bit = isPPC64 && VT == MVT::i64; 12455 unsigned Reg = StringSwitch<unsigned>(RegName) 12456 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 12457 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 12458 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 12459 (is64Bit ? PPC::X13 : PPC::R13)) 12460 .Default(0); 12461 12462 if (Reg) 12463 return Reg; 12464 report_fatal_error("Invalid register name global variable"); 12465 } 12466 12467 bool 12468 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12469 // The PowerPC target isn't yet aware of offsets. 12470 return false; 12471 } 12472 12473 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12474 const CallInst &I, 12475 unsigned Intrinsic) const { 12476 switch (Intrinsic) { 12477 case Intrinsic::ppc_qpx_qvlfd: 12478 case Intrinsic::ppc_qpx_qvlfs: 12479 case Intrinsic::ppc_qpx_qvlfcd: 12480 case Intrinsic::ppc_qpx_qvlfcs: 12481 case Intrinsic::ppc_qpx_qvlfiwa: 12482 case Intrinsic::ppc_qpx_qvlfiwz: 12483 case Intrinsic::ppc_altivec_lvx: 12484 case Intrinsic::ppc_altivec_lvxl: 12485 case Intrinsic::ppc_altivec_lvebx: 12486 case Intrinsic::ppc_altivec_lvehx: 12487 case Intrinsic::ppc_altivec_lvewx: 12488 case Intrinsic::ppc_vsx_lxvd2x: 12489 case Intrinsic::ppc_vsx_lxvw4x: { 12490 EVT VT; 12491 switch (Intrinsic) { 12492 case Intrinsic::ppc_altivec_lvebx: 12493 VT = MVT::i8; 12494 break; 12495 case Intrinsic::ppc_altivec_lvehx: 12496 VT = MVT::i16; 12497 break; 12498 case Intrinsic::ppc_altivec_lvewx: 12499 VT = MVT::i32; 12500 break; 12501 case Intrinsic::ppc_vsx_lxvd2x: 12502 VT = MVT::v2f64; 12503 break; 12504 case Intrinsic::ppc_qpx_qvlfd: 12505 VT = MVT::v4f64; 12506 break; 12507 case Intrinsic::ppc_qpx_qvlfs: 12508 VT = MVT::v4f32; 12509 break; 12510 case Intrinsic::ppc_qpx_qvlfcd: 12511 VT = MVT::v2f64; 12512 break; 12513 case Intrinsic::ppc_qpx_qvlfcs: 12514 VT = MVT::v2f32; 12515 break; 12516 default: 12517 VT = MVT::v4i32; 12518 break; 12519 } 12520 12521 Info.opc = ISD::INTRINSIC_W_CHAIN; 12522 Info.memVT = VT; 12523 Info.ptrVal = I.getArgOperand(0); 12524 Info.offset = -VT.getStoreSize()+1; 12525 Info.size = 2*VT.getStoreSize()-1; 12526 Info.align = 1; 12527 Info.vol = false; 12528 Info.readMem = true; 12529 Info.writeMem = false; 12530 return true; 12531 } 12532 case Intrinsic::ppc_qpx_qvlfda: 12533 case Intrinsic::ppc_qpx_qvlfsa: 12534 case Intrinsic::ppc_qpx_qvlfcda: 12535 case Intrinsic::ppc_qpx_qvlfcsa: 12536 case Intrinsic::ppc_qpx_qvlfiwaa: 12537 case Intrinsic::ppc_qpx_qvlfiwza: { 12538 EVT VT; 12539 switch (Intrinsic) { 12540 case Intrinsic::ppc_qpx_qvlfda: 12541 VT = MVT::v4f64; 12542 break; 12543 case Intrinsic::ppc_qpx_qvlfsa: 12544 VT = MVT::v4f32; 12545 break; 12546 case Intrinsic::ppc_qpx_qvlfcda: 12547 VT = MVT::v2f64; 12548 break; 12549 case Intrinsic::ppc_qpx_qvlfcsa: 12550 VT = MVT::v2f32; 12551 break; 12552 default: 12553 VT = MVT::v4i32; 12554 break; 12555 } 12556 12557 Info.opc = ISD::INTRINSIC_W_CHAIN; 12558 Info.memVT = VT; 12559 Info.ptrVal = I.getArgOperand(0); 12560 Info.offset = 0; 12561 Info.size = VT.getStoreSize(); 12562 Info.align = 1; 12563 Info.vol = false; 12564 Info.readMem = true; 12565 Info.writeMem = false; 12566 return true; 12567 } 12568 case Intrinsic::ppc_qpx_qvstfd: 12569 case Intrinsic::ppc_qpx_qvstfs: 12570 case Intrinsic::ppc_qpx_qvstfcd: 12571 case Intrinsic::ppc_qpx_qvstfcs: 12572 case Intrinsic::ppc_qpx_qvstfiw: 12573 case Intrinsic::ppc_altivec_stvx: 12574 case Intrinsic::ppc_altivec_stvxl: 12575 case Intrinsic::ppc_altivec_stvebx: 12576 case Intrinsic::ppc_altivec_stvehx: 12577 case Intrinsic::ppc_altivec_stvewx: 12578 case Intrinsic::ppc_vsx_stxvd2x: 12579 case Intrinsic::ppc_vsx_stxvw4x: { 12580 EVT VT; 12581 switch (Intrinsic) { 12582 case Intrinsic::ppc_altivec_stvebx: 12583 VT = MVT::i8; 12584 break; 12585 case Intrinsic::ppc_altivec_stvehx: 12586 VT = MVT::i16; 12587 break; 12588 case Intrinsic::ppc_altivec_stvewx: 12589 VT = MVT::i32; 12590 break; 12591 case Intrinsic::ppc_vsx_stxvd2x: 12592 VT = MVT::v2f64; 12593 break; 12594 case Intrinsic::ppc_qpx_qvstfd: 12595 VT = MVT::v4f64; 12596 break; 12597 case Intrinsic::ppc_qpx_qvstfs: 12598 VT = MVT::v4f32; 12599 break; 12600 case Intrinsic::ppc_qpx_qvstfcd: 12601 VT = MVT::v2f64; 12602 break; 12603 case Intrinsic::ppc_qpx_qvstfcs: 12604 VT = MVT::v2f32; 12605 break; 12606 default: 12607 VT = MVT::v4i32; 12608 break; 12609 } 12610 12611 Info.opc = ISD::INTRINSIC_VOID; 12612 Info.memVT = VT; 12613 Info.ptrVal = I.getArgOperand(1); 12614 Info.offset = -VT.getStoreSize()+1; 12615 Info.size = 2*VT.getStoreSize()-1; 12616 Info.align = 1; 12617 Info.vol = false; 12618 Info.readMem = false; 12619 Info.writeMem = true; 12620 return true; 12621 } 12622 case Intrinsic::ppc_qpx_qvstfda: 12623 case Intrinsic::ppc_qpx_qvstfsa: 12624 case Intrinsic::ppc_qpx_qvstfcda: 12625 case Intrinsic::ppc_qpx_qvstfcsa: 12626 case Intrinsic::ppc_qpx_qvstfiwa: { 12627 EVT VT; 12628 switch (Intrinsic) { 12629 case Intrinsic::ppc_qpx_qvstfda: 12630 VT = MVT::v4f64; 12631 break; 12632 case Intrinsic::ppc_qpx_qvstfsa: 12633 VT = MVT::v4f32; 12634 break; 12635 case Intrinsic::ppc_qpx_qvstfcda: 12636 VT = MVT::v2f64; 12637 break; 12638 case Intrinsic::ppc_qpx_qvstfcsa: 12639 VT = MVT::v2f32; 12640 break; 12641 default: 12642 VT = MVT::v4i32; 12643 break; 12644 } 12645 12646 Info.opc = ISD::INTRINSIC_VOID; 12647 Info.memVT = VT; 12648 Info.ptrVal = I.getArgOperand(1); 12649 Info.offset = 0; 12650 Info.size = VT.getStoreSize(); 12651 Info.align = 1; 12652 Info.vol = false; 12653 Info.readMem = false; 12654 Info.writeMem = true; 12655 return true; 12656 } 12657 default: 12658 break; 12659 } 12660 12661 return false; 12662 } 12663 12664 /// getOptimalMemOpType - Returns the target specific optimal type for load 12665 /// and store operations as a result of memset, memcpy, and memmove 12666 /// lowering. If DstAlign is zero that means it's safe to destination 12667 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 12668 /// means there isn't a need to check it against alignment requirement, 12669 /// probably because the source does not need to be loaded. If 'IsMemset' is 12670 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 12671 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 12672 /// source is constant so it does not need to be loaded. 12673 /// It returns EVT::Other if the type should be determined using generic 12674 /// target-independent logic. 12675 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 12676 unsigned DstAlign, unsigned SrcAlign, 12677 bool IsMemset, bool ZeroMemset, 12678 bool MemcpyStrSrc, 12679 MachineFunction &MF) const { 12680 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 12681 const Function *F = MF.getFunction(); 12682 // When expanding a memset, require at least two QPX instructions to cover 12683 // the cost of loading the value to be stored from the constant pool. 12684 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 12685 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 12686 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 12687 return MVT::v4f64; 12688 } 12689 12690 // We should use Altivec/VSX loads and stores when available. For unaligned 12691 // addresses, unaligned VSX loads are only fast starting with the P8. 12692 if (Subtarget.hasAltivec() && Size >= 16 && 12693 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 12694 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 12695 return MVT::v4i32; 12696 } 12697 12698 if (Subtarget.isPPC64()) { 12699 return MVT::i64; 12700 } 12701 12702 return MVT::i32; 12703 } 12704 12705 /// \brief Returns true if it is beneficial to convert a load of a constant 12706 /// to just the constant itself. 12707 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12708 Type *Ty) const { 12709 assert(Ty->isIntegerTy()); 12710 12711 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 12712 return !(BitSize == 0 || BitSize > 64); 12713 } 12714 12715 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 12716 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12717 return false; 12718 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 12719 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 12720 return NumBits1 == 64 && NumBits2 == 32; 12721 } 12722 12723 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 12724 if (!VT1.isInteger() || !VT2.isInteger()) 12725 return false; 12726 unsigned NumBits1 = VT1.getSizeInBits(); 12727 unsigned NumBits2 = VT2.getSizeInBits(); 12728 return NumBits1 == 64 && NumBits2 == 32; 12729 } 12730 12731 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12732 // Generally speaking, zexts are not free, but they are free when they can be 12733 // folded with other operations. 12734 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 12735 EVT MemVT = LD->getMemoryVT(); 12736 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 12737 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 12738 (LD->getExtensionType() == ISD::NON_EXTLOAD || 12739 LD->getExtensionType() == ISD::ZEXTLOAD)) 12740 return true; 12741 } 12742 12743 // FIXME: Add other cases... 12744 // - 32-bit shifts with a zext to i64 12745 // - zext after ctlz, bswap, etc. 12746 // - zext after and by a constant mask 12747 12748 return TargetLowering::isZExtFree(Val, VT2); 12749 } 12750 12751 bool PPCTargetLowering::isFPExtFree(EVT VT) const { 12752 assert(VT.isFloatingPoint()); 12753 return true; 12754 } 12755 12756 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12757 return isInt<16>(Imm) || isUInt<16>(Imm); 12758 } 12759 12760 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12761 return isInt<16>(Imm) || isUInt<16>(Imm); 12762 } 12763 12764 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12765 unsigned, 12766 unsigned, 12767 bool *Fast) const { 12768 if (DisablePPCUnaligned) 12769 return false; 12770 12771 // PowerPC supports unaligned memory access for simple non-vector types. 12772 // Although accessing unaligned addresses is not as efficient as accessing 12773 // aligned addresses, it is generally more efficient than manual expansion, 12774 // and generally only traps for software emulation when crossing page 12775 // boundaries. 12776 12777 if (!VT.isSimple()) 12778 return false; 12779 12780 if (VT.getSimpleVT().isVector()) { 12781 if (Subtarget.hasVSX()) { 12782 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 12783 VT != MVT::v4f32 && VT != MVT::v4i32) 12784 return false; 12785 } else { 12786 return false; 12787 } 12788 } 12789 12790 if (VT == MVT::ppcf128) 12791 return false; 12792 12793 if (Fast) 12794 *Fast = true; 12795 12796 return true; 12797 } 12798 12799 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 12800 VT = VT.getScalarType(); 12801 12802 if (!VT.isSimple()) 12803 return false; 12804 12805 switch (VT.getSimpleVT().SimpleTy) { 12806 case MVT::f32: 12807 case MVT::f64: 12808 return true; 12809 default: 12810 break; 12811 } 12812 12813 return false; 12814 } 12815 12816 const MCPhysReg * 12817 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 12818 // LR is a callee-save register, but we must treat it as clobbered by any call 12819 // site. Hence we include LR in the scratch registers, which are in turn added 12820 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 12821 // to CTR, which is used by any indirect call. 12822 static const MCPhysReg ScratchRegs[] = { 12823 PPC::X12, PPC::LR8, PPC::CTR8, 0 12824 }; 12825 12826 return ScratchRegs; 12827 } 12828 12829 unsigned PPCTargetLowering::getExceptionPointerRegister( 12830 const Constant *PersonalityFn) const { 12831 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 12832 } 12833 12834 unsigned PPCTargetLowering::getExceptionSelectorRegister( 12835 const Constant *PersonalityFn) const { 12836 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 12837 } 12838 12839 bool 12840 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 12841 EVT VT , unsigned DefinedValues) const { 12842 if (VT == MVT::v2i64) 12843 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 12844 12845 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 12846 return true; 12847 12848 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 12849 } 12850 12851 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 12852 if (DisableILPPref || Subtarget.enableMachineScheduler()) 12853 return TargetLowering::getSchedulingPreference(N); 12854 12855 return Sched::ILP; 12856 } 12857 12858 // Create a fast isel object. 12859 FastISel * 12860 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 12861 const TargetLibraryInfo *LibInfo) const { 12862 return PPC::createFastISel(FuncInfo, LibInfo); 12863 } 12864 12865 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12866 if (Subtarget.isDarwinABI()) return; 12867 if (!Subtarget.isPPC64()) return; 12868 12869 // Update IsSplitCSR in PPCFunctionInfo 12870 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 12871 PFI->setIsSplitCSR(true); 12872 } 12873 12874 void PPCTargetLowering::insertCopiesSplitCSR( 12875 MachineBasicBlock *Entry, 12876 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12877 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 12878 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12879 if (!IStart) 12880 return; 12881 12882 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12883 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12884 MachineBasicBlock::iterator MBBI = Entry->begin(); 12885 for (const MCPhysReg *I = IStart; *I; ++I) { 12886 const TargetRegisterClass *RC = nullptr; 12887 if (PPC::G8RCRegClass.contains(*I)) 12888 RC = &PPC::G8RCRegClass; 12889 else if (PPC::F8RCRegClass.contains(*I)) 12890 RC = &PPC::F8RCRegClass; 12891 else if (PPC::CRRCRegClass.contains(*I)) 12892 RC = &PPC::CRRCRegClass; 12893 else if (PPC::VRRCRegClass.contains(*I)) 12894 RC = &PPC::VRRCRegClass; 12895 else 12896 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12897 12898 unsigned NewVR = MRI->createVirtualRegister(RC); 12899 // Create copy from CSR to a virtual register. 12900 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12901 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12902 // nounwind. If we want to generalize this later, we may need to emit 12903 // CFI pseudo-instructions. 12904 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12905 Attribute::NoUnwind) && 12906 "Function should be nounwind in insertCopiesSplitCSR!"); 12907 Entry->addLiveIn(*I); 12908 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12909 .addReg(*I); 12910 12911 // Insert the copy-back instructions right before the terminator 12912 for (auto *Exit : Exits) 12913 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12914 TII->get(TargetOpcode::COPY), *I) 12915 .addReg(NewVR); 12916 } 12917 } 12918 12919 // Override to enable LOAD_STACK_GUARD lowering on Linux. 12920 bool PPCTargetLowering::useLoadStackGuardNode() const { 12921 if (!Subtarget.isTargetLinux()) 12922 return TargetLowering::useLoadStackGuardNode(); 12923 return true; 12924 } 12925 12926 // Override to disable global variable loading on Linux. 12927 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 12928 if (!Subtarget.isTargetLinux()) 12929 return TargetLowering::insertSSPDeclarations(M); 12930 } 12931 12932 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 12933 if (!VT.isSimple() || !Subtarget.hasVSX()) 12934 return false; 12935 12936 switch(VT.getSimpleVT().SimpleTy) { 12937 default: 12938 // For FP types that are currently not supported by PPC backend, return 12939 // false. Examples: f16, f80. 12940 return false; 12941 case MVT::f32: 12942 case MVT::f64: 12943 case MVT::ppcf128: 12944 return Imm.isPosZero(); 12945 } 12946 } 12947