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/MathExtras.h" 83 #include "llvm/Support/raw_ostream.h" 84 #include "llvm/Target/TargetInstrInfo.h" 85 #include "llvm/Target/TargetLowering.h" 86 #include "llvm/Target/TargetMachine.h" 87 #include "llvm/Target/TargetOptions.h" 88 #include "llvm/Target/TargetRegisterInfo.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstdint> 92 #include <iterator> 93 #include <list> 94 #include <utility> 95 #include <vector> 96 97 using namespace llvm; 98 99 #define DEBUG_TYPE "ppc-lowering" 100 101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 103 104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 106 107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 109 110 static cl::opt<bool> DisableSCO("disable-ppc-sco", 111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 112 113 STATISTIC(NumTailCalls, "Number of tail calls"); 114 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 115 116 // FIXME: Remove this once the bug has been fixed! 117 extern cl::opt<bool> ANDIGlueBug; 118 119 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 120 const PPCSubtarget &STI) 121 : TargetLowering(TM), Subtarget(STI) { 122 // Use _setjmp/_longjmp instead of setjmp/longjmp. 123 setUseUnderscoreSetJmp(true); 124 setUseUnderscoreLongJmp(true); 125 126 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 127 // arguments are at least 4/8 bytes aligned. 128 bool isPPC64 = Subtarget.isPPC64(); 129 setMinStackArgumentAlignment(isPPC64 ? 8:4); 130 131 // Set up the register classes. 132 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 133 if (!useSoftFloat()) { 134 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 135 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 136 } 137 138 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD 139 for (MVT VT : MVT::integer_valuetypes()) { 140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 142 } 143 144 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 145 146 // PowerPC has pre-inc load and store's. 147 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 148 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 149 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 150 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 151 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 152 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 153 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 154 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 155 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 156 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 157 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 158 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 159 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 160 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 161 162 if (Subtarget.useCRBits()) { 163 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 164 165 if (isPPC64 || Subtarget.hasFPCVT()) { 166 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 167 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 168 isPPC64 ? MVT::i64 : MVT::i32); 169 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 170 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 171 isPPC64 ? MVT::i64 : MVT::i32); 172 } else { 173 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 174 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 175 } 176 177 // PowerPC does not support direct load / store of condition registers 178 setOperationAction(ISD::LOAD, MVT::i1, Custom); 179 setOperationAction(ISD::STORE, MVT::i1, Custom); 180 181 // FIXME: Remove this once the ANDI glue bug is fixed: 182 if (ANDIGlueBug) 183 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 184 185 for (MVT VT : MVT::integer_valuetypes()) { 186 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 187 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 188 setTruncStoreAction(VT, MVT::i1, Expand); 189 } 190 191 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 192 } 193 194 // This is used in the ppcf128->int sequence. Note it has different semantics 195 // from FP_ROUND: that rounds to nearest, this rounds to zero. 196 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 197 198 // We do not currently implement these libm ops for PowerPC. 199 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 200 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 201 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 202 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 203 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 204 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 205 206 // PowerPC has no SREM/UREM instructions 207 setOperationAction(ISD::SREM, MVT::i32, Expand); 208 setOperationAction(ISD::UREM, MVT::i32, Expand); 209 setOperationAction(ISD::SREM, MVT::i64, Expand); 210 setOperationAction(ISD::UREM, MVT::i64, Expand); 211 212 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 213 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 214 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 215 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 216 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 217 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 218 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 219 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 220 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 221 222 // We don't support sin/cos/sqrt/fmod/pow 223 setOperationAction(ISD::FSIN , MVT::f64, Expand); 224 setOperationAction(ISD::FCOS , MVT::f64, Expand); 225 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 226 setOperationAction(ISD::FREM , MVT::f64, Expand); 227 setOperationAction(ISD::FPOW , MVT::f64, Expand); 228 setOperationAction(ISD::FMA , MVT::f64, Legal); 229 setOperationAction(ISD::FSIN , MVT::f32, Expand); 230 setOperationAction(ISD::FCOS , MVT::f32, Expand); 231 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 232 setOperationAction(ISD::FREM , MVT::f32, Expand); 233 setOperationAction(ISD::FPOW , MVT::f32, Expand); 234 setOperationAction(ISD::FMA , MVT::f32, Legal); 235 236 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 237 238 // If we're enabling GP optimizations, use hardware square root 239 if (!Subtarget.hasFSQRT() && 240 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 241 Subtarget.hasFRE())) 242 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 243 244 if (!Subtarget.hasFSQRT() && 245 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 246 Subtarget.hasFRES())) 247 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 248 249 if (Subtarget.hasFCPSGN()) { 250 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 251 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 252 } else { 253 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 254 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 255 } 256 257 if (Subtarget.hasFPRND()) { 258 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 259 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 260 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 261 setOperationAction(ISD::FROUND, MVT::f64, Legal); 262 263 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 264 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 265 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 266 setOperationAction(ISD::FROUND, MVT::f32, Legal); 267 } 268 269 // PowerPC does not have BSWAP 270 // CTPOP or CTTZ were introduced in P8/P9 respectivelly 271 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 272 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 273 if (Subtarget.isISA3_0()) { 274 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 275 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 276 } else { 277 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 278 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 279 } 280 281 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 282 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 283 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 284 } else { 285 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 286 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 287 } 288 289 // PowerPC does not have ROTR 290 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 291 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 292 293 if (!Subtarget.useCRBits()) { 294 // PowerPC does not have Select 295 setOperationAction(ISD::SELECT, MVT::i32, Expand); 296 setOperationAction(ISD::SELECT, MVT::i64, Expand); 297 setOperationAction(ISD::SELECT, MVT::f32, Expand); 298 setOperationAction(ISD::SELECT, MVT::f64, Expand); 299 } 300 301 // PowerPC wants to turn select_cc of FP into fsel when possible. 302 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 303 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 304 305 // PowerPC wants to optimize integer setcc a bit 306 if (!Subtarget.useCRBits()) 307 setOperationAction(ISD::SETCC, MVT::i32, Custom); 308 309 // PowerPC does not have BRCOND which requires SetCC 310 if (!Subtarget.useCRBits()) 311 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 312 313 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 314 315 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 316 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 317 318 // PowerPC does not have [U|S]INT_TO_FP 319 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 320 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 321 322 if (Subtarget.hasDirectMove() && isPPC64) { 323 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 324 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 325 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 326 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 327 } else { 328 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 329 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 330 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 331 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 332 } 333 334 // We cannot sextinreg(i1). Expand to shifts. 335 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 336 337 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 338 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 339 // support continuation, user-level threading, and etc.. As a result, no 340 // other SjLj exception interfaces are implemented and please don't build 341 // your own exception handling based on them. 342 // LLVM/Clang supports zero-cost DWARF exception handling. 343 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 344 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 345 346 // We want to legalize GlobalAddress and ConstantPool nodes into the 347 // appropriate instructions to materialize the address. 348 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 349 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 350 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 351 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 352 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 353 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 354 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 355 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 356 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 357 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 358 359 // TRAP is legal. 360 setOperationAction(ISD::TRAP, MVT::Other, Legal); 361 362 // TRAMPOLINE is custom lowered. 363 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 364 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 365 366 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 367 setOperationAction(ISD::VASTART , MVT::Other, Custom); 368 369 if (Subtarget.isSVR4ABI()) { 370 if (isPPC64) { 371 // VAARG always uses double-word chunks, so promote anything smaller. 372 setOperationAction(ISD::VAARG, MVT::i1, Promote); 373 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 374 setOperationAction(ISD::VAARG, MVT::i8, Promote); 375 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 376 setOperationAction(ISD::VAARG, MVT::i16, Promote); 377 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 378 setOperationAction(ISD::VAARG, MVT::i32, Promote); 379 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 380 setOperationAction(ISD::VAARG, MVT::Other, Expand); 381 } else { 382 // VAARG is custom lowered with the 32-bit SVR4 ABI. 383 setOperationAction(ISD::VAARG, MVT::Other, Custom); 384 setOperationAction(ISD::VAARG, MVT::i64, Custom); 385 } 386 } else 387 setOperationAction(ISD::VAARG, MVT::Other, Expand); 388 389 if (Subtarget.isSVR4ABI() && !isPPC64) 390 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 391 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 392 else 393 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 394 395 // Use the default implementation. 396 setOperationAction(ISD::VAEND , MVT::Other, Expand); 397 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 398 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 399 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 400 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 401 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 402 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 403 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 404 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 405 406 // We want to custom lower some of our intrinsics. 407 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 408 409 // To handle counter-based loop conditions. 410 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 411 412 // Comparisons that require checking two conditions. 413 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 414 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 415 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 416 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 417 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 418 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 419 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 420 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 421 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 422 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 423 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 424 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 425 426 if (Subtarget.has64BitSupport()) { 427 // They also have instructions for converting between i64 and fp. 428 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 429 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 430 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 431 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 432 // This is just the low 32 bits of a (signed) fp->i64 conversion. 433 // We cannot do this with Promote because i64 is not a legal type. 434 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 435 436 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 437 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 438 } else { 439 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 440 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 441 } 442 443 // With the instructions enabled under FPCVT, we can do everything. 444 if (Subtarget.hasFPCVT()) { 445 if (Subtarget.has64BitSupport()) { 446 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 447 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 448 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 449 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 450 } 451 452 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 453 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 454 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 455 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 456 } 457 458 if (Subtarget.use64BitRegs()) { 459 // 64-bit PowerPC implementations can support i64 types directly 460 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 461 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 462 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 463 // 64-bit PowerPC wants to expand i128 shifts itself. 464 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 465 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 466 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 467 } else { 468 // 32-bit PowerPC wants to expand i64 shifts itself. 469 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 470 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 471 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 472 } 473 474 if (Subtarget.hasAltivec()) { 475 // First set operation action for all vector types to expand. Then we 476 // will selectively turn on ones that can be effectively codegen'd. 477 for (MVT VT : MVT::vector_valuetypes()) { 478 // add/sub are legal for all supported vector VT's. 479 setOperationAction(ISD::ADD, VT, Legal); 480 setOperationAction(ISD::SUB, VT, Legal); 481 482 // Vector instructions introduced in P8 483 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 484 setOperationAction(ISD::CTPOP, VT, Legal); 485 setOperationAction(ISD::CTLZ, VT, Legal); 486 } 487 else { 488 setOperationAction(ISD::CTPOP, VT, Expand); 489 setOperationAction(ISD::CTLZ, VT, Expand); 490 } 491 492 // Vector instructions introduced in P9 493 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 494 setOperationAction(ISD::CTTZ, VT, Legal); 495 else 496 setOperationAction(ISD::CTTZ, VT, Expand); 497 498 // We promote all shuffles to v16i8. 499 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 500 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 501 502 // We promote all non-typed operations to v4i32. 503 setOperationAction(ISD::AND , VT, Promote); 504 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 505 setOperationAction(ISD::OR , VT, Promote); 506 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 507 setOperationAction(ISD::XOR , VT, Promote); 508 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 509 setOperationAction(ISD::LOAD , VT, Promote); 510 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 511 setOperationAction(ISD::SELECT, VT, Promote); 512 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 513 setOperationAction(ISD::SELECT_CC, VT, Promote); 514 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 515 setOperationAction(ISD::STORE, VT, Promote); 516 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 517 518 // No other operations are legal. 519 setOperationAction(ISD::MUL , VT, Expand); 520 setOperationAction(ISD::SDIV, VT, Expand); 521 setOperationAction(ISD::SREM, VT, Expand); 522 setOperationAction(ISD::UDIV, VT, Expand); 523 setOperationAction(ISD::UREM, VT, Expand); 524 setOperationAction(ISD::FDIV, VT, Expand); 525 setOperationAction(ISD::FREM, VT, Expand); 526 setOperationAction(ISD::FNEG, VT, Expand); 527 setOperationAction(ISD::FSQRT, VT, Expand); 528 setOperationAction(ISD::FLOG, VT, Expand); 529 setOperationAction(ISD::FLOG10, VT, Expand); 530 setOperationAction(ISD::FLOG2, VT, Expand); 531 setOperationAction(ISD::FEXP, VT, Expand); 532 setOperationAction(ISD::FEXP2, VT, Expand); 533 setOperationAction(ISD::FSIN, VT, Expand); 534 setOperationAction(ISD::FCOS, VT, Expand); 535 setOperationAction(ISD::FABS, VT, Expand); 536 setOperationAction(ISD::FPOWI, VT, Expand); 537 setOperationAction(ISD::FFLOOR, VT, Expand); 538 setOperationAction(ISD::FCEIL, VT, Expand); 539 setOperationAction(ISD::FTRUNC, VT, Expand); 540 setOperationAction(ISD::FRINT, VT, Expand); 541 setOperationAction(ISD::FNEARBYINT, VT, Expand); 542 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 543 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 544 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 545 setOperationAction(ISD::MULHU, VT, Expand); 546 setOperationAction(ISD::MULHS, VT, Expand); 547 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 548 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 549 setOperationAction(ISD::UDIVREM, VT, Expand); 550 setOperationAction(ISD::SDIVREM, VT, Expand); 551 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 552 setOperationAction(ISD::FPOW, VT, Expand); 553 setOperationAction(ISD::BSWAP, VT, Expand); 554 setOperationAction(ISD::VSELECT, VT, Expand); 555 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 556 setOperationAction(ISD::ROTL, VT, Expand); 557 setOperationAction(ISD::ROTR, VT, Expand); 558 559 for (MVT InnerVT : MVT::vector_valuetypes()) { 560 setTruncStoreAction(VT, InnerVT, Expand); 561 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 562 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 563 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 564 } 565 } 566 567 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 568 // with merges, splats, etc. 569 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 570 571 setOperationAction(ISD::AND , MVT::v4i32, Legal); 572 setOperationAction(ISD::OR , MVT::v4i32, Legal); 573 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 574 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 575 setOperationAction(ISD::SELECT, MVT::v4i32, 576 Subtarget.useCRBits() ? Legal : Expand); 577 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 578 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 579 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 580 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 581 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 582 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 583 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 584 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 585 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 586 587 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 588 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 589 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 590 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 591 592 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 593 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 594 595 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 596 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 597 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 598 } 599 600 if (Subtarget.hasP8Altivec()) 601 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 602 else 603 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 604 605 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 606 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 607 608 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 609 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 610 611 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 612 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 613 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 614 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 615 616 // Altivec does not contain unordered floating-point compare instructions 617 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 618 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 619 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 620 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 621 622 if (Subtarget.hasVSX()) { 623 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 624 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 625 if (Subtarget.hasP8Vector()) { 626 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 627 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 628 } 629 if (Subtarget.hasDirectMove() && isPPC64) { 630 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 633 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 634 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 635 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 636 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 637 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 638 } 639 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 640 641 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 642 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 643 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 644 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 645 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 646 647 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 648 649 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 650 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 651 652 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 653 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 654 655 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 656 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 657 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 658 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 659 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 660 661 // Share the Altivec comparison restrictions. 662 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 663 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 664 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 665 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 666 667 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 668 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 669 670 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 671 672 if (Subtarget.hasP8Vector()) 673 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 674 675 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 676 677 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 678 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 679 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 680 681 if (Subtarget.hasP8Altivec()) { 682 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 683 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 684 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 685 686 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 687 } 688 else { 689 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 690 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 691 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 692 693 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 694 695 // VSX v2i64 only supports non-arithmetic operations. 696 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 697 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 698 } 699 700 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 701 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 702 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 703 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 704 705 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 706 707 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 708 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 709 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 710 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 711 712 // Vector operation legalization checks the result type of 713 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 714 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 715 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 716 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 717 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 718 719 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 720 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 721 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 722 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 723 724 if (Subtarget.hasDirectMove()) 725 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 727 728 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 729 } 730 731 if (Subtarget.hasP8Altivec()) { 732 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 733 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 734 } 735 736 if (Subtarget.hasP9Vector()) { 737 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 739 } 740 } 741 742 if (Subtarget.hasQPX()) { 743 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 744 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 745 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 746 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 747 748 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 749 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 750 751 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 752 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 753 754 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 755 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 756 757 if (!Subtarget.useCRBits()) 758 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 759 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 760 761 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 762 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 763 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 764 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 765 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 766 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 767 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 768 769 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 770 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 771 772 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 773 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 774 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 775 776 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 777 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 778 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 779 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 780 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand); 781 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 782 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 783 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 784 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 785 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 786 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 787 788 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 789 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 790 791 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 792 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 793 794 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 795 796 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 797 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 798 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 799 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 800 801 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 802 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 803 804 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 805 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 806 807 if (!Subtarget.useCRBits()) 808 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 809 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 810 811 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 812 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 813 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 814 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 815 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 816 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 817 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 818 819 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 820 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 821 822 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 823 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 824 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 825 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 826 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand); 827 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 828 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 829 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 830 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 831 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 832 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 833 834 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 835 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 836 837 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 838 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 839 840 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 841 842 setOperationAction(ISD::AND , MVT::v4i1, Legal); 843 setOperationAction(ISD::OR , MVT::v4i1, Legal); 844 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 845 846 if (!Subtarget.useCRBits()) 847 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 848 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 849 850 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 851 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 852 853 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 854 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 855 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 856 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 857 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 858 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 859 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 860 861 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 862 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 863 864 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 865 866 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 867 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 868 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 869 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 870 871 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 872 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 873 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 874 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 875 876 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 877 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 878 879 // These need to set FE_INEXACT, and so cannot be vectorized here. 880 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 881 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 882 883 if (TM.Options.UnsafeFPMath) { 884 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 885 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 886 887 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 888 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 889 } else { 890 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 891 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 892 893 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 894 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 895 } 896 } 897 898 if (Subtarget.has64BitSupport()) 899 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 900 901 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 902 903 if (!isPPC64) { 904 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 905 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 906 } 907 908 setBooleanContents(ZeroOrOneBooleanContent); 909 910 if (Subtarget.hasAltivec()) { 911 // Altivec instructions set fields to all zeros or all ones. 912 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 913 } 914 915 if (!isPPC64) { 916 // These libcalls are not available in 32-bit. 917 setLibcallName(RTLIB::SHL_I128, nullptr); 918 setLibcallName(RTLIB::SRL_I128, nullptr); 919 setLibcallName(RTLIB::SRA_I128, nullptr); 920 } 921 922 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 923 924 // We have target-specific dag combine patterns for the following nodes: 925 setTargetDAGCombine(ISD::SINT_TO_FP); 926 setTargetDAGCombine(ISD::BUILD_VECTOR); 927 if (Subtarget.hasFPCVT()) 928 setTargetDAGCombine(ISD::UINT_TO_FP); 929 setTargetDAGCombine(ISD::LOAD); 930 setTargetDAGCombine(ISD::STORE); 931 setTargetDAGCombine(ISD::BR_CC); 932 if (Subtarget.useCRBits()) 933 setTargetDAGCombine(ISD::BRCOND); 934 setTargetDAGCombine(ISD::BSWAP); 935 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 936 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 937 setTargetDAGCombine(ISD::INTRINSIC_VOID); 938 939 setTargetDAGCombine(ISD::SIGN_EXTEND); 940 setTargetDAGCombine(ISD::ZERO_EXTEND); 941 setTargetDAGCombine(ISD::ANY_EXTEND); 942 943 if (Subtarget.useCRBits()) { 944 setTargetDAGCombine(ISD::TRUNCATE); 945 setTargetDAGCombine(ISD::SETCC); 946 setTargetDAGCombine(ISD::SELECT_CC); 947 } 948 949 // Use reciprocal estimates. 950 if (TM.Options.UnsafeFPMath) { 951 setTargetDAGCombine(ISD::FDIV); 952 setTargetDAGCombine(ISD::FSQRT); 953 } 954 955 // Darwin long double math library functions have $LDBL128 appended. 956 if (Subtarget.isDarwin()) { 957 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 958 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 959 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 960 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 961 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 962 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 963 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 964 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 965 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 966 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 967 } 968 969 // With 32 condition bits, we don't need to sink (and duplicate) compares 970 // aggressively in CodeGenPrep. 971 if (Subtarget.useCRBits()) { 972 setHasMultipleConditionRegisters(); 973 setJumpIsExpensive(); 974 } 975 976 setMinFunctionAlignment(2); 977 if (Subtarget.isDarwin()) 978 setPrefFunctionAlignment(4); 979 980 switch (Subtarget.getDarwinDirective()) { 981 default: break; 982 case PPC::DIR_970: 983 case PPC::DIR_A2: 984 case PPC::DIR_E500mc: 985 case PPC::DIR_E5500: 986 case PPC::DIR_PWR4: 987 case PPC::DIR_PWR5: 988 case PPC::DIR_PWR5X: 989 case PPC::DIR_PWR6: 990 case PPC::DIR_PWR6X: 991 case PPC::DIR_PWR7: 992 case PPC::DIR_PWR8: 993 case PPC::DIR_PWR9: 994 setPrefFunctionAlignment(4); 995 setPrefLoopAlignment(4); 996 break; 997 } 998 999 if (Subtarget.enableMachineScheduler()) 1000 setSchedulingPreference(Sched::Source); 1001 else 1002 setSchedulingPreference(Sched::Hybrid); 1003 1004 computeRegisterProperties(STI.getRegisterInfo()); 1005 1006 // The Freescale cores do better with aggressive inlining of memcpy and 1007 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1008 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1009 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1010 MaxStoresPerMemset = 32; 1011 MaxStoresPerMemsetOptSize = 16; 1012 MaxStoresPerMemcpy = 32; 1013 MaxStoresPerMemcpyOptSize = 8; 1014 MaxStoresPerMemmove = 32; 1015 MaxStoresPerMemmoveOptSize = 8; 1016 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1017 // The A2 also benefits from (very) aggressive inlining of memcpy and 1018 // friends. The overhead of a the function call, even when warm, can be 1019 // over one hundred cycles. 1020 MaxStoresPerMemset = 128; 1021 MaxStoresPerMemcpy = 128; 1022 MaxStoresPerMemmove = 128; 1023 } 1024 } 1025 1026 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1027 /// the desired ByVal argument alignment. 1028 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1029 unsigned MaxMaxAlign) { 1030 if (MaxAlign == MaxMaxAlign) 1031 return; 1032 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1033 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1034 MaxAlign = 32; 1035 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1036 MaxAlign = 16; 1037 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1038 unsigned EltAlign = 0; 1039 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1040 if (EltAlign > MaxAlign) 1041 MaxAlign = EltAlign; 1042 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1043 for (auto *EltTy : STy->elements()) { 1044 unsigned EltAlign = 0; 1045 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1046 if (EltAlign > MaxAlign) 1047 MaxAlign = EltAlign; 1048 if (MaxAlign == MaxMaxAlign) 1049 break; 1050 } 1051 } 1052 } 1053 1054 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1055 /// function arguments in the caller parameter area. 1056 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1057 const DataLayout &DL) const { 1058 // Darwin passes everything on 4 byte boundary. 1059 if (Subtarget.isDarwin()) 1060 return 4; 1061 1062 // 16byte and wider vectors are passed on 16byte boundary. 1063 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1064 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1065 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1066 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1067 return Align; 1068 } 1069 1070 bool PPCTargetLowering::useSoftFloat() const { 1071 return Subtarget.useSoftFloat(); 1072 } 1073 1074 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1075 switch ((PPCISD::NodeType)Opcode) { 1076 case PPCISD::FIRST_NUMBER: break; 1077 case PPCISD::FSEL: return "PPCISD::FSEL"; 1078 case PPCISD::FCFID: return "PPCISD::FCFID"; 1079 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1080 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1081 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1082 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1083 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1084 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1085 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1086 case PPCISD::FRE: return "PPCISD::FRE"; 1087 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1088 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1089 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1090 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1091 case PPCISD::VPERM: return "PPCISD::VPERM"; 1092 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1093 case PPCISD::XXINSERT: return "PPCISD::XXINSERT"; 1094 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1095 case PPCISD::CMPB: return "PPCISD::CMPB"; 1096 case PPCISD::Hi: return "PPCISD::Hi"; 1097 case PPCISD::Lo: return "PPCISD::Lo"; 1098 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1099 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1100 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1101 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1102 case PPCISD::SRL: return "PPCISD::SRL"; 1103 case PPCISD::SRA: return "PPCISD::SRA"; 1104 case PPCISD::SHL: return "PPCISD::SHL"; 1105 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1106 case PPCISD::CALL: return "PPCISD::CALL"; 1107 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1108 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1109 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1110 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1111 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1112 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1113 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1114 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1115 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1116 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1117 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1118 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1119 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1120 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1121 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1122 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1123 case PPCISD::VCMP: return "PPCISD::VCMP"; 1124 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1125 case PPCISD::LBRX: return "PPCISD::LBRX"; 1126 case PPCISD::STBRX: return "PPCISD::STBRX"; 1127 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1128 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1129 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1130 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1131 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1132 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1133 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1134 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1135 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1136 case PPCISD::BDZ: return "PPCISD::BDZ"; 1137 case PPCISD::MFFS: return "PPCISD::MFFS"; 1138 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1139 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1140 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1141 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1142 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1143 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1144 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1145 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1146 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1147 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1148 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1149 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1150 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1151 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1152 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1153 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1154 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1155 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1156 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1157 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1158 case PPCISD::SC: return "PPCISD::SC"; 1159 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1160 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1161 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1162 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1163 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1164 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1165 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1166 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1167 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1168 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1169 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1170 } 1171 return nullptr; 1172 } 1173 1174 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1175 EVT VT) const { 1176 if (!VT.isVector()) 1177 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1178 1179 if (Subtarget.hasQPX()) 1180 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1181 1182 return VT.changeVectorElementTypeToInteger(); 1183 } 1184 1185 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1186 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1187 return true; 1188 } 1189 1190 //===----------------------------------------------------------------------===// 1191 // Node matching predicates, for use by the tblgen matching code. 1192 //===----------------------------------------------------------------------===// 1193 1194 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1195 static bool isFloatingPointZero(SDValue Op) { 1196 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1197 return CFP->getValueAPF().isZero(); 1198 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1199 // Maybe this has already been legalized into the constant pool? 1200 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1201 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1202 return CFP->getValueAPF().isZero(); 1203 } 1204 return false; 1205 } 1206 1207 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1208 /// true if Op is undef or if it matches the specified value. 1209 static bool isConstantOrUndef(int Op, int Val) { 1210 return Op < 0 || Op == Val; 1211 } 1212 1213 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1214 /// VPKUHUM instruction. 1215 /// The ShuffleKind distinguishes between big-endian operations with 1216 /// two different inputs (0), either-endian operations with two identical 1217 /// inputs (1), and little-endian operations with two different inputs (2). 1218 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1219 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1220 SelectionDAG &DAG) { 1221 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1222 if (ShuffleKind == 0) { 1223 if (IsLE) 1224 return false; 1225 for (unsigned i = 0; i != 16; ++i) 1226 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1227 return false; 1228 } else if (ShuffleKind == 2) { 1229 if (!IsLE) 1230 return false; 1231 for (unsigned i = 0; i != 16; ++i) 1232 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1233 return false; 1234 } else if (ShuffleKind == 1) { 1235 unsigned j = IsLE ? 0 : 1; 1236 for (unsigned i = 0; i != 8; ++i) 1237 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1238 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1239 return false; 1240 } 1241 return true; 1242 } 1243 1244 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1245 /// VPKUWUM instruction. 1246 /// The ShuffleKind distinguishes between big-endian operations with 1247 /// two different inputs (0), either-endian operations with two identical 1248 /// inputs (1), and little-endian operations with two different inputs (2). 1249 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1250 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1251 SelectionDAG &DAG) { 1252 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1253 if (ShuffleKind == 0) { 1254 if (IsLE) 1255 return false; 1256 for (unsigned i = 0; i != 16; i += 2) 1257 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1258 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1259 return false; 1260 } else if (ShuffleKind == 2) { 1261 if (!IsLE) 1262 return false; 1263 for (unsigned i = 0; i != 16; i += 2) 1264 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1265 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1266 return false; 1267 } else if (ShuffleKind == 1) { 1268 unsigned j = IsLE ? 0 : 2; 1269 for (unsigned i = 0; i != 8; i += 2) 1270 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1271 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1272 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1273 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1274 return false; 1275 } 1276 return true; 1277 } 1278 1279 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1280 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1281 /// current subtarget. 1282 /// 1283 /// The ShuffleKind distinguishes between big-endian operations with 1284 /// two different inputs (0), either-endian operations with two identical 1285 /// inputs (1), and little-endian operations with two different inputs (2). 1286 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1287 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1288 SelectionDAG &DAG) { 1289 const PPCSubtarget& Subtarget = 1290 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1291 if (!Subtarget.hasP8Vector()) 1292 return false; 1293 1294 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1295 if (ShuffleKind == 0) { 1296 if (IsLE) 1297 return false; 1298 for (unsigned i = 0; i != 16; i += 4) 1299 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1300 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1301 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1302 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1303 return false; 1304 } else if (ShuffleKind == 2) { 1305 if (!IsLE) 1306 return false; 1307 for (unsigned i = 0; i != 16; i += 4) 1308 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1309 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1310 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1311 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1312 return false; 1313 } else if (ShuffleKind == 1) { 1314 unsigned j = IsLE ? 0 : 4; 1315 for (unsigned i = 0; i != 8; i += 4) 1316 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1317 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1318 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1319 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1320 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1321 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1322 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1323 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1324 return false; 1325 } 1326 return true; 1327 } 1328 1329 /// isVMerge - Common function, used to match vmrg* shuffles. 1330 /// 1331 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1332 unsigned LHSStart, unsigned RHSStart) { 1333 if (N->getValueType(0) != MVT::v16i8) 1334 return false; 1335 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1336 "Unsupported merge size!"); 1337 1338 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1339 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1340 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1341 LHSStart+j+i*UnitSize) || 1342 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1343 RHSStart+j+i*UnitSize)) 1344 return false; 1345 } 1346 return true; 1347 } 1348 1349 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1350 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1351 /// The ShuffleKind distinguishes between big-endian merges with two 1352 /// different inputs (0), either-endian merges with two identical inputs (1), 1353 /// and little-endian merges with two different inputs (2). For the latter, 1354 /// the input operands are swapped (see PPCInstrAltivec.td). 1355 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1356 unsigned ShuffleKind, SelectionDAG &DAG) { 1357 if (DAG.getDataLayout().isLittleEndian()) { 1358 if (ShuffleKind == 1) // unary 1359 return isVMerge(N, UnitSize, 0, 0); 1360 else if (ShuffleKind == 2) // swapped 1361 return isVMerge(N, UnitSize, 0, 16); 1362 else 1363 return false; 1364 } else { 1365 if (ShuffleKind == 1) // unary 1366 return isVMerge(N, UnitSize, 8, 8); 1367 else if (ShuffleKind == 0) // normal 1368 return isVMerge(N, UnitSize, 8, 24); 1369 else 1370 return false; 1371 } 1372 } 1373 1374 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1375 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1376 /// The ShuffleKind distinguishes between big-endian merges with two 1377 /// different inputs (0), either-endian merges with two identical inputs (1), 1378 /// and little-endian merges with two different inputs (2). For the latter, 1379 /// the input operands are swapped (see PPCInstrAltivec.td). 1380 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1381 unsigned ShuffleKind, SelectionDAG &DAG) { 1382 if (DAG.getDataLayout().isLittleEndian()) { 1383 if (ShuffleKind == 1) // unary 1384 return isVMerge(N, UnitSize, 8, 8); 1385 else if (ShuffleKind == 2) // swapped 1386 return isVMerge(N, UnitSize, 8, 24); 1387 else 1388 return false; 1389 } else { 1390 if (ShuffleKind == 1) // unary 1391 return isVMerge(N, UnitSize, 0, 0); 1392 else if (ShuffleKind == 0) // normal 1393 return isVMerge(N, UnitSize, 0, 16); 1394 else 1395 return false; 1396 } 1397 } 1398 1399 /** 1400 * \brief Common function used to match vmrgew and vmrgow shuffles 1401 * 1402 * The indexOffset determines whether to look for even or odd words in 1403 * the shuffle mask. This is based on the of the endianness of the target 1404 * machine. 1405 * - Little Endian: 1406 * - Use offset of 0 to check for odd elements 1407 * - Use offset of 4 to check for even elements 1408 * - Big Endian: 1409 * - Use offset of 0 to check for even elements 1410 * - Use offset of 4 to check for odd elements 1411 * A detailed description of the vector element ordering for little endian and 1412 * big endian can be found at 1413 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1414 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1415 * compiler differences mean to you 1416 * 1417 * The mask to the shuffle vector instruction specifies the indices of the 1418 * elements from the two input vectors to place in the result. The elements are 1419 * numbered in array-access order, starting with the first vector. These vectors 1420 * are always of type v16i8, thus each vector will contain 16 elements of size 1421 * 8. More info on the shuffle vector can be found in the 1422 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1423 * Language Reference. 1424 * 1425 * The RHSStartValue indicates whether the same input vectors are used (unary) 1426 * or two different input vectors are used, based on the following: 1427 * - If the instruction uses the same vector for both inputs, the range of the 1428 * indices will be 0 to 15. In this case, the RHSStart value passed should 1429 * be 0. 1430 * - If the instruction has two different vectors then the range of the 1431 * indices will be 0 to 31. In this case, the RHSStart value passed should 1432 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1433 * to 31 specify elements in the second vector). 1434 * 1435 * \param[in] N The shuffle vector SD Node to analyze 1436 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1437 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1438 * vector to the shuffle_vector instruction 1439 * \return true iff this shuffle vector represents an even or odd word merge 1440 */ 1441 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1442 unsigned RHSStartValue) { 1443 if (N->getValueType(0) != MVT::v16i8) 1444 return false; 1445 1446 for (unsigned i = 0; i < 2; ++i) 1447 for (unsigned j = 0; j < 4; ++j) 1448 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1449 i*RHSStartValue+j+IndexOffset) || 1450 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1451 i*RHSStartValue+j+IndexOffset+8)) 1452 return false; 1453 return true; 1454 } 1455 1456 /** 1457 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or 1458 * vmrgow instructions. 1459 * 1460 * \param[in] N The shuffle vector SD Node to analyze 1461 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1462 * \param[in] ShuffleKind Identify the type of merge: 1463 * - 0 = big-endian merge with two different inputs; 1464 * - 1 = either-endian merge with two identical inputs; 1465 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1466 * little-endian merges). 1467 * \param[in] DAG The current SelectionDAG 1468 * \return true iff this shuffle mask 1469 */ 1470 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1471 unsigned ShuffleKind, SelectionDAG &DAG) { 1472 if (DAG.getDataLayout().isLittleEndian()) { 1473 unsigned indexOffset = CheckEven ? 4 : 0; 1474 if (ShuffleKind == 1) // Unary 1475 return isVMerge(N, indexOffset, 0); 1476 else if (ShuffleKind == 2) // swapped 1477 return isVMerge(N, indexOffset, 16); 1478 else 1479 return false; 1480 } 1481 else { 1482 unsigned indexOffset = CheckEven ? 0 : 4; 1483 if (ShuffleKind == 1) // Unary 1484 return isVMerge(N, indexOffset, 0); 1485 else if (ShuffleKind == 0) // Normal 1486 return isVMerge(N, indexOffset, 16); 1487 else 1488 return false; 1489 } 1490 return false; 1491 } 1492 1493 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1494 /// amount, otherwise return -1. 1495 /// The ShuffleKind distinguishes between big-endian operations with two 1496 /// different inputs (0), either-endian operations with two identical inputs 1497 /// (1), and little-endian operations with two different inputs (2). For the 1498 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1499 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1500 SelectionDAG &DAG) { 1501 if (N->getValueType(0) != MVT::v16i8) 1502 return -1; 1503 1504 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1505 1506 // Find the first non-undef value in the shuffle mask. 1507 unsigned i; 1508 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1509 /*search*/; 1510 1511 if (i == 16) return -1; // all undef. 1512 1513 // Otherwise, check to see if the rest of the elements are consecutively 1514 // numbered from this value. 1515 unsigned ShiftAmt = SVOp->getMaskElt(i); 1516 if (ShiftAmt < i) return -1; 1517 1518 ShiftAmt -= i; 1519 bool isLE = DAG.getDataLayout().isLittleEndian(); 1520 1521 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1522 // Check the rest of the elements to see if they are consecutive. 1523 for (++i; i != 16; ++i) 1524 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1525 return -1; 1526 } else if (ShuffleKind == 1) { 1527 // Check the rest of the elements to see if they are consecutive. 1528 for (++i; i != 16; ++i) 1529 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1530 return -1; 1531 } else 1532 return -1; 1533 1534 if (isLE) 1535 ShiftAmt = 16 - ShiftAmt; 1536 1537 return ShiftAmt; 1538 } 1539 1540 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1541 /// specifies a splat of a single element that is suitable for input to 1542 /// VSPLTB/VSPLTH/VSPLTW. 1543 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1544 assert(N->getValueType(0) == MVT::v16i8 && 1545 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1546 1547 // The consecutive indices need to specify an element, not part of two 1548 // different elements. So abandon ship early if this isn't the case. 1549 if (N->getMaskElt(0) % EltSize != 0) 1550 return false; 1551 1552 // This is a splat operation if each element of the permute is the same, and 1553 // if the value doesn't reference the second vector. 1554 unsigned ElementBase = N->getMaskElt(0); 1555 1556 // FIXME: Handle UNDEF elements too! 1557 if (ElementBase >= 16) 1558 return false; 1559 1560 // Check that the indices are consecutive, in the case of a multi-byte element 1561 // splatted with a v16i8 mask. 1562 for (unsigned i = 1; i != EltSize; ++i) 1563 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1564 return false; 1565 1566 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1567 if (N->getMaskElt(i) < 0) continue; 1568 for (unsigned j = 0; j != EltSize; ++j) 1569 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1570 return false; 1571 } 1572 return true; 1573 } 1574 1575 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1576 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1577 // Check that the mask is shuffling words 1578 for (unsigned i = 0; i < 4; ++i) { 1579 unsigned B0 = N->getMaskElt(i*4); 1580 unsigned B1 = N->getMaskElt(i*4+1); 1581 unsigned B2 = N->getMaskElt(i*4+2); 1582 unsigned B3 = N->getMaskElt(i*4+3); 1583 if (B0 % 4) 1584 return false; 1585 if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1) 1586 return false; 1587 } 1588 1589 // Now we look at mask elements 0,4,8,12 1590 unsigned M0 = N->getMaskElt(0) / 4; 1591 unsigned M1 = N->getMaskElt(4) / 4; 1592 unsigned M2 = N->getMaskElt(8) / 4; 1593 unsigned M3 = N->getMaskElt(12) / 4; 1594 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1595 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1596 1597 // Below, let H and L be arbitrary elements of the shuffle mask 1598 // where H is in the range [4,7] and L is in the range [0,3]. 1599 // H, 1, 2, 3 or L, 5, 6, 7 1600 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1601 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1602 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1603 InsertAtByte = IsLE ? 12 : 0; 1604 Swap = M0 < 4; 1605 return true; 1606 } 1607 // 0, H, 2, 3 or 4, L, 6, 7 1608 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1609 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1610 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1611 InsertAtByte = IsLE ? 8 : 4; 1612 Swap = M1 < 4; 1613 return true; 1614 } 1615 // 0, 1, H, 3 or 4, 5, L, 7 1616 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1617 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1618 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1619 InsertAtByte = IsLE ? 4 : 8; 1620 Swap = M2 < 4; 1621 return true; 1622 } 1623 // 0, 1, 2, H or 4, 5, 6, L 1624 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1625 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1626 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1627 InsertAtByte = IsLE ? 0 : 12; 1628 Swap = M3 < 4; 1629 return true; 1630 } 1631 1632 // If both vector operands for the shuffle are the same vector, the mask will 1633 // contain only elements from the first one and the second one will be undef. 1634 if (N->getOperand(1).isUndef()) { 1635 ShiftElts = 0; 1636 Swap = true; 1637 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1638 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1639 InsertAtByte = IsLE ? 12 : 0; 1640 return true; 1641 } 1642 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1643 InsertAtByte = IsLE ? 8 : 4; 1644 return true; 1645 } 1646 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1647 InsertAtByte = IsLE ? 4 : 8; 1648 return true; 1649 } 1650 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1651 InsertAtByte = IsLE ? 0 : 12; 1652 return true; 1653 } 1654 } 1655 1656 return false; 1657 } 1658 1659 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1660 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1661 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1662 SelectionDAG &DAG) { 1663 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1664 assert(isSplatShuffleMask(SVOp, EltSize)); 1665 if (DAG.getDataLayout().isLittleEndian()) 1666 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1667 else 1668 return SVOp->getMaskElt(0) / EltSize; 1669 } 1670 1671 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1672 /// by using a vspltis[bhw] instruction of the specified element size, return 1673 /// the constant being splatted. The ByteSize field indicates the number of 1674 /// bytes of each element [124] -> [bhw]. 1675 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1676 SDValue OpVal(nullptr, 0); 1677 1678 // If ByteSize of the splat is bigger than the element size of the 1679 // build_vector, then we have a case where we are checking for a splat where 1680 // multiple elements of the buildvector are folded together into a single 1681 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1682 unsigned EltSize = 16/N->getNumOperands(); 1683 if (EltSize < ByteSize) { 1684 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1685 SDValue UniquedVals[4]; 1686 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1687 1688 // See if all of the elements in the buildvector agree across. 1689 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1690 if (N->getOperand(i).isUndef()) continue; 1691 // If the element isn't a constant, bail fully out. 1692 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1693 1694 if (!UniquedVals[i&(Multiple-1)].getNode()) 1695 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1696 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1697 return SDValue(); // no match. 1698 } 1699 1700 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1701 // either constant or undef values that are identical for each chunk. See 1702 // if these chunks can form into a larger vspltis*. 1703 1704 // Check to see if all of the leading entries are either 0 or -1. If 1705 // neither, then this won't fit into the immediate field. 1706 bool LeadingZero = true; 1707 bool LeadingOnes = true; 1708 for (unsigned i = 0; i != Multiple-1; ++i) { 1709 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1710 1711 LeadingZero &= isNullConstant(UniquedVals[i]); 1712 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 1713 } 1714 // Finally, check the least significant entry. 1715 if (LeadingZero) { 1716 if (!UniquedVals[Multiple-1].getNode()) 1717 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 1718 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1719 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 1720 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1721 } 1722 if (LeadingOnes) { 1723 if (!UniquedVals[Multiple-1].getNode()) 1724 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 1725 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1726 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1727 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1728 } 1729 1730 return SDValue(); 1731 } 1732 1733 // Check to see if this buildvec has a single non-undef value in its elements. 1734 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1735 if (N->getOperand(i).isUndef()) continue; 1736 if (!OpVal.getNode()) 1737 OpVal = N->getOperand(i); 1738 else if (OpVal != N->getOperand(i)) 1739 return SDValue(); 1740 } 1741 1742 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1743 1744 unsigned ValSizeInBytes = EltSize; 1745 uint64_t Value = 0; 1746 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1747 Value = CN->getZExtValue(); 1748 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 1749 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 1750 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 1751 } 1752 1753 // If the splat value is larger than the element value, then we can never do 1754 // this splat. The only case that we could fit the replicated bits into our 1755 // immediate field for would be zero, and we prefer to use vxor for it. 1756 if (ValSizeInBytes < ByteSize) return SDValue(); 1757 1758 // If the element value is larger than the splat value, check if it consists 1759 // of a repeated bit pattern of size ByteSize. 1760 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 1761 return SDValue(); 1762 1763 // Properly sign extend the value. 1764 int MaskVal = SignExtend32(Value, ByteSize * 8); 1765 1766 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 1767 if (MaskVal == 0) return SDValue(); 1768 1769 // Finally, if this value fits in a 5 bit sext field, return it 1770 if (SignExtend32<5>(MaskVal) == MaskVal) 1771 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 1772 return SDValue(); 1773 } 1774 1775 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 1776 /// amount, otherwise return -1. 1777 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 1778 EVT VT = N->getValueType(0); 1779 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 1780 return -1; 1781 1782 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1783 1784 // Find the first non-undef value in the shuffle mask. 1785 unsigned i; 1786 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 1787 /*search*/; 1788 1789 if (i == 4) return -1; // all undef. 1790 1791 // Otherwise, check to see if the rest of the elements are consecutively 1792 // numbered from this value. 1793 unsigned ShiftAmt = SVOp->getMaskElt(i); 1794 if (ShiftAmt < i) return -1; 1795 ShiftAmt -= i; 1796 1797 // Check the rest of the elements to see if they are consecutive. 1798 for (++i; i != 4; ++i) 1799 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1800 return -1; 1801 1802 return ShiftAmt; 1803 } 1804 1805 //===----------------------------------------------------------------------===// 1806 // Addressing Mode Selection 1807 //===----------------------------------------------------------------------===// 1808 1809 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 1810 /// or 64-bit immediate, and if the value can be accurately represented as a 1811 /// sign extension from a 16-bit value. If so, this returns true and the 1812 /// immediate. 1813 static bool isIntS16Immediate(SDNode *N, short &Imm) { 1814 if (!isa<ConstantSDNode>(N)) 1815 return false; 1816 1817 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); 1818 if (N->getValueType(0) == MVT::i32) 1819 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 1820 else 1821 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 1822 } 1823 static bool isIntS16Immediate(SDValue Op, short &Imm) { 1824 return isIntS16Immediate(Op.getNode(), Imm); 1825 } 1826 1827 /// SelectAddressRegReg - Given the specified addressed, check to see if it 1828 /// can be represented as an indexed [r+r] operation. Returns false if it 1829 /// can be more efficiently represented with [r+imm]. 1830 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 1831 SDValue &Index, 1832 SelectionDAG &DAG) const { 1833 short imm = 0; 1834 if (N.getOpcode() == ISD::ADD) { 1835 if (isIntS16Immediate(N.getOperand(1), imm)) 1836 return false; // r+i 1837 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 1838 return false; // r+i 1839 1840 Base = N.getOperand(0); 1841 Index = N.getOperand(1); 1842 return true; 1843 } else if (N.getOpcode() == ISD::OR) { 1844 if (isIntS16Immediate(N.getOperand(1), imm)) 1845 return false; // r+i can fold it if we can. 1846 1847 // If this is an or of disjoint bitfields, we can codegen this as an add 1848 // (for better address arithmetic) if the LHS and RHS of the OR are provably 1849 // disjoint. 1850 APInt LHSKnownZero, LHSKnownOne; 1851 APInt RHSKnownZero, RHSKnownOne; 1852 DAG.computeKnownBits(N.getOperand(0), 1853 LHSKnownZero, LHSKnownOne); 1854 1855 if (LHSKnownZero.getBoolValue()) { 1856 DAG.computeKnownBits(N.getOperand(1), 1857 RHSKnownZero, RHSKnownOne); 1858 // If all of the bits are known zero on the LHS or RHS, the add won't 1859 // carry. 1860 if (~(LHSKnownZero | RHSKnownZero) == 0) { 1861 Base = N.getOperand(0); 1862 Index = N.getOperand(1); 1863 return true; 1864 } 1865 } 1866 } 1867 1868 return false; 1869 } 1870 1871 // If we happen to be doing an i64 load or store into a stack slot that has 1872 // less than a 4-byte alignment, then the frame-index elimination may need to 1873 // use an indexed load or store instruction (because the offset may not be a 1874 // multiple of 4). The extra register needed to hold the offset comes from the 1875 // register scavenger, and it is possible that the scavenger will need to use 1876 // an emergency spill slot. As a result, we need to make sure that a spill slot 1877 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 1878 // stack slot. 1879 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 1880 // FIXME: This does not handle the LWA case. 1881 if (VT != MVT::i64) 1882 return; 1883 1884 // NOTE: We'll exclude negative FIs here, which come from argument 1885 // lowering, because there are no known test cases triggering this problem 1886 // using packed structures (or similar). We can remove this exclusion if 1887 // we find such a test case. The reason why this is so test-case driven is 1888 // because this entire 'fixup' is only to prevent crashes (from the 1889 // register scavenger) on not-really-valid inputs. For example, if we have: 1890 // %a = alloca i1 1891 // %b = bitcast i1* %a to i64* 1892 // store i64* a, i64 b 1893 // then the store should really be marked as 'align 1', but is not. If it 1894 // were marked as 'align 1' then the indexed form would have been 1895 // instruction-selected initially, and the problem this 'fixup' is preventing 1896 // won't happen regardless. 1897 if (FrameIdx < 0) 1898 return; 1899 1900 MachineFunction &MF = DAG.getMachineFunction(); 1901 MachineFrameInfo &MFI = MF.getFrameInfo(); 1902 1903 unsigned Align = MFI.getObjectAlignment(FrameIdx); 1904 if (Align >= 4) 1905 return; 1906 1907 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1908 FuncInfo->setHasNonRISpills(); 1909 } 1910 1911 /// Returns true if the address N can be represented by a base register plus 1912 /// a signed 16-bit displacement [r+imm], and if it is not better 1913 /// represented as reg+reg. If Aligned is true, only accept displacements 1914 /// suitable for STD and friends, i.e. multiples of 4. 1915 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 1916 SDValue &Base, 1917 SelectionDAG &DAG, 1918 bool Aligned) const { 1919 // FIXME dl should come from parent load or store, not from address 1920 SDLoc dl(N); 1921 // If this can be more profitably realized as r+r, fail. 1922 if (SelectAddressRegReg(N, Disp, Base, DAG)) 1923 return false; 1924 1925 if (N.getOpcode() == ISD::ADD) { 1926 short imm = 0; 1927 if (isIntS16Immediate(N.getOperand(1), imm) && 1928 (!Aligned || (imm & 3) == 0)) { 1929 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 1930 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1931 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1932 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1933 } else { 1934 Base = N.getOperand(0); 1935 } 1936 return true; // [r+i] 1937 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 1938 // Match LOAD (ADD (X, Lo(G))). 1939 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 1940 && "Cannot handle constant offsets yet!"); 1941 Disp = N.getOperand(1).getOperand(0); // The global address. 1942 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 1943 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 1944 Disp.getOpcode() == ISD::TargetConstantPool || 1945 Disp.getOpcode() == ISD::TargetJumpTable); 1946 Base = N.getOperand(0); 1947 return true; // [&g+r] 1948 } 1949 } else if (N.getOpcode() == ISD::OR) { 1950 short imm = 0; 1951 if (isIntS16Immediate(N.getOperand(1), imm) && 1952 (!Aligned || (imm & 3) == 0)) { 1953 // If this is an or of disjoint bitfields, we can codegen this as an add 1954 // (for better address arithmetic) if the LHS and RHS of the OR are 1955 // provably disjoint. 1956 APInt LHSKnownZero, LHSKnownOne; 1957 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne); 1958 1959 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 1960 // If all of the bits are known zero on the LHS or RHS, the add won't 1961 // carry. 1962 if (FrameIndexSDNode *FI = 1963 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1964 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1965 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1966 } else { 1967 Base = N.getOperand(0); 1968 } 1969 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 1970 return true; 1971 } 1972 } 1973 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 1974 // Loading from a constant address. 1975 1976 // If this address fits entirely in a 16-bit sext immediate field, codegen 1977 // this as "d, 0" 1978 short Imm; 1979 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) { 1980 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 1981 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 1982 CN->getValueType(0)); 1983 return true; 1984 } 1985 1986 // Handle 32-bit sext immediates with LIS + addr mode. 1987 if ((CN->getValueType(0) == MVT::i32 || 1988 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 1989 (!Aligned || (CN->getZExtValue() & 3) == 0)) { 1990 int Addr = (int)CN->getZExtValue(); 1991 1992 // Otherwise, break this down into an LIS + disp. 1993 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 1994 1995 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 1996 MVT::i32); 1997 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 1998 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 1999 return true; 2000 } 2001 } 2002 2003 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2004 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2005 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2006 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2007 } else 2008 Base = N; 2009 return true; // [r+0] 2010 } 2011 2012 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2013 /// represented as an indexed [r+r] operation. 2014 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2015 SDValue &Index, 2016 SelectionDAG &DAG) const { 2017 // Check to see if we can easily represent this as an [r+r] address. This 2018 // will fail if it thinks that the address is more profitably represented as 2019 // reg+imm, e.g. where imm = 0. 2020 if (SelectAddressRegReg(N, Base, Index, DAG)) 2021 return true; 2022 2023 // If the operand is an addition, always emit this as [r+r], since this is 2024 // better (for code size, and execution, as the memop does the add for free) 2025 // than emitting an explicit add. 2026 if (N.getOpcode() == ISD::ADD) { 2027 Base = N.getOperand(0); 2028 Index = N.getOperand(1); 2029 return true; 2030 } 2031 2032 // Otherwise, do it the hard way, using R0 as the base register. 2033 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2034 N.getValueType()); 2035 Index = N; 2036 return true; 2037 } 2038 2039 /// getPreIndexedAddressParts - returns true by value, base pointer and 2040 /// offset pointer and addressing mode by reference if the node's address 2041 /// can be legally represented as pre-indexed load / store address. 2042 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2043 SDValue &Offset, 2044 ISD::MemIndexedMode &AM, 2045 SelectionDAG &DAG) const { 2046 if (DisablePPCPreinc) return false; 2047 2048 bool isLoad = true; 2049 SDValue Ptr; 2050 EVT VT; 2051 unsigned Alignment; 2052 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2053 Ptr = LD->getBasePtr(); 2054 VT = LD->getMemoryVT(); 2055 Alignment = LD->getAlignment(); 2056 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2057 Ptr = ST->getBasePtr(); 2058 VT = ST->getMemoryVT(); 2059 Alignment = ST->getAlignment(); 2060 isLoad = false; 2061 } else 2062 return false; 2063 2064 // PowerPC doesn't have preinc load/store instructions for vectors (except 2065 // for QPX, which does have preinc r+r forms). 2066 if (VT.isVector()) { 2067 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2068 return false; 2069 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2070 AM = ISD::PRE_INC; 2071 return true; 2072 } 2073 } 2074 2075 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2076 // Common code will reject creating a pre-inc form if the base pointer 2077 // is a frame index, or if N is a store and the base pointer is either 2078 // the same as or a predecessor of the value being stored. Check for 2079 // those situations here, and try with swapped Base/Offset instead. 2080 bool Swap = false; 2081 2082 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2083 Swap = true; 2084 else if (!isLoad) { 2085 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2086 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2087 Swap = true; 2088 } 2089 2090 if (Swap) 2091 std::swap(Base, Offset); 2092 2093 AM = ISD::PRE_INC; 2094 return true; 2095 } 2096 2097 // LDU/STU can only handle immediates that are a multiple of 4. 2098 if (VT != MVT::i64) { 2099 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false)) 2100 return false; 2101 } else { 2102 // LDU/STU need an address with at least 4-byte alignment. 2103 if (Alignment < 4) 2104 return false; 2105 2106 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true)) 2107 return false; 2108 } 2109 2110 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2111 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2112 // sext i32 to i64 when addr mode is r+i. 2113 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2114 LD->getExtensionType() == ISD::SEXTLOAD && 2115 isa<ConstantSDNode>(Offset)) 2116 return false; 2117 } 2118 2119 AM = ISD::PRE_INC; 2120 return true; 2121 } 2122 2123 //===----------------------------------------------------------------------===// 2124 // LowerOperation implementation 2125 //===----------------------------------------------------------------------===// 2126 2127 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2128 /// and LoOpFlags to the target MO flags. 2129 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2130 unsigned &HiOpFlags, unsigned &LoOpFlags, 2131 const GlobalValue *GV = nullptr) { 2132 HiOpFlags = PPCII::MO_HA; 2133 LoOpFlags = PPCII::MO_LO; 2134 2135 // Don't use the pic base if not in PIC relocation model. 2136 if (IsPIC) { 2137 HiOpFlags |= PPCII::MO_PIC_FLAG; 2138 LoOpFlags |= PPCII::MO_PIC_FLAG; 2139 } 2140 2141 // If this is a reference to a global value that requires a non-lazy-ptr, make 2142 // sure that instruction lowering adds it. 2143 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2144 HiOpFlags |= PPCII::MO_NLP_FLAG; 2145 LoOpFlags |= PPCII::MO_NLP_FLAG; 2146 2147 if (GV->hasHiddenVisibility()) { 2148 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2149 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2150 } 2151 } 2152 } 2153 2154 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2155 SelectionDAG &DAG) { 2156 SDLoc DL(HiPart); 2157 EVT PtrVT = HiPart.getValueType(); 2158 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2159 2160 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2161 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2162 2163 // With PIC, the first instruction is actually "GR+hi(&G)". 2164 if (isPIC) 2165 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2166 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2167 2168 // Generate non-pic code that has direct accesses to the constant pool. 2169 // The address of the global is just (hi(&g)+lo(&g)). 2170 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2171 } 2172 2173 static void setUsesTOCBasePtr(MachineFunction &MF) { 2174 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2175 FuncInfo->setUsesTOCBasePtr(); 2176 } 2177 2178 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2179 setUsesTOCBasePtr(DAG.getMachineFunction()); 2180 } 2181 2182 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2183 SDValue GA) { 2184 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2185 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2186 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2187 2188 SDValue Ops[] = { GA, Reg }; 2189 return DAG.getMemIntrinsicNode( 2190 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2191 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true, 2192 false, 0); 2193 } 2194 2195 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2196 SelectionDAG &DAG) const { 2197 EVT PtrVT = Op.getValueType(); 2198 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2199 const Constant *C = CP->getConstVal(); 2200 2201 // 64-bit SVR4 ABI code is always position-independent. 2202 // The actual address of the GlobalValue is stored in the TOC. 2203 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2204 setUsesTOCBasePtr(DAG); 2205 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2206 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2207 } 2208 2209 unsigned MOHiFlag, MOLoFlag; 2210 bool IsPIC = isPositionIndependent(); 2211 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2212 2213 if (IsPIC && Subtarget.isSVR4ABI()) { 2214 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2215 PPCII::MO_PIC_FLAG); 2216 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2217 } 2218 2219 SDValue CPIHi = 2220 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2221 SDValue CPILo = 2222 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2223 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2224 } 2225 2226 // For 64-bit PowerPC, prefer the more compact relative encodings. 2227 // This trades 32 bits per jump table entry for one or two instructions 2228 // on the jump site. 2229 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2230 if (isJumpTableRelative()) 2231 return MachineJumpTableInfo::EK_LabelDifference32; 2232 2233 return TargetLowering::getJumpTableEncoding(); 2234 } 2235 2236 bool PPCTargetLowering::isJumpTableRelative() const { 2237 if (Subtarget.isPPC64()) 2238 return true; 2239 return TargetLowering::isJumpTableRelative(); 2240 } 2241 2242 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2243 SelectionDAG &DAG) const { 2244 if (!Subtarget.isPPC64()) 2245 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2246 2247 switch (getTargetMachine().getCodeModel()) { 2248 case CodeModel::Default: 2249 case CodeModel::Small: 2250 case CodeModel::Medium: 2251 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2252 default: 2253 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2254 getPointerTy(DAG.getDataLayout())); 2255 } 2256 } 2257 2258 const MCExpr * 2259 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2260 unsigned JTI, 2261 MCContext &Ctx) const { 2262 if (!Subtarget.isPPC64()) 2263 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2264 2265 switch (getTargetMachine().getCodeModel()) { 2266 case CodeModel::Default: 2267 case CodeModel::Small: 2268 case CodeModel::Medium: 2269 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2270 default: 2271 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2272 } 2273 } 2274 2275 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2276 EVT PtrVT = Op.getValueType(); 2277 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2278 2279 // 64-bit SVR4 ABI code is always position-independent. 2280 // The actual address of the GlobalValue is stored in the TOC. 2281 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2282 setUsesTOCBasePtr(DAG); 2283 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2284 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2285 } 2286 2287 unsigned MOHiFlag, MOLoFlag; 2288 bool IsPIC = isPositionIndependent(); 2289 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2290 2291 if (IsPIC && Subtarget.isSVR4ABI()) { 2292 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2293 PPCII::MO_PIC_FLAG); 2294 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2295 } 2296 2297 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2298 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2299 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2300 } 2301 2302 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2303 SelectionDAG &DAG) const { 2304 EVT PtrVT = Op.getValueType(); 2305 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2306 const BlockAddress *BA = BASDN->getBlockAddress(); 2307 2308 // 64-bit SVR4 ABI code is always position-independent. 2309 // The actual BlockAddress is stored in the TOC. 2310 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2311 setUsesTOCBasePtr(DAG); 2312 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2313 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 2314 } 2315 2316 unsigned MOHiFlag, MOLoFlag; 2317 bool IsPIC = isPositionIndependent(); 2318 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2319 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2320 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2321 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2322 } 2323 2324 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2325 SelectionDAG &DAG) const { 2326 // FIXME: TLS addresses currently use medium model code sequences, 2327 // which is the most useful form. Eventually support for small and 2328 // large models could be added if users need it, at the cost of 2329 // additional complexity. 2330 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2331 if (DAG.getTarget().Options.EmulatedTLS) 2332 return LowerToTLSEmulatedModel(GA, DAG); 2333 2334 SDLoc dl(GA); 2335 const GlobalValue *GV = GA->getGlobal(); 2336 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2337 bool is64bit = Subtarget.isPPC64(); 2338 const Module *M = DAG.getMachineFunction().getFunction()->getParent(); 2339 PICLevel::Level picLevel = M->getPICLevel(); 2340 2341 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2342 2343 if (Model == TLSModel::LocalExec) { 2344 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2345 PPCII::MO_TPREL_HA); 2346 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2347 PPCII::MO_TPREL_LO); 2348 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2, 2349 is64bit ? MVT::i64 : MVT::i32); 2350 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2351 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2352 } 2353 2354 if (Model == TLSModel::InitialExec) { 2355 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2356 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2357 PPCII::MO_TLS); 2358 SDValue GOTPtr; 2359 if (is64bit) { 2360 setUsesTOCBasePtr(DAG); 2361 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2362 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2363 PtrVT, GOTReg, TGA); 2364 } else 2365 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2366 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2367 PtrVT, TGA, GOTPtr); 2368 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2369 } 2370 2371 if (Model == TLSModel::GeneralDynamic) { 2372 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2373 SDValue GOTPtr; 2374 if (is64bit) { 2375 setUsesTOCBasePtr(DAG); 2376 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2377 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2378 GOTReg, TGA); 2379 } else { 2380 if (picLevel == PICLevel::SmallPIC) 2381 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2382 else 2383 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2384 } 2385 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2386 GOTPtr, TGA, TGA); 2387 } 2388 2389 if (Model == TLSModel::LocalDynamic) { 2390 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2391 SDValue GOTPtr; 2392 if (is64bit) { 2393 setUsesTOCBasePtr(DAG); 2394 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2395 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2396 GOTReg, TGA); 2397 } else { 2398 if (picLevel == PICLevel::SmallPIC) 2399 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2400 else 2401 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2402 } 2403 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2404 PtrVT, GOTPtr, TGA, TGA); 2405 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2406 PtrVT, TLSAddr, TGA); 2407 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2408 } 2409 2410 llvm_unreachable("Unknown TLS model!"); 2411 } 2412 2413 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2414 SelectionDAG &DAG) const { 2415 EVT PtrVT = Op.getValueType(); 2416 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2417 SDLoc DL(GSDN); 2418 const GlobalValue *GV = GSDN->getGlobal(); 2419 2420 // 64-bit SVR4 ABI code is always position-independent. 2421 // The actual address of the GlobalValue is stored in the TOC. 2422 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2423 setUsesTOCBasePtr(DAG); 2424 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2425 return getTOCEntry(DAG, DL, true, GA); 2426 } 2427 2428 unsigned MOHiFlag, MOLoFlag; 2429 bool IsPIC = isPositionIndependent(); 2430 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2431 2432 if (IsPIC && Subtarget.isSVR4ABI()) { 2433 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2434 GSDN->getOffset(), 2435 PPCII::MO_PIC_FLAG); 2436 return getTOCEntry(DAG, DL, false, GA); 2437 } 2438 2439 SDValue GAHi = 2440 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2441 SDValue GALo = 2442 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2443 2444 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2445 2446 // If the global reference is actually to a non-lazy-pointer, we have to do an 2447 // extra load to get the address of the global. 2448 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2449 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2450 return Ptr; 2451 } 2452 2453 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2454 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2455 SDLoc dl(Op); 2456 2457 if (Op.getValueType() == MVT::v2i64) { 2458 // When the operands themselves are v2i64 values, we need to do something 2459 // special because VSX has no underlying comparison operations for these. 2460 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2461 // Equality can be handled by casting to the legal type for Altivec 2462 // comparisons, everything else needs to be expanded. 2463 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2464 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2465 DAG.getSetCC(dl, MVT::v4i32, 2466 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2467 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2468 CC)); 2469 } 2470 2471 return SDValue(); 2472 } 2473 2474 // We handle most of these in the usual way. 2475 return Op; 2476 } 2477 2478 // If we're comparing for equality to zero, expose the fact that this is 2479 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2480 // fold the new nodes. 2481 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2482 return V; 2483 2484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2485 // Leave comparisons against 0 and -1 alone for now, since they're usually 2486 // optimized. FIXME: revisit this when we can custom lower all setcc 2487 // optimizations. 2488 if (C->isAllOnesValue() || C->isNullValue()) 2489 return SDValue(); 2490 } 2491 2492 // If we have an integer seteq/setne, turn it into a compare against zero 2493 // by xor'ing the rhs with the lhs, which is faster than setting a 2494 // condition register, reading it back out, and masking the correct bit. The 2495 // normal approach here uses sub to do this instead of xor. Using xor exposes 2496 // the result to other bit-twiddling opportunities. 2497 EVT LHSVT = Op.getOperand(0).getValueType(); 2498 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2499 EVT VT = Op.getValueType(); 2500 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2501 Op.getOperand(1)); 2502 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2503 } 2504 return SDValue(); 2505 } 2506 2507 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2508 SDNode *Node = Op.getNode(); 2509 EVT VT = Node->getValueType(0); 2510 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2511 SDValue InChain = Node->getOperand(0); 2512 SDValue VAListPtr = Node->getOperand(1); 2513 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2514 SDLoc dl(Node); 2515 2516 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2517 2518 // gpr_index 2519 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2520 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2521 InChain = GprIndex.getValue(1); 2522 2523 if (VT == MVT::i64) { 2524 // Check if GprIndex is even 2525 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2526 DAG.getConstant(1, dl, MVT::i32)); 2527 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2528 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2529 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2530 DAG.getConstant(1, dl, MVT::i32)); 2531 // Align GprIndex to be even if it isn't 2532 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2533 GprIndex); 2534 } 2535 2536 // fpr index is 1 byte after gpr 2537 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2538 DAG.getConstant(1, dl, MVT::i32)); 2539 2540 // fpr 2541 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2542 FprPtr, MachinePointerInfo(SV), MVT::i8); 2543 InChain = FprIndex.getValue(1); 2544 2545 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2546 DAG.getConstant(8, dl, MVT::i32)); 2547 2548 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2549 DAG.getConstant(4, dl, MVT::i32)); 2550 2551 // areas 2552 SDValue OverflowArea = 2553 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2554 InChain = OverflowArea.getValue(1); 2555 2556 SDValue RegSaveArea = 2557 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2558 InChain = RegSaveArea.getValue(1); 2559 2560 // select overflow_area if index > 8 2561 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2562 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2563 2564 // adjustment constant gpr_index * 4/8 2565 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2566 VT.isInteger() ? GprIndex : FprIndex, 2567 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2568 MVT::i32)); 2569 2570 // OurReg = RegSaveArea + RegConstant 2571 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2572 RegConstant); 2573 2574 // Floating types are 32 bytes into RegSaveArea 2575 if (VT.isFloatingPoint()) 2576 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2577 DAG.getConstant(32, dl, MVT::i32)); 2578 2579 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2580 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2581 VT.isInteger() ? GprIndex : FprIndex, 2582 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2583 MVT::i32)); 2584 2585 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2586 VT.isInteger() ? VAListPtr : FprPtr, 2587 MachinePointerInfo(SV), MVT::i8); 2588 2589 // determine if we should load from reg_save_area or overflow_area 2590 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2591 2592 // increase overflow_area by 4/8 if gpr/fpr > 8 2593 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2594 DAG.getConstant(VT.isInteger() ? 4 : 8, 2595 dl, MVT::i32)); 2596 2597 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2598 OverflowAreaPlusN); 2599 2600 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2601 MachinePointerInfo(), MVT::i32); 2602 2603 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2604 } 2605 2606 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 2607 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2608 2609 // We have to copy the entire va_list struct: 2610 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2611 return DAG.getMemcpy(Op.getOperand(0), Op, 2612 Op.getOperand(1), Op.getOperand(2), 2613 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 2614 false, MachinePointerInfo(), MachinePointerInfo()); 2615 } 2616 2617 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2618 SelectionDAG &DAG) const { 2619 return Op.getOperand(0); 2620 } 2621 2622 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2623 SelectionDAG &DAG) const { 2624 SDValue Chain = Op.getOperand(0); 2625 SDValue Trmp = Op.getOperand(1); // trampoline 2626 SDValue FPtr = Op.getOperand(2); // nested function 2627 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2628 SDLoc dl(Op); 2629 2630 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2631 bool isPPC64 = (PtrVT == MVT::i64); 2632 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 2633 2634 TargetLowering::ArgListTy Args; 2635 TargetLowering::ArgListEntry Entry; 2636 2637 Entry.Ty = IntPtrTy; 2638 Entry.Node = Trmp; Args.push_back(Entry); 2639 2640 // TrampSize == (isPPC64 ? 48 : 40); 2641 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 2642 isPPC64 ? MVT::i64 : MVT::i32); 2643 Args.push_back(Entry); 2644 2645 Entry.Node = FPtr; Args.push_back(Entry); 2646 Entry.Node = Nest; Args.push_back(Entry); 2647 2648 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2649 TargetLowering::CallLoweringInfo CLI(DAG); 2650 CLI.setDebugLoc(dl).setChain(Chain) 2651 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2652 DAG.getExternalSymbol("__trampoline_setup", PtrVT), 2653 std::move(Args)); 2654 2655 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2656 return CallResult.second; 2657 } 2658 2659 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2660 MachineFunction &MF = DAG.getMachineFunction(); 2661 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2662 EVT PtrVT = getPointerTy(MF.getDataLayout()); 2663 2664 SDLoc dl(Op); 2665 2666 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2667 // vastart just stores the address of the VarArgsFrameIndex slot into the 2668 // memory location argument. 2669 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2670 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2671 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2672 MachinePointerInfo(SV)); 2673 } 2674 2675 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2676 // We suppose the given va_list is already allocated. 2677 // 2678 // typedef struct { 2679 // char gpr; /* index into the array of 8 GPRs 2680 // * stored in the register save area 2681 // * gpr=0 corresponds to r3, 2682 // * gpr=1 to r4, etc. 2683 // */ 2684 // char fpr; /* index into the array of 8 FPRs 2685 // * stored in the register save area 2686 // * fpr=0 corresponds to f1, 2687 // * fpr=1 to f2, etc. 2688 // */ 2689 // char *overflow_arg_area; 2690 // /* location on stack that holds 2691 // * the next overflow argument 2692 // */ 2693 // char *reg_save_area; 2694 // /* where r3:r10 and f1:f8 (if saved) 2695 // * are stored 2696 // */ 2697 // } va_list[1]; 2698 2699 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 2700 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 2701 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2702 PtrVT); 2703 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2704 PtrVT); 2705 2706 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2707 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 2708 2709 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2710 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 2711 2712 uint64_t FPROffset = 1; 2713 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 2714 2715 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2716 2717 // Store first byte : number of int regs 2718 SDValue firstStore = 2719 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 2720 MachinePointerInfo(SV), MVT::i8); 2721 uint64_t nextOffset = FPROffset; 2722 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2723 ConstFPROffset); 2724 2725 // Store second byte : number of float regs 2726 SDValue secondStore = 2727 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2728 MachinePointerInfo(SV, nextOffset), MVT::i8); 2729 nextOffset += StackOffset; 2730 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2731 2732 // Store second word : arguments given on stack 2733 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2734 MachinePointerInfo(SV, nextOffset)); 2735 nextOffset += FrameOffset; 2736 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2737 2738 // Store third word : arguments given in registers 2739 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2740 MachinePointerInfo(SV, nextOffset)); 2741 } 2742 2743 #include "PPCGenCallingConv.inc" 2744 2745 // Function whose sole purpose is to kill compiler warnings 2746 // stemming from unused functions included from PPCGenCallingConv.inc. 2747 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2748 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 2749 } 2750 2751 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 2752 CCValAssign::LocInfo &LocInfo, 2753 ISD::ArgFlagsTy &ArgFlags, 2754 CCState &State) { 2755 return true; 2756 } 2757 2758 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 2759 MVT &LocVT, 2760 CCValAssign::LocInfo &LocInfo, 2761 ISD::ArgFlagsTy &ArgFlags, 2762 CCState &State) { 2763 static const MCPhysReg ArgRegs[] = { 2764 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2765 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2766 }; 2767 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2768 2769 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2770 2771 // Skip one register if the first unallocated register has an even register 2772 // number and there are still argument registers available which have not been 2773 // allocated yet. RegNum is actually an index into ArgRegs, which means we 2774 // need to skip a register if RegNum is odd. 2775 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 2776 State.AllocateReg(ArgRegs[RegNum]); 2777 } 2778 2779 // Always return false here, as this function only makes sure that the first 2780 // unallocated register has an odd register number and does not actually 2781 // allocate a register for the current argument. 2782 return false; 2783 } 2784 2785 bool 2786 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 2787 MVT &LocVT, 2788 CCValAssign::LocInfo &LocInfo, 2789 ISD::ArgFlagsTy &ArgFlags, 2790 CCState &State) { 2791 static const MCPhysReg ArgRegs[] = { 2792 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2793 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2794 }; 2795 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2796 2797 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2798 int RegsLeft = NumArgRegs - RegNum; 2799 2800 // Skip if there is not enough registers left for long double type (4 gpr regs 2801 // in soft float mode) and put long double argument on the stack. 2802 if (RegNum != NumArgRegs && RegsLeft < 4) { 2803 for (int i = 0; i < RegsLeft; i++) { 2804 State.AllocateReg(ArgRegs[RegNum + i]); 2805 } 2806 } 2807 2808 return false; 2809 } 2810 2811 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 2812 MVT &LocVT, 2813 CCValAssign::LocInfo &LocInfo, 2814 ISD::ArgFlagsTy &ArgFlags, 2815 CCState &State) { 2816 static const MCPhysReg ArgRegs[] = { 2817 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 2818 PPC::F8 2819 }; 2820 2821 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2822 2823 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2824 2825 // If there is only one Floating-point register left we need to put both f64 2826 // values of a split ppc_fp128 value on the stack. 2827 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 2828 State.AllocateReg(ArgRegs[RegNum]); 2829 } 2830 2831 // Always return false here, as this function only makes sure that the two f64 2832 // values a ppc_fp128 value is split into are both passed in registers or both 2833 // passed on the stack and does not actually allocate a register for the 2834 // current argument. 2835 return false; 2836 } 2837 2838 /// FPR - The set of FP registers that should be allocated for arguments, 2839 /// on Darwin. 2840 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 2841 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 2842 PPC::F11, PPC::F12, PPC::F13}; 2843 2844 /// QFPR - The set of QPX registers that should be allocated for arguments. 2845 static const MCPhysReg QFPR[] = { 2846 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 2847 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 2848 2849 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 2850 /// the stack. 2851 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 2852 unsigned PtrByteSize) { 2853 unsigned ArgSize = ArgVT.getStoreSize(); 2854 if (Flags.isByVal()) 2855 ArgSize = Flags.getByValSize(); 2856 2857 // Round up to multiples of the pointer size, except for array members, 2858 // which are always packed. 2859 if (!Flags.isInConsecutiveRegs()) 2860 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2861 2862 return ArgSize; 2863 } 2864 2865 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 2866 /// on the stack. 2867 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 2868 ISD::ArgFlagsTy Flags, 2869 unsigned PtrByteSize) { 2870 unsigned Align = PtrByteSize; 2871 2872 // Altivec parameters are padded to a 16 byte boundary. 2873 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 2874 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 2875 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 2876 ArgVT == MVT::v1i128) 2877 Align = 16; 2878 // QPX vector types stored in double-precision are padded to a 32 byte 2879 // boundary. 2880 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 2881 Align = 32; 2882 2883 // ByVal parameters are aligned as requested. 2884 if (Flags.isByVal()) { 2885 unsigned BVAlign = Flags.getByValAlign(); 2886 if (BVAlign > PtrByteSize) { 2887 if (BVAlign % PtrByteSize != 0) 2888 llvm_unreachable( 2889 "ByVal alignment is not a multiple of the pointer size"); 2890 2891 Align = BVAlign; 2892 } 2893 } 2894 2895 // Array members are always packed to their original alignment. 2896 if (Flags.isInConsecutiveRegs()) { 2897 // If the array member was split into multiple registers, the first 2898 // needs to be aligned to the size of the full type. (Except for 2899 // ppcf128, which is only aligned as its f64 components.) 2900 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 2901 Align = OrigVT.getStoreSize(); 2902 else 2903 Align = ArgVT.getStoreSize(); 2904 } 2905 2906 return Align; 2907 } 2908 2909 /// CalculateStackSlotUsed - Return whether this argument will use its 2910 /// stack slot (instead of being passed in registers). ArgOffset, 2911 /// AvailableFPRs, and AvailableVRs must hold the current argument 2912 /// position, and will be updated to account for this argument. 2913 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 2914 ISD::ArgFlagsTy Flags, 2915 unsigned PtrByteSize, 2916 unsigned LinkageSize, 2917 unsigned ParamAreaSize, 2918 unsigned &ArgOffset, 2919 unsigned &AvailableFPRs, 2920 unsigned &AvailableVRs, bool HasQPX) { 2921 bool UseMemory = false; 2922 2923 // Respect alignment of argument on the stack. 2924 unsigned Align = 2925 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 2926 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 2927 // If there's no space left in the argument save area, we must 2928 // use memory (this check also catches zero-sized arguments). 2929 if (ArgOffset >= LinkageSize + ParamAreaSize) 2930 UseMemory = true; 2931 2932 // Allocate argument on the stack. 2933 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 2934 if (Flags.isInConsecutiveRegsLast()) 2935 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2936 // If we overran the argument save area, we must use memory 2937 // (this check catches arguments passed partially in memory) 2938 if (ArgOffset > LinkageSize + ParamAreaSize) 2939 UseMemory = true; 2940 2941 // However, if the argument is actually passed in an FPR or a VR, 2942 // we don't use memory after all. 2943 if (!Flags.isByVal()) { 2944 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 2945 // QPX registers overlap with the scalar FP registers. 2946 (HasQPX && (ArgVT == MVT::v4f32 || 2947 ArgVT == MVT::v4f64 || 2948 ArgVT == MVT::v4i1))) 2949 if (AvailableFPRs > 0) { 2950 --AvailableFPRs; 2951 return false; 2952 } 2953 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 2954 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 2955 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 2956 ArgVT == MVT::v1i128) 2957 if (AvailableVRs > 0) { 2958 --AvailableVRs; 2959 return false; 2960 } 2961 } 2962 2963 return UseMemory; 2964 } 2965 2966 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 2967 /// ensure minimum alignment required for target. 2968 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 2969 unsigned NumBytes) { 2970 unsigned TargetAlign = Lowering->getStackAlignment(); 2971 unsigned AlignMask = TargetAlign - 1; 2972 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 2973 return NumBytes; 2974 } 2975 2976 SDValue PPCTargetLowering::LowerFormalArguments( 2977 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2978 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2979 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2980 if (Subtarget.isSVR4ABI()) { 2981 if (Subtarget.isPPC64()) 2982 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 2983 dl, DAG, InVals); 2984 else 2985 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 2986 dl, DAG, InVals); 2987 } else { 2988 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 2989 dl, DAG, InVals); 2990 } 2991 } 2992 2993 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 2994 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2995 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 2996 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2997 2998 // 32-bit SVR4 ABI Stack Frame Layout: 2999 // +-----------------------------------+ 3000 // +--> | Back chain | 3001 // | +-----------------------------------+ 3002 // | | Floating-point register save area | 3003 // | +-----------------------------------+ 3004 // | | General register save area | 3005 // | +-----------------------------------+ 3006 // | | CR save word | 3007 // | +-----------------------------------+ 3008 // | | VRSAVE save word | 3009 // | +-----------------------------------+ 3010 // | | Alignment padding | 3011 // | +-----------------------------------+ 3012 // | | Vector register save area | 3013 // | +-----------------------------------+ 3014 // | | Local variable space | 3015 // | +-----------------------------------+ 3016 // | | Parameter list area | 3017 // | +-----------------------------------+ 3018 // | | LR save word | 3019 // | +-----------------------------------+ 3020 // SP--> +--- | Back chain | 3021 // +-----------------------------------+ 3022 // 3023 // Specifications: 3024 // System V Application Binary Interface PowerPC Processor Supplement 3025 // AltiVec Technology Programming Interface Manual 3026 3027 MachineFunction &MF = DAG.getMachineFunction(); 3028 MachineFrameInfo &MFI = MF.getFrameInfo(); 3029 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3030 3031 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3032 // Potential tail calls could cause overwriting of argument stack slots. 3033 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3034 (CallConv == CallingConv::Fast)); 3035 unsigned PtrByteSize = 4; 3036 3037 // Assign locations to all of the incoming arguments. 3038 SmallVector<CCValAssign, 16> ArgLocs; 3039 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3040 *DAG.getContext()); 3041 3042 // Reserve space for the linkage area on the stack. 3043 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3044 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3045 if (useSoftFloat()) 3046 CCInfo.PreAnalyzeFormalArguments(Ins); 3047 3048 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3049 CCInfo.clearWasPPCF128(); 3050 3051 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3052 CCValAssign &VA = ArgLocs[i]; 3053 3054 // Arguments stored in registers. 3055 if (VA.isRegLoc()) { 3056 const TargetRegisterClass *RC; 3057 EVT ValVT = VA.getValVT(); 3058 3059 switch (ValVT.getSimpleVT().SimpleTy) { 3060 default: 3061 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3062 case MVT::i1: 3063 case MVT::i32: 3064 RC = &PPC::GPRCRegClass; 3065 break; 3066 case MVT::f32: 3067 if (Subtarget.hasP8Vector()) 3068 RC = &PPC::VSSRCRegClass; 3069 else 3070 RC = &PPC::F4RCRegClass; 3071 break; 3072 case MVT::f64: 3073 if (Subtarget.hasVSX()) 3074 RC = &PPC::VSFRCRegClass; 3075 else 3076 RC = &PPC::F8RCRegClass; 3077 break; 3078 case MVT::v16i8: 3079 case MVT::v8i16: 3080 case MVT::v4i32: 3081 RC = &PPC::VRRCRegClass; 3082 break; 3083 case MVT::v4f32: 3084 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3085 break; 3086 case MVT::v2f64: 3087 case MVT::v2i64: 3088 RC = &PPC::VRRCRegClass; 3089 break; 3090 case MVT::v4f64: 3091 RC = &PPC::QFRCRegClass; 3092 break; 3093 case MVT::v4i1: 3094 RC = &PPC::QBRCRegClass; 3095 break; 3096 } 3097 3098 // Transform the arguments stored in physical registers into virtual ones. 3099 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3100 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3101 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3102 3103 if (ValVT == MVT::i1) 3104 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3105 3106 InVals.push_back(ArgValue); 3107 } else { 3108 // Argument stored in memory. 3109 assert(VA.isMemLoc()); 3110 3111 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3112 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(), 3113 isImmutable); 3114 3115 // Create load nodes to retrieve arguments from the stack. 3116 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3117 InVals.push_back( 3118 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3119 } 3120 } 3121 3122 // Assign locations to all of the incoming aggregate by value arguments. 3123 // Aggregates passed by value are stored in the local variable space of the 3124 // caller's stack frame, right above the parameter list area. 3125 SmallVector<CCValAssign, 16> ByValArgLocs; 3126 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3127 ByValArgLocs, *DAG.getContext()); 3128 3129 // Reserve stack space for the allocations in CCInfo. 3130 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3131 3132 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3133 3134 // Area that is at least reserved in the caller of this function. 3135 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3136 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3137 3138 // Set the size that is at least reserved in caller of this function. Tail 3139 // call optimized function's reserved stack space needs to be aligned so that 3140 // taking the difference between two stack areas will result in an aligned 3141 // stack. 3142 MinReservedArea = 3143 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3144 FuncInfo->setMinReservedArea(MinReservedArea); 3145 3146 SmallVector<SDValue, 8> MemOps; 3147 3148 // If the function takes variable number of arguments, make a frame index for 3149 // the start of the first vararg value... for expansion of llvm.va_start. 3150 if (isVarArg) { 3151 static const MCPhysReg GPArgRegs[] = { 3152 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3153 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3154 }; 3155 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3156 3157 static const MCPhysReg FPArgRegs[] = { 3158 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3159 PPC::F8 3160 }; 3161 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3162 3163 if (useSoftFloat()) 3164 NumFPArgRegs = 0; 3165 3166 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3167 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3168 3169 // Make room for NumGPArgRegs and NumFPArgRegs. 3170 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3171 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3172 3173 FuncInfo->setVarArgsStackOffset( 3174 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3175 CCInfo.getNextStackOffset(), true)); 3176 3177 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3178 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3179 3180 // The fixed integer arguments of a variadic function are stored to the 3181 // VarArgsFrameIndex on the stack so that they may be loaded by 3182 // dereferencing the result of va_next. 3183 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3184 // Get an existing live-in vreg, or add a new one. 3185 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3186 if (!VReg) 3187 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3188 3189 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3190 SDValue Store = 3191 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3192 MemOps.push_back(Store); 3193 // Increment the address by four for the next argument to store 3194 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3195 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3196 } 3197 3198 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3199 // is set. 3200 // The double arguments are stored to the VarArgsFrameIndex 3201 // on the stack. 3202 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3203 // Get an existing live-in vreg, or add a new one. 3204 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3205 if (!VReg) 3206 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3207 3208 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3209 SDValue Store = 3210 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3211 MemOps.push_back(Store); 3212 // Increment the address by eight for the next argument to store 3213 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3214 PtrVT); 3215 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3216 } 3217 } 3218 3219 if (!MemOps.empty()) 3220 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3221 3222 return Chain; 3223 } 3224 3225 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3226 // value to MVT::i64 and then truncate to the correct register size. 3227 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3228 EVT ObjectVT, SelectionDAG &DAG, 3229 SDValue ArgVal, 3230 const SDLoc &dl) const { 3231 if (Flags.isSExt()) 3232 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3233 DAG.getValueType(ObjectVT)); 3234 else if (Flags.isZExt()) 3235 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3236 DAG.getValueType(ObjectVT)); 3237 3238 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3239 } 3240 3241 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3242 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3243 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3244 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3245 // TODO: add description of PPC stack frame format, or at least some docs. 3246 // 3247 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3248 bool isLittleEndian = Subtarget.isLittleEndian(); 3249 MachineFunction &MF = DAG.getMachineFunction(); 3250 MachineFrameInfo &MFI = MF.getFrameInfo(); 3251 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3252 3253 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3254 "fastcc not supported on varargs functions"); 3255 3256 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3257 // Potential tail calls could cause overwriting of argument stack slots. 3258 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3259 (CallConv == CallingConv::Fast)); 3260 unsigned PtrByteSize = 8; 3261 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3262 3263 static const MCPhysReg GPR[] = { 3264 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3265 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3266 }; 3267 static const MCPhysReg VR[] = { 3268 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3269 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3270 }; 3271 3272 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3273 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3274 const unsigned Num_VR_Regs = array_lengthof(VR); 3275 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3276 3277 // Do a first pass over the arguments to determine whether the ABI 3278 // guarantees that our caller has allocated the parameter save area 3279 // on its stack frame. In the ELFv1 ABI, this is always the case; 3280 // in the ELFv2 ABI, it is true if this is a vararg function or if 3281 // any parameter is located in a stack slot. 3282 3283 bool HasParameterArea = !isELFv2ABI || isVarArg; 3284 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3285 unsigned NumBytes = LinkageSize; 3286 unsigned AvailableFPRs = Num_FPR_Regs; 3287 unsigned AvailableVRs = Num_VR_Regs; 3288 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3289 if (Ins[i].Flags.isNest()) 3290 continue; 3291 3292 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3293 PtrByteSize, LinkageSize, ParamAreaSize, 3294 NumBytes, AvailableFPRs, AvailableVRs, 3295 Subtarget.hasQPX())) 3296 HasParameterArea = true; 3297 } 3298 3299 // Add DAG nodes to load the arguments or copy them out of registers. On 3300 // entry to a function on PPC, the arguments start after the linkage area, 3301 // although the first ones are often in registers. 3302 3303 unsigned ArgOffset = LinkageSize; 3304 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3305 unsigned &QFPR_idx = FPR_idx; 3306 SmallVector<SDValue, 8> MemOps; 3307 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3308 unsigned CurArgIdx = 0; 3309 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3310 SDValue ArgVal; 3311 bool needsLoad = false; 3312 EVT ObjectVT = Ins[ArgNo].VT; 3313 EVT OrigVT = Ins[ArgNo].ArgVT; 3314 unsigned ObjSize = ObjectVT.getStoreSize(); 3315 unsigned ArgSize = ObjSize; 3316 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3317 if (Ins[ArgNo].isOrigArg()) { 3318 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3319 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3320 } 3321 // We re-align the argument offset for each argument, except when using the 3322 // fast calling convention, when we need to make sure we do that only when 3323 // we'll actually use a stack slot. 3324 unsigned CurArgOffset, Align; 3325 auto ComputeArgOffset = [&]() { 3326 /* Respect alignment of argument on the stack. */ 3327 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3328 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3329 CurArgOffset = ArgOffset; 3330 }; 3331 3332 if (CallConv != CallingConv::Fast) { 3333 ComputeArgOffset(); 3334 3335 /* Compute GPR index associated with argument offset. */ 3336 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3337 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3338 } 3339 3340 // FIXME the codegen can be much improved in some cases. 3341 // We do not have to keep everything in memory. 3342 if (Flags.isByVal()) { 3343 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3344 3345 if (CallConv == CallingConv::Fast) 3346 ComputeArgOffset(); 3347 3348 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3349 ObjSize = Flags.getByValSize(); 3350 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3351 // Empty aggregate parameters do not take up registers. Examples: 3352 // struct { } a; 3353 // union { } b; 3354 // int c[0]; 3355 // etc. However, we have to provide a place-holder in InVals, so 3356 // pretend we have an 8-byte item at the current address for that 3357 // purpose. 3358 if (!ObjSize) { 3359 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3360 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3361 InVals.push_back(FIN); 3362 continue; 3363 } 3364 3365 // Create a stack object covering all stack doublewords occupied 3366 // by the argument. If the argument is (fully or partially) on 3367 // the stack, or if the argument is fully in registers but the 3368 // caller has allocated the parameter save anyway, we can refer 3369 // directly to the caller's stack frame. Otherwise, create a 3370 // local copy in our own frame. 3371 int FI; 3372 if (HasParameterArea || 3373 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3374 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3375 else 3376 FI = MFI.CreateStackObject(ArgSize, Align, false); 3377 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3378 3379 // Handle aggregates smaller than 8 bytes. 3380 if (ObjSize < PtrByteSize) { 3381 // The value of the object is its address, which differs from the 3382 // address of the enclosing doubleword on big-endian systems. 3383 SDValue Arg = FIN; 3384 if (!isLittleEndian) { 3385 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3386 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3387 } 3388 InVals.push_back(Arg); 3389 3390 if (GPR_idx != Num_GPR_Regs) { 3391 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3392 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3393 SDValue Store; 3394 3395 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3396 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3397 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3398 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3399 MachinePointerInfo(&*FuncArg), ObjType); 3400 } else { 3401 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3402 // store the whole register as-is to the parameter save area 3403 // slot. 3404 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3405 MachinePointerInfo(&*FuncArg)); 3406 } 3407 3408 MemOps.push_back(Store); 3409 } 3410 // Whether we copied from a register or not, advance the offset 3411 // into the parameter save area by a full doubleword. 3412 ArgOffset += PtrByteSize; 3413 continue; 3414 } 3415 3416 // The value of the object is its address, which is the address of 3417 // its first stack doubleword. 3418 InVals.push_back(FIN); 3419 3420 // Store whatever pieces of the object are in registers to memory. 3421 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3422 if (GPR_idx == Num_GPR_Regs) 3423 break; 3424 3425 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3427 SDValue Addr = FIN; 3428 if (j) { 3429 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3430 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3431 } 3432 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3433 MachinePointerInfo(&*FuncArg, j)); 3434 MemOps.push_back(Store); 3435 ++GPR_idx; 3436 } 3437 ArgOffset += ArgSize; 3438 continue; 3439 } 3440 3441 switch (ObjectVT.getSimpleVT().SimpleTy) { 3442 default: llvm_unreachable("Unhandled argument type!"); 3443 case MVT::i1: 3444 case MVT::i32: 3445 case MVT::i64: 3446 if (Flags.isNest()) { 3447 // The 'nest' parameter, if any, is passed in R11. 3448 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3449 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3450 3451 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3452 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3453 3454 break; 3455 } 3456 3457 // These can be scalar arguments or elements of an integer array type 3458 // passed directly. Clang may use those instead of "byval" aggregate 3459 // types to avoid forcing arguments to memory unnecessarily. 3460 if (GPR_idx != Num_GPR_Regs) { 3461 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3462 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3463 3464 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3465 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3466 // value to MVT::i64 and then truncate to the correct register size. 3467 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3468 } else { 3469 if (CallConv == CallingConv::Fast) 3470 ComputeArgOffset(); 3471 3472 needsLoad = true; 3473 ArgSize = PtrByteSize; 3474 } 3475 if (CallConv != CallingConv::Fast || needsLoad) 3476 ArgOffset += 8; 3477 break; 3478 3479 case MVT::f32: 3480 case MVT::f64: 3481 // These can be scalar arguments or elements of a float array type 3482 // passed directly. The latter are used to implement ELFv2 homogenous 3483 // float aggregates. 3484 if (FPR_idx != Num_FPR_Regs) { 3485 unsigned VReg; 3486 3487 if (ObjectVT == MVT::f32) 3488 VReg = MF.addLiveIn(FPR[FPR_idx], 3489 Subtarget.hasP8Vector() 3490 ? &PPC::VSSRCRegClass 3491 : &PPC::F4RCRegClass); 3492 else 3493 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3494 ? &PPC::VSFRCRegClass 3495 : &PPC::F8RCRegClass); 3496 3497 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3498 ++FPR_idx; 3499 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3500 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3501 // once we support fp <-> gpr moves. 3502 3503 // This can only ever happen in the presence of f32 array types, 3504 // since otherwise we never run out of FPRs before running out 3505 // of GPRs. 3506 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3507 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3508 3509 if (ObjectVT == MVT::f32) { 3510 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3511 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3512 DAG.getConstant(32, dl, MVT::i32)); 3513 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3514 } 3515 3516 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3517 } else { 3518 if (CallConv == CallingConv::Fast) 3519 ComputeArgOffset(); 3520 3521 needsLoad = true; 3522 } 3523 3524 // When passing an array of floats, the array occupies consecutive 3525 // space in the argument area; only round up to the next doubleword 3526 // at the end of the array. Otherwise, each float takes 8 bytes. 3527 if (CallConv != CallingConv::Fast || needsLoad) { 3528 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3529 ArgOffset += ArgSize; 3530 if (Flags.isInConsecutiveRegsLast()) 3531 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3532 } 3533 break; 3534 case MVT::v4f32: 3535 case MVT::v4i32: 3536 case MVT::v8i16: 3537 case MVT::v16i8: 3538 case MVT::v2f64: 3539 case MVT::v2i64: 3540 case MVT::v1i128: 3541 if (!Subtarget.hasQPX()) { 3542 // These can be scalar arguments or elements of a vector array type 3543 // passed directly. The latter are used to implement ELFv2 homogenous 3544 // vector aggregates. 3545 if (VR_idx != Num_VR_Regs) { 3546 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3547 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3548 ++VR_idx; 3549 } else { 3550 if (CallConv == CallingConv::Fast) 3551 ComputeArgOffset(); 3552 3553 needsLoad = true; 3554 } 3555 if (CallConv != CallingConv::Fast || needsLoad) 3556 ArgOffset += 16; 3557 break; 3558 } // not QPX 3559 3560 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3561 "Invalid QPX parameter type"); 3562 /* fall through */ 3563 3564 case MVT::v4f64: 3565 case MVT::v4i1: 3566 // QPX vectors are treated like their scalar floating-point subregisters 3567 // (except that they're larger). 3568 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3569 if (QFPR_idx != Num_QFPR_Regs) { 3570 const TargetRegisterClass *RC; 3571 switch (ObjectVT.getSimpleVT().SimpleTy) { 3572 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3573 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3574 default: RC = &PPC::QBRCRegClass; break; 3575 } 3576 3577 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3578 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3579 ++QFPR_idx; 3580 } else { 3581 if (CallConv == CallingConv::Fast) 3582 ComputeArgOffset(); 3583 needsLoad = true; 3584 } 3585 if (CallConv != CallingConv::Fast || needsLoad) 3586 ArgOffset += Sz; 3587 break; 3588 } 3589 3590 // We need to load the argument to a virtual register if we determined 3591 // above that we ran out of physical registers of the appropriate type. 3592 if (needsLoad) { 3593 if (ObjSize < ArgSize && !isLittleEndian) 3594 CurArgOffset += ArgSize - ObjSize; 3595 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3596 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3597 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3598 } 3599 3600 InVals.push_back(ArgVal); 3601 } 3602 3603 // Area that is at least reserved in the caller of this function. 3604 unsigned MinReservedArea; 3605 if (HasParameterArea) 3606 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3607 else 3608 MinReservedArea = LinkageSize; 3609 3610 // Set the size that is at least reserved in caller of this function. Tail 3611 // call optimized functions' reserved stack space needs to be aligned so that 3612 // taking the difference between two stack areas will result in an aligned 3613 // stack. 3614 MinReservedArea = 3615 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3616 FuncInfo->setMinReservedArea(MinReservedArea); 3617 3618 // If the function takes variable number of arguments, make a frame index for 3619 // the start of the first vararg value... for expansion of llvm.va_start. 3620 if (isVarArg) { 3621 int Depth = ArgOffset; 3622 3623 FuncInfo->setVarArgsFrameIndex( 3624 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3625 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3626 3627 // If this function is vararg, store any remaining integer argument regs 3628 // to their spots on the stack so that they may be loaded by dereferencing 3629 // the result of va_next. 3630 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3631 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3632 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3633 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3634 SDValue Store = 3635 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3636 MemOps.push_back(Store); 3637 // Increment the address by four for the next argument to store 3638 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3639 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3640 } 3641 } 3642 3643 if (!MemOps.empty()) 3644 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3645 3646 return Chain; 3647 } 3648 3649 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3650 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3651 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3652 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3653 // TODO: add description of PPC stack frame format, or at least some docs. 3654 // 3655 MachineFunction &MF = DAG.getMachineFunction(); 3656 MachineFrameInfo &MFI = MF.getFrameInfo(); 3657 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3658 3659 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3660 bool isPPC64 = PtrVT == MVT::i64; 3661 // Potential tail calls could cause overwriting of argument stack slots. 3662 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3663 (CallConv == CallingConv::Fast)); 3664 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3665 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3666 unsigned ArgOffset = LinkageSize; 3667 // Area that is at least reserved in caller of this function. 3668 unsigned MinReservedArea = ArgOffset; 3669 3670 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3671 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3672 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3673 }; 3674 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3675 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3676 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3677 }; 3678 static const MCPhysReg VR[] = { 3679 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3680 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3681 }; 3682 3683 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3684 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3685 const unsigned Num_VR_Regs = array_lengthof( VR); 3686 3687 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3688 3689 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3690 3691 // In 32-bit non-varargs functions, the stack space for vectors is after the 3692 // stack space for non-vectors. We do not use this space unless we have 3693 // too many vectors to fit in registers, something that only occurs in 3694 // constructed examples:), but we have to walk the arglist to figure 3695 // that out...for the pathological case, compute VecArgOffset as the 3696 // start of the vector parameter area. Computing VecArgOffset is the 3697 // entire point of the following loop. 3698 unsigned VecArgOffset = ArgOffset; 3699 if (!isVarArg && !isPPC64) { 3700 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3701 ++ArgNo) { 3702 EVT ObjectVT = Ins[ArgNo].VT; 3703 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3704 3705 if (Flags.isByVal()) { 3706 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3707 unsigned ObjSize = Flags.getByValSize(); 3708 unsigned ArgSize = 3709 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3710 VecArgOffset += ArgSize; 3711 continue; 3712 } 3713 3714 switch(ObjectVT.getSimpleVT().SimpleTy) { 3715 default: llvm_unreachable("Unhandled argument type!"); 3716 case MVT::i1: 3717 case MVT::i32: 3718 case MVT::f32: 3719 VecArgOffset += 4; 3720 break; 3721 case MVT::i64: // PPC64 3722 case MVT::f64: 3723 // FIXME: We are guaranteed to be !isPPC64 at this point. 3724 // Does MVT::i64 apply? 3725 VecArgOffset += 8; 3726 break; 3727 case MVT::v4f32: 3728 case MVT::v4i32: 3729 case MVT::v8i16: 3730 case MVT::v16i8: 3731 // Nothing to do, we're only looking at Nonvector args here. 3732 break; 3733 } 3734 } 3735 } 3736 // We've found where the vector parameter area in memory is. Skip the 3737 // first 12 parameters; these don't use that memory. 3738 VecArgOffset = ((VecArgOffset+15)/16)*16; 3739 VecArgOffset += 12*16; 3740 3741 // Add DAG nodes to load the arguments or copy them out of registers. On 3742 // entry to a function on PPC, the arguments start after the linkage area, 3743 // although the first ones are often in registers. 3744 3745 SmallVector<SDValue, 8> MemOps; 3746 unsigned nAltivecParamsAtEnd = 0; 3747 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3748 unsigned CurArgIdx = 0; 3749 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3750 SDValue ArgVal; 3751 bool needsLoad = false; 3752 EVT ObjectVT = Ins[ArgNo].VT; 3753 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 3754 unsigned ArgSize = ObjSize; 3755 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3756 if (Ins[ArgNo].isOrigArg()) { 3757 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3758 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3759 } 3760 unsigned CurArgOffset = ArgOffset; 3761 3762 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 3763 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 3764 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 3765 if (isVarArg || isPPC64) { 3766 MinReservedArea = ((MinReservedArea+15)/16)*16; 3767 MinReservedArea += CalculateStackSlotSize(ObjectVT, 3768 Flags, 3769 PtrByteSize); 3770 } else nAltivecParamsAtEnd++; 3771 } else 3772 // Calculate min reserved area. 3773 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 3774 Flags, 3775 PtrByteSize); 3776 3777 // FIXME the codegen can be much improved in some cases. 3778 // We do not have to keep everything in memory. 3779 if (Flags.isByVal()) { 3780 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3781 3782 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3783 ObjSize = Flags.getByValSize(); 3784 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3785 // Objects of size 1 and 2 are right justified, everything else is 3786 // left justified. This means the memory address is adjusted forwards. 3787 if (ObjSize==1 || ObjSize==2) { 3788 CurArgOffset = CurArgOffset + (4 - ObjSize); 3789 } 3790 // The value of the object is its address. 3791 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 3792 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3793 InVals.push_back(FIN); 3794 if (ObjSize==1 || ObjSize==2) { 3795 if (GPR_idx != Num_GPR_Regs) { 3796 unsigned VReg; 3797 if (isPPC64) 3798 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3799 else 3800 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3801 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3802 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 3803 SDValue Store = 3804 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 3805 MachinePointerInfo(&*FuncArg), ObjType); 3806 MemOps.push_back(Store); 3807 ++GPR_idx; 3808 } 3809 3810 ArgOffset += PtrByteSize; 3811 3812 continue; 3813 } 3814 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3815 // Store whatever pieces of the object are in registers 3816 // to memory. ArgOffset will be the address of the beginning 3817 // of the object. 3818 if (GPR_idx != Num_GPR_Regs) { 3819 unsigned VReg; 3820 if (isPPC64) 3821 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3822 else 3823 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3824 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3825 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3826 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3827 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3828 MachinePointerInfo(&*FuncArg, j)); 3829 MemOps.push_back(Store); 3830 ++GPR_idx; 3831 ArgOffset += PtrByteSize; 3832 } else { 3833 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 3834 break; 3835 } 3836 } 3837 continue; 3838 } 3839 3840 switch (ObjectVT.getSimpleVT().SimpleTy) { 3841 default: llvm_unreachable("Unhandled argument type!"); 3842 case MVT::i1: 3843 case MVT::i32: 3844 if (!isPPC64) { 3845 if (GPR_idx != Num_GPR_Regs) { 3846 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3847 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3848 3849 if (ObjectVT == MVT::i1) 3850 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 3851 3852 ++GPR_idx; 3853 } else { 3854 needsLoad = true; 3855 ArgSize = PtrByteSize; 3856 } 3857 // All int arguments reserve stack space in the Darwin ABI. 3858 ArgOffset += PtrByteSize; 3859 break; 3860 } 3861 LLVM_FALLTHROUGH; 3862 case MVT::i64: // PPC64 3863 if (GPR_idx != Num_GPR_Regs) { 3864 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3865 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3866 3867 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3868 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3869 // value to MVT::i64 and then truncate to the correct register size. 3870 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3871 3872 ++GPR_idx; 3873 } else { 3874 needsLoad = true; 3875 ArgSize = PtrByteSize; 3876 } 3877 // All int arguments reserve stack space in the Darwin ABI. 3878 ArgOffset += 8; 3879 break; 3880 3881 case MVT::f32: 3882 case MVT::f64: 3883 // Every 4 bytes of argument space consumes one of the GPRs available for 3884 // argument passing. 3885 if (GPR_idx != Num_GPR_Regs) { 3886 ++GPR_idx; 3887 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 3888 ++GPR_idx; 3889 } 3890 if (FPR_idx != Num_FPR_Regs) { 3891 unsigned VReg; 3892 3893 if (ObjectVT == MVT::f32) 3894 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 3895 else 3896 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 3897 3898 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3899 ++FPR_idx; 3900 } else { 3901 needsLoad = true; 3902 } 3903 3904 // All FP arguments reserve stack space in the Darwin ABI. 3905 ArgOffset += isPPC64 ? 8 : ObjSize; 3906 break; 3907 case MVT::v4f32: 3908 case MVT::v4i32: 3909 case MVT::v8i16: 3910 case MVT::v16i8: 3911 // Note that vector arguments in registers don't reserve stack space, 3912 // except in varargs functions. 3913 if (VR_idx != Num_VR_Regs) { 3914 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3915 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3916 if (isVarArg) { 3917 while ((ArgOffset % 16) != 0) { 3918 ArgOffset += PtrByteSize; 3919 if (GPR_idx != Num_GPR_Regs) 3920 GPR_idx++; 3921 } 3922 ArgOffset += 16; 3923 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 3924 } 3925 ++VR_idx; 3926 } else { 3927 if (!isVarArg && !isPPC64) { 3928 // Vectors go after all the nonvectors. 3929 CurArgOffset = VecArgOffset; 3930 VecArgOffset += 16; 3931 } else { 3932 // Vectors are aligned. 3933 ArgOffset = ((ArgOffset+15)/16)*16; 3934 CurArgOffset = ArgOffset; 3935 ArgOffset += 16; 3936 } 3937 needsLoad = true; 3938 } 3939 break; 3940 } 3941 3942 // We need to load the argument to a virtual register if we determined above 3943 // that we ran out of physical registers of the appropriate type. 3944 if (needsLoad) { 3945 int FI = MFI.CreateFixedObject(ObjSize, 3946 CurArgOffset + (ArgSize - ObjSize), 3947 isImmutable); 3948 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3949 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3950 } 3951 3952 InVals.push_back(ArgVal); 3953 } 3954 3955 // Allow for Altivec parameters at the end, if needed. 3956 if (nAltivecParamsAtEnd) { 3957 MinReservedArea = ((MinReservedArea+15)/16)*16; 3958 MinReservedArea += 16*nAltivecParamsAtEnd; 3959 } 3960 3961 // Area that is at least reserved in the caller of this function. 3962 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 3963 3964 // Set the size that is at least reserved in caller of this function. Tail 3965 // call optimized functions' reserved stack space needs to be aligned so that 3966 // taking the difference between two stack areas will result in an aligned 3967 // stack. 3968 MinReservedArea = 3969 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3970 FuncInfo->setMinReservedArea(MinReservedArea); 3971 3972 // If the function takes variable number of arguments, make a frame index for 3973 // the start of the first vararg value... for expansion of llvm.va_start. 3974 if (isVarArg) { 3975 int Depth = ArgOffset; 3976 3977 FuncInfo->setVarArgsFrameIndex( 3978 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3979 Depth, true)); 3980 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3981 3982 // If this function is vararg, store any remaining integer argument regs 3983 // to their spots on the stack so that they may be loaded by dereferencing 3984 // the result of va_next. 3985 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 3986 unsigned VReg; 3987 3988 if (isPPC64) 3989 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3990 else 3991 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3992 3993 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3994 SDValue Store = 3995 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3996 MemOps.push_back(Store); 3997 // Increment the address by four for the next argument to store 3998 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3999 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4000 } 4001 } 4002 4003 if (!MemOps.empty()) 4004 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4005 4006 return Chain; 4007 } 4008 4009 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4010 /// adjusted to accommodate the arguments for the tailcall. 4011 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4012 unsigned ParamSize) { 4013 4014 if (!isTailCall) return 0; 4015 4016 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4017 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4018 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4019 // Remember only if the new adjustement is bigger. 4020 if (SPDiff < FI->getTailCallSPDelta()) 4021 FI->setTailCallSPDelta(SPDiff); 4022 4023 return SPDiff; 4024 } 4025 4026 static bool isFunctionGlobalAddress(SDValue Callee); 4027 4028 static bool 4029 resideInSameSection(const Function *Caller, SDValue Callee, 4030 const TargetMachine &TM) { 4031 // If !G, Callee can be an external symbol. 4032 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4033 if (!G) 4034 return false; 4035 4036 const GlobalValue *GV = G->getGlobal(); 4037 if (!GV->isStrongDefinitionForLinker()) 4038 return false; 4039 4040 // Any explicitly-specified sections and section prefixes must also match. 4041 // Also, if we're using -ffunction-sections, then each function is always in 4042 // a different section (the same is true for COMDAT functions). 4043 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4044 GV->getSection() != Caller->getSection()) 4045 return false; 4046 if (const auto *F = dyn_cast<Function>(GV)) { 4047 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4048 return false; 4049 } 4050 4051 // If the callee might be interposed, then we can't assume the ultimate call 4052 // target will be in the same section. Even in cases where we can assume that 4053 // interposition won't happen, in any case where the linker might insert a 4054 // stub to allow for interposition, we must generate code as though 4055 // interposition might occur. To understand why this matters, consider a 4056 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4057 // in the same section, but a is in a different module (i.e. has a different 4058 // TOC base pointer). If the linker allows for interposition between b and c, 4059 // then it will generate a stub for the call edge between b and c which will 4060 // save the TOC pointer into the designated stack slot allocated by b. If we 4061 // return true here, and therefore allow a tail call between b and c, that 4062 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4063 // pointer into the stack slot allocated by a (where the a -> b stub saved 4064 // a's TOC base pointer). If we're not considering a tail call, but rather, 4065 // whether a nop is needed after the call instruction in b, because the linker 4066 // will insert a stub, it might complain about a missing nop if we omit it 4067 // (although many don't complain in this case). 4068 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4069 return false; 4070 4071 return true; 4072 } 4073 4074 static bool 4075 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4076 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4077 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4078 4079 const unsigned PtrByteSize = 8; 4080 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4081 4082 static const MCPhysReg GPR[] = { 4083 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4084 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4085 }; 4086 static const MCPhysReg VR[] = { 4087 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4088 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4089 }; 4090 4091 const unsigned NumGPRs = array_lengthof(GPR); 4092 const unsigned NumFPRs = 13; 4093 const unsigned NumVRs = array_lengthof(VR); 4094 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4095 4096 unsigned NumBytes = LinkageSize; 4097 unsigned AvailableFPRs = NumFPRs; 4098 unsigned AvailableVRs = NumVRs; 4099 4100 for (const ISD::OutputArg& Param : Outs) { 4101 if (Param.Flags.isNest()) continue; 4102 4103 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4104 PtrByteSize, LinkageSize, ParamAreaSize, 4105 NumBytes, AvailableFPRs, AvailableVRs, 4106 Subtarget.hasQPX())) 4107 return true; 4108 } 4109 return false; 4110 } 4111 4112 static bool 4113 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) { 4114 if (CS->arg_size() != CallerFn->getArgumentList().size()) 4115 return false; 4116 4117 ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin(); 4118 ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end(); 4119 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4120 4121 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4122 const Value* CalleeArg = *CalleeArgIter; 4123 const Value* CallerArg = &(*CallerArgIter); 4124 if (CalleeArg == CallerArg) 4125 continue; 4126 4127 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4128 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4129 // } 4130 // 1st argument of callee is undef and has the same type as caller. 4131 if (CalleeArg->getType() == CallerArg->getType() && 4132 isa<UndefValue>(CalleeArg)) 4133 continue; 4134 4135 return false; 4136 } 4137 4138 return true; 4139 } 4140 4141 bool 4142 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4143 SDValue Callee, 4144 CallingConv::ID CalleeCC, 4145 ImmutableCallSite *CS, 4146 bool isVarArg, 4147 const SmallVectorImpl<ISD::OutputArg> &Outs, 4148 const SmallVectorImpl<ISD::InputArg> &Ins, 4149 SelectionDAG& DAG) const { 4150 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4151 4152 if (DisableSCO && !TailCallOpt) return false; 4153 4154 // Variadic argument functions are not supported. 4155 if (isVarArg) return false; 4156 4157 MachineFunction &MF = DAG.getMachineFunction(); 4158 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4159 4160 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has 4161 // the same calling convention 4162 if (CallerCC != CalleeCC) return false; 4163 4164 // SCO support C calling convention 4165 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C) 4166 return false; 4167 4168 // Caller contains any byval parameter is not supported. 4169 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4170 return false; 4171 4172 // Callee contains any byval parameter is not supported, too. 4173 // Note: This is a quick work around, because in some cases, e.g. 4174 // caller's stack size > callee's stack size, we are still able to apply 4175 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574 4176 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4177 return false; 4178 4179 // No TCO/SCO on indirect call because Caller have to restore its TOC 4180 if (!isFunctionGlobalAddress(Callee) && 4181 !isa<ExternalSymbolSDNode>(Callee)) 4182 return false; 4183 4184 // Check if Callee resides in the same section, because for now, PPC64 SVR4 4185 // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another 4186 // section. 4187 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4188 if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine())) 4189 return false; 4190 4191 // TCO allows altering callee ABI, so we don't have to check further. 4192 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4193 return true; 4194 4195 if (DisableSCO) return false; 4196 4197 // If callee use the same argument list that caller is using, then we can 4198 // apply SCO on this case. If it is not, then we need to check if callee needs 4199 // stack for passing arguments. 4200 if (!hasSameArgumentList(MF.getFunction(), CS) && 4201 needStackSlotPassParameters(Subtarget, Outs)) { 4202 return false; 4203 } 4204 4205 return true; 4206 } 4207 4208 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4209 /// for tail call optimization. Targets which want to do tail call 4210 /// optimization should implement this function. 4211 bool 4212 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4213 CallingConv::ID CalleeCC, 4214 bool isVarArg, 4215 const SmallVectorImpl<ISD::InputArg> &Ins, 4216 SelectionDAG& DAG) const { 4217 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4218 return false; 4219 4220 // Variable argument functions are not supported. 4221 if (isVarArg) 4222 return false; 4223 4224 MachineFunction &MF = DAG.getMachineFunction(); 4225 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4226 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4227 // Functions containing by val parameters are not supported. 4228 for (unsigned i = 0; i != Ins.size(); i++) { 4229 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4230 if (Flags.isByVal()) return false; 4231 } 4232 4233 // Non-PIC/GOT tail calls are supported. 4234 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4235 return true; 4236 4237 // At the moment we can only do local tail calls (in same module, hidden 4238 // or protected) if we are generating PIC. 4239 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4240 return G->getGlobal()->hasHiddenVisibility() 4241 || G->getGlobal()->hasProtectedVisibility(); 4242 } 4243 4244 return false; 4245 } 4246 4247 /// isCallCompatibleAddress - Return the immediate to use if the specified 4248 /// 32-bit value is representable in the immediate field of a BxA instruction. 4249 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4250 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4251 if (!C) return nullptr; 4252 4253 int Addr = C->getZExtValue(); 4254 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4255 SignExtend32<26>(Addr) != Addr) 4256 return nullptr; // Top 6 bits have to be sext of immediate. 4257 4258 return DAG 4259 .getConstant( 4260 (int)C->getZExtValue() >> 2, SDLoc(Op), 4261 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4262 .getNode(); 4263 } 4264 4265 namespace { 4266 4267 struct TailCallArgumentInfo { 4268 SDValue Arg; 4269 SDValue FrameIdxOp; 4270 int FrameIdx = 0; 4271 4272 TailCallArgumentInfo() = default; 4273 }; 4274 4275 } // end anonymous namespace 4276 4277 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4278 static void StoreTailCallArgumentsToStackSlot( 4279 SelectionDAG &DAG, SDValue Chain, 4280 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4281 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4282 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4283 SDValue Arg = TailCallArgs[i].Arg; 4284 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4285 int FI = TailCallArgs[i].FrameIdx; 4286 // Store relative to framepointer. 4287 MemOpChains.push_back(DAG.getStore( 4288 Chain, dl, Arg, FIN, 4289 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4290 } 4291 } 4292 4293 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4294 /// the appropriate stack slot for the tail call optimized function call. 4295 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4296 SDValue OldRetAddr, SDValue OldFP, 4297 int SPDiff, const SDLoc &dl) { 4298 if (SPDiff) { 4299 // Calculate the new stack slot for the return address. 4300 MachineFunction &MF = DAG.getMachineFunction(); 4301 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4302 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4303 bool isPPC64 = Subtarget.isPPC64(); 4304 int SlotSize = isPPC64 ? 8 : 4; 4305 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4306 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4307 NewRetAddrLoc, true); 4308 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4309 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4310 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4311 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4312 4313 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4314 // slot as the FP is never overwritten. 4315 if (Subtarget.isDarwinABI()) { 4316 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4317 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4318 true); 4319 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4320 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4321 MachinePointerInfo::getFixedStack( 4322 DAG.getMachineFunction(), NewFPIdx)); 4323 } 4324 } 4325 return Chain; 4326 } 4327 4328 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4329 /// the position of the argument. 4330 static void 4331 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4332 SDValue Arg, int SPDiff, unsigned ArgOffset, 4333 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4334 int Offset = ArgOffset + SPDiff; 4335 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4336 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4337 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4338 SDValue FIN = DAG.getFrameIndex(FI, VT); 4339 TailCallArgumentInfo Info; 4340 Info.Arg = Arg; 4341 Info.FrameIdxOp = FIN; 4342 Info.FrameIdx = FI; 4343 TailCallArguments.push_back(Info); 4344 } 4345 4346 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4347 /// stack slot. Returns the chain as result and the loaded frame pointers in 4348 /// LROpOut/FPOpout. Used when tail calling. 4349 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4350 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4351 SDValue &FPOpOut, const SDLoc &dl) const { 4352 if (SPDiff) { 4353 // Load the LR and FP stack slot for later adjusting. 4354 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4355 LROpOut = getReturnAddrFrameIndex(DAG); 4356 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4357 Chain = SDValue(LROpOut.getNode(), 1); 4358 4359 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4360 // slot as the FP is never overwritten. 4361 if (Subtarget.isDarwinABI()) { 4362 FPOpOut = getFramePointerFrameIndex(DAG); 4363 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4364 Chain = SDValue(FPOpOut.getNode(), 1); 4365 } 4366 } 4367 return Chain; 4368 } 4369 4370 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4371 /// by "Src" to address "Dst" of size "Size". Alignment information is 4372 /// specified by the specific parameter attribute. The copy will be passed as 4373 /// a byval function parameter. 4374 /// Sometimes what we are copying is the end of a larger object, the part that 4375 /// does not fit in registers. 4376 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4377 SDValue Chain, ISD::ArgFlagsTy Flags, 4378 SelectionDAG &DAG, const SDLoc &dl) { 4379 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4380 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4381 false, false, false, MachinePointerInfo(), 4382 MachinePointerInfo()); 4383 } 4384 4385 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4386 /// tail calls. 4387 static void LowerMemOpCallTo( 4388 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4389 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4390 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4391 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4392 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4393 if (!isTailCall) { 4394 if (isVector) { 4395 SDValue StackPtr; 4396 if (isPPC64) 4397 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4398 else 4399 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4400 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4401 DAG.getConstant(ArgOffset, dl, PtrVT)); 4402 } 4403 MemOpChains.push_back( 4404 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4405 // Calculate and remember argument location. 4406 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4407 TailCallArguments); 4408 } 4409 4410 static void 4411 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4412 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4413 SDValue FPOp, 4414 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4415 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4416 // might overwrite each other in case of tail call optimization. 4417 SmallVector<SDValue, 8> MemOpChains2; 4418 // Do not flag preceding copytoreg stuff together with the following stuff. 4419 InFlag = SDValue(); 4420 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4421 MemOpChains2, dl); 4422 if (!MemOpChains2.empty()) 4423 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4424 4425 // Store the return address to the appropriate stack slot. 4426 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4427 4428 // Emit callseq_end just before tailcall node. 4429 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4430 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4431 InFlag = Chain.getValue(1); 4432 } 4433 4434 // Is this global address that of a function that can be called by name? (as 4435 // opposed to something that must hold a descriptor for an indirect call). 4436 static bool isFunctionGlobalAddress(SDValue Callee) { 4437 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4438 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4439 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4440 return false; 4441 4442 return G->getGlobal()->getValueType()->isFunctionTy(); 4443 } 4444 4445 return false; 4446 } 4447 4448 static unsigned 4449 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4450 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4451 bool isPatchPoint, bool hasNest, 4452 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4453 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4454 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) { 4455 bool isPPC64 = Subtarget.isPPC64(); 4456 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4457 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4458 4459 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4460 NodeTys.push_back(MVT::Other); // Returns a chain 4461 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4462 4463 unsigned CallOpc = PPCISD::CALL; 4464 4465 bool needIndirectCall = true; 4466 if (!isSVR4ABI || !isPPC64) 4467 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4468 // If this is an absolute destination address, use the munged value. 4469 Callee = SDValue(Dest, 0); 4470 needIndirectCall = false; 4471 } 4472 4473 // PC-relative references to external symbols should go through $stub, unless 4474 // we're building with the leopard linker or later, which automatically 4475 // synthesizes these stubs. 4476 const TargetMachine &TM = DAG.getTarget(); 4477 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent(); 4478 const GlobalValue *GV = nullptr; 4479 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4480 GV = G->getGlobal(); 4481 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4482 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4483 4484 if (isFunctionGlobalAddress(Callee)) { 4485 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4486 // A call to a TLS address is actually an indirect call to a 4487 // thread-specific pointer. 4488 unsigned OpFlags = 0; 4489 if (UsePlt) 4490 OpFlags = PPCII::MO_PLT; 4491 4492 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4493 // every direct call is) turn it into a TargetGlobalAddress / 4494 // TargetExternalSymbol node so that legalize doesn't hack it. 4495 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4496 Callee.getValueType(), 0, OpFlags); 4497 needIndirectCall = false; 4498 } 4499 4500 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4501 unsigned char OpFlags = 0; 4502 4503 if (UsePlt) 4504 OpFlags = PPCII::MO_PLT; 4505 4506 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4507 OpFlags); 4508 needIndirectCall = false; 4509 } 4510 4511 if (isPatchPoint) { 4512 // We'll form an invalid direct call when lowering a patchpoint; the full 4513 // sequence for an indirect call is complicated, and many of the 4514 // instructions introduced might have side effects (and, thus, can't be 4515 // removed later). The call itself will be removed as soon as the 4516 // argument/return lowering is complete, so the fact that it has the wrong 4517 // kind of operands should not really matter. 4518 needIndirectCall = false; 4519 } 4520 4521 if (needIndirectCall) { 4522 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4523 // to do the call, we can't use PPCISD::CALL. 4524 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4525 4526 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4527 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4528 // entry point, but to the function descriptor (the function entry point 4529 // address is part of the function descriptor though). 4530 // The function descriptor is a three doubleword structure with the 4531 // following fields: function entry point, TOC base address and 4532 // environment pointer. 4533 // Thus for a call through a function pointer, the following actions need 4534 // to be performed: 4535 // 1. Save the TOC of the caller in the TOC save area of its stack 4536 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4537 // 2. Load the address of the function entry point from the function 4538 // descriptor. 4539 // 3. Load the TOC of the callee from the function descriptor into r2. 4540 // 4. Load the environment pointer from the function descriptor into 4541 // r11. 4542 // 5. Branch to the function entry point address. 4543 // 6. On return of the callee, the TOC of the caller needs to be 4544 // restored (this is done in FinishCall()). 4545 // 4546 // The loads are scheduled at the beginning of the call sequence, and the 4547 // register copies are flagged together to ensure that no other 4548 // operations can be scheduled in between. E.g. without flagging the 4549 // copies together, a TOC access in the caller could be scheduled between 4550 // the assignment of the callee TOC and the branch to the callee, which 4551 // results in the TOC access going through the TOC of the callee instead 4552 // of going through the TOC of the caller, which leads to incorrect code. 4553 4554 // Load the address of the function entry point from the function 4555 // descriptor. 4556 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4557 if (LDChain.getValueType() == MVT::Glue) 4558 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4559 4560 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4561 ? (MachineMemOperand::MODereferenceable | 4562 MachineMemOperand::MOInvariant) 4563 : MachineMemOperand::MONone; 4564 4565 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr); 4566 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4567 /* Alignment = */ 8, MMOFlags); 4568 4569 // Load environment pointer into r11. 4570 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4571 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4572 SDValue LoadEnvPtr = 4573 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4574 /* Alignment = */ 8, MMOFlags); 4575 4576 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4577 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4578 SDValue TOCPtr = 4579 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4580 /* Alignment = */ 8, MMOFlags); 4581 4582 setUsesTOCBasePtr(DAG); 4583 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4584 InFlag); 4585 Chain = TOCVal.getValue(0); 4586 InFlag = TOCVal.getValue(1); 4587 4588 // If the function call has an explicit 'nest' parameter, it takes the 4589 // place of the environment pointer. 4590 if (!hasNest) { 4591 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4592 InFlag); 4593 4594 Chain = EnvVal.getValue(0); 4595 InFlag = EnvVal.getValue(1); 4596 } 4597 4598 MTCTROps[0] = Chain; 4599 MTCTROps[1] = LoadFuncPtr; 4600 MTCTROps[2] = InFlag; 4601 } 4602 4603 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4604 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4605 InFlag = Chain.getValue(1); 4606 4607 NodeTys.clear(); 4608 NodeTys.push_back(MVT::Other); 4609 NodeTys.push_back(MVT::Glue); 4610 Ops.push_back(Chain); 4611 CallOpc = PPCISD::BCTRL; 4612 Callee.setNode(nullptr); 4613 // Add use of X11 (holding environment pointer) 4614 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4615 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4616 // Add CTR register as callee so a bctr can be emitted later. 4617 if (isTailCall) 4618 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4619 } 4620 4621 // If this is a direct call, pass the chain and the callee. 4622 if (Callee.getNode()) { 4623 Ops.push_back(Chain); 4624 Ops.push_back(Callee); 4625 } 4626 // If this is a tail call add stack pointer delta. 4627 if (isTailCall) 4628 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 4629 4630 // Add argument registers to the end of the list so that they are known live 4631 // into the call. 4632 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4633 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4634 RegsToPass[i].second.getValueType())); 4635 4636 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4637 // into the call. 4638 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 4639 setUsesTOCBasePtr(DAG); 4640 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4641 } 4642 4643 return CallOpc; 4644 } 4645 4646 SDValue PPCTargetLowering::LowerCallResult( 4647 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4648 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4649 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4650 SmallVector<CCValAssign, 16> RVLocs; 4651 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4652 *DAG.getContext()); 4653 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 4654 4655 // Copy all of the result registers out of their specified physreg. 4656 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4657 CCValAssign &VA = RVLocs[i]; 4658 assert(VA.isRegLoc() && "Can only return in registers!"); 4659 4660 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4661 VA.getLocReg(), VA.getLocVT(), InFlag); 4662 Chain = Val.getValue(1); 4663 InFlag = Val.getValue(2); 4664 4665 switch (VA.getLocInfo()) { 4666 default: llvm_unreachable("Unknown loc info!"); 4667 case CCValAssign::Full: break; 4668 case CCValAssign::AExt: 4669 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4670 break; 4671 case CCValAssign::ZExt: 4672 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4673 DAG.getValueType(VA.getValVT())); 4674 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4675 break; 4676 case CCValAssign::SExt: 4677 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4678 DAG.getValueType(VA.getValVT())); 4679 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4680 break; 4681 } 4682 4683 InVals.push_back(Val); 4684 } 4685 4686 return Chain; 4687 } 4688 4689 SDValue PPCTargetLowering::FinishCall( 4690 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 4691 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 4692 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 4693 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 4694 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 4695 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const { 4696 std::vector<EVT> NodeTys; 4697 SmallVector<SDValue, 8> Ops; 4698 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 4699 SPDiff, isTailCall, isPatchPoint, hasNest, 4700 RegsToPass, Ops, NodeTys, CS, Subtarget); 4701 4702 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 4703 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 4704 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 4705 4706 // When performing tail call optimization the callee pops its arguments off 4707 // the stack. Account for this here so these bytes can be pushed back on in 4708 // PPCFrameLowering::eliminateCallFramePseudoInstr. 4709 int BytesCalleePops = 4710 (CallConv == CallingConv::Fast && 4711 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 4712 4713 // Add a register mask operand representing the call-preserved registers. 4714 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4715 const uint32_t *Mask = 4716 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 4717 assert(Mask && "Missing call preserved mask for calling convention"); 4718 Ops.push_back(DAG.getRegisterMask(Mask)); 4719 4720 if (InFlag.getNode()) 4721 Ops.push_back(InFlag); 4722 4723 // Emit tail call. 4724 if (isTailCall) { 4725 assert(((Callee.getOpcode() == ISD::Register && 4726 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 4727 Callee.getOpcode() == ISD::TargetExternalSymbol || 4728 Callee.getOpcode() == ISD::TargetGlobalAddress || 4729 isa<ConstantSDNode>(Callee)) && 4730 "Expecting an global address, external symbol, absolute value or register"); 4731 4732 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 4733 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 4734 } 4735 4736 // Add a NOP immediately after the branch instruction when using the 64-bit 4737 // SVR4 ABI. At link time, if caller and callee are in a different module and 4738 // thus have a different TOC, the call will be replaced with a call to a stub 4739 // function which saves the current TOC, loads the TOC of the callee and 4740 // branches to the callee. The NOP will be replaced with a load instruction 4741 // which restores the TOC of the caller from the TOC save slot of the current 4742 // stack frame. If caller and callee belong to the same module (and have the 4743 // same TOC), the NOP will remain unchanged. 4744 4745 MachineFunction &MF = DAG.getMachineFunction(); 4746 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 4747 !isPatchPoint) { 4748 if (CallOpc == PPCISD::BCTRL) { 4749 // This is a call through a function pointer. 4750 // Restore the caller TOC from the save area into R2. 4751 // See PrepareCall() for more information about calls through function 4752 // pointers in the 64-bit SVR4 ABI. 4753 // We are using a target-specific load with r2 hard coded, because the 4754 // result of a target-independent load would never go directly into r2, 4755 // since r2 is a reserved register (which prevents the register allocator 4756 // from allocating it), resulting in an additional register being 4757 // allocated and an unnecessary move instruction being generated. 4758 CallOpc = PPCISD::BCTRL_LOAD_TOC; 4759 4760 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4761 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 4762 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 4763 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 4764 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 4765 4766 // The address needs to go after the chain input but before the flag (or 4767 // any other variadic arguments). 4768 Ops.insert(std::next(Ops.begin()), AddTOC); 4769 } else if (CallOpc == PPCISD::CALL && 4770 !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) { 4771 // Otherwise insert NOP for non-local calls. 4772 CallOpc = PPCISD::CALL_NOP; 4773 } 4774 } 4775 4776 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 4777 InFlag = Chain.getValue(1); 4778 4779 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4780 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 4781 InFlag, dl); 4782 if (!Ins.empty()) 4783 InFlag = Chain.getValue(1); 4784 4785 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 4786 Ins, dl, DAG, InVals); 4787 } 4788 4789 SDValue 4790 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 4791 SmallVectorImpl<SDValue> &InVals) const { 4792 SelectionDAG &DAG = CLI.DAG; 4793 SDLoc &dl = CLI.DL; 4794 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 4795 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 4796 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 4797 SDValue Chain = CLI.Chain; 4798 SDValue Callee = CLI.Callee; 4799 bool &isTailCall = CLI.IsTailCall; 4800 CallingConv::ID CallConv = CLI.CallConv; 4801 bool isVarArg = CLI.IsVarArg; 4802 bool isPatchPoint = CLI.IsPatchPoint; 4803 ImmutableCallSite *CS = CLI.CS; 4804 4805 if (isTailCall) { 4806 if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall())) 4807 isTailCall = false; 4808 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 4809 isTailCall = 4810 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 4811 isVarArg, Outs, Ins, DAG); 4812 else 4813 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 4814 Ins, DAG); 4815 if (isTailCall) { 4816 ++NumTailCalls; 4817 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4818 ++NumSiblingCalls; 4819 4820 assert(isa<GlobalAddressSDNode>(Callee) && 4821 "Callee should be an llvm::Function object."); 4822 DEBUG( 4823 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 4824 const unsigned Width = 80 - strlen("TCO caller: ") 4825 - strlen(", callee linkage: 0, 0"); 4826 dbgs() << "TCO caller: " 4827 << left_justify(DAG.getMachineFunction().getName(), Width) 4828 << ", callee linkage: " 4829 << GV->getVisibility() << ", " << GV->getLinkage() << "\n" 4830 ); 4831 } 4832 } 4833 4834 if (!isTailCall && CS && CS->isMustTailCall()) 4835 report_fatal_error("failed to perform tail call elimination on a call " 4836 "site marked musttail"); 4837 4838 // When long calls (i.e. indirect calls) are always used, calls are always 4839 // made via function pointer. If we have a function name, first translate it 4840 // into a pointer. 4841 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 4842 !isTailCall) 4843 Callee = LowerGlobalAddress(Callee, DAG); 4844 4845 if (Subtarget.isSVR4ABI()) { 4846 if (Subtarget.isPPC64()) 4847 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 4848 isTailCall, isPatchPoint, Outs, OutVals, Ins, 4849 dl, DAG, InVals, CS); 4850 else 4851 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 4852 isTailCall, isPatchPoint, Outs, OutVals, Ins, 4853 dl, DAG, InVals, CS); 4854 } 4855 4856 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 4857 isTailCall, isPatchPoint, Outs, OutVals, Ins, 4858 dl, DAG, InVals, CS); 4859 } 4860 4861 SDValue PPCTargetLowering::LowerCall_32SVR4( 4862 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 4863 bool isTailCall, bool isPatchPoint, 4864 const SmallVectorImpl<ISD::OutputArg> &Outs, 4865 const SmallVectorImpl<SDValue> &OutVals, 4866 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4867 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 4868 ImmutableCallSite *CS) const { 4869 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 4870 // of the 32-bit SVR4 ABI stack frame layout. 4871 4872 assert((CallConv == CallingConv::C || 4873 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 4874 4875 unsigned PtrByteSize = 4; 4876 4877 MachineFunction &MF = DAG.getMachineFunction(); 4878 4879 // Mark this function as potentially containing a function that contains a 4880 // tail call. As a consequence the frame pointer will be used for dynamicalloc 4881 // and restoring the callers stack pointer in this functions epilog. This is 4882 // done because by tail calling the called function might overwrite the value 4883 // in this function's (MF) stack pointer stack slot 0(SP). 4884 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4885 CallConv == CallingConv::Fast) 4886 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 4887 4888 // Count how many bytes are to be pushed on the stack, including the linkage 4889 // area, parameter list area and the part of the local variable space which 4890 // contains copies of aggregates which are passed by value. 4891 4892 // Assign locations to all of the outgoing arguments. 4893 SmallVector<CCValAssign, 16> ArgLocs; 4894 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 4895 4896 // Reserve space for the linkage area on the stack. 4897 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 4898 PtrByteSize); 4899 if (useSoftFloat()) 4900 CCInfo.PreAnalyzeCallOperands(Outs); 4901 4902 if (isVarArg) { 4903 // Handle fixed and variable vector arguments differently. 4904 // Fixed vector arguments go into registers as long as registers are 4905 // available. Variable vector arguments always go into memory. 4906 unsigned NumArgs = Outs.size(); 4907 4908 for (unsigned i = 0; i != NumArgs; ++i) { 4909 MVT ArgVT = Outs[i].VT; 4910 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4911 bool Result; 4912 4913 if (Outs[i].IsFixed) { 4914 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 4915 CCInfo); 4916 } else { 4917 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 4918 ArgFlags, CCInfo); 4919 } 4920 4921 if (Result) { 4922 #ifndef NDEBUG 4923 errs() << "Call operand #" << i << " has unhandled type " 4924 << EVT(ArgVT).getEVTString() << "\n"; 4925 #endif 4926 llvm_unreachable(nullptr); 4927 } 4928 } 4929 } else { 4930 // All arguments are treated the same. 4931 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 4932 } 4933 CCInfo.clearWasPPCF128(); 4934 4935 // Assign locations to all of the outgoing aggregate by value arguments. 4936 SmallVector<CCValAssign, 16> ByValArgLocs; 4937 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 4938 4939 // Reserve stack space for the allocations in CCInfo. 4940 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 4941 4942 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 4943 4944 // Size of the linkage area, parameter list area and the part of the local 4945 // space variable where copies of aggregates which are passed by value are 4946 // stored. 4947 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 4948 4949 // Calculate by how many bytes the stack has to be adjusted in case of tail 4950 // call optimization. 4951 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 4952 4953 // Adjust the stack pointer for the new arguments... 4954 // These operations are automatically eliminated by the prolog/epilog pass 4955 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4956 dl); 4957 SDValue CallSeqStart = Chain; 4958 4959 // Load the return address and frame pointer so it can be moved somewhere else 4960 // later. 4961 SDValue LROp, FPOp; 4962 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 4963 4964 // Set up a copy of the stack pointer for use loading and storing any 4965 // arguments that may not fit in the registers available for argument 4966 // passing. 4967 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4968 4969 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4970 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 4971 SmallVector<SDValue, 8> MemOpChains; 4972 4973 bool seenFloatArg = false; 4974 // Walk the register/memloc assignments, inserting copies/loads. 4975 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 4976 i != e; 4977 ++i) { 4978 CCValAssign &VA = ArgLocs[i]; 4979 SDValue Arg = OutVals[i]; 4980 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4981 4982 if (Flags.isByVal()) { 4983 // Argument is an aggregate which is passed by value, thus we need to 4984 // create a copy of it in the local variable space of the current stack 4985 // frame (which is the stack frame of the caller) and pass the address of 4986 // this copy to the callee. 4987 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 4988 CCValAssign &ByValVA = ByValArgLocs[j++]; 4989 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 4990 4991 // Memory reserved in the local variable space of the callers stack frame. 4992 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 4993 4994 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 4995 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 4996 StackPtr, PtrOff); 4997 4998 // Create a copy of the argument in the local area of the current 4999 // stack frame. 5000 SDValue MemcpyCall = 5001 CreateCopyOfByValArgument(Arg, PtrOff, 5002 CallSeqStart.getNode()->getOperand(0), 5003 Flags, DAG, dl); 5004 5005 // This must go outside the CALLSEQ_START..END. 5006 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 5007 CallSeqStart.getNode()->getOperand(1), 5008 SDLoc(MemcpyCall)); 5009 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5010 NewCallSeqStart.getNode()); 5011 Chain = CallSeqStart = NewCallSeqStart; 5012 5013 // Pass the address of the aggregate copy on the stack either in a 5014 // physical register or in the parameter list area of the current stack 5015 // frame to the callee. 5016 Arg = PtrOff; 5017 } 5018 5019 if (VA.isRegLoc()) { 5020 if (Arg.getValueType() == MVT::i1) 5021 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 5022 5023 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5024 // Put argument in a physical register. 5025 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5026 } else { 5027 // Put argument in the parameter list area of the current stack frame. 5028 assert(VA.isMemLoc()); 5029 unsigned LocMemOffset = VA.getLocMemOffset(); 5030 5031 if (!isTailCall) { 5032 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5033 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5034 StackPtr, PtrOff); 5035 5036 MemOpChains.push_back( 5037 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5038 } else { 5039 // Calculate and remember argument location. 5040 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5041 TailCallArguments); 5042 } 5043 } 5044 } 5045 5046 if (!MemOpChains.empty()) 5047 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5048 5049 // Build a sequence of copy-to-reg nodes chained together with token chain 5050 // and flag operands which copy the outgoing args into the appropriate regs. 5051 SDValue InFlag; 5052 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5053 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5054 RegsToPass[i].second, InFlag); 5055 InFlag = Chain.getValue(1); 5056 } 5057 5058 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5059 // registers. 5060 if (isVarArg) { 5061 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5062 SDValue Ops[] = { Chain, InFlag }; 5063 5064 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5065 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5066 5067 InFlag = Chain.getValue(1); 5068 } 5069 5070 if (isTailCall) 5071 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5072 TailCallArguments); 5073 5074 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5075 /* unused except on PPC64 ELFv1 */ false, DAG, 5076 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5077 NumBytes, Ins, InVals, CS); 5078 } 5079 5080 // Copy an argument into memory, being careful to do this outside the 5081 // call sequence for the call to which the argument belongs. 5082 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5083 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5084 SelectionDAG &DAG, const SDLoc &dl) const { 5085 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5086 CallSeqStart.getNode()->getOperand(0), 5087 Flags, DAG, dl); 5088 // The MEMCPY must go outside the CALLSEQ_START..END. 5089 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 5090 CallSeqStart.getNode()->getOperand(1), 5091 SDLoc(MemcpyCall)); 5092 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5093 NewCallSeqStart.getNode()); 5094 return NewCallSeqStart; 5095 } 5096 5097 SDValue PPCTargetLowering::LowerCall_64SVR4( 5098 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5099 bool isTailCall, bool isPatchPoint, 5100 const SmallVectorImpl<ISD::OutputArg> &Outs, 5101 const SmallVectorImpl<SDValue> &OutVals, 5102 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5103 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5104 ImmutableCallSite *CS) const { 5105 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5106 bool isLittleEndian = Subtarget.isLittleEndian(); 5107 unsigned NumOps = Outs.size(); 5108 bool hasNest = false; 5109 bool IsSibCall = false; 5110 5111 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5112 unsigned PtrByteSize = 8; 5113 5114 MachineFunction &MF = DAG.getMachineFunction(); 5115 5116 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5117 IsSibCall = true; 5118 5119 // Mark this function as potentially containing a function that contains a 5120 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5121 // and restoring the callers stack pointer in this functions epilog. This is 5122 // done because by tail calling the called function might overwrite the value 5123 // in this function's (MF) stack pointer stack slot 0(SP). 5124 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5125 CallConv == CallingConv::Fast) 5126 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5127 5128 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5129 "fastcc not supported on varargs functions"); 5130 5131 // Count how many bytes are to be pushed on the stack, including the linkage 5132 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5133 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5134 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5135 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5136 unsigned NumBytes = LinkageSize; 5137 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5138 unsigned &QFPR_idx = FPR_idx; 5139 5140 static const MCPhysReg GPR[] = { 5141 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5142 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5143 }; 5144 static const MCPhysReg VR[] = { 5145 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5146 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5147 }; 5148 5149 const unsigned NumGPRs = array_lengthof(GPR); 5150 const unsigned NumFPRs = 13; 5151 const unsigned NumVRs = array_lengthof(VR); 5152 const unsigned NumQFPRs = NumFPRs; 5153 5154 // When using the fast calling convention, we don't provide backing for 5155 // arguments that will be in registers. 5156 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5157 5158 // Add up all the space actually used. 5159 for (unsigned i = 0; i != NumOps; ++i) { 5160 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5161 EVT ArgVT = Outs[i].VT; 5162 EVT OrigVT = Outs[i].ArgVT; 5163 5164 if (Flags.isNest()) 5165 continue; 5166 5167 if (CallConv == CallingConv::Fast) { 5168 if (Flags.isByVal()) 5169 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5170 else 5171 switch (ArgVT.getSimpleVT().SimpleTy) { 5172 default: llvm_unreachable("Unexpected ValueType for argument!"); 5173 case MVT::i1: 5174 case MVT::i32: 5175 case MVT::i64: 5176 if (++NumGPRsUsed <= NumGPRs) 5177 continue; 5178 break; 5179 case MVT::v4i32: 5180 case MVT::v8i16: 5181 case MVT::v16i8: 5182 case MVT::v2f64: 5183 case MVT::v2i64: 5184 case MVT::v1i128: 5185 if (++NumVRsUsed <= NumVRs) 5186 continue; 5187 break; 5188 case MVT::v4f32: 5189 // When using QPX, this is handled like a FP register, otherwise, it 5190 // is an Altivec register. 5191 if (Subtarget.hasQPX()) { 5192 if (++NumFPRsUsed <= NumFPRs) 5193 continue; 5194 } else { 5195 if (++NumVRsUsed <= NumVRs) 5196 continue; 5197 } 5198 break; 5199 case MVT::f32: 5200 case MVT::f64: 5201 case MVT::v4f64: // QPX 5202 case MVT::v4i1: // QPX 5203 if (++NumFPRsUsed <= NumFPRs) 5204 continue; 5205 break; 5206 } 5207 } 5208 5209 /* Respect alignment of argument on the stack. */ 5210 unsigned Align = 5211 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5212 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5213 5214 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5215 if (Flags.isInConsecutiveRegsLast()) 5216 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5217 } 5218 5219 unsigned NumBytesActuallyUsed = NumBytes; 5220 5221 // The prolog code of the callee may store up to 8 GPR argument registers to 5222 // the stack, allowing va_start to index over them in memory if its varargs. 5223 // Because we cannot tell if this is needed on the caller side, we have to 5224 // conservatively assume that it is needed. As such, make sure we have at 5225 // least enough stack space for the caller to store the 8 GPRs. 5226 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area. 5227 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5228 5229 // Tail call needs the stack to be aligned. 5230 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5231 CallConv == CallingConv::Fast) 5232 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5233 5234 int SPDiff = 0; 5235 5236 // Calculate by how many bytes the stack has to be adjusted in case of tail 5237 // call optimization. 5238 if (!IsSibCall) 5239 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5240 5241 // To protect arguments on the stack from being clobbered in a tail call, 5242 // force all the loads to happen before doing any other lowering. 5243 if (isTailCall) 5244 Chain = DAG.getStackArgumentTokenFactor(Chain); 5245 5246 // Adjust the stack pointer for the new arguments... 5247 // These operations are automatically eliminated by the prolog/epilog pass 5248 if (!IsSibCall) 5249 Chain = DAG.getCALLSEQ_START(Chain, 5250 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 5251 SDValue CallSeqStart = Chain; 5252 5253 // Load the return address and frame pointer so it can be move somewhere else 5254 // later. 5255 SDValue LROp, FPOp; 5256 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5257 5258 // Set up a copy of the stack pointer for use loading and storing any 5259 // arguments that may not fit in the registers available for argument 5260 // passing. 5261 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5262 5263 // Figure out which arguments are going to go in registers, and which in 5264 // memory. Also, if this is a vararg function, floating point operations 5265 // must be stored to our stack, and loaded into integer regs as well, if 5266 // any integer regs are available for argument passing. 5267 unsigned ArgOffset = LinkageSize; 5268 5269 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5270 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5271 5272 SmallVector<SDValue, 8> MemOpChains; 5273 for (unsigned i = 0; i != NumOps; ++i) { 5274 SDValue Arg = OutVals[i]; 5275 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5276 EVT ArgVT = Outs[i].VT; 5277 EVT OrigVT = Outs[i].ArgVT; 5278 5279 // PtrOff will be used to store the current argument to the stack if a 5280 // register cannot be found for it. 5281 SDValue PtrOff; 5282 5283 // We re-align the argument offset for each argument, except when using the 5284 // fast calling convention, when we need to make sure we do that only when 5285 // we'll actually use a stack slot. 5286 auto ComputePtrOff = [&]() { 5287 /* Respect alignment of argument on the stack. */ 5288 unsigned Align = 5289 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5290 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5291 5292 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5293 5294 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5295 }; 5296 5297 if (CallConv != CallingConv::Fast) { 5298 ComputePtrOff(); 5299 5300 /* Compute GPR index associated with argument offset. */ 5301 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5302 GPR_idx = std::min(GPR_idx, NumGPRs); 5303 } 5304 5305 // Promote integers to 64-bit values. 5306 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5307 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5308 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5309 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5310 } 5311 5312 // FIXME memcpy is used way more than necessary. Correctness first. 5313 // Note: "by value" is code for passing a structure by value, not 5314 // basic types. 5315 if (Flags.isByVal()) { 5316 // Note: Size includes alignment padding, so 5317 // struct x { short a; char b; } 5318 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5319 // These are the proper values we need for right-justifying the 5320 // aggregate in a parameter register. 5321 unsigned Size = Flags.getByValSize(); 5322 5323 // An empty aggregate parameter takes up no storage and no 5324 // registers. 5325 if (Size == 0) 5326 continue; 5327 5328 if (CallConv == CallingConv::Fast) 5329 ComputePtrOff(); 5330 5331 // All aggregates smaller than 8 bytes must be passed right-justified. 5332 if (Size==1 || Size==2 || Size==4) { 5333 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5334 if (GPR_idx != NumGPRs) { 5335 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5336 MachinePointerInfo(), VT); 5337 MemOpChains.push_back(Load.getValue(1)); 5338 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5339 5340 ArgOffset += PtrByteSize; 5341 continue; 5342 } 5343 } 5344 5345 if (GPR_idx == NumGPRs && Size < 8) { 5346 SDValue AddPtr = PtrOff; 5347 if (!isLittleEndian) { 5348 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5349 PtrOff.getValueType()); 5350 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5351 } 5352 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5353 CallSeqStart, 5354 Flags, DAG, dl); 5355 ArgOffset += PtrByteSize; 5356 continue; 5357 } 5358 // Copy entire object into memory. There are cases where gcc-generated 5359 // code assumes it is there, even if it could be put entirely into 5360 // registers. (This is not what the doc says.) 5361 5362 // FIXME: The above statement is likely due to a misunderstanding of the 5363 // documents. All arguments must be copied into the parameter area BY 5364 // THE CALLEE in the event that the callee takes the address of any 5365 // formal argument. That has not yet been implemented. However, it is 5366 // reasonable to use the stack area as a staging area for the register 5367 // load. 5368 5369 // Skip this for small aggregates, as we will use the same slot for a 5370 // right-justified copy, below. 5371 if (Size >= 8) 5372 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5373 CallSeqStart, 5374 Flags, DAG, dl); 5375 5376 // When a register is available, pass a small aggregate right-justified. 5377 if (Size < 8 && GPR_idx != NumGPRs) { 5378 // The easiest way to get this right-justified in a register 5379 // is to copy the structure into the rightmost portion of a 5380 // local variable slot, then load the whole slot into the 5381 // register. 5382 // FIXME: The memcpy seems to produce pretty awful code for 5383 // small aggregates, particularly for packed ones. 5384 // FIXME: It would be preferable to use the slot in the 5385 // parameter save area instead of a new local variable. 5386 SDValue AddPtr = PtrOff; 5387 if (!isLittleEndian) { 5388 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5389 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5390 } 5391 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5392 CallSeqStart, 5393 Flags, DAG, dl); 5394 5395 // Load the slot into the register. 5396 SDValue Load = 5397 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5398 MemOpChains.push_back(Load.getValue(1)); 5399 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5400 5401 // Done with this argument. 5402 ArgOffset += PtrByteSize; 5403 continue; 5404 } 5405 5406 // For aggregates larger than PtrByteSize, copy the pieces of the 5407 // object that fit into registers from the parameter save area. 5408 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5409 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5410 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5411 if (GPR_idx != NumGPRs) { 5412 SDValue Load = 5413 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5414 MemOpChains.push_back(Load.getValue(1)); 5415 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5416 ArgOffset += PtrByteSize; 5417 } else { 5418 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5419 break; 5420 } 5421 } 5422 continue; 5423 } 5424 5425 switch (Arg.getSimpleValueType().SimpleTy) { 5426 default: llvm_unreachable("Unexpected ValueType for argument!"); 5427 case MVT::i1: 5428 case MVT::i32: 5429 case MVT::i64: 5430 if (Flags.isNest()) { 5431 // The 'nest' parameter, if any, is passed in R11. 5432 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5433 hasNest = true; 5434 break; 5435 } 5436 5437 // These can be scalar arguments or elements of an integer array type 5438 // passed directly. Clang may use those instead of "byval" aggregate 5439 // types to avoid forcing arguments to memory unnecessarily. 5440 if (GPR_idx != NumGPRs) { 5441 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5442 } else { 5443 if (CallConv == CallingConv::Fast) 5444 ComputePtrOff(); 5445 5446 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5447 true, isTailCall, false, MemOpChains, 5448 TailCallArguments, dl); 5449 if (CallConv == CallingConv::Fast) 5450 ArgOffset += PtrByteSize; 5451 } 5452 if (CallConv != CallingConv::Fast) 5453 ArgOffset += PtrByteSize; 5454 break; 5455 case MVT::f32: 5456 case MVT::f64: { 5457 // These can be scalar arguments or elements of a float array type 5458 // passed directly. The latter are used to implement ELFv2 homogenous 5459 // float aggregates. 5460 5461 // Named arguments go into FPRs first, and once they overflow, the 5462 // remaining arguments go into GPRs and then the parameter save area. 5463 // Unnamed arguments for vararg functions always go to GPRs and 5464 // then the parameter save area. For now, put all arguments to vararg 5465 // routines always in both locations (FPR *and* GPR or stack slot). 5466 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5467 bool NeededLoad = false; 5468 5469 // First load the argument into the next available FPR. 5470 if (FPR_idx != NumFPRs) 5471 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5472 5473 // Next, load the argument into GPR or stack slot if needed. 5474 if (!NeedGPROrStack) 5475 ; 5476 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5477 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5478 // once we support fp <-> gpr moves. 5479 5480 // In the non-vararg case, this can only ever happen in the 5481 // presence of f32 array types, since otherwise we never run 5482 // out of FPRs before running out of GPRs. 5483 SDValue ArgVal; 5484 5485 // Double values are always passed in a single GPR. 5486 if (Arg.getValueType() != MVT::f32) { 5487 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5488 5489 // Non-array float values are extended and passed in a GPR. 5490 } else if (!Flags.isInConsecutiveRegs()) { 5491 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5492 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5493 5494 // If we have an array of floats, we collect every odd element 5495 // together with its predecessor into one GPR. 5496 } else if (ArgOffset % PtrByteSize != 0) { 5497 SDValue Lo, Hi; 5498 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5499 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5500 if (!isLittleEndian) 5501 std::swap(Lo, Hi); 5502 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5503 5504 // The final element, if even, goes into the first half of a GPR. 5505 } else if (Flags.isInConsecutiveRegsLast()) { 5506 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5507 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5508 if (!isLittleEndian) 5509 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5510 DAG.getConstant(32, dl, MVT::i32)); 5511 5512 // Non-final even elements are skipped; they will be handled 5513 // together the with subsequent argument on the next go-around. 5514 } else 5515 ArgVal = SDValue(); 5516 5517 if (ArgVal.getNode()) 5518 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5519 } else { 5520 if (CallConv == CallingConv::Fast) 5521 ComputePtrOff(); 5522 5523 // Single-precision floating-point values are mapped to the 5524 // second (rightmost) word of the stack doubleword. 5525 if (Arg.getValueType() == MVT::f32 && 5526 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5527 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5528 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5529 } 5530 5531 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5532 true, isTailCall, false, MemOpChains, 5533 TailCallArguments, dl); 5534 5535 NeededLoad = true; 5536 } 5537 // When passing an array of floats, the array occupies consecutive 5538 // space in the argument area; only round up to the next doubleword 5539 // at the end of the array. Otherwise, each float takes 8 bytes. 5540 if (CallConv != CallingConv::Fast || NeededLoad) { 5541 ArgOffset += (Arg.getValueType() == MVT::f32 && 5542 Flags.isInConsecutiveRegs()) ? 4 : 8; 5543 if (Flags.isInConsecutiveRegsLast()) 5544 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5545 } 5546 break; 5547 } 5548 case MVT::v4f32: 5549 case MVT::v4i32: 5550 case MVT::v8i16: 5551 case MVT::v16i8: 5552 case MVT::v2f64: 5553 case MVT::v2i64: 5554 case MVT::v1i128: 5555 if (!Subtarget.hasQPX()) { 5556 // These can be scalar arguments or elements of a vector array type 5557 // passed directly. The latter are used to implement ELFv2 homogenous 5558 // vector aggregates. 5559 5560 // For a varargs call, named arguments go into VRs or on the stack as 5561 // usual; unnamed arguments always go to the stack or the corresponding 5562 // GPRs when within range. For now, we always put the value in both 5563 // locations (or even all three). 5564 if (isVarArg) { 5565 // We could elide this store in the case where the object fits 5566 // entirely in R registers. Maybe later. 5567 SDValue Store = 5568 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5569 MemOpChains.push_back(Store); 5570 if (VR_idx != NumVRs) { 5571 SDValue Load = 5572 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 5573 MemOpChains.push_back(Load.getValue(1)); 5574 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5575 } 5576 ArgOffset += 16; 5577 for (unsigned i=0; i<16; i+=PtrByteSize) { 5578 if (GPR_idx == NumGPRs) 5579 break; 5580 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5581 DAG.getConstant(i, dl, PtrVT)); 5582 SDValue Load = 5583 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5584 MemOpChains.push_back(Load.getValue(1)); 5585 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5586 } 5587 break; 5588 } 5589 5590 // Non-varargs Altivec params go into VRs or on the stack. 5591 if (VR_idx != NumVRs) { 5592 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5593 } else { 5594 if (CallConv == CallingConv::Fast) 5595 ComputePtrOff(); 5596 5597 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5598 true, isTailCall, true, MemOpChains, 5599 TailCallArguments, dl); 5600 if (CallConv == CallingConv::Fast) 5601 ArgOffset += 16; 5602 } 5603 5604 if (CallConv != CallingConv::Fast) 5605 ArgOffset += 16; 5606 break; 5607 } // not QPX 5608 5609 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5610 "Invalid QPX parameter type"); 5611 5612 /* fall through */ 5613 case MVT::v4f64: 5614 case MVT::v4i1: { 5615 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5616 if (isVarArg) { 5617 // We could elide this store in the case where the object fits 5618 // entirely in R registers. Maybe later. 5619 SDValue Store = 5620 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5621 MemOpChains.push_back(Store); 5622 if (QFPR_idx != NumQFPRs) { 5623 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 5624 PtrOff, MachinePointerInfo()); 5625 MemOpChains.push_back(Load.getValue(1)); 5626 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5627 } 5628 ArgOffset += (IsF32 ? 16 : 32); 5629 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5630 if (GPR_idx == NumGPRs) 5631 break; 5632 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5633 DAG.getConstant(i, dl, PtrVT)); 5634 SDValue Load = 5635 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5636 MemOpChains.push_back(Load.getValue(1)); 5637 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5638 } 5639 break; 5640 } 5641 5642 // Non-varargs QPX params go into registers or on the stack. 5643 if (QFPR_idx != NumQFPRs) { 5644 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5645 } else { 5646 if (CallConv == CallingConv::Fast) 5647 ComputePtrOff(); 5648 5649 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5650 true, isTailCall, true, MemOpChains, 5651 TailCallArguments, dl); 5652 if (CallConv == CallingConv::Fast) 5653 ArgOffset += (IsF32 ? 16 : 32); 5654 } 5655 5656 if (CallConv != CallingConv::Fast) 5657 ArgOffset += (IsF32 ? 16 : 32); 5658 break; 5659 } 5660 } 5661 } 5662 5663 assert(NumBytesActuallyUsed == ArgOffset); 5664 (void)NumBytesActuallyUsed; 5665 5666 if (!MemOpChains.empty()) 5667 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5668 5669 // Check if this is an indirect call (MTCTR/BCTRL). 5670 // See PrepareCall() for more information about calls through function 5671 // pointers in the 64-bit SVR4 ABI. 5672 if (!isTailCall && !isPatchPoint && 5673 !isFunctionGlobalAddress(Callee) && 5674 !isa<ExternalSymbolSDNode>(Callee)) { 5675 // Load r2 into a virtual register and store it to the TOC save area. 5676 setUsesTOCBasePtr(DAG); 5677 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 5678 // TOC save area offset. 5679 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5680 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5681 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5682 Chain = DAG.getStore( 5683 Val.getValue(1), dl, Val, AddPtr, 5684 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 5685 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 5686 // This does not mean the MTCTR instruction must use R12; it's easier 5687 // to model this as an extra parameter, so do that. 5688 if (isELFv2ABI && !isPatchPoint) 5689 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 5690 } 5691 5692 // Build a sequence of copy-to-reg nodes chained together with token chain 5693 // and flag operands which copy the outgoing args into the appropriate regs. 5694 SDValue InFlag; 5695 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5696 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5697 RegsToPass[i].second, InFlag); 5698 InFlag = Chain.getValue(1); 5699 } 5700 5701 if (isTailCall && !IsSibCall) 5702 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5703 TailCallArguments); 5704 5705 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 5706 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 5707 SPDiff, NumBytes, Ins, InVals, CS); 5708 } 5709 5710 SDValue PPCTargetLowering::LowerCall_Darwin( 5711 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5712 bool isTailCall, bool isPatchPoint, 5713 const SmallVectorImpl<ISD::OutputArg> &Outs, 5714 const SmallVectorImpl<SDValue> &OutVals, 5715 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5716 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5717 ImmutableCallSite *CS) const { 5718 unsigned NumOps = Outs.size(); 5719 5720 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5721 bool isPPC64 = PtrVT == MVT::i64; 5722 unsigned PtrByteSize = isPPC64 ? 8 : 4; 5723 5724 MachineFunction &MF = DAG.getMachineFunction(); 5725 5726 // Mark this function as potentially containing a function that contains a 5727 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5728 // and restoring the callers stack pointer in this functions epilog. This is 5729 // done because by tail calling the called function might overwrite the value 5730 // in this function's (MF) stack pointer stack slot 0(SP). 5731 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5732 CallConv == CallingConv::Fast) 5733 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5734 5735 // Count how many bytes are to be pushed on the stack, including the linkage 5736 // area, and parameter passing area. We start with 24/48 bytes, which is 5737 // prereserved space for [SP][CR][LR][3 x unused]. 5738 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5739 unsigned NumBytes = LinkageSize; 5740 5741 // Add up all the space actually used. 5742 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 5743 // they all go in registers, but we must reserve stack space for them for 5744 // possible use by the caller. In varargs or 64-bit calls, parameters are 5745 // assigned stack space in order, with padding so Altivec parameters are 5746 // 16-byte aligned. 5747 unsigned nAltivecParamsAtEnd = 0; 5748 for (unsigned i = 0; i != NumOps; ++i) { 5749 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5750 EVT ArgVT = Outs[i].VT; 5751 // Varargs Altivec parameters are padded to a 16 byte boundary. 5752 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 5753 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 5754 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 5755 if (!isVarArg && !isPPC64) { 5756 // Non-varargs Altivec parameters go after all the non-Altivec 5757 // parameters; handle those later so we know how much padding we need. 5758 nAltivecParamsAtEnd++; 5759 continue; 5760 } 5761 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 5762 NumBytes = ((NumBytes+15)/16)*16; 5763 } 5764 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5765 } 5766 5767 // Allow for Altivec parameters at the end, if needed. 5768 if (nAltivecParamsAtEnd) { 5769 NumBytes = ((NumBytes+15)/16)*16; 5770 NumBytes += 16*nAltivecParamsAtEnd; 5771 } 5772 5773 // The prolog code of the callee may store up to 8 GPR argument registers to 5774 // the stack, allowing va_start to index over them in memory if its varargs. 5775 // Because we cannot tell if this is needed on the caller side, we have to 5776 // conservatively assume that it is needed. As such, make sure we have at 5777 // least enough stack space for the caller to store the 8 GPRs. 5778 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5779 5780 // Tail call needs the stack to be aligned. 5781 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5782 CallConv == CallingConv::Fast) 5783 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5784 5785 // Calculate by how many bytes the stack has to be adjusted in case of tail 5786 // call optimization. 5787 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5788 5789 // To protect arguments on the stack from being clobbered in a tail call, 5790 // force all the loads to happen before doing any other lowering. 5791 if (isTailCall) 5792 Chain = DAG.getStackArgumentTokenFactor(Chain); 5793 5794 // Adjust the stack pointer for the new arguments... 5795 // These operations are automatically eliminated by the prolog/epilog pass 5796 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5797 dl); 5798 SDValue CallSeqStart = Chain; 5799 5800 // Load the return address and frame pointer so it can be move somewhere else 5801 // later. 5802 SDValue LROp, FPOp; 5803 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5804 5805 // Set up a copy of the stack pointer for use loading and storing any 5806 // arguments that may not fit in the registers available for argument 5807 // passing. 5808 SDValue StackPtr; 5809 if (isPPC64) 5810 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5811 else 5812 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5813 5814 // Figure out which arguments are going to go in registers, and which in 5815 // memory. Also, if this is a vararg function, floating point operations 5816 // must be stored to our stack, and loaded into integer regs as well, if 5817 // any integer regs are available for argument passing. 5818 unsigned ArgOffset = LinkageSize; 5819 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5820 5821 static const MCPhysReg GPR_32[] = { // 32-bit registers. 5822 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 5823 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 5824 }; 5825 static const MCPhysReg GPR_64[] = { // 64-bit registers. 5826 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5827 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5828 }; 5829 static const MCPhysReg VR[] = { 5830 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5831 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5832 }; 5833 const unsigned NumGPRs = array_lengthof(GPR_32); 5834 const unsigned NumFPRs = 13; 5835 const unsigned NumVRs = array_lengthof(VR); 5836 5837 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 5838 5839 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5840 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5841 5842 SmallVector<SDValue, 8> MemOpChains; 5843 for (unsigned i = 0; i != NumOps; ++i) { 5844 SDValue Arg = OutVals[i]; 5845 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5846 5847 // PtrOff will be used to store the current argument to the stack if a 5848 // register cannot be found for it. 5849 SDValue PtrOff; 5850 5851 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5852 5853 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5854 5855 // On PPC64, promote integers to 64-bit values. 5856 if (isPPC64 && Arg.getValueType() == MVT::i32) { 5857 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5858 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5859 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5860 } 5861 5862 // FIXME memcpy is used way more than necessary. Correctness first. 5863 // Note: "by value" is code for passing a structure by value, not 5864 // basic types. 5865 if (Flags.isByVal()) { 5866 unsigned Size = Flags.getByValSize(); 5867 // Very small objects are passed right-justified. Everything else is 5868 // passed left-justified. 5869 if (Size==1 || Size==2) { 5870 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 5871 if (GPR_idx != NumGPRs) { 5872 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5873 MachinePointerInfo(), VT); 5874 MemOpChains.push_back(Load.getValue(1)); 5875 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5876 5877 ArgOffset += PtrByteSize; 5878 } else { 5879 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5880 PtrOff.getValueType()); 5881 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5882 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5883 CallSeqStart, 5884 Flags, DAG, dl); 5885 ArgOffset += PtrByteSize; 5886 } 5887 continue; 5888 } 5889 // Copy entire object into memory. There are cases where gcc-generated 5890 // code assumes it is there, even if it could be put entirely into 5891 // registers. (This is not what the doc says.) 5892 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5893 CallSeqStart, 5894 Flags, DAG, dl); 5895 5896 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 5897 // copy the pieces of the object that fit into registers from the 5898 // parameter save area. 5899 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5900 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5901 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5902 if (GPR_idx != NumGPRs) { 5903 SDValue Load = 5904 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5905 MemOpChains.push_back(Load.getValue(1)); 5906 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5907 ArgOffset += PtrByteSize; 5908 } else { 5909 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5910 break; 5911 } 5912 } 5913 continue; 5914 } 5915 5916 switch (Arg.getSimpleValueType().SimpleTy) { 5917 default: llvm_unreachable("Unexpected ValueType for argument!"); 5918 case MVT::i1: 5919 case MVT::i32: 5920 case MVT::i64: 5921 if (GPR_idx != NumGPRs) { 5922 if (Arg.getValueType() == MVT::i1) 5923 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 5924 5925 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5926 } else { 5927 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5928 isPPC64, isTailCall, false, MemOpChains, 5929 TailCallArguments, dl); 5930 } 5931 ArgOffset += PtrByteSize; 5932 break; 5933 case MVT::f32: 5934 case MVT::f64: 5935 if (FPR_idx != NumFPRs) { 5936 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5937 5938 if (isVarArg) { 5939 SDValue Store = 5940 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5941 MemOpChains.push_back(Store); 5942 5943 // Float varargs are always shadowed in available integer registers 5944 if (GPR_idx != NumGPRs) { 5945 SDValue Load = 5946 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 5947 MemOpChains.push_back(Load.getValue(1)); 5948 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5949 } 5950 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 5951 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5952 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5953 SDValue Load = 5954 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 5955 MemOpChains.push_back(Load.getValue(1)); 5956 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5957 } 5958 } else { 5959 // If we have any FPRs remaining, we may also have GPRs remaining. 5960 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 5961 // GPRs. 5962 if (GPR_idx != NumGPRs) 5963 ++GPR_idx; 5964 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 5965 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 5966 ++GPR_idx; 5967 } 5968 } else 5969 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5970 isPPC64, isTailCall, false, MemOpChains, 5971 TailCallArguments, dl); 5972 if (isPPC64) 5973 ArgOffset += 8; 5974 else 5975 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 5976 break; 5977 case MVT::v4f32: 5978 case MVT::v4i32: 5979 case MVT::v8i16: 5980 case MVT::v16i8: 5981 if (isVarArg) { 5982 // These go aligned on the stack, or in the corresponding R registers 5983 // when within range. The Darwin PPC ABI doc claims they also go in 5984 // V registers; in fact gcc does this only for arguments that are 5985 // prototyped, not for those that match the ... We do it for all 5986 // arguments, seems to work. 5987 while (ArgOffset % 16 !=0) { 5988 ArgOffset += PtrByteSize; 5989 if (GPR_idx != NumGPRs) 5990 GPR_idx++; 5991 } 5992 // We could elide this store in the case where the object fits 5993 // entirely in R registers. Maybe later. 5994 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5995 DAG.getConstant(ArgOffset, dl, PtrVT)); 5996 SDValue Store = 5997 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5998 MemOpChains.push_back(Store); 5999 if (VR_idx != NumVRs) { 6000 SDValue Load = 6001 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6002 MemOpChains.push_back(Load.getValue(1)); 6003 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6004 } 6005 ArgOffset += 16; 6006 for (unsigned i=0; i<16; i+=PtrByteSize) { 6007 if (GPR_idx == NumGPRs) 6008 break; 6009 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6010 DAG.getConstant(i, dl, PtrVT)); 6011 SDValue Load = 6012 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6013 MemOpChains.push_back(Load.getValue(1)); 6014 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6015 } 6016 break; 6017 } 6018 6019 // Non-varargs Altivec params generally go in registers, but have 6020 // stack space allocated at the end. 6021 if (VR_idx != NumVRs) { 6022 // Doesn't have GPR space allocated. 6023 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6024 } else if (nAltivecParamsAtEnd==0) { 6025 // We are emitting Altivec params in order. 6026 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6027 isPPC64, isTailCall, true, MemOpChains, 6028 TailCallArguments, dl); 6029 ArgOffset += 16; 6030 } 6031 break; 6032 } 6033 } 6034 // If all Altivec parameters fit in registers, as they usually do, 6035 // they get stack space following the non-Altivec parameters. We 6036 // don't track this here because nobody below needs it. 6037 // If there are more Altivec parameters than fit in registers emit 6038 // the stores here. 6039 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6040 unsigned j = 0; 6041 // Offset is aligned; skip 1st 12 params which go in V registers. 6042 ArgOffset = ((ArgOffset+15)/16)*16; 6043 ArgOffset += 12*16; 6044 for (unsigned i = 0; i != NumOps; ++i) { 6045 SDValue Arg = OutVals[i]; 6046 EVT ArgType = Outs[i].VT; 6047 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6048 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6049 if (++j > NumVRs) { 6050 SDValue PtrOff; 6051 // We are emitting Altivec params in order. 6052 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6053 isPPC64, isTailCall, true, MemOpChains, 6054 TailCallArguments, dl); 6055 ArgOffset += 16; 6056 } 6057 } 6058 } 6059 } 6060 6061 if (!MemOpChains.empty()) 6062 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6063 6064 // On Darwin, R12 must contain the address of an indirect callee. This does 6065 // not mean the MTCTR instruction must use R12; it's easier to model this as 6066 // an extra parameter, so do that. 6067 if (!isTailCall && 6068 !isFunctionGlobalAddress(Callee) && 6069 !isa<ExternalSymbolSDNode>(Callee) && 6070 !isBLACompatibleAddress(Callee, DAG)) 6071 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6072 PPC::R12), Callee)); 6073 6074 // Build a sequence of copy-to-reg nodes chained together with token chain 6075 // and flag operands which copy the outgoing args into the appropriate regs. 6076 SDValue InFlag; 6077 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6078 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6079 RegsToPass[i].second, InFlag); 6080 InFlag = Chain.getValue(1); 6081 } 6082 6083 if (isTailCall) 6084 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6085 TailCallArguments); 6086 6087 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6088 /* unused except on PPC64 ELFv1 */ false, DAG, 6089 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6090 NumBytes, Ins, InVals, CS); 6091 } 6092 6093 bool 6094 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6095 MachineFunction &MF, bool isVarArg, 6096 const SmallVectorImpl<ISD::OutputArg> &Outs, 6097 LLVMContext &Context) const { 6098 SmallVector<CCValAssign, 16> RVLocs; 6099 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6100 return CCInfo.CheckReturn(Outs, RetCC_PPC); 6101 } 6102 6103 SDValue 6104 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6105 bool isVarArg, 6106 const SmallVectorImpl<ISD::OutputArg> &Outs, 6107 const SmallVectorImpl<SDValue> &OutVals, 6108 const SDLoc &dl, SelectionDAG &DAG) const { 6109 SmallVector<CCValAssign, 16> RVLocs; 6110 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6111 *DAG.getContext()); 6112 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 6113 6114 SDValue Flag; 6115 SmallVector<SDValue, 4> RetOps(1, Chain); 6116 6117 // Copy the result values into the output registers. 6118 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6119 CCValAssign &VA = RVLocs[i]; 6120 assert(VA.isRegLoc() && "Can only return in registers!"); 6121 6122 SDValue Arg = OutVals[i]; 6123 6124 switch (VA.getLocInfo()) { 6125 default: llvm_unreachable("Unknown loc info!"); 6126 case CCValAssign::Full: break; 6127 case CCValAssign::AExt: 6128 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6129 break; 6130 case CCValAssign::ZExt: 6131 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6132 break; 6133 case CCValAssign::SExt: 6134 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6135 break; 6136 } 6137 6138 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6139 Flag = Chain.getValue(1); 6140 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6141 } 6142 6143 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6144 const MCPhysReg *I = 6145 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6146 if (I) { 6147 for (; *I; ++I) { 6148 6149 if (PPC::G8RCRegClass.contains(*I)) 6150 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6151 else if (PPC::F8RCRegClass.contains(*I)) 6152 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6153 else if (PPC::CRRCRegClass.contains(*I)) 6154 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6155 else if (PPC::VRRCRegClass.contains(*I)) 6156 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6157 else 6158 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6159 } 6160 } 6161 6162 RetOps[0] = Chain; // Update chain. 6163 6164 // Add the flag if we have it. 6165 if (Flag.getNode()) 6166 RetOps.push_back(Flag); 6167 6168 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6169 } 6170 6171 SDValue 6172 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6173 SelectionDAG &DAG) const { 6174 SDLoc dl(Op); 6175 6176 // Get the corect type for integers. 6177 EVT IntVT = Op.getValueType(); 6178 6179 // Get the inputs. 6180 SDValue Chain = Op.getOperand(0); 6181 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6182 // Build a DYNAREAOFFSET node. 6183 SDValue Ops[2] = {Chain, FPSIdx}; 6184 SDVTList VTs = DAG.getVTList(IntVT); 6185 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6186 } 6187 6188 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6189 SelectionDAG &DAG) const { 6190 // When we pop the dynamic allocation we need to restore the SP link. 6191 SDLoc dl(Op); 6192 6193 // Get the corect type for pointers. 6194 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6195 6196 // Construct the stack pointer operand. 6197 bool isPPC64 = Subtarget.isPPC64(); 6198 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6199 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6200 6201 // Get the operands for the STACKRESTORE. 6202 SDValue Chain = Op.getOperand(0); 6203 SDValue SaveSP = Op.getOperand(1); 6204 6205 // Load the old link SP. 6206 SDValue LoadLinkSP = 6207 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6208 6209 // Restore the stack pointer. 6210 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6211 6212 // Store the old link SP. 6213 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6214 } 6215 6216 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6217 MachineFunction &MF = DAG.getMachineFunction(); 6218 bool isPPC64 = Subtarget.isPPC64(); 6219 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6220 6221 // Get current frame pointer save index. The users of this index will be 6222 // primarily DYNALLOC instructions. 6223 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6224 int RASI = FI->getReturnAddrSaveIndex(); 6225 6226 // If the frame pointer save index hasn't been defined yet. 6227 if (!RASI) { 6228 // Find out what the fix offset of the frame pointer save area. 6229 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6230 // Allocate the frame index for frame pointer save area. 6231 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6232 // Save the result. 6233 FI->setReturnAddrSaveIndex(RASI); 6234 } 6235 return DAG.getFrameIndex(RASI, PtrVT); 6236 } 6237 6238 SDValue 6239 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6240 MachineFunction &MF = DAG.getMachineFunction(); 6241 bool isPPC64 = Subtarget.isPPC64(); 6242 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6243 6244 // Get current frame pointer save index. The users of this index will be 6245 // primarily DYNALLOC instructions. 6246 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6247 int FPSI = FI->getFramePointerSaveIndex(); 6248 6249 // If the frame pointer save index hasn't been defined yet. 6250 if (!FPSI) { 6251 // Find out what the fix offset of the frame pointer save area. 6252 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6253 // Allocate the frame index for frame pointer save area. 6254 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6255 // Save the result. 6256 FI->setFramePointerSaveIndex(FPSI); 6257 } 6258 return DAG.getFrameIndex(FPSI, PtrVT); 6259 } 6260 6261 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6262 SelectionDAG &DAG) const { 6263 // Get the inputs. 6264 SDValue Chain = Op.getOperand(0); 6265 SDValue Size = Op.getOperand(1); 6266 SDLoc dl(Op); 6267 6268 // Get the corect type for pointers. 6269 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6270 // Negate the size. 6271 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6272 DAG.getConstant(0, dl, PtrVT), Size); 6273 // Construct a node for the frame pointer save index. 6274 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6275 // Build a DYNALLOC node. 6276 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6277 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6278 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6279 } 6280 6281 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6282 SelectionDAG &DAG) const { 6283 MachineFunction &MF = DAG.getMachineFunction(); 6284 6285 bool isPPC64 = Subtarget.isPPC64(); 6286 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6287 6288 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6289 return DAG.getFrameIndex(FI, PtrVT); 6290 } 6291 6292 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6293 SelectionDAG &DAG) const { 6294 SDLoc DL(Op); 6295 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6296 DAG.getVTList(MVT::i32, MVT::Other), 6297 Op.getOperand(0), Op.getOperand(1)); 6298 } 6299 6300 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6301 SelectionDAG &DAG) const { 6302 SDLoc DL(Op); 6303 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6304 Op.getOperand(0), Op.getOperand(1)); 6305 } 6306 6307 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6308 if (Op.getValueType().isVector()) 6309 return LowerVectorLoad(Op, DAG); 6310 6311 assert(Op.getValueType() == MVT::i1 && 6312 "Custom lowering only for i1 loads"); 6313 6314 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6315 6316 SDLoc dl(Op); 6317 LoadSDNode *LD = cast<LoadSDNode>(Op); 6318 6319 SDValue Chain = LD->getChain(); 6320 SDValue BasePtr = LD->getBasePtr(); 6321 MachineMemOperand *MMO = LD->getMemOperand(); 6322 6323 SDValue NewLD = 6324 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6325 BasePtr, MVT::i8, MMO); 6326 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6327 6328 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6329 return DAG.getMergeValues(Ops, dl); 6330 } 6331 6332 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6333 if (Op.getOperand(1).getValueType().isVector()) 6334 return LowerVectorStore(Op, DAG); 6335 6336 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6337 "Custom lowering only for i1 stores"); 6338 6339 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6340 6341 SDLoc dl(Op); 6342 StoreSDNode *ST = cast<StoreSDNode>(Op); 6343 6344 SDValue Chain = ST->getChain(); 6345 SDValue BasePtr = ST->getBasePtr(); 6346 SDValue Value = ST->getValue(); 6347 MachineMemOperand *MMO = ST->getMemOperand(); 6348 6349 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6350 Value); 6351 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6352 } 6353 6354 // FIXME: Remove this once the ANDI glue bug is fixed: 6355 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6356 assert(Op.getValueType() == MVT::i1 && 6357 "Custom lowering only for i1 results"); 6358 6359 SDLoc DL(Op); 6360 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6361 Op.getOperand(0)); 6362 } 6363 6364 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6365 /// possible. 6366 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6367 // Not FP? Not a fsel. 6368 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6369 !Op.getOperand(2).getValueType().isFloatingPoint()) 6370 return Op; 6371 6372 // We might be able to do better than this under some circumstances, but in 6373 // general, fsel-based lowering of select is a finite-math-only optimization. 6374 // For more information, see section F.3 of the 2.06 ISA specification. 6375 if (!DAG.getTarget().Options.NoInfsFPMath || 6376 !DAG.getTarget().Options.NoNaNsFPMath) 6377 return Op; 6378 // TODO: Propagate flags from the select rather than global settings. 6379 SDNodeFlags Flags; 6380 Flags.setNoInfs(true); 6381 Flags.setNoNaNs(true); 6382 6383 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6384 6385 EVT ResVT = Op.getValueType(); 6386 EVT CmpVT = Op.getOperand(0).getValueType(); 6387 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6388 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6389 SDLoc dl(Op); 6390 6391 // If the RHS of the comparison is a 0.0, we don't need to do the 6392 // subtraction at all. 6393 SDValue Sel1; 6394 if (isFloatingPointZero(RHS)) 6395 switch (CC) { 6396 default: break; // SETUO etc aren't handled by fsel. 6397 case ISD::SETNE: 6398 std::swap(TV, FV); 6399 case ISD::SETEQ: 6400 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6401 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6402 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6403 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6404 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6405 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6406 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6407 case ISD::SETULT: 6408 case ISD::SETLT: 6409 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6410 case ISD::SETOGE: 6411 case ISD::SETGE: 6412 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6413 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6414 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6415 case ISD::SETUGT: 6416 case ISD::SETGT: 6417 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6418 case ISD::SETOLE: 6419 case ISD::SETLE: 6420 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6421 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6422 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6423 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6424 } 6425 6426 SDValue Cmp; 6427 switch (CC) { 6428 default: break; // SETUO etc aren't handled by fsel. 6429 case ISD::SETNE: 6430 std::swap(TV, FV); 6431 case ISD::SETEQ: 6432 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags); 6433 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6434 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6435 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6436 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6437 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6438 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6439 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6440 case ISD::SETULT: 6441 case ISD::SETLT: 6442 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags); 6443 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6444 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6445 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6446 case ISD::SETOGE: 6447 case ISD::SETGE: 6448 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags); 6449 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6450 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6451 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6452 case ISD::SETUGT: 6453 case ISD::SETGT: 6454 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags); 6455 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6456 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6457 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6458 case ISD::SETOLE: 6459 case ISD::SETLE: 6460 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags); 6461 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6462 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6463 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6464 } 6465 return Op; 6466 } 6467 6468 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6469 SelectionDAG &DAG, 6470 const SDLoc &dl) const { 6471 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6472 SDValue Src = Op.getOperand(0); 6473 if (Src.getValueType() == MVT::f32) 6474 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6475 6476 SDValue Tmp; 6477 switch (Op.getSimpleValueType().SimpleTy) { 6478 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6479 case MVT::i32: 6480 Tmp = DAG.getNode( 6481 Op.getOpcode() == ISD::FP_TO_SINT 6482 ? PPCISD::FCTIWZ 6483 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6484 dl, MVT::f64, Src); 6485 break; 6486 case MVT::i64: 6487 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6488 "i64 FP_TO_UINT is supported only with FPCVT"); 6489 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6490 PPCISD::FCTIDUZ, 6491 dl, MVT::f64, Src); 6492 break; 6493 } 6494 6495 // Convert the FP value to an int value through memory. 6496 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 6497 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 6498 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 6499 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 6500 MachinePointerInfo MPI = 6501 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 6502 6503 // Emit a store to the stack slot. 6504 SDValue Chain; 6505 if (i32Stack) { 6506 MachineFunction &MF = DAG.getMachineFunction(); 6507 MachineMemOperand *MMO = 6508 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 6509 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 6510 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 6511 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 6512 } else 6513 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 6514 6515 // Result is a load from the stack slot. If loading 4 bytes, make sure to 6516 // add in a bias on big endian. 6517 if (Op.getValueType() == MVT::i32 && !i32Stack) { 6518 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 6519 DAG.getConstant(4, dl, FIPtr.getValueType())); 6520 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 6521 } 6522 6523 RLI.Chain = Chain; 6524 RLI.Ptr = FIPtr; 6525 RLI.MPI = MPI; 6526 } 6527 6528 /// \brief Custom lowers floating point to integer conversions to use 6529 /// the direct move instructions available in ISA 2.07 to avoid the 6530 /// need for load/store combinations. 6531 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 6532 SelectionDAG &DAG, 6533 const SDLoc &dl) const { 6534 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6535 SDValue Src = Op.getOperand(0); 6536 6537 if (Src.getValueType() == MVT::f32) 6538 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6539 6540 SDValue Tmp; 6541 switch (Op.getSimpleValueType().SimpleTy) { 6542 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6543 case MVT::i32: 6544 Tmp = DAG.getNode( 6545 Op.getOpcode() == ISD::FP_TO_SINT 6546 ? PPCISD::FCTIWZ 6547 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6548 dl, MVT::f64, Src); 6549 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 6550 break; 6551 case MVT::i64: 6552 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6553 "i64 FP_TO_UINT is supported only with FPCVT"); 6554 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6555 PPCISD::FCTIDUZ, 6556 dl, MVT::f64, Src); 6557 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 6558 break; 6559 } 6560 return Tmp; 6561 } 6562 6563 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 6564 const SDLoc &dl) const { 6565 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 6566 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 6567 6568 ReuseLoadInfo RLI; 6569 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6570 6571 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6572 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6573 } 6574 6575 // We're trying to insert a regular store, S, and then a load, L. If the 6576 // incoming value, O, is a load, we might just be able to have our load use the 6577 // address used by O. However, we don't know if anything else will store to 6578 // that address before we can load from it. To prevent this situation, we need 6579 // to insert our load, L, into the chain as a peer of O. To do this, we give L 6580 // the same chain operand as O, we create a token factor from the chain results 6581 // of O and L, and we replace all uses of O's chain result with that token 6582 // factor (see spliceIntoChain below for this last part). 6583 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 6584 ReuseLoadInfo &RLI, 6585 SelectionDAG &DAG, 6586 ISD::LoadExtType ET) const { 6587 SDLoc dl(Op); 6588 if (ET == ISD::NON_EXTLOAD && 6589 (Op.getOpcode() == ISD::FP_TO_UINT || 6590 Op.getOpcode() == ISD::FP_TO_SINT) && 6591 isOperationLegalOrCustom(Op.getOpcode(), 6592 Op.getOperand(0).getValueType())) { 6593 6594 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6595 return true; 6596 } 6597 6598 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 6599 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 6600 LD->isNonTemporal()) 6601 return false; 6602 if (LD->getMemoryVT() != MemVT) 6603 return false; 6604 6605 RLI.Ptr = LD->getBasePtr(); 6606 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 6607 assert(LD->getAddressingMode() == ISD::PRE_INC && 6608 "Non-pre-inc AM on PPC?"); 6609 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 6610 LD->getOffset()); 6611 } 6612 6613 RLI.Chain = LD->getChain(); 6614 RLI.MPI = LD->getPointerInfo(); 6615 RLI.IsDereferenceable = LD->isDereferenceable(); 6616 RLI.IsInvariant = LD->isInvariant(); 6617 RLI.Alignment = LD->getAlignment(); 6618 RLI.AAInfo = LD->getAAInfo(); 6619 RLI.Ranges = LD->getRanges(); 6620 6621 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 6622 return true; 6623 } 6624 6625 // Given the head of the old chain, ResChain, insert a token factor containing 6626 // it and NewResChain, and make users of ResChain now be users of that token 6627 // factor. 6628 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 6629 SDValue NewResChain, 6630 SelectionDAG &DAG) const { 6631 if (!ResChain) 6632 return; 6633 6634 SDLoc dl(NewResChain); 6635 6636 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6637 NewResChain, DAG.getUNDEF(MVT::Other)); 6638 assert(TF.getNode() != NewResChain.getNode() && 6639 "A new TF really is required here"); 6640 6641 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 6642 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 6643 } 6644 6645 /// \brief Analyze profitability of direct move 6646 /// prefer float load to int load plus direct move 6647 /// when there is no integer use of int load 6648 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 6649 SDNode *Origin = Op.getOperand(0).getNode(); 6650 if (Origin->getOpcode() != ISD::LOAD) 6651 return true; 6652 6653 // If there is no LXSIBZX/LXSIHZX, like Power8, 6654 // prefer direct move if the memory size is 1 or 2 bytes. 6655 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 6656 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 6657 return true; 6658 6659 for (SDNode::use_iterator UI = Origin->use_begin(), 6660 UE = Origin->use_end(); 6661 UI != UE; ++UI) { 6662 6663 // Only look at the users of the loaded value. 6664 if (UI.getUse().get().getResNo() != 0) 6665 continue; 6666 6667 if (UI->getOpcode() != ISD::SINT_TO_FP && 6668 UI->getOpcode() != ISD::UINT_TO_FP) 6669 return true; 6670 } 6671 6672 return false; 6673 } 6674 6675 /// \brief Custom lowers integer to floating point conversions to use 6676 /// the direct move instructions available in ISA 2.07 to avoid the 6677 /// need for load/store combinations. 6678 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 6679 SelectionDAG &DAG, 6680 const SDLoc &dl) const { 6681 assert((Op.getValueType() == MVT::f32 || 6682 Op.getValueType() == MVT::f64) && 6683 "Invalid floating point type as target of conversion"); 6684 assert(Subtarget.hasFPCVT() && 6685 "Int to FP conversions with direct moves require FPCVT"); 6686 SDValue FP; 6687 SDValue Src = Op.getOperand(0); 6688 bool SinglePrec = Op.getValueType() == MVT::f32; 6689 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 6690 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 6691 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 6692 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 6693 6694 if (WordInt) { 6695 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 6696 dl, MVT::f64, Src); 6697 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6698 } 6699 else { 6700 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 6701 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6702 } 6703 6704 return FP; 6705 } 6706 6707 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 6708 SelectionDAG &DAG) const { 6709 SDLoc dl(Op); 6710 6711 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 6712 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 6713 return SDValue(); 6714 6715 SDValue Value = Op.getOperand(0); 6716 // The values are now known to be -1 (false) or 1 (true). To convert this 6717 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 6718 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 6719 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 6720 6721 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 6722 6723 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 6724 6725 if (Op.getValueType() != MVT::v4f64) 6726 Value = DAG.getNode(ISD::FP_ROUND, dl, 6727 Op.getValueType(), Value, 6728 DAG.getIntPtrConstant(1, dl)); 6729 return Value; 6730 } 6731 6732 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 6733 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 6734 return SDValue(); 6735 6736 if (Op.getOperand(0).getValueType() == MVT::i1) 6737 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 6738 DAG.getConstantFP(1.0, dl, Op.getValueType()), 6739 DAG.getConstantFP(0.0, dl, Op.getValueType())); 6740 6741 // If we have direct moves, we can do all the conversion, skip the store/load 6742 // however, without FPCVT we can't do most conversions. 6743 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 6744 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 6745 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 6746 6747 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 6748 "UINT_TO_FP is supported only with FPCVT"); 6749 6750 // If we have FCFIDS, then use it when converting to single-precision. 6751 // Otherwise, convert to double-precision and then round. 6752 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 6753 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 6754 : PPCISD::FCFIDS) 6755 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 6756 : PPCISD::FCFID); 6757 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 6758 ? MVT::f32 6759 : MVT::f64; 6760 6761 if (Op.getOperand(0).getValueType() == MVT::i64) { 6762 SDValue SINT = Op.getOperand(0); 6763 // When converting to single-precision, we actually need to convert 6764 // to double-precision first and then round to single-precision. 6765 // To avoid double-rounding effects during that operation, we have 6766 // to prepare the input operand. Bits that might be truncated when 6767 // converting to double-precision are replaced by a bit that won't 6768 // be lost at this stage, but is below the single-precision rounding 6769 // position. 6770 // 6771 // However, if -enable-unsafe-fp-math is in effect, accept double 6772 // rounding to avoid the extra overhead. 6773 if (Op.getValueType() == MVT::f32 && 6774 !Subtarget.hasFPCVT() && 6775 !DAG.getTarget().Options.UnsafeFPMath) { 6776 6777 // Twiddle input to make sure the low 11 bits are zero. (If this 6778 // is the case, we are guaranteed the value will fit into the 53 bit 6779 // mantissa of an IEEE double-precision value without rounding.) 6780 // If any of those low 11 bits were not zero originally, make sure 6781 // bit 12 (value 2048) is set instead, so that the final rounding 6782 // to single-precision gets the correct result. 6783 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 6784 SINT, DAG.getConstant(2047, dl, MVT::i64)); 6785 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 6786 Round, DAG.getConstant(2047, dl, MVT::i64)); 6787 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 6788 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 6789 Round, DAG.getConstant(-2048, dl, MVT::i64)); 6790 6791 // However, we cannot use that value unconditionally: if the magnitude 6792 // of the input value is small, the bit-twiddling we did above might 6793 // end up visibly changing the output. Fortunately, in that case, we 6794 // don't need to twiddle bits since the original input will convert 6795 // exactly to double-precision floating-point already. Therefore, 6796 // construct a conditional to use the original value if the top 11 6797 // bits are all sign-bit copies, and use the rounded value computed 6798 // above otherwise. 6799 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 6800 SINT, DAG.getConstant(53, dl, MVT::i32)); 6801 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 6802 Cond, DAG.getConstant(1, dl, MVT::i64)); 6803 Cond = DAG.getSetCC(dl, MVT::i32, 6804 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 6805 6806 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 6807 } 6808 6809 ReuseLoadInfo RLI; 6810 SDValue Bits; 6811 6812 MachineFunction &MF = DAG.getMachineFunction(); 6813 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 6814 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6815 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6816 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6817 } else if (Subtarget.hasLFIWAX() && 6818 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 6819 MachineMemOperand *MMO = 6820 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6821 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6822 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6823 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 6824 DAG.getVTList(MVT::f64, MVT::Other), 6825 Ops, MVT::i32, MMO); 6826 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6827 } else if (Subtarget.hasFPCVT() && 6828 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 6829 MachineMemOperand *MMO = 6830 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6831 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6832 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6833 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 6834 DAG.getVTList(MVT::f64, MVT::Other), 6835 Ops, MVT::i32, MMO); 6836 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6837 } else if (((Subtarget.hasLFIWAX() && 6838 SINT.getOpcode() == ISD::SIGN_EXTEND) || 6839 (Subtarget.hasFPCVT() && 6840 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 6841 SINT.getOperand(0).getValueType() == MVT::i32) { 6842 MachineFrameInfo &MFI = MF.getFrameInfo(); 6843 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6844 6845 int FrameIdx = MFI.CreateStackObject(4, 4, false); 6846 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6847 6848 SDValue Store = 6849 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 6850 MachinePointerInfo::getFixedStack( 6851 DAG.getMachineFunction(), FrameIdx)); 6852 6853 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 6854 "Expected an i32 store"); 6855 6856 RLI.Ptr = FIdx; 6857 RLI.Chain = Store; 6858 RLI.MPI = 6859 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 6860 RLI.Alignment = 4; 6861 6862 MachineMemOperand *MMO = 6863 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6864 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6865 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6866 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 6867 PPCISD::LFIWZX : PPCISD::LFIWAX, 6868 dl, DAG.getVTList(MVT::f64, MVT::Other), 6869 Ops, MVT::i32, MMO); 6870 } else 6871 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 6872 6873 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 6874 6875 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 6876 FP = DAG.getNode(ISD::FP_ROUND, dl, 6877 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 6878 return FP; 6879 } 6880 6881 assert(Op.getOperand(0).getValueType() == MVT::i32 && 6882 "Unhandled INT_TO_FP type in custom expander!"); 6883 // Since we only generate this in 64-bit mode, we can take advantage of 6884 // 64-bit registers. In particular, sign extend the input value into the 6885 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 6886 // then lfd it and fcfid it. 6887 MachineFunction &MF = DAG.getMachineFunction(); 6888 MachineFrameInfo &MFI = MF.getFrameInfo(); 6889 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6890 6891 SDValue Ld; 6892 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 6893 ReuseLoadInfo RLI; 6894 bool ReusingLoad; 6895 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 6896 DAG))) { 6897 int FrameIdx = MFI.CreateStackObject(4, 4, false); 6898 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6899 6900 SDValue Store = 6901 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 6902 MachinePointerInfo::getFixedStack( 6903 DAG.getMachineFunction(), FrameIdx)); 6904 6905 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 6906 "Expected an i32 store"); 6907 6908 RLI.Ptr = FIdx; 6909 RLI.Chain = Store; 6910 RLI.MPI = 6911 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 6912 RLI.Alignment = 4; 6913 } 6914 6915 MachineMemOperand *MMO = 6916 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6917 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6918 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6919 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 6920 PPCISD::LFIWZX : PPCISD::LFIWAX, 6921 dl, DAG.getVTList(MVT::f64, MVT::Other), 6922 Ops, MVT::i32, MMO); 6923 if (ReusingLoad) 6924 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 6925 } else { 6926 assert(Subtarget.isPPC64() && 6927 "i32->FP without LFIWAX supported only on PPC64"); 6928 6929 int FrameIdx = MFI.CreateStackObject(8, 8, false); 6930 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6931 6932 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 6933 Op.getOperand(0)); 6934 6935 // STD the extended value into the stack slot. 6936 SDValue Store = DAG.getStore( 6937 DAG.getEntryNode(), dl, Ext64, FIdx, 6938 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 6939 6940 // Load the value as a double. 6941 Ld = DAG.getLoad( 6942 MVT::f64, dl, Store, FIdx, 6943 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 6944 } 6945 6946 // FCFID it and return it. 6947 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 6948 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 6949 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 6950 DAG.getIntPtrConstant(0, dl)); 6951 return FP; 6952 } 6953 6954 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 6955 SelectionDAG &DAG) const { 6956 SDLoc dl(Op); 6957 /* 6958 The rounding mode is in bits 30:31 of FPSR, and has the following 6959 settings: 6960 00 Round to nearest 6961 01 Round to 0 6962 10 Round to +inf 6963 11 Round to -inf 6964 6965 FLT_ROUNDS, on the other hand, expects the following: 6966 -1 Undefined 6967 0 Round to 0 6968 1 Round to nearest 6969 2 Round to +inf 6970 3 Round to -inf 6971 6972 To perform the conversion, we do: 6973 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 6974 */ 6975 6976 MachineFunction &MF = DAG.getMachineFunction(); 6977 EVT VT = Op.getValueType(); 6978 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6979 6980 // Save FP Control Word to register 6981 EVT NodeTys[] = { 6982 MVT::f64, // return register 6983 MVT::Glue // unused in this context 6984 }; 6985 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 6986 6987 // Save FP register to stack slot 6988 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 6989 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 6990 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 6991 MachinePointerInfo()); 6992 6993 // Load FP Control Word from low 32 bits of stack slot. 6994 SDValue Four = DAG.getConstant(4, dl, PtrVT); 6995 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 6996 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 6997 6998 // Transform as necessary 6999 SDValue CWD1 = 7000 DAG.getNode(ISD::AND, dl, MVT::i32, 7001 CWD, DAG.getConstant(3, dl, MVT::i32)); 7002 SDValue CWD2 = 7003 DAG.getNode(ISD::SRL, dl, MVT::i32, 7004 DAG.getNode(ISD::AND, dl, MVT::i32, 7005 DAG.getNode(ISD::XOR, dl, MVT::i32, 7006 CWD, DAG.getConstant(3, dl, MVT::i32)), 7007 DAG.getConstant(3, dl, MVT::i32)), 7008 DAG.getConstant(1, dl, MVT::i32)); 7009 7010 SDValue RetVal = 7011 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7012 7013 return DAG.getNode((VT.getSizeInBits() < 16 ? 7014 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7015 } 7016 7017 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7018 EVT VT = Op.getValueType(); 7019 unsigned BitWidth = VT.getSizeInBits(); 7020 SDLoc dl(Op); 7021 assert(Op.getNumOperands() == 3 && 7022 VT == Op.getOperand(1).getValueType() && 7023 "Unexpected SHL!"); 7024 7025 // Expand into a bunch of logical ops. Note that these ops 7026 // depend on the PPC behavior for oversized shift amounts. 7027 SDValue Lo = Op.getOperand(0); 7028 SDValue Hi = Op.getOperand(1); 7029 SDValue Amt = Op.getOperand(2); 7030 EVT AmtVT = Amt.getValueType(); 7031 7032 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7033 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7034 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7035 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7036 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7037 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7038 DAG.getConstant(-BitWidth, dl, AmtVT)); 7039 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7040 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7041 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7042 SDValue OutOps[] = { OutLo, OutHi }; 7043 return DAG.getMergeValues(OutOps, dl); 7044 } 7045 7046 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7047 EVT VT = Op.getValueType(); 7048 SDLoc dl(Op); 7049 unsigned BitWidth = VT.getSizeInBits(); 7050 assert(Op.getNumOperands() == 3 && 7051 VT == Op.getOperand(1).getValueType() && 7052 "Unexpected SRL!"); 7053 7054 // Expand into a bunch of logical ops. Note that these ops 7055 // depend on the PPC behavior for oversized shift amounts. 7056 SDValue Lo = Op.getOperand(0); 7057 SDValue Hi = Op.getOperand(1); 7058 SDValue Amt = Op.getOperand(2); 7059 EVT AmtVT = Amt.getValueType(); 7060 7061 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7062 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7063 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7064 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7065 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7066 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7067 DAG.getConstant(-BitWidth, dl, AmtVT)); 7068 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7069 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7070 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7071 SDValue OutOps[] = { OutLo, OutHi }; 7072 return DAG.getMergeValues(OutOps, dl); 7073 } 7074 7075 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7076 SDLoc dl(Op); 7077 EVT VT = Op.getValueType(); 7078 unsigned BitWidth = VT.getSizeInBits(); 7079 assert(Op.getNumOperands() == 3 && 7080 VT == Op.getOperand(1).getValueType() && 7081 "Unexpected SRA!"); 7082 7083 // Expand into a bunch of logical ops, followed by a select_cc. 7084 SDValue Lo = Op.getOperand(0); 7085 SDValue Hi = Op.getOperand(1); 7086 SDValue Amt = Op.getOperand(2); 7087 EVT AmtVT = Amt.getValueType(); 7088 7089 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7090 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7091 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7092 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7093 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7094 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7095 DAG.getConstant(-BitWidth, dl, AmtVT)); 7096 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7097 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7098 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7099 Tmp4, Tmp6, ISD::SETLE); 7100 SDValue OutOps[] = { OutLo, OutHi }; 7101 return DAG.getMergeValues(OutOps, dl); 7102 } 7103 7104 //===----------------------------------------------------------------------===// 7105 // Vector related lowering. 7106 // 7107 7108 /// BuildSplatI - Build a canonical splati of Val with an element size of 7109 /// SplatSize. Cast the result to VT. 7110 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7111 SelectionDAG &DAG, const SDLoc &dl) { 7112 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7113 7114 static const MVT VTys[] = { // canonical VT to use for each size. 7115 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7116 }; 7117 7118 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7119 7120 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7121 if (Val == -1) 7122 SplatSize = 1; 7123 7124 EVT CanonicalVT = VTys[SplatSize-1]; 7125 7126 // Build a canonical splat for this value. 7127 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7128 } 7129 7130 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7131 /// specified intrinsic ID. 7132 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7133 const SDLoc &dl, EVT DestVT = MVT::Other) { 7134 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7135 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7136 DAG.getConstant(IID, dl, MVT::i32), Op); 7137 } 7138 7139 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7140 /// specified intrinsic ID. 7141 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7142 SelectionDAG &DAG, const SDLoc &dl, 7143 EVT DestVT = MVT::Other) { 7144 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7145 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7146 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7147 } 7148 7149 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7150 /// specified intrinsic ID. 7151 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7152 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7153 EVT DestVT = MVT::Other) { 7154 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7155 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7156 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7157 } 7158 7159 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7160 /// amount. The result has the specified value type. 7161 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7162 SelectionDAG &DAG, const SDLoc &dl) { 7163 // Force LHS/RHS to be the right type. 7164 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7165 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7166 7167 int Ops[16]; 7168 for (unsigned i = 0; i != 16; ++i) 7169 Ops[i] = i + Amt; 7170 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7171 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7172 } 7173 7174 /// Do we have an efficient pattern in a .td file for this node? 7175 /// 7176 /// \param V - pointer to the BuildVectorSDNode being matched 7177 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7178 /// 7179 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7180 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7181 /// the opposite is true (expansion is beneficial) are: 7182 /// - The node builds a vector out of integers that are not 32 or 64-bits 7183 /// - The node builds a vector out of constants 7184 /// - The node is a "load-and-splat" 7185 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7186 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7187 bool HasDirectMove) { 7188 EVT VecVT = V->getValueType(0); 7189 bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 || 7190 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7191 if (!RightType) 7192 return false; 7193 7194 bool IsSplat = true; 7195 bool IsLoad = false; 7196 SDValue Op0 = V->getOperand(0); 7197 7198 // This function is called in a block that confirms the node is not a constant 7199 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7200 // different constants. 7201 if (V->isConstant()) 7202 return false; 7203 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7204 if (V->getOperand(i).isUndef()) 7205 return false; 7206 // We want to expand nodes that represent load-and-splat even if the 7207 // loaded value is a floating point truncation or conversion to int. 7208 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7209 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7210 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7211 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7212 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7213 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7214 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7215 IsLoad = true; 7216 // If the operands are different or the input is not a load and has more 7217 // uses than just this BV node, then it isn't a splat. 7218 if (V->getOperand(i) != Op0 || 7219 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7220 IsSplat = false; 7221 } 7222 return !(IsSplat && IsLoad); 7223 } 7224 7225 // If this is a case we can't handle, return null and let the default 7226 // expansion code take care of it. If we CAN select this case, and if it 7227 // selects to a single instruction, return Op. Otherwise, if we can codegen 7228 // this case more efficiently than a constant pool load, lower it to the 7229 // sequence of ops that should be used. 7230 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7231 SelectionDAG &DAG) const { 7232 SDLoc dl(Op); 7233 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7234 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7235 7236 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7237 // We first build an i32 vector, load it into a QPX register, 7238 // then convert it to a floating-point vector and compare it 7239 // to a zero vector to get the boolean result. 7240 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7241 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7242 MachinePointerInfo PtrInfo = 7243 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7244 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7245 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7246 7247 assert(BVN->getNumOperands() == 4 && 7248 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7249 7250 bool IsConst = true; 7251 for (unsigned i = 0; i < 4; ++i) { 7252 if (BVN->getOperand(i).isUndef()) continue; 7253 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7254 IsConst = false; 7255 break; 7256 } 7257 } 7258 7259 if (IsConst) { 7260 Constant *One = 7261 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7262 Constant *NegOne = 7263 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7264 7265 Constant *CV[4]; 7266 for (unsigned i = 0; i < 4; ++i) { 7267 if (BVN->getOperand(i).isUndef()) 7268 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7269 else if (isNullConstant(BVN->getOperand(i))) 7270 CV[i] = NegOne; 7271 else 7272 CV[i] = One; 7273 } 7274 7275 Constant *CP = ConstantVector::get(CV); 7276 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7277 16 /* alignment */); 7278 7279 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7280 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7281 return DAG.getMemIntrinsicNode( 7282 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7283 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7284 } 7285 7286 SmallVector<SDValue, 4> Stores; 7287 for (unsigned i = 0; i < 4; ++i) { 7288 if (BVN->getOperand(i).isUndef()) continue; 7289 7290 unsigned Offset = 4*i; 7291 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7292 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7293 7294 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7295 if (StoreSize > 4) { 7296 Stores.push_back( 7297 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7298 PtrInfo.getWithOffset(Offset), MVT::i32)); 7299 } else { 7300 SDValue StoreValue = BVN->getOperand(i); 7301 if (StoreSize < 4) 7302 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7303 7304 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7305 PtrInfo.getWithOffset(Offset))); 7306 } 7307 } 7308 7309 SDValue StoreChain; 7310 if (!Stores.empty()) 7311 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7312 else 7313 StoreChain = DAG.getEntryNode(); 7314 7315 // Now load from v4i32 into the QPX register; this will extend it to 7316 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7317 // is typed as v4f64 because the QPX register integer states are not 7318 // explicitly represented. 7319 7320 SDValue Ops[] = {StoreChain, 7321 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7322 FIdx}; 7323 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7324 7325 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7326 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7327 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7328 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7329 LoadedVect); 7330 7331 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7332 7333 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7334 } 7335 7336 // All other QPX vectors are handled by generic code. 7337 if (Subtarget.hasQPX()) 7338 return SDValue(); 7339 7340 // Check if this is a splat of a constant value. 7341 APInt APSplatBits, APSplatUndef; 7342 unsigned SplatBitSize; 7343 bool HasAnyUndefs; 7344 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7345 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7346 SplatBitSize > 32) { 7347 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7348 // lowered to VSX instructions under certain conditions. 7349 // Without VSX, there is no pattern more efficient than expanding the node. 7350 if (Subtarget.hasVSX() && 7351 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove())) 7352 return Op; 7353 return SDValue(); 7354 } 7355 7356 unsigned SplatBits = APSplatBits.getZExtValue(); 7357 unsigned SplatUndef = APSplatUndef.getZExtValue(); 7358 unsigned SplatSize = SplatBitSize / 8; 7359 7360 // First, handle single instruction cases. 7361 7362 // All zeros? 7363 if (SplatBits == 0) { 7364 // Canonicalize all zero vectors to be v4i32. 7365 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 7366 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 7367 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 7368 } 7369 return Op; 7370 } 7371 7372 // We have XXSPLTIB for constant splats one byte wide 7373 if (Subtarget.hasP9Vector() && SplatSize == 1) { 7374 // This is a splat of 1-byte elements with some elements potentially undef. 7375 // Rather than trying to match undef in the SDAG patterns, ensure that all 7376 // elements are the same constant. 7377 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 7378 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 7379 dl, MVT::i32)); 7380 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 7381 if (Op.getValueType() != MVT::v16i8) 7382 return DAG.getBitcast(Op.getValueType(), NewBV); 7383 return NewBV; 7384 } 7385 return Op; 7386 } 7387 7388 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 7389 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 7390 (32-SplatBitSize)); 7391 if (SextVal >= -16 && SextVal <= 15) 7392 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 7393 7394 // Two instruction sequences. 7395 7396 // If this value is in the range [-32,30] and is even, use: 7397 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 7398 // If this value is in the range [17,31] and is odd, use: 7399 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 7400 // If this value is in the range [-31,-17] and is odd, use: 7401 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 7402 // Note the last two are three-instruction sequences. 7403 if (SextVal >= -32 && SextVal <= 31) { 7404 // To avoid having these optimizations undone by constant folding, 7405 // we convert to a pseudo that will be expanded later into one of 7406 // the above forms. 7407 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 7408 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 7409 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 7410 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 7411 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 7412 if (VT == Op.getValueType()) 7413 return RetVal; 7414 else 7415 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 7416 } 7417 7418 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 7419 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 7420 // for fneg/fabs. 7421 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 7422 // Make -1 and vspltisw -1: 7423 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 7424 7425 // Make the VSLW intrinsic, computing 0x8000_0000. 7426 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 7427 OnesV, DAG, dl); 7428 7429 // xor by OnesV to invert it. 7430 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 7431 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7432 } 7433 7434 // Check to see if this is a wide variety of vsplti*, binop self cases. 7435 static const signed char SplatCsts[] = { 7436 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 7437 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 7438 }; 7439 7440 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 7441 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 7442 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 7443 int i = SplatCsts[idx]; 7444 7445 // Figure out what shift amount will be used by altivec if shifted by i in 7446 // this splat size. 7447 unsigned TypeShiftAmt = i & (SplatBitSize-1); 7448 7449 // vsplti + shl self. 7450 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 7451 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7452 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7453 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 7454 Intrinsic::ppc_altivec_vslw 7455 }; 7456 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7457 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7458 } 7459 7460 // vsplti + srl self. 7461 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7462 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7463 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7464 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 7465 Intrinsic::ppc_altivec_vsrw 7466 }; 7467 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7468 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7469 } 7470 7471 // vsplti + sra self. 7472 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7473 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7474 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7475 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 7476 Intrinsic::ppc_altivec_vsraw 7477 }; 7478 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7479 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7480 } 7481 7482 // vsplti + rol self. 7483 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 7484 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 7485 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7486 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7487 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 7488 Intrinsic::ppc_altivec_vrlw 7489 }; 7490 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7491 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7492 } 7493 7494 // t = vsplti c, result = vsldoi t, t, 1 7495 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 7496 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7497 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 7498 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7499 } 7500 // t = vsplti c, result = vsldoi t, t, 2 7501 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 7502 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7503 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 7504 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7505 } 7506 // t = vsplti c, result = vsldoi t, t, 3 7507 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 7508 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7509 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 7510 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7511 } 7512 } 7513 7514 return SDValue(); 7515 } 7516 7517 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7518 /// the specified operations to build the shuffle. 7519 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7520 SDValue RHS, SelectionDAG &DAG, 7521 const SDLoc &dl) { 7522 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7523 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7524 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7525 7526 enum { 7527 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7528 OP_VMRGHW, 7529 OP_VMRGLW, 7530 OP_VSPLTISW0, 7531 OP_VSPLTISW1, 7532 OP_VSPLTISW2, 7533 OP_VSPLTISW3, 7534 OP_VSLDOI4, 7535 OP_VSLDOI8, 7536 OP_VSLDOI12 7537 }; 7538 7539 if (OpNum == OP_COPY) { 7540 if (LHSID == (1*9+2)*9+3) return LHS; 7541 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7542 return RHS; 7543 } 7544 7545 SDValue OpLHS, OpRHS; 7546 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7547 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7548 7549 int ShufIdxs[16]; 7550 switch (OpNum) { 7551 default: llvm_unreachable("Unknown i32 permute!"); 7552 case OP_VMRGHW: 7553 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 7554 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 7555 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 7556 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 7557 break; 7558 case OP_VMRGLW: 7559 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 7560 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 7561 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 7562 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 7563 break; 7564 case OP_VSPLTISW0: 7565 for (unsigned i = 0; i != 16; ++i) 7566 ShufIdxs[i] = (i&3)+0; 7567 break; 7568 case OP_VSPLTISW1: 7569 for (unsigned i = 0; i != 16; ++i) 7570 ShufIdxs[i] = (i&3)+4; 7571 break; 7572 case OP_VSPLTISW2: 7573 for (unsigned i = 0; i != 16; ++i) 7574 ShufIdxs[i] = (i&3)+8; 7575 break; 7576 case OP_VSPLTISW3: 7577 for (unsigned i = 0; i != 16; ++i) 7578 ShufIdxs[i] = (i&3)+12; 7579 break; 7580 case OP_VSLDOI4: 7581 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 7582 case OP_VSLDOI8: 7583 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 7584 case OP_VSLDOI12: 7585 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 7586 } 7587 EVT VT = OpLHS.getValueType(); 7588 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 7589 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 7590 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 7591 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7592 } 7593 7594 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 7595 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 7596 /// return the code it can be lowered into. Worst case, it can always be 7597 /// lowered into a vperm. 7598 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 7599 SelectionDAG &DAG) const { 7600 SDLoc dl(Op); 7601 SDValue V1 = Op.getOperand(0); 7602 SDValue V2 = Op.getOperand(1); 7603 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 7604 EVT VT = Op.getValueType(); 7605 bool isLittleEndian = Subtarget.isLittleEndian(); 7606 7607 unsigned ShiftElts, InsertAtByte; 7608 bool Swap; 7609 if (Subtarget.hasP9Vector() && 7610 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 7611 isLittleEndian)) { 7612 if (Swap) 7613 std::swap(V1, V2); 7614 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7615 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 7616 if (ShiftElts) { 7617 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 7618 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7619 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl, 7620 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7621 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 7622 } 7623 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2, 7624 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7625 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 7626 } 7627 7628 if (Subtarget.hasVSX()) { 7629 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 7630 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 7631 7632 // If the source for the shuffle is a scalar_to_vector that came from a 7633 // 32-bit load, it will have used LXVWSX so we don't need to splat again. 7634 if (Subtarget.hasP9Vector() && 7635 ((isLittleEndian && SplatIdx == 3) || 7636 (!isLittleEndian && SplatIdx == 0))) { 7637 SDValue Src = V1.getOperand(0); 7638 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR && 7639 Src.getOperand(0).getOpcode() == ISD::LOAD && 7640 Src.getOperand(0).hasOneUse()) 7641 return V1; 7642 } 7643 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7644 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 7645 DAG.getConstant(SplatIdx, dl, MVT::i32)); 7646 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 7647 } 7648 7649 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 7650 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 7651 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 7652 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 7653 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 7654 } 7655 } 7656 7657 if (Subtarget.hasQPX()) { 7658 if (VT.getVectorNumElements() != 4) 7659 return SDValue(); 7660 7661 if (V2.isUndef()) V2 = V1; 7662 7663 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 7664 if (AlignIdx != -1) { 7665 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 7666 DAG.getConstant(AlignIdx, dl, MVT::i32)); 7667 } else if (SVOp->isSplat()) { 7668 int SplatIdx = SVOp->getSplatIndex(); 7669 if (SplatIdx >= 4) { 7670 std::swap(V1, V2); 7671 SplatIdx -= 4; 7672 } 7673 7674 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 7675 DAG.getConstant(SplatIdx, dl, MVT::i32)); 7676 } 7677 7678 // Lower this into a qvgpci/qvfperm pair. 7679 7680 // Compute the qvgpci literal 7681 unsigned idx = 0; 7682 for (unsigned i = 0; i < 4; ++i) { 7683 int m = SVOp->getMaskElt(i); 7684 unsigned mm = m >= 0 ? (unsigned) m : i; 7685 idx |= mm << (3-i)*3; 7686 } 7687 7688 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 7689 DAG.getConstant(idx, dl, MVT::i32)); 7690 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 7691 } 7692 7693 // Cases that are handled by instructions that take permute immediates 7694 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 7695 // selected by the instruction selector. 7696 if (V2.isUndef()) { 7697 if (PPC::isSplatShuffleMask(SVOp, 1) || 7698 PPC::isSplatShuffleMask(SVOp, 2) || 7699 PPC::isSplatShuffleMask(SVOp, 4) || 7700 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 7701 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 7702 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 7703 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 7704 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 7705 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 7706 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 7707 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 7708 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 7709 (Subtarget.hasP8Altivec() && ( 7710 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 7711 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 7712 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 7713 return Op; 7714 } 7715 } 7716 7717 // Altivec has a variety of "shuffle immediates" that take two vector inputs 7718 // and produce a fixed permutation. If any of these match, do not lower to 7719 // VPERM. 7720 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 7721 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 7722 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 7723 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 7724 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 7725 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 7726 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 7727 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 7728 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 7729 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 7730 (Subtarget.hasP8Altivec() && ( 7731 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 7732 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 7733 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 7734 return Op; 7735 7736 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 7737 // perfect shuffle table to emit an optimal matching sequence. 7738 ArrayRef<int> PermMask = SVOp->getMask(); 7739 7740 unsigned PFIndexes[4]; 7741 bool isFourElementShuffle = true; 7742 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 7743 unsigned EltNo = 8; // Start out undef. 7744 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 7745 if (PermMask[i*4+j] < 0) 7746 continue; // Undef, ignore it. 7747 7748 unsigned ByteSource = PermMask[i*4+j]; 7749 if ((ByteSource & 3) != j) { 7750 isFourElementShuffle = false; 7751 break; 7752 } 7753 7754 if (EltNo == 8) { 7755 EltNo = ByteSource/4; 7756 } else if (EltNo != ByteSource/4) { 7757 isFourElementShuffle = false; 7758 break; 7759 } 7760 } 7761 PFIndexes[i] = EltNo; 7762 } 7763 7764 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 7765 // perfect shuffle vector to determine if it is cost effective to do this as 7766 // discrete instructions, or whether we should use a vperm. 7767 // For now, we skip this for little endian until such time as we have a 7768 // little-endian perfect shuffle table. 7769 if (isFourElementShuffle && !isLittleEndian) { 7770 // Compute the index in the perfect shuffle table. 7771 unsigned PFTableIndex = 7772 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7773 7774 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7775 unsigned Cost = (PFEntry >> 30); 7776 7777 // Determining when to avoid vperm is tricky. Many things affect the cost 7778 // of vperm, particularly how many times the perm mask needs to be computed. 7779 // For example, if the perm mask can be hoisted out of a loop or is already 7780 // used (perhaps because there are multiple permutes with the same shuffle 7781 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 7782 // the loop requires an extra register. 7783 // 7784 // As a compromise, we only emit discrete instructions if the shuffle can be 7785 // generated in 3 or fewer operations. When we have loop information 7786 // available, if this block is within a loop, we should avoid using vperm 7787 // for 3-operation perms and use a constant pool load instead. 7788 if (Cost < 3) 7789 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7790 } 7791 7792 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 7793 // vector that will get spilled to the constant pool. 7794 if (V2.isUndef()) V2 = V1; 7795 7796 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 7797 // that it is in input element units, not in bytes. Convert now. 7798 7799 // For little endian, the order of the input vectors is reversed, and 7800 // the permutation mask is complemented with respect to 31. This is 7801 // necessary to produce proper semantics with the big-endian-biased vperm 7802 // instruction. 7803 EVT EltVT = V1.getValueType().getVectorElementType(); 7804 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 7805 7806 SmallVector<SDValue, 16> ResultMask; 7807 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 7808 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 7809 7810 for (unsigned j = 0; j != BytesPerElement; ++j) 7811 if (isLittleEndian) 7812 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 7813 dl, MVT::i32)); 7814 else 7815 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 7816 MVT::i32)); 7817 } 7818 7819 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 7820 if (isLittleEndian) 7821 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 7822 V2, V1, VPermMask); 7823 else 7824 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 7825 V1, V2, VPermMask); 7826 } 7827 7828 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 7829 /// vector comparison. If it is, return true and fill in Opc/isDot with 7830 /// information about the intrinsic. 7831 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 7832 bool &isDot, const PPCSubtarget &Subtarget) { 7833 unsigned IntrinsicID = 7834 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 7835 CompareOpc = -1; 7836 isDot = false; 7837 switch (IntrinsicID) { 7838 default: 7839 return false; 7840 // Comparison predicates. 7841 case Intrinsic::ppc_altivec_vcmpbfp_p: 7842 CompareOpc = 966; 7843 isDot = true; 7844 break; 7845 case Intrinsic::ppc_altivec_vcmpeqfp_p: 7846 CompareOpc = 198; 7847 isDot = true; 7848 break; 7849 case Intrinsic::ppc_altivec_vcmpequb_p: 7850 CompareOpc = 6; 7851 isDot = true; 7852 break; 7853 case Intrinsic::ppc_altivec_vcmpequh_p: 7854 CompareOpc = 70; 7855 isDot = true; 7856 break; 7857 case Intrinsic::ppc_altivec_vcmpequw_p: 7858 CompareOpc = 134; 7859 isDot = true; 7860 break; 7861 case Intrinsic::ppc_altivec_vcmpequd_p: 7862 if (Subtarget.hasP8Altivec()) { 7863 CompareOpc = 199; 7864 isDot = true; 7865 } else 7866 return false; 7867 break; 7868 case Intrinsic::ppc_altivec_vcmpneb_p: 7869 case Intrinsic::ppc_altivec_vcmpneh_p: 7870 case Intrinsic::ppc_altivec_vcmpnew_p: 7871 case Intrinsic::ppc_altivec_vcmpnezb_p: 7872 case Intrinsic::ppc_altivec_vcmpnezh_p: 7873 case Intrinsic::ppc_altivec_vcmpnezw_p: 7874 if (Subtarget.hasP9Altivec()) { 7875 switch (IntrinsicID) { 7876 default: 7877 llvm_unreachable("Unknown comparison intrinsic."); 7878 case Intrinsic::ppc_altivec_vcmpneb_p: 7879 CompareOpc = 7; 7880 break; 7881 case Intrinsic::ppc_altivec_vcmpneh_p: 7882 CompareOpc = 71; 7883 break; 7884 case Intrinsic::ppc_altivec_vcmpnew_p: 7885 CompareOpc = 135; 7886 break; 7887 case Intrinsic::ppc_altivec_vcmpnezb_p: 7888 CompareOpc = 263; 7889 break; 7890 case Intrinsic::ppc_altivec_vcmpnezh_p: 7891 CompareOpc = 327; 7892 break; 7893 case Intrinsic::ppc_altivec_vcmpnezw_p: 7894 CompareOpc = 391; 7895 break; 7896 } 7897 isDot = true; 7898 } else 7899 return false; 7900 break; 7901 case Intrinsic::ppc_altivec_vcmpgefp_p: 7902 CompareOpc = 454; 7903 isDot = true; 7904 break; 7905 case Intrinsic::ppc_altivec_vcmpgtfp_p: 7906 CompareOpc = 710; 7907 isDot = true; 7908 break; 7909 case Intrinsic::ppc_altivec_vcmpgtsb_p: 7910 CompareOpc = 774; 7911 isDot = true; 7912 break; 7913 case Intrinsic::ppc_altivec_vcmpgtsh_p: 7914 CompareOpc = 838; 7915 isDot = true; 7916 break; 7917 case Intrinsic::ppc_altivec_vcmpgtsw_p: 7918 CompareOpc = 902; 7919 isDot = true; 7920 break; 7921 case Intrinsic::ppc_altivec_vcmpgtsd_p: 7922 if (Subtarget.hasP8Altivec()) { 7923 CompareOpc = 967; 7924 isDot = true; 7925 } else 7926 return false; 7927 break; 7928 case Intrinsic::ppc_altivec_vcmpgtub_p: 7929 CompareOpc = 518; 7930 isDot = true; 7931 break; 7932 case Intrinsic::ppc_altivec_vcmpgtuh_p: 7933 CompareOpc = 582; 7934 isDot = true; 7935 break; 7936 case Intrinsic::ppc_altivec_vcmpgtuw_p: 7937 CompareOpc = 646; 7938 isDot = true; 7939 break; 7940 case Intrinsic::ppc_altivec_vcmpgtud_p: 7941 if (Subtarget.hasP8Altivec()) { 7942 CompareOpc = 711; 7943 isDot = true; 7944 } else 7945 return false; 7946 break; 7947 7948 // VSX predicate comparisons use the same infrastructure 7949 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 7950 case Intrinsic::ppc_vsx_xvcmpgedp_p: 7951 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 7952 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 7953 case Intrinsic::ppc_vsx_xvcmpgesp_p: 7954 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 7955 if (Subtarget.hasVSX()) { 7956 switch (IntrinsicID) { 7957 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 7958 CompareOpc = 99; 7959 break; 7960 case Intrinsic::ppc_vsx_xvcmpgedp_p: 7961 CompareOpc = 115; 7962 break; 7963 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 7964 CompareOpc = 107; 7965 break; 7966 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 7967 CompareOpc = 67; 7968 break; 7969 case Intrinsic::ppc_vsx_xvcmpgesp_p: 7970 CompareOpc = 83; 7971 break; 7972 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 7973 CompareOpc = 75; 7974 break; 7975 } 7976 isDot = true; 7977 } else 7978 return false; 7979 break; 7980 7981 // Normal Comparisons. 7982 case Intrinsic::ppc_altivec_vcmpbfp: 7983 CompareOpc = 966; 7984 break; 7985 case Intrinsic::ppc_altivec_vcmpeqfp: 7986 CompareOpc = 198; 7987 break; 7988 case Intrinsic::ppc_altivec_vcmpequb: 7989 CompareOpc = 6; 7990 break; 7991 case Intrinsic::ppc_altivec_vcmpequh: 7992 CompareOpc = 70; 7993 break; 7994 case Intrinsic::ppc_altivec_vcmpequw: 7995 CompareOpc = 134; 7996 break; 7997 case Intrinsic::ppc_altivec_vcmpequd: 7998 if (Subtarget.hasP8Altivec()) 7999 CompareOpc = 199; 8000 else 8001 return false; 8002 break; 8003 case Intrinsic::ppc_altivec_vcmpneb: 8004 case Intrinsic::ppc_altivec_vcmpneh: 8005 case Intrinsic::ppc_altivec_vcmpnew: 8006 case Intrinsic::ppc_altivec_vcmpnezb: 8007 case Intrinsic::ppc_altivec_vcmpnezh: 8008 case Intrinsic::ppc_altivec_vcmpnezw: 8009 if (Subtarget.hasP9Altivec()) 8010 switch (IntrinsicID) { 8011 default: 8012 llvm_unreachable("Unknown comparison intrinsic."); 8013 case Intrinsic::ppc_altivec_vcmpneb: 8014 CompareOpc = 7; 8015 break; 8016 case Intrinsic::ppc_altivec_vcmpneh: 8017 CompareOpc = 71; 8018 break; 8019 case Intrinsic::ppc_altivec_vcmpnew: 8020 CompareOpc = 135; 8021 break; 8022 case Intrinsic::ppc_altivec_vcmpnezb: 8023 CompareOpc = 263; 8024 break; 8025 case Intrinsic::ppc_altivec_vcmpnezh: 8026 CompareOpc = 327; 8027 break; 8028 case Intrinsic::ppc_altivec_vcmpnezw: 8029 CompareOpc = 391; 8030 break; 8031 } 8032 else 8033 return false; 8034 break; 8035 case Intrinsic::ppc_altivec_vcmpgefp: 8036 CompareOpc = 454; 8037 break; 8038 case Intrinsic::ppc_altivec_vcmpgtfp: 8039 CompareOpc = 710; 8040 break; 8041 case Intrinsic::ppc_altivec_vcmpgtsb: 8042 CompareOpc = 774; 8043 break; 8044 case Intrinsic::ppc_altivec_vcmpgtsh: 8045 CompareOpc = 838; 8046 break; 8047 case Intrinsic::ppc_altivec_vcmpgtsw: 8048 CompareOpc = 902; 8049 break; 8050 case Intrinsic::ppc_altivec_vcmpgtsd: 8051 if (Subtarget.hasP8Altivec()) 8052 CompareOpc = 967; 8053 else 8054 return false; 8055 break; 8056 case Intrinsic::ppc_altivec_vcmpgtub: 8057 CompareOpc = 518; 8058 break; 8059 case Intrinsic::ppc_altivec_vcmpgtuh: 8060 CompareOpc = 582; 8061 break; 8062 case Intrinsic::ppc_altivec_vcmpgtuw: 8063 CompareOpc = 646; 8064 break; 8065 case Intrinsic::ppc_altivec_vcmpgtud: 8066 if (Subtarget.hasP8Altivec()) 8067 CompareOpc = 711; 8068 else 8069 return false; 8070 break; 8071 } 8072 return true; 8073 } 8074 8075 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8076 /// lower, do it, otherwise return null. 8077 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8078 SelectionDAG &DAG) const { 8079 unsigned IntrinsicID = 8080 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8081 8082 if (IntrinsicID == Intrinsic::thread_pointer) { 8083 // Reads the thread pointer register, used for __builtin_thread_pointer. 8084 bool is64bit = Subtarget.isPPC64(); 8085 return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2, 8086 is64bit ? MVT::i64 : MVT::i32); 8087 } 8088 8089 // If this is a lowered altivec predicate compare, CompareOpc is set to the 8090 // opcode number of the comparison. 8091 SDLoc dl(Op); 8092 int CompareOpc; 8093 bool isDot; 8094 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 8095 return SDValue(); // Don't custom lower most intrinsics. 8096 8097 // If this is a non-dot comparison, make the VCMP node and we are done. 8098 if (!isDot) { 8099 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 8100 Op.getOperand(1), Op.getOperand(2), 8101 DAG.getConstant(CompareOpc, dl, MVT::i32)); 8102 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 8103 } 8104 8105 // Create the PPCISD altivec 'dot' comparison node. 8106 SDValue Ops[] = { 8107 Op.getOperand(2), // LHS 8108 Op.getOperand(3), // RHS 8109 DAG.getConstant(CompareOpc, dl, MVT::i32) 8110 }; 8111 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 8112 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8113 8114 // Now that we have the comparison, emit a copy from the CR to a GPR. 8115 // This is flagged to the above dot comparison. 8116 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 8117 DAG.getRegister(PPC::CR6, MVT::i32), 8118 CompNode.getValue(1)); 8119 8120 // Unpack the result based on how the target uses it. 8121 unsigned BitNo; // Bit # of CR6. 8122 bool InvertBit; // Invert result? 8123 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 8124 default: // Can't happen, don't crash on invalid number though. 8125 case 0: // Return the value of the EQ bit of CR6. 8126 BitNo = 0; InvertBit = false; 8127 break; 8128 case 1: // Return the inverted value of the EQ bit of CR6. 8129 BitNo = 0; InvertBit = true; 8130 break; 8131 case 2: // Return the value of the LT bit of CR6. 8132 BitNo = 2; InvertBit = false; 8133 break; 8134 case 3: // Return the inverted value of the LT bit of CR6. 8135 BitNo = 2; InvertBit = true; 8136 break; 8137 } 8138 8139 // Shift the bit into the low position. 8140 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 8141 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 8142 // Isolate the bit. 8143 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 8144 DAG.getConstant(1, dl, MVT::i32)); 8145 8146 // If we are supposed to, toggle the bit. 8147 if (InvertBit) 8148 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 8149 DAG.getConstant(1, dl, MVT::i32)); 8150 return Flags; 8151 } 8152 8153 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 8154 SelectionDAG &DAG) const { 8155 SDLoc dl(Op); 8156 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 8157 // instructions), but for smaller types, we need to first extend up to v2i32 8158 // before doing going farther. 8159 if (Op.getValueType() == MVT::v2i64) { 8160 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 8161 if (ExtVT != MVT::v2i32) { 8162 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 8163 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 8164 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 8165 ExtVT.getVectorElementType(), 4))); 8166 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 8167 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 8168 DAG.getValueType(MVT::v2i32)); 8169 } 8170 8171 return Op; 8172 } 8173 8174 return SDValue(); 8175 } 8176 8177 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 8178 SelectionDAG &DAG) const { 8179 SDLoc dl(Op); 8180 // Create a stack slot that is 16-byte aligned. 8181 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8182 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8183 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8184 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8185 8186 // Store the input value into Value#0 of the stack slot. 8187 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8188 MachinePointerInfo()); 8189 // Load it out. 8190 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 8191 } 8192 8193 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8194 SelectionDAG &DAG) const { 8195 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 8196 "Should only be called for ISD::INSERT_VECTOR_ELT"); 8197 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8198 // We have legal lowering for constant indices but not for variable ones. 8199 if (C) 8200 return Op; 8201 return SDValue(); 8202 } 8203 8204 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8205 SelectionDAG &DAG) const { 8206 SDLoc dl(Op); 8207 SDNode *N = Op.getNode(); 8208 8209 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 8210 "Unknown extract_vector_elt type"); 8211 8212 SDValue Value = N->getOperand(0); 8213 8214 // The first part of this is like the store lowering except that we don't 8215 // need to track the chain. 8216 8217 // The values are now known to be -1 (false) or 1 (true). To convert this 8218 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8219 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8220 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8221 8222 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8223 // understand how to form the extending load. 8224 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8225 8226 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8227 8228 // Now convert to an integer and store. 8229 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8230 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8231 Value); 8232 8233 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8234 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8235 MachinePointerInfo PtrInfo = 8236 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8237 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8238 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8239 8240 SDValue StoreChain = DAG.getEntryNode(); 8241 SDValue Ops[] = {StoreChain, 8242 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8243 Value, FIdx}; 8244 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8245 8246 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8247 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8248 8249 // Extract the value requested. 8250 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 8251 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8252 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8253 8254 SDValue IntVal = 8255 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 8256 8257 if (!Subtarget.useCRBits()) 8258 return IntVal; 8259 8260 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 8261 } 8262 8263 /// Lowering for QPX v4i1 loads 8264 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 8265 SelectionDAG &DAG) const { 8266 SDLoc dl(Op); 8267 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 8268 SDValue LoadChain = LN->getChain(); 8269 SDValue BasePtr = LN->getBasePtr(); 8270 8271 if (Op.getValueType() == MVT::v4f64 || 8272 Op.getValueType() == MVT::v4f32) { 8273 EVT MemVT = LN->getMemoryVT(); 8274 unsigned Alignment = LN->getAlignment(); 8275 8276 // If this load is properly aligned, then it is legal. 8277 if (Alignment >= MemVT.getStoreSize()) 8278 return Op; 8279 8280 EVT ScalarVT = Op.getValueType().getScalarType(), 8281 ScalarMemVT = MemVT.getScalarType(); 8282 unsigned Stride = ScalarMemVT.getStoreSize(); 8283 8284 SDValue Vals[4], LoadChains[4]; 8285 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8286 SDValue Load; 8287 if (ScalarVT != ScalarMemVT) 8288 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 8289 BasePtr, 8290 LN->getPointerInfo().getWithOffset(Idx * Stride), 8291 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8292 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8293 else 8294 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 8295 LN->getPointerInfo().getWithOffset(Idx * Stride), 8296 MinAlign(Alignment, Idx * Stride), 8297 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8298 8299 if (Idx == 0 && LN->isIndexed()) { 8300 assert(LN->getAddressingMode() == ISD::PRE_INC && 8301 "Unknown addressing mode on vector load"); 8302 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 8303 LN->getAddressingMode()); 8304 } 8305 8306 Vals[Idx] = Load; 8307 LoadChains[Idx] = Load.getValue(1); 8308 8309 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8310 DAG.getConstant(Stride, dl, 8311 BasePtr.getValueType())); 8312 } 8313 8314 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8315 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 8316 8317 if (LN->isIndexed()) { 8318 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 8319 return DAG.getMergeValues(RetOps, dl); 8320 } 8321 8322 SDValue RetOps[] = { Value, TF }; 8323 return DAG.getMergeValues(RetOps, dl); 8324 } 8325 8326 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 8327 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 8328 8329 // To lower v4i1 from a byte array, we load the byte elements of the 8330 // vector and then reuse the BUILD_VECTOR logic. 8331 8332 SDValue VectElmts[4], VectElmtChains[4]; 8333 for (unsigned i = 0; i < 4; ++i) { 8334 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 8335 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 8336 8337 VectElmts[i] = DAG.getExtLoad( 8338 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 8339 LN->getPointerInfo().getWithOffset(i), MVT::i8, 8340 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8341 VectElmtChains[i] = VectElmts[i].getValue(1); 8342 } 8343 8344 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 8345 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 8346 8347 SDValue RVals[] = { Value, LoadChain }; 8348 return DAG.getMergeValues(RVals, dl); 8349 } 8350 8351 /// Lowering for QPX v4i1 stores 8352 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 8353 SelectionDAG &DAG) const { 8354 SDLoc dl(Op); 8355 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 8356 SDValue StoreChain = SN->getChain(); 8357 SDValue BasePtr = SN->getBasePtr(); 8358 SDValue Value = SN->getValue(); 8359 8360 if (Value.getValueType() == MVT::v4f64 || 8361 Value.getValueType() == MVT::v4f32) { 8362 EVT MemVT = SN->getMemoryVT(); 8363 unsigned Alignment = SN->getAlignment(); 8364 8365 // If this store is properly aligned, then it is legal. 8366 if (Alignment >= MemVT.getStoreSize()) 8367 return Op; 8368 8369 EVT ScalarVT = Value.getValueType().getScalarType(), 8370 ScalarMemVT = MemVT.getScalarType(); 8371 unsigned Stride = ScalarMemVT.getStoreSize(); 8372 8373 SDValue Stores[4]; 8374 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8375 SDValue Ex = DAG.getNode( 8376 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 8377 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 8378 SDValue Store; 8379 if (ScalarVT != ScalarMemVT) 8380 Store = 8381 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 8382 SN->getPointerInfo().getWithOffset(Idx * Stride), 8383 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8384 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 8385 else 8386 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 8387 SN->getPointerInfo().getWithOffset(Idx * Stride), 8388 MinAlign(Alignment, Idx * Stride), 8389 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 8390 8391 if (Idx == 0 && SN->isIndexed()) { 8392 assert(SN->getAddressingMode() == ISD::PRE_INC && 8393 "Unknown addressing mode on vector store"); 8394 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 8395 SN->getAddressingMode()); 8396 } 8397 8398 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8399 DAG.getConstant(Stride, dl, 8400 BasePtr.getValueType())); 8401 Stores[Idx] = Store; 8402 } 8403 8404 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8405 8406 if (SN->isIndexed()) { 8407 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 8408 return DAG.getMergeValues(RetOps, dl); 8409 } 8410 8411 return TF; 8412 } 8413 8414 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 8415 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 8416 8417 // The values are now known to be -1 (false) or 1 (true). To convert this 8418 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8419 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8420 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8421 8422 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8423 // understand how to form the extending load. 8424 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8425 8426 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8427 8428 // Now convert to an integer and store. 8429 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8430 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8431 Value); 8432 8433 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8434 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8435 MachinePointerInfo PtrInfo = 8436 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8437 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8438 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8439 8440 SDValue Ops[] = {StoreChain, 8441 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8442 Value, FIdx}; 8443 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8444 8445 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8446 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8447 8448 // Move data into the byte array. 8449 SDValue Loads[4], LoadChains[4]; 8450 for (unsigned i = 0; i < 4; ++i) { 8451 unsigned Offset = 4*i; 8452 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8453 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8454 8455 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 8456 PtrInfo.getWithOffset(Offset)); 8457 LoadChains[i] = Loads[i].getValue(1); 8458 } 8459 8460 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8461 8462 SDValue Stores[4]; 8463 for (unsigned i = 0; i < 4; ++i) { 8464 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 8465 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 8466 8467 Stores[i] = DAG.getTruncStore( 8468 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 8469 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 8470 SN->getAAInfo()); 8471 } 8472 8473 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8474 8475 return StoreChain; 8476 } 8477 8478 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 8479 SDLoc dl(Op); 8480 if (Op.getValueType() == MVT::v4i32) { 8481 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8482 8483 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 8484 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 8485 8486 SDValue RHSSwap = // = vrlw RHS, 16 8487 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 8488 8489 // Shrinkify inputs to v8i16. 8490 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 8491 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 8492 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 8493 8494 // Low parts multiplied together, generating 32-bit results (we ignore the 8495 // top parts). 8496 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 8497 LHS, RHS, DAG, dl, MVT::v4i32); 8498 8499 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 8500 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 8501 // Shift the high parts up 16 bits. 8502 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 8503 Neg16, DAG, dl); 8504 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 8505 } else if (Op.getValueType() == MVT::v8i16) { 8506 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8507 8508 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 8509 8510 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 8511 LHS, RHS, Zero, DAG, dl); 8512 } else if (Op.getValueType() == MVT::v16i8) { 8513 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8514 bool isLittleEndian = Subtarget.isLittleEndian(); 8515 8516 // Multiply the even 8-bit parts, producing 16-bit sums. 8517 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 8518 LHS, RHS, DAG, dl, MVT::v8i16); 8519 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 8520 8521 // Multiply the odd 8-bit parts, producing 16-bit sums. 8522 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 8523 LHS, RHS, DAG, dl, MVT::v8i16); 8524 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 8525 8526 // Merge the results together. Because vmuleub and vmuloub are 8527 // instructions with a big-endian bias, we must reverse the 8528 // element numbering and reverse the meaning of "odd" and "even" 8529 // when generating little endian code. 8530 int Ops[16]; 8531 for (unsigned i = 0; i != 8; ++i) { 8532 if (isLittleEndian) { 8533 Ops[i*2 ] = 2*i; 8534 Ops[i*2+1] = 2*i+16; 8535 } else { 8536 Ops[i*2 ] = 2*i+1; 8537 Ops[i*2+1] = 2*i+1+16; 8538 } 8539 } 8540 if (isLittleEndian) 8541 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 8542 else 8543 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 8544 } else { 8545 llvm_unreachable("Unknown mul to lower!"); 8546 } 8547 } 8548 8549 /// LowerOperation - Provide custom lowering hooks for some operations. 8550 /// 8551 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8552 switch (Op.getOpcode()) { 8553 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 8554 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8555 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8556 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8557 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8558 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 8559 case ISD::SETCC: return LowerSETCC(Op, DAG); 8560 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 8561 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 8562 case ISD::VASTART: 8563 return LowerVASTART(Op, DAG); 8564 8565 case ISD::VAARG: 8566 return LowerVAARG(Op, DAG); 8567 8568 case ISD::VACOPY: 8569 return LowerVACOPY(Op, DAG); 8570 8571 case ISD::STACKRESTORE: 8572 return LowerSTACKRESTORE(Op, DAG); 8573 8574 case ISD::DYNAMIC_STACKALLOC: 8575 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8576 8577 case ISD::GET_DYNAMIC_AREA_OFFSET: 8578 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 8579 8580 case ISD::EH_DWARF_CFA: 8581 return LowerEH_DWARF_CFA(Op, DAG); 8582 8583 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 8584 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 8585 8586 case ISD::LOAD: return LowerLOAD(Op, DAG); 8587 case ISD::STORE: return LowerSTORE(Op, DAG); 8588 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 8589 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8590 case ISD::FP_TO_UINT: 8591 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 8592 SDLoc(Op)); 8593 case ISD::UINT_TO_FP: 8594 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8595 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8596 8597 // Lower 64-bit shifts. 8598 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 8599 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 8600 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 8601 8602 // Vector-related lowering. 8603 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 8604 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8605 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 8606 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 8607 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 8608 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8609 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8610 case ISD::MUL: return LowerMUL(Op, DAG); 8611 8612 // For counter-based loop handling. 8613 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 8614 8615 // Frame & Return address. 8616 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8617 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8618 } 8619 } 8620 8621 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 8622 SmallVectorImpl<SDValue>&Results, 8623 SelectionDAG &DAG) const { 8624 SDLoc dl(N); 8625 switch (N->getOpcode()) { 8626 default: 8627 llvm_unreachable("Do not know how to custom type legalize this operation!"); 8628 case ISD::READCYCLECOUNTER: { 8629 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 8630 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 8631 8632 Results.push_back(RTB); 8633 Results.push_back(RTB.getValue(1)); 8634 Results.push_back(RTB.getValue(2)); 8635 break; 8636 } 8637 case ISD::INTRINSIC_W_CHAIN: { 8638 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 8639 Intrinsic::ppc_is_decremented_ctr_nonzero) 8640 break; 8641 8642 assert(N->getValueType(0) == MVT::i1 && 8643 "Unexpected result type for CTR decrement intrinsic"); 8644 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 8645 N->getValueType(0)); 8646 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 8647 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 8648 N->getOperand(1)); 8649 8650 Results.push_back(NewInt); 8651 Results.push_back(NewInt.getValue(1)); 8652 break; 8653 } 8654 case ISD::VAARG: { 8655 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 8656 return; 8657 8658 EVT VT = N->getValueType(0); 8659 8660 if (VT == MVT::i64) { 8661 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 8662 8663 Results.push_back(NewNode); 8664 Results.push_back(NewNode.getValue(1)); 8665 } 8666 return; 8667 } 8668 case ISD::FP_ROUND_INREG: { 8669 assert(N->getValueType(0) == MVT::ppcf128); 8670 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 8671 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8672 MVT::f64, N->getOperand(0), 8673 DAG.getIntPtrConstant(0, dl)); 8674 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8675 MVT::f64, N->getOperand(0), 8676 DAG.getIntPtrConstant(1, dl)); 8677 8678 // Add the two halves of the long double in round-to-zero mode. 8679 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8680 8681 // We know the low half is about to be thrown away, so just use something 8682 // convenient. 8683 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 8684 FPreg, FPreg)); 8685 return; 8686 } 8687 case ISD::FP_TO_SINT: 8688 case ISD::FP_TO_UINT: 8689 // LowerFP_TO_INT() can only handle f32 and f64. 8690 if (N->getOperand(0).getValueType() == MVT::ppcf128) 8691 return; 8692 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 8693 return; 8694 } 8695 } 8696 8697 //===----------------------------------------------------------------------===// 8698 // Other Lowering Code 8699 //===----------------------------------------------------------------------===// 8700 8701 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 8702 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 8703 Function *Func = Intrinsic::getDeclaration(M, Id); 8704 return Builder.CreateCall(Func, {}); 8705 } 8706 8707 // The mappings for emitLeading/TrailingFence is taken from 8708 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 8709 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 8710 AtomicOrdering Ord, bool IsStore, 8711 bool IsLoad) const { 8712 if (Ord == AtomicOrdering::SequentiallyConsistent) 8713 return callIntrinsic(Builder, Intrinsic::ppc_sync); 8714 if (isReleaseOrStronger(Ord)) 8715 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 8716 return nullptr; 8717 } 8718 8719 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 8720 AtomicOrdering Ord, bool IsStore, 8721 bool IsLoad) const { 8722 if (IsLoad && isAcquireOrStronger(Ord)) 8723 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 8724 // FIXME: this is too conservative, a dependent branch + isync is enough. 8725 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 8726 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 8727 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 8728 return nullptr; 8729 } 8730 8731 MachineBasicBlock * 8732 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 8733 unsigned AtomicSize, 8734 unsigned BinOpcode, 8735 unsigned CmpOpcode, 8736 unsigned CmpPred) const { 8737 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 8738 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 8739 8740 auto LoadMnemonic = PPC::LDARX; 8741 auto StoreMnemonic = PPC::STDCX; 8742 switch (AtomicSize) { 8743 default: 8744 llvm_unreachable("Unexpected size of atomic entity"); 8745 case 1: 8746 LoadMnemonic = PPC::LBARX; 8747 StoreMnemonic = PPC::STBCX; 8748 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 8749 break; 8750 case 2: 8751 LoadMnemonic = PPC::LHARX; 8752 StoreMnemonic = PPC::STHCX; 8753 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 8754 break; 8755 case 4: 8756 LoadMnemonic = PPC::LWARX; 8757 StoreMnemonic = PPC::STWCX; 8758 break; 8759 case 8: 8760 LoadMnemonic = PPC::LDARX; 8761 StoreMnemonic = PPC::STDCX; 8762 break; 8763 } 8764 8765 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8766 MachineFunction *F = BB->getParent(); 8767 MachineFunction::iterator It = ++BB->getIterator(); 8768 8769 unsigned dest = MI.getOperand(0).getReg(); 8770 unsigned ptrA = MI.getOperand(1).getReg(); 8771 unsigned ptrB = MI.getOperand(2).getReg(); 8772 unsigned incr = MI.getOperand(3).getReg(); 8773 DebugLoc dl = MI.getDebugLoc(); 8774 8775 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 8776 MachineBasicBlock *loop2MBB = 8777 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 8778 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 8779 F->insert(It, loopMBB); 8780 if (CmpOpcode) 8781 F->insert(It, loop2MBB); 8782 F->insert(It, exitMBB); 8783 exitMBB->splice(exitMBB->begin(), BB, 8784 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8785 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8786 8787 MachineRegisterInfo &RegInfo = F->getRegInfo(); 8788 unsigned TmpReg = (!BinOpcode) ? incr : 8789 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 8790 : &PPC::GPRCRegClass); 8791 8792 // thisMBB: 8793 // ... 8794 // fallthrough --> loopMBB 8795 BB->addSuccessor(loopMBB); 8796 8797 // loopMBB: 8798 // l[wd]arx dest, ptr 8799 // add r0, dest, incr 8800 // st[wd]cx. r0, ptr 8801 // bne- loopMBB 8802 // fallthrough --> exitMBB 8803 8804 // For max/min... 8805 // loopMBB: 8806 // l[wd]arx dest, ptr 8807 // cmpl?[wd] incr, dest 8808 // bgt exitMBB 8809 // loop2MBB: 8810 // st[wd]cx. dest, ptr 8811 // bne- loopMBB 8812 // fallthrough --> exitMBB 8813 8814 BB = loopMBB; 8815 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 8816 .addReg(ptrA).addReg(ptrB); 8817 if (BinOpcode) 8818 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 8819 if (CmpOpcode) { 8820 // Signed comparisons of byte or halfword values must be sign-extended. 8821 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 8822 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 8823 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 8824 ExtReg).addReg(dest); 8825 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 8826 .addReg(incr).addReg(ExtReg); 8827 } else 8828 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 8829 .addReg(incr).addReg(dest); 8830 8831 BuildMI(BB, dl, TII->get(PPC::BCC)) 8832 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 8833 BB->addSuccessor(loop2MBB); 8834 BB->addSuccessor(exitMBB); 8835 BB = loop2MBB; 8836 } 8837 BuildMI(BB, dl, TII->get(StoreMnemonic)) 8838 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 8839 BuildMI(BB, dl, TII->get(PPC::BCC)) 8840 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 8841 BB->addSuccessor(loopMBB); 8842 BB->addSuccessor(exitMBB); 8843 8844 // exitMBB: 8845 // ... 8846 BB = exitMBB; 8847 return BB; 8848 } 8849 8850 MachineBasicBlock * 8851 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 8852 MachineBasicBlock *BB, 8853 bool is8bit, // operation 8854 unsigned BinOpcode, 8855 unsigned CmpOpcode, 8856 unsigned CmpPred) const { 8857 // If we support part-word atomic mnemonics, just use them 8858 if (Subtarget.hasPartwordAtomics()) 8859 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 8860 CmpOpcode, CmpPred); 8861 8862 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 8863 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 8864 // In 64 bit mode we have to use 64 bits for addresses, even though the 8865 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 8866 // registers without caring whether they're 32 or 64, but here we're 8867 // doing actual arithmetic on the addresses. 8868 bool is64bit = Subtarget.isPPC64(); 8869 bool isLittleEndian = Subtarget.isLittleEndian(); 8870 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 8871 8872 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8873 MachineFunction *F = BB->getParent(); 8874 MachineFunction::iterator It = ++BB->getIterator(); 8875 8876 unsigned dest = MI.getOperand(0).getReg(); 8877 unsigned ptrA = MI.getOperand(1).getReg(); 8878 unsigned ptrB = MI.getOperand(2).getReg(); 8879 unsigned incr = MI.getOperand(3).getReg(); 8880 DebugLoc dl = MI.getDebugLoc(); 8881 8882 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 8883 MachineBasicBlock *loop2MBB = 8884 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 8885 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 8886 F->insert(It, loopMBB); 8887 if (CmpOpcode) 8888 F->insert(It, loop2MBB); 8889 F->insert(It, exitMBB); 8890 exitMBB->splice(exitMBB->begin(), BB, 8891 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8892 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8893 8894 MachineRegisterInfo &RegInfo = F->getRegInfo(); 8895 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 8896 : &PPC::GPRCRegClass; 8897 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 8898 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 8899 unsigned ShiftReg = 8900 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 8901 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 8902 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 8903 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 8904 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 8905 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 8906 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 8907 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 8908 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 8909 unsigned Ptr1Reg; 8910 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 8911 8912 // thisMBB: 8913 // ... 8914 // fallthrough --> loopMBB 8915 BB->addSuccessor(loopMBB); 8916 8917 // The 4-byte load must be aligned, while a char or short may be 8918 // anywhere in the word. Hence all this nasty bookkeeping code. 8919 // add ptr1, ptrA, ptrB [copy if ptrA==0] 8920 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 8921 // xori shift, shift1, 24 [16] 8922 // rlwinm ptr, ptr1, 0, 0, 29 8923 // slw incr2, incr, shift 8924 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 8925 // slw mask, mask2, shift 8926 // loopMBB: 8927 // lwarx tmpDest, ptr 8928 // add tmp, tmpDest, incr2 8929 // andc tmp2, tmpDest, mask 8930 // and tmp3, tmp, mask 8931 // or tmp4, tmp3, tmp2 8932 // stwcx. tmp4, ptr 8933 // bne- loopMBB 8934 // fallthrough --> exitMBB 8935 // srw dest, tmpDest, shift 8936 if (ptrA != ZeroReg) { 8937 Ptr1Reg = RegInfo.createVirtualRegister(RC); 8938 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 8939 .addReg(ptrA).addReg(ptrB); 8940 } else { 8941 Ptr1Reg = ptrB; 8942 } 8943 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 8944 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 8945 if (!isLittleEndian) 8946 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 8947 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 8948 if (is64bit) 8949 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 8950 .addReg(Ptr1Reg).addImm(0).addImm(61); 8951 else 8952 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 8953 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 8954 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 8955 .addReg(incr).addReg(ShiftReg); 8956 if (is8bit) 8957 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 8958 else { 8959 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 8960 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 8961 } 8962 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 8963 .addReg(Mask2Reg).addReg(ShiftReg); 8964 8965 BB = loopMBB; 8966 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 8967 .addReg(ZeroReg).addReg(PtrReg); 8968 if (BinOpcode) 8969 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 8970 .addReg(Incr2Reg).addReg(TmpDestReg); 8971 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 8972 .addReg(TmpDestReg).addReg(MaskReg); 8973 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 8974 .addReg(TmpReg).addReg(MaskReg); 8975 if (CmpOpcode) { 8976 // For unsigned comparisons, we can directly compare the shifted values. 8977 // For signed comparisons we shift and sign extend. 8978 unsigned SReg = RegInfo.createVirtualRegister(RC); 8979 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 8980 .addReg(TmpDestReg).addReg(MaskReg); 8981 unsigned ValueReg = SReg; 8982 unsigned CmpReg = Incr2Reg; 8983 if (CmpOpcode == PPC::CMPW) { 8984 ValueReg = RegInfo.createVirtualRegister(RC); 8985 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 8986 .addReg(SReg).addReg(ShiftReg); 8987 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 8988 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 8989 .addReg(ValueReg); 8990 ValueReg = ValueSReg; 8991 CmpReg = incr; 8992 } 8993 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 8994 .addReg(CmpReg).addReg(ValueReg); 8995 BuildMI(BB, dl, TII->get(PPC::BCC)) 8996 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 8997 BB->addSuccessor(loop2MBB); 8998 BB->addSuccessor(exitMBB); 8999 BB = loop2MBB; 9000 } 9001 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 9002 .addReg(Tmp3Reg).addReg(Tmp2Reg); 9003 BuildMI(BB, dl, TII->get(PPC::STWCX)) 9004 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 9005 BuildMI(BB, dl, TII->get(PPC::BCC)) 9006 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9007 BB->addSuccessor(loopMBB); 9008 BB->addSuccessor(exitMBB); 9009 9010 // exitMBB: 9011 // ... 9012 BB = exitMBB; 9013 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 9014 .addReg(ShiftReg); 9015 return BB; 9016 } 9017 9018 llvm::MachineBasicBlock * 9019 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 9020 MachineBasicBlock *MBB) const { 9021 DebugLoc DL = MI.getDebugLoc(); 9022 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9023 9024 MachineFunction *MF = MBB->getParent(); 9025 MachineRegisterInfo &MRI = MF->getRegInfo(); 9026 9027 const BasicBlock *BB = MBB->getBasicBlock(); 9028 MachineFunction::iterator I = ++MBB->getIterator(); 9029 9030 // Memory Reference 9031 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9032 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9033 9034 unsigned DstReg = MI.getOperand(0).getReg(); 9035 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 9036 assert(RC->hasType(MVT::i32) && "Invalid destination!"); 9037 unsigned mainDstReg = MRI.createVirtualRegister(RC); 9038 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 9039 9040 MVT PVT = getPointerTy(MF->getDataLayout()); 9041 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9042 "Invalid Pointer Size!"); 9043 // For v = setjmp(buf), we generate 9044 // 9045 // thisMBB: 9046 // SjLjSetup mainMBB 9047 // bl mainMBB 9048 // v_restore = 1 9049 // b sinkMBB 9050 // 9051 // mainMBB: 9052 // buf[LabelOffset] = LR 9053 // v_main = 0 9054 // 9055 // sinkMBB: 9056 // v = phi(main, restore) 9057 // 9058 9059 MachineBasicBlock *thisMBB = MBB; 9060 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 9061 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 9062 MF->insert(I, mainMBB); 9063 MF->insert(I, sinkMBB); 9064 9065 MachineInstrBuilder MIB; 9066 9067 // Transfer the remainder of BB and its successor edges to sinkMBB. 9068 sinkMBB->splice(sinkMBB->begin(), MBB, 9069 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9070 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 9071 9072 // Note that the structure of the jmp_buf used here is not compatible 9073 // with that used by libc, and is not designed to be. Specifically, it 9074 // stores only those 'reserved' registers that LLVM does not otherwise 9075 // understand how to spill. Also, by convention, by the time this 9076 // intrinsic is called, Clang has already stored the frame address in the 9077 // first slot of the buffer and stack address in the third. Following the 9078 // X86 target code, we'll store the jump address in the second slot. We also 9079 // need to save the TOC pointer (R2) to handle jumps between shared 9080 // libraries, and that will be stored in the fourth slot. The thread 9081 // identifier (R13) is not affected. 9082 9083 // thisMBB: 9084 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9085 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9086 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9087 9088 // Prepare IP either in reg. 9089 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 9090 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 9091 unsigned BufReg = MI.getOperand(1).getReg(); 9092 9093 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 9094 setUsesTOCBasePtr(*MBB->getParent()); 9095 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 9096 .addReg(PPC::X2) 9097 .addImm(TOCOffset) 9098 .addReg(BufReg); 9099 MIB.setMemRefs(MMOBegin, MMOEnd); 9100 } 9101 9102 // Naked functions never have a base pointer, and so we use r1. For all 9103 // other functions, this decision must be delayed until during PEI. 9104 unsigned BaseReg; 9105 if (MF->getFunction()->hasFnAttribute(Attribute::Naked)) 9106 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 9107 else 9108 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 9109 9110 MIB = BuildMI(*thisMBB, MI, DL, 9111 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 9112 .addReg(BaseReg) 9113 .addImm(BPOffset) 9114 .addReg(BufReg); 9115 MIB.setMemRefs(MMOBegin, MMOEnd); 9116 9117 // Setup 9118 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 9119 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9120 MIB.addRegMask(TRI->getNoPreservedMask()); 9121 9122 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 9123 9124 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 9125 .addMBB(mainMBB); 9126 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 9127 9128 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 9129 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 9130 9131 // mainMBB: 9132 // mainDstReg = 0 9133 MIB = 9134 BuildMI(mainMBB, DL, 9135 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 9136 9137 // Store IP 9138 if (Subtarget.isPPC64()) { 9139 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 9140 .addReg(LabelReg) 9141 .addImm(LabelOffset) 9142 .addReg(BufReg); 9143 } else { 9144 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 9145 .addReg(LabelReg) 9146 .addImm(LabelOffset) 9147 .addReg(BufReg); 9148 } 9149 9150 MIB.setMemRefs(MMOBegin, MMOEnd); 9151 9152 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 9153 mainMBB->addSuccessor(sinkMBB); 9154 9155 // sinkMBB: 9156 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 9157 TII->get(PPC::PHI), DstReg) 9158 .addReg(mainDstReg).addMBB(mainMBB) 9159 .addReg(restoreDstReg).addMBB(thisMBB); 9160 9161 MI.eraseFromParent(); 9162 return sinkMBB; 9163 } 9164 9165 MachineBasicBlock * 9166 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 9167 MachineBasicBlock *MBB) const { 9168 DebugLoc DL = MI.getDebugLoc(); 9169 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9170 9171 MachineFunction *MF = MBB->getParent(); 9172 MachineRegisterInfo &MRI = MF->getRegInfo(); 9173 9174 // Memory Reference 9175 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9176 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9177 9178 MVT PVT = getPointerTy(MF->getDataLayout()); 9179 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9180 "Invalid Pointer Size!"); 9181 9182 const TargetRegisterClass *RC = 9183 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9184 unsigned Tmp = MRI.createVirtualRegister(RC); 9185 // Since FP is only updated here but NOT referenced, it's treated as GPR. 9186 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 9187 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 9188 unsigned BP = 9189 (PVT == MVT::i64) 9190 ? PPC::X30 9191 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 9192 : PPC::R30); 9193 9194 MachineInstrBuilder MIB; 9195 9196 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9197 const int64_t SPOffset = 2 * PVT.getStoreSize(); 9198 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9199 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9200 9201 unsigned BufReg = MI.getOperand(0).getReg(); 9202 9203 // Reload FP (the jumped-to function may not have had a 9204 // frame pointer, and if so, then its r31 will be restored 9205 // as necessary). 9206 if (PVT == MVT::i64) { 9207 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 9208 .addImm(0) 9209 .addReg(BufReg); 9210 } else { 9211 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 9212 .addImm(0) 9213 .addReg(BufReg); 9214 } 9215 MIB.setMemRefs(MMOBegin, MMOEnd); 9216 9217 // Reload IP 9218 if (PVT == MVT::i64) { 9219 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 9220 .addImm(LabelOffset) 9221 .addReg(BufReg); 9222 } else { 9223 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 9224 .addImm(LabelOffset) 9225 .addReg(BufReg); 9226 } 9227 MIB.setMemRefs(MMOBegin, MMOEnd); 9228 9229 // Reload SP 9230 if (PVT == MVT::i64) { 9231 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 9232 .addImm(SPOffset) 9233 .addReg(BufReg); 9234 } else { 9235 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 9236 .addImm(SPOffset) 9237 .addReg(BufReg); 9238 } 9239 MIB.setMemRefs(MMOBegin, MMOEnd); 9240 9241 // Reload BP 9242 if (PVT == MVT::i64) { 9243 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 9244 .addImm(BPOffset) 9245 .addReg(BufReg); 9246 } else { 9247 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 9248 .addImm(BPOffset) 9249 .addReg(BufReg); 9250 } 9251 MIB.setMemRefs(MMOBegin, MMOEnd); 9252 9253 // Reload TOC 9254 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 9255 setUsesTOCBasePtr(*MBB->getParent()); 9256 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 9257 .addImm(TOCOffset) 9258 .addReg(BufReg); 9259 9260 MIB.setMemRefs(MMOBegin, MMOEnd); 9261 } 9262 9263 // Jump 9264 BuildMI(*MBB, MI, DL, 9265 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 9266 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 9267 9268 MI.eraseFromParent(); 9269 return MBB; 9270 } 9271 9272 MachineBasicBlock * 9273 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9274 MachineBasicBlock *BB) const { 9275 if (MI.getOpcode() == TargetOpcode::STACKMAP || 9276 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9277 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 9278 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9279 // Call lowering should have added an r2 operand to indicate a dependence 9280 // on the TOC base pointer value. It can't however, because there is no 9281 // way to mark the dependence as implicit there, and so the stackmap code 9282 // will confuse it with a regular operand. Instead, add the dependence 9283 // here. 9284 setUsesTOCBasePtr(*BB->getParent()); 9285 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 9286 } 9287 9288 return emitPatchPoint(MI, BB); 9289 } 9290 9291 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 9292 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 9293 return emitEHSjLjSetJmp(MI, BB); 9294 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 9295 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 9296 return emitEHSjLjLongJmp(MI, BB); 9297 } 9298 9299 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9300 9301 // To "insert" these instructions we actually have to insert their 9302 // control-flow patterns. 9303 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9304 MachineFunction::iterator It = ++BB->getIterator(); 9305 9306 MachineFunction *F = BB->getParent(); 9307 9308 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9309 MI.getOpcode() == PPC::SELECT_CC_I8 || 9310 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 9311 SmallVector<MachineOperand, 2> Cond; 9312 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9313 MI.getOpcode() == PPC::SELECT_CC_I8) 9314 Cond.push_back(MI.getOperand(4)); 9315 else 9316 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 9317 Cond.push_back(MI.getOperand(1)); 9318 9319 DebugLoc dl = MI.getDebugLoc(); 9320 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 9321 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 9322 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9323 MI.getOpcode() == PPC::SELECT_CC_I8 || 9324 MI.getOpcode() == PPC::SELECT_CC_F4 || 9325 MI.getOpcode() == PPC::SELECT_CC_F8 || 9326 MI.getOpcode() == PPC::SELECT_CC_QFRC || 9327 MI.getOpcode() == PPC::SELECT_CC_QSRC || 9328 MI.getOpcode() == PPC::SELECT_CC_QBRC || 9329 MI.getOpcode() == PPC::SELECT_CC_VRRC || 9330 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 9331 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 9332 MI.getOpcode() == PPC::SELECT_CC_VSRC || 9333 MI.getOpcode() == PPC::SELECT_I4 || 9334 MI.getOpcode() == PPC::SELECT_I8 || 9335 MI.getOpcode() == PPC::SELECT_F4 || 9336 MI.getOpcode() == PPC::SELECT_F8 || 9337 MI.getOpcode() == PPC::SELECT_QFRC || 9338 MI.getOpcode() == PPC::SELECT_QSRC || 9339 MI.getOpcode() == PPC::SELECT_QBRC || 9340 MI.getOpcode() == PPC::SELECT_VRRC || 9341 MI.getOpcode() == PPC::SELECT_VSFRC || 9342 MI.getOpcode() == PPC::SELECT_VSSRC || 9343 MI.getOpcode() == PPC::SELECT_VSRC) { 9344 // The incoming instruction knows the destination vreg to set, the 9345 // condition code register to branch on, the true/false values to 9346 // select between, and a branch opcode to use. 9347 9348 // thisMBB: 9349 // ... 9350 // TrueVal = ... 9351 // cmpTY ccX, r1, r2 9352 // bCC copy1MBB 9353 // fallthrough --> copy0MBB 9354 MachineBasicBlock *thisMBB = BB; 9355 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9356 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9357 DebugLoc dl = MI.getDebugLoc(); 9358 F->insert(It, copy0MBB); 9359 F->insert(It, sinkMBB); 9360 9361 // Transfer the remainder of BB and its successor edges to sinkMBB. 9362 sinkMBB->splice(sinkMBB->begin(), BB, 9363 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9364 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9365 9366 // Next, add the true and fallthrough blocks as its successors. 9367 BB->addSuccessor(copy0MBB); 9368 BB->addSuccessor(sinkMBB); 9369 9370 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 9371 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 9372 MI.getOpcode() == PPC::SELECT_QFRC || 9373 MI.getOpcode() == PPC::SELECT_QSRC || 9374 MI.getOpcode() == PPC::SELECT_QBRC || 9375 MI.getOpcode() == PPC::SELECT_VRRC || 9376 MI.getOpcode() == PPC::SELECT_VSFRC || 9377 MI.getOpcode() == PPC::SELECT_VSSRC || 9378 MI.getOpcode() == PPC::SELECT_VSRC) { 9379 BuildMI(BB, dl, TII->get(PPC::BC)) 9380 .addReg(MI.getOperand(1).getReg()) 9381 .addMBB(sinkMBB); 9382 } else { 9383 unsigned SelectPred = MI.getOperand(4).getImm(); 9384 BuildMI(BB, dl, TII->get(PPC::BCC)) 9385 .addImm(SelectPred) 9386 .addReg(MI.getOperand(1).getReg()) 9387 .addMBB(sinkMBB); 9388 } 9389 9390 // copy0MBB: 9391 // %FalseValue = ... 9392 // # fallthrough to sinkMBB 9393 BB = copy0MBB; 9394 9395 // Update machine-CFG edges 9396 BB->addSuccessor(sinkMBB); 9397 9398 // sinkMBB: 9399 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9400 // ... 9401 BB = sinkMBB; 9402 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 9403 .addReg(MI.getOperand(3).getReg()) 9404 .addMBB(copy0MBB) 9405 .addReg(MI.getOperand(2).getReg()) 9406 .addMBB(thisMBB); 9407 } else if (MI.getOpcode() == PPC::ReadTB) { 9408 // To read the 64-bit time-base register on a 32-bit target, we read the 9409 // two halves. Should the counter have wrapped while it was being read, we 9410 // need to try again. 9411 // ... 9412 // readLoop: 9413 // mfspr Rx,TBU # load from TBU 9414 // mfspr Ry,TB # load from TB 9415 // mfspr Rz,TBU # load from TBU 9416 // cmpw crX,Rx,Rz # check if 'old'='new' 9417 // bne readLoop # branch if they're not equal 9418 // ... 9419 9420 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 9421 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9422 DebugLoc dl = MI.getDebugLoc(); 9423 F->insert(It, readMBB); 9424 F->insert(It, sinkMBB); 9425 9426 // Transfer the remainder of BB and its successor edges to sinkMBB. 9427 sinkMBB->splice(sinkMBB->begin(), BB, 9428 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9429 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9430 9431 BB->addSuccessor(readMBB); 9432 BB = readMBB; 9433 9434 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9435 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9436 unsigned LoReg = MI.getOperand(0).getReg(); 9437 unsigned HiReg = MI.getOperand(1).getReg(); 9438 9439 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 9440 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 9441 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 9442 9443 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 9444 9445 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 9446 .addReg(HiReg).addReg(ReadAgainReg); 9447 BuildMI(BB, dl, TII->get(PPC::BCC)) 9448 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 9449 9450 BB->addSuccessor(readMBB); 9451 BB->addSuccessor(sinkMBB); 9452 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 9453 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 9454 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 9455 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 9456 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 9457 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 9458 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 9459 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 9460 9461 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 9462 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 9463 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 9464 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 9465 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 9466 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 9467 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 9468 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 9469 9470 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 9471 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 9472 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 9473 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 9474 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 9475 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 9476 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 9477 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 9478 9479 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 9480 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 9481 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 9482 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 9483 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 9484 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 9485 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 9486 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 9487 9488 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 9489 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 9490 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 9491 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 9492 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 9493 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 9494 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 9495 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 9496 9497 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 9498 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 9499 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 9500 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 9501 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 9502 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 9503 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 9504 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 9505 9506 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 9507 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 9508 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 9509 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 9510 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 9511 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 9512 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 9513 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 9514 9515 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 9516 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 9517 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 9518 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 9519 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 9520 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 9521 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 9522 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 9523 9524 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 9525 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 9526 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 9527 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 9528 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 9529 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 9530 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 9531 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 9532 9533 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 9534 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 9535 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 9536 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 9537 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 9538 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 9539 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 9540 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 9541 9542 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 9543 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 9544 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 9545 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 9546 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 9547 BB = EmitAtomicBinary(MI, BB, 4, 0); 9548 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 9549 BB = EmitAtomicBinary(MI, BB, 8, 0); 9550 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 9551 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 9552 (Subtarget.hasPartwordAtomics() && 9553 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 9554 (Subtarget.hasPartwordAtomics() && 9555 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 9556 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 9557 9558 auto LoadMnemonic = PPC::LDARX; 9559 auto StoreMnemonic = PPC::STDCX; 9560 switch (MI.getOpcode()) { 9561 default: 9562 llvm_unreachable("Compare and swap of unknown size"); 9563 case PPC::ATOMIC_CMP_SWAP_I8: 9564 LoadMnemonic = PPC::LBARX; 9565 StoreMnemonic = PPC::STBCX; 9566 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 9567 break; 9568 case PPC::ATOMIC_CMP_SWAP_I16: 9569 LoadMnemonic = PPC::LHARX; 9570 StoreMnemonic = PPC::STHCX; 9571 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 9572 break; 9573 case PPC::ATOMIC_CMP_SWAP_I32: 9574 LoadMnemonic = PPC::LWARX; 9575 StoreMnemonic = PPC::STWCX; 9576 break; 9577 case PPC::ATOMIC_CMP_SWAP_I64: 9578 LoadMnemonic = PPC::LDARX; 9579 StoreMnemonic = PPC::STDCX; 9580 break; 9581 } 9582 unsigned dest = MI.getOperand(0).getReg(); 9583 unsigned ptrA = MI.getOperand(1).getReg(); 9584 unsigned ptrB = MI.getOperand(2).getReg(); 9585 unsigned oldval = MI.getOperand(3).getReg(); 9586 unsigned newval = MI.getOperand(4).getReg(); 9587 DebugLoc dl = MI.getDebugLoc(); 9588 9589 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 9590 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 9591 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 9592 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9593 F->insert(It, loop1MBB); 9594 F->insert(It, loop2MBB); 9595 F->insert(It, midMBB); 9596 F->insert(It, exitMBB); 9597 exitMBB->splice(exitMBB->begin(), BB, 9598 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9599 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9600 9601 // thisMBB: 9602 // ... 9603 // fallthrough --> loopMBB 9604 BB->addSuccessor(loop1MBB); 9605 9606 // loop1MBB: 9607 // l[bhwd]arx dest, ptr 9608 // cmp[wd] dest, oldval 9609 // bne- midMBB 9610 // loop2MBB: 9611 // st[bhwd]cx. newval, ptr 9612 // bne- loopMBB 9613 // b exitBB 9614 // midMBB: 9615 // st[bhwd]cx. dest, ptr 9616 // exitBB: 9617 BB = loop1MBB; 9618 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9619 .addReg(ptrA).addReg(ptrB); 9620 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 9621 .addReg(oldval).addReg(dest); 9622 BuildMI(BB, dl, TII->get(PPC::BCC)) 9623 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 9624 BB->addSuccessor(loop2MBB); 9625 BB->addSuccessor(midMBB); 9626 9627 BB = loop2MBB; 9628 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9629 .addReg(newval).addReg(ptrA).addReg(ptrB); 9630 BuildMI(BB, dl, TII->get(PPC::BCC)) 9631 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 9632 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 9633 BB->addSuccessor(loop1MBB); 9634 BB->addSuccessor(exitMBB); 9635 9636 BB = midMBB; 9637 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9638 .addReg(dest).addReg(ptrA).addReg(ptrB); 9639 BB->addSuccessor(exitMBB); 9640 9641 // exitMBB: 9642 // ... 9643 BB = exitMBB; 9644 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 9645 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 9646 // We must use 64-bit registers for addresses when targeting 64-bit, 9647 // since we're actually doing arithmetic on them. Other registers 9648 // can be 32-bit. 9649 bool is64bit = Subtarget.isPPC64(); 9650 bool isLittleEndian = Subtarget.isLittleEndian(); 9651 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 9652 9653 unsigned dest = MI.getOperand(0).getReg(); 9654 unsigned ptrA = MI.getOperand(1).getReg(); 9655 unsigned ptrB = MI.getOperand(2).getReg(); 9656 unsigned oldval = MI.getOperand(3).getReg(); 9657 unsigned newval = MI.getOperand(4).getReg(); 9658 DebugLoc dl = MI.getDebugLoc(); 9659 9660 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 9661 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 9662 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 9663 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9664 F->insert(It, loop1MBB); 9665 F->insert(It, loop2MBB); 9666 F->insert(It, midMBB); 9667 F->insert(It, exitMBB); 9668 exitMBB->splice(exitMBB->begin(), BB, 9669 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9670 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9671 9672 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9673 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9674 : &PPC::GPRCRegClass; 9675 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9676 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9677 unsigned ShiftReg = 9678 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9679 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 9680 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 9681 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 9682 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 9683 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9684 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9685 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9686 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9687 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9688 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9689 unsigned Ptr1Reg; 9690 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 9691 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9692 // thisMBB: 9693 // ... 9694 // fallthrough --> loopMBB 9695 BB->addSuccessor(loop1MBB); 9696 9697 // The 4-byte load must be aligned, while a char or short may be 9698 // anywhere in the word. Hence all this nasty bookkeeping code. 9699 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9700 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9701 // xori shift, shift1, 24 [16] 9702 // rlwinm ptr, ptr1, 0, 0, 29 9703 // slw newval2, newval, shift 9704 // slw oldval2, oldval,shift 9705 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9706 // slw mask, mask2, shift 9707 // and newval3, newval2, mask 9708 // and oldval3, oldval2, mask 9709 // loop1MBB: 9710 // lwarx tmpDest, ptr 9711 // and tmp, tmpDest, mask 9712 // cmpw tmp, oldval3 9713 // bne- midMBB 9714 // loop2MBB: 9715 // andc tmp2, tmpDest, mask 9716 // or tmp4, tmp2, newval3 9717 // stwcx. tmp4, ptr 9718 // bne- loop1MBB 9719 // b exitBB 9720 // midMBB: 9721 // stwcx. tmpDest, ptr 9722 // exitBB: 9723 // srw dest, tmpDest, shift 9724 if (ptrA != ZeroReg) { 9725 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9726 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9727 .addReg(ptrA).addReg(ptrB); 9728 } else { 9729 Ptr1Reg = ptrB; 9730 } 9731 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9732 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9733 if (!isLittleEndian) 9734 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9735 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9736 if (is64bit) 9737 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9738 .addReg(Ptr1Reg).addImm(0).addImm(61); 9739 else 9740 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9741 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9742 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 9743 .addReg(newval).addReg(ShiftReg); 9744 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 9745 .addReg(oldval).addReg(ShiftReg); 9746 if (is8bit) 9747 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9748 else { 9749 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9750 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 9751 .addReg(Mask3Reg).addImm(65535); 9752 } 9753 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9754 .addReg(Mask2Reg).addReg(ShiftReg); 9755 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 9756 .addReg(NewVal2Reg).addReg(MaskReg); 9757 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 9758 .addReg(OldVal2Reg).addReg(MaskReg); 9759 9760 BB = loop1MBB; 9761 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9762 .addReg(ZeroReg).addReg(PtrReg); 9763 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 9764 .addReg(TmpDestReg).addReg(MaskReg); 9765 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 9766 .addReg(TmpReg).addReg(OldVal3Reg); 9767 BuildMI(BB, dl, TII->get(PPC::BCC)) 9768 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 9769 BB->addSuccessor(loop2MBB); 9770 BB->addSuccessor(midMBB); 9771 9772 BB = loop2MBB; 9773 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 9774 .addReg(TmpDestReg).addReg(MaskReg); 9775 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 9776 .addReg(Tmp2Reg).addReg(NewVal3Reg); 9777 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 9778 .addReg(ZeroReg).addReg(PtrReg); 9779 BuildMI(BB, dl, TII->get(PPC::BCC)) 9780 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 9781 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 9782 BB->addSuccessor(loop1MBB); 9783 BB->addSuccessor(exitMBB); 9784 9785 BB = midMBB; 9786 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 9787 .addReg(ZeroReg).addReg(PtrReg); 9788 BB->addSuccessor(exitMBB); 9789 9790 // exitMBB: 9791 // ... 9792 BB = exitMBB; 9793 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 9794 .addReg(ShiftReg); 9795 } else if (MI.getOpcode() == PPC::FADDrtz) { 9796 // This pseudo performs an FADD with rounding mode temporarily forced 9797 // to round-to-zero. We emit this via custom inserter since the FPSCR 9798 // is not modeled at the SelectionDAG level. 9799 unsigned Dest = MI.getOperand(0).getReg(); 9800 unsigned Src1 = MI.getOperand(1).getReg(); 9801 unsigned Src2 = MI.getOperand(2).getReg(); 9802 DebugLoc dl = MI.getDebugLoc(); 9803 9804 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9805 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 9806 9807 // Save FPSCR value. 9808 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 9809 9810 // Set rounding mode to round-to-zero. 9811 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 9812 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 9813 9814 // Perform addition. 9815 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 9816 9817 // Restore FPSCR value. 9818 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 9819 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 9820 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 9821 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 9822 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 9823 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 9824 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 9825 ? PPC::ANDIo8 9826 : PPC::ANDIo; 9827 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 9828 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 9829 9830 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9831 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 9832 &PPC::GPRCRegClass : 9833 &PPC::G8RCRegClass); 9834 9835 DebugLoc dl = MI.getDebugLoc(); 9836 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 9837 .addReg(MI.getOperand(1).getReg()) 9838 .addImm(1); 9839 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 9840 MI.getOperand(0).getReg()) 9841 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 9842 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 9843 DebugLoc Dl = MI.getDebugLoc(); 9844 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9845 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 9846 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 9847 return BB; 9848 } else { 9849 llvm_unreachable("Unexpected instr type to insert"); 9850 } 9851 9852 MI.eraseFromParent(); // The pseudo instruction is gone now. 9853 return BB; 9854 } 9855 9856 //===----------------------------------------------------------------------===// 9857 // Target Optimization Hooks 9858 //===----------------------------------------------------------------------===// 9859 9860 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 9861 // For the estimates, convergence is quadratic, so we essentially double the 9862 // number of digits correct after every iteration. For both FRE and FRSQRTE, 9863 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 9864 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 9865 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 9866 if (VT.getScalarType() == MVT::f64) 9867 RefinementSteps++; 9868 return RefinementSteps; 9869 } 9870 9871 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 9872 int Enabled, int &RefinementSteps, 9873 bool &UseOneConstNR, 9874 bool Reciprocal) const { 9875 EVT VT = Operand.getValueType(); 9876 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 9877 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 9878 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 9879 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 9880 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 9881 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 9882 if (RefinementSteps == ReciprocalEstimate::Unspecified) 9883 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 9884 9885 UseOneConstNR = true; 9886 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 9887 } 9888 return SDValue(); 9889 } 9890 9891 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 9892 int Enabled, 9893 int &RefinementSteps) const { 9894 EVT VT = Operand.getValueType(); 9895 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 9896 (VT == MVT::f64 && Subtarget.hasFRE()) || 9897 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 9898 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 9899 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 9900 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 9901 if (RefinementSteps == ReciprocalEstimate::Unspecified) 9902 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 9903 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 9904 } 9905 return SDValue(); 9906 } 9907 9908 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 9909 // Note: This functionality is used only when unsafe-fp-math is enabled, and 9910 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 9911 // enabled for division), this functionality is redundant with the default 9912 // combiner logic (once the division -> reciprocal/multiply transformation 9913 // has taken place). As a result, this matters more for older cores than for 9914 // newer ones. 9915 9916 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 9917 // reciprocal if there are two or more FDIVs (for embedded cores with only 9918 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 9919 switch (Subtarget.getDarwinDirective()) { 9920 default: 9921 return 3; 9922 case PPC::DIR_440: 9923 case PPC::DIR_A2: 9924 case PPC::DIR_E500mc: 9925 case PPC::DIR_E5500: 9926 return 2; 9927 } 9928 } 9929 9930 // isConsecutiveLSLoc needs to work even if all adds have not yet been 9931 // collapsed, and so we need to look through chains of them. 9932 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 9933 int64_t& Offset, SelectionDAG &DAG) { 9934 if (DAG.isBaseWithConstantOffset(Loc)) { 9935 Base = Loc.getOperand(0); 9936 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 9937 9938 // The base might itself be a base plus an offset, and if so, accumulate 9939 // that as well. 9940 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 9941 } 9942 } 9943 9944 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 9945 unsigned Bytes, int Dist, 9946 SelectionDAG &DAG) { 9947 if (VT.getSizeInBits() / 8 != Bytes) 9948 return false; 9949 9950 SDValue BaseLoc = Base->getBasePtr(); 9951 if (Loc.getOpcode() == ISD::FrameIndex) { 9952 if (BaseLoc.getOpcode() != ISD::FrameIndex) 9953 return false; 9954 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9955 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 9956 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 9957 int FS = MFI.getObjectSize(FI); 9958 int BFS = MFI.getObjectSize(BFI); 9959 if (FS != BFS || FS != (int)Bytes) return false; 9960 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 9961 } 9962 9963 SDValue Base1 = Loc, Base2 = BaseLoc; 9964 int64_t Offset1 = 0, Offset2 = 0; 9965 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 9966 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 9967 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 9968 return true; 9969 9970 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9971 const GlobalValue *GV1 = nullptr; 9972 const GlobalValue *GV2 = nullptr; 9973 Offset1 = 0; 9974 Offset2 = 0; 9975 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 9976 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 9977 if (isGA1 && isGA2 && GV1 == GV2) 9978 return Offset1 == (Offset2 + Dist*Bytes); 9979 return false; 9980 } 9981 9982 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 9983 // not enforce equality of the chain operands. 9984 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 9985 unsigned Bytes, int Dist, 9986 SelectionDAG &DAG) { 9987 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 9988 EVT VT = LS->getMemoryVT(); 9989 SDValue Loc = LS->getBasePtr(); 9990 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 9991 } 9992 9993 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 9994 EVT VT; 9995 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 9996 default: return false; 9997 case Intrinsic::ppc_qpx_qvlfd: 9998 case Intrinsic::ppc_qpx_qvlfda: 9999 VT = MVT::v4f64; 10000 break; 10001 case Intrinsic::ppc_qpx_qvlfs: 10002 case Intrinsic::ppc_qpx_qvlfsa: 10003 VT = MVT::v4f32; 10004 break; 10005 case Intrinsic::ppc_qpx_qvlfcd: 10006 case Intrinsic::ppc_qpx_qvlfcda: 10007 VT = MVT::v2f64; 10008 break; 10009 case Intrinsic::ppc_qpx_qvlfcs: 10010 case Intrinsic::ppc_qpx_qvlfcsa: 10011 VT = MVT::v2f32; 10012 break; 10013 case Intrinsic::ppc_qpx_qvlfiwa: 10014 case Intrinsic::ppc_qpx_qvlfiwz: 10015 case Intrinsic::ppc_altivec_lvx: 10016 case Intrinsic::ppc_altivec_lvxl: 10017 case Intrinsic::ppc_vsx_lxvw4x: 10018 case Intrinsic::ppc_vsx_lxvw4x_be: 10019 VT = MVT::v4i32; 10020 break; 10021 case Intrinsic::ppc_vsx_lxvd2x: 10022 case Intrinsic::ppc_vsx_lxvd2x_be: 10023 VT = MVT::v2f64; 10024 break; 10025 case Intrinsic::ppc_altivec_lvebx: 10026 VT = MVT::i8; 10027 break; 10028 case Intrinsic::ppc_altivec_lvehx: 10029 VT = MVT::i16; 10030 break; 10031 case Intrinsic::ppc_altivec_lvewx: 10032 VT = MVT::i32; 10033 break; 10034 } 10035 10036 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 10037 } 10038 10039 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 10040 EVT VT; 10041 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10042 default: return false; 10043 case Intrinsic::ppc_qpx_qvstfd: 10044 case Intrinsic::ppc_qpx_qvstfda: 10045 VT = MVT::v4f64; 10046 break; 10047 case Intrinsic::ppc_qpx_qvstfs: 10048 case Intrinsic::ppc_qpx_qvstfsa: 10049 VT = MVT::v4f32; 10050 break; 10051 case Intrinsic::ppc_qpx_qvstfcd: 10052 case Intrinsic::ppc_qpx_qvstfcda: 10053 VT = MVT::v2f64; 10054 break; 10055 case Intrinsic::ppc_qpx_qvstfcs: 10056 case Intrinsic::ppc_qpx_qvstfcsa: 10057 VT = MVT::v2f32; 10058 break; 10059 case Intrinsic::ppc_qpx_qvstfiw: 10060 case Intrinsic::ppc_qpx_qvstfiwa: 10061 case Intrinsic::ppc_altivec_stvx: 10062 case Intrinsic::ppc_altivec_stvxl: 10063 case Intrinsic::ppc_vsx_stxvw4x: 10064 VT = MVT::v4i32; 10065 break; 10066 case Intrinsic::ppc_vsx_stxvd2x: 10067 VT = MVT::v2f64; 10068 break; 10069 case Intrinsic::ppc_vsx_stxvw4x_be: 10070 VT = MVT::v4i32; 10071 break; 10072 case Intrinsic::ppc_vsx_stxvd2x_be: 10073 VT = MVT::v2f64; 10074 break; 10075 case Intrinsic::ppc_altivec_stvebx: 10076 VT = MVT::i8; 10077 break; 10078 case Intrinsic::ppc_altivec_stvehx: 10079 VT = MVT::i16; 10080 break; 10081 case Intrinsic::ppc_altivec_stvewx: 10082 VT = MVT::i32; 10083 break; 10084 } 10085 10086 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 10087 } 10088 10089 return false; 10090 } 10091 10092 // Return true is there is a nearyby consecutive load to the one provided 10093 // (regardless of alignment). We search up and down the chain, looking though 10094 // token factors and other loads (but nothing else). As a result, a true result 10095 // indicates that it is safe to create a new consecutive load adjacent to the 10096 // load provided. 10097 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 10098 SDValue Chain = LD->getChain(); 10099 EVT VT = LD->getMemoryVT(); 10100 10101 SmallSet<SDNode *, 16> LoadRoots; 10102 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 10103 SmallSet<SDNode *, 16> Visited; 10104 10105 // First, search up the chain, branching to follow all token-factor operands. 10106 // If we find a consecutive load, then we're done, otherwise, record all 10107 // nodes just above the top-level loads and token factors. 10108 while (!Queue.empty()) { 10109 SDNode *ChainNext = Queue.pop_back_val(); 10110 if (!Visited.insert(ChainNext).second) 10111 continue; 10112 10113 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 10114 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10115 return true; 10116 10117 if (!Visited.count(ChainLD->getChain().getNode())) 10118 Queue.push_back(ChainLD->getChain().getNode()); 10119 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 10120 for (const SDUse &O : ChainNext->ops()) 10121 if (!Visited.count(O.getNode())) 10122 Queue.push_back(O.getNode()); 10123 } else 10124 LoadRoots.insert(ChainNext); 10125 } 10126 10127 // Second, search down the chain, starting from the top-level nodes recorded 10128 // in the first phase. These top-level nodes are the nodes just above all 10129 // loads and token factors. Starting with their uses, recursively look though 10130 // all loads (just the chain uses) and token factors to find a consecutive 10131 // load. 10132 Visited.clear(); 10133 Queue.clear(); 10134 10135 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 10136 IE = LoadRoots.end(); I != IE; ++I) { 10137 Queue.push_back(*I); 10138 10139 while (!Queue.empty()) { 10140 SDNode *LoadRoot = Queue.pop_back_val(); 10141 if (!Visited.insert(LoadRoot).second) 10142 continue; 10143 10144 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 10145 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10146 return true; 10147 10148 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 10149 UE = LoadRoot->use_end(); UI != UE; ++UI) 10150 if (((isa<MemSDNode>(*UI) && 10151 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 10152 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 10153 Queue.push_back(*UI); 10154 } 10155 } 10156 10157 return false; 10158 } 10159 10160 /// This function is called when we have proved that a SETCC node can be replaced 10161 /// by subtraction (and other supporting instructions) so that the result of 10162 /// comparison is kept in a GPR instead of CR. This function is purely for 10163 /// codegen purposes and has some flags to guide the codegen process. 10164 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 10165 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 10166 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10167 10168 // Zero extend the operands to the largest legal integer. Originally, they 10169 // must be of a strictly smaller size. 10170 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 10171 DAG.getConstant(Size, DL, MVT::i32)); 10172 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 10173 DAG.getConstant(Size, DL, MVT::i32)); 10174 10175 // Swap if needed. Depends on the condition code. 10176 if (Swap) 10177 std::swap(Op0, Op1); 10178 10179 // Subtract extended integers. 10180 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 10181 10182 // Move the sign bit to the least significant position and zero out the rest. 10183 // Now the least significant bit carries the result of original comparison. 10184 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 10185 DAG.getConstant(Size - 1, DL, MVT::i32)); 10186 auto Final = Shifted; 10187 10188 // Complement the result if needed. Based on the condition code. 10189 if (Complement) 10190 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 10191 DAG.getConstant(1, DL, MVT::i64)); 10192 10193 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 10194 } 10195 10196 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 10197 DAGCombinerInfo &DCI) const { 10198 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10199 10200 SelectionDAG &DAG = DCI.DAG; 10201 SDLoc DL(N); 10202 10203 // Size of integers being compared has a critical role in the following 10204 // analysis, so we prefer to do this when all types are legal. 10205 if (!DCI.isAfterLegalizeVectorOps()) 10206 return SDValue(); 10207 10208 // If all users of SETCC extend its value to a legal integer type 10209 // then we replace SETCC with a subtraction 10210 for (SDNode::use_iterator UI = N->use_begin(), 10211 UE = N->use_end(); UI != UE; ++UI) { 10212 if (UI->getOpcode() != ISD::ZERO_EXTEND) 10213 return SDValue(); 10214 } 10215 10216 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10217 auto OpSize = N->getOperand(0).getValueSizeInBits(); 10218 10219 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 10220 10221 if (OpSize < Size) { 10222 switch (CC) { 10223 default: break; 10224 case ISD::SETULT: 10225 return generateEquivalentSub(N, Size, false, false, DL, DAG); 10226 case ISD::SETULE: 10227 return generateEquivalentSub(N, Size, true, true, DL, DAG); 10228 case ISD::SETUGT: 10229 return generateEquivalentSub(N, Size, false, true, DL, DAG); 10230 case ISD::SETUGE: 10231 return generateEquivalentSub(N, Size, true, false, DL, DAG); 10232 } 10233 } 10234 10235 return SDValue(); 10236 } 10237 10238 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 10239 DAGCombinerInfo &DCI) const { 10240 SelectionDAG &DAG = DCI.DAG; 10241 SDLoc dl(N); 10242 10243 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 10244 // If we're tracking CR bits, we need to be careful that we don't have: 10245 // trunc(binary-ops(zext(x), zext(y))) 10246 // or 10247 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 10248 // such that we're unnecessarily moving things into GPRs when it would be 10249 // better to keep them in CR bits. 10250 10251 // Note that trunc here can be an actual i1 trunc, or can be the effective 10252 // truncation that comes from a setcc or select_cc. 10253 if (N->getOpcode() == ISD::TRUNCATE && 10254 N->getValueType(0) != MVT::i1) 10255 return SDValue(); 10256 10257 if (N->getOperand(0).getValueType() != MVT::i32 && 10258 N->getOperand(0).getValueType() != MVT::i64) 10259 return SDValue(); 10260 10261 if (N->getOpcode() == ISD::SETCC || 10262 N->getOpcode() == ISD::SELECT_CC) { 10263 // If we're looking at a comparison, then we need to make sure that the 10264 // high bits (all except for the first) don't matter the result. 10265 ISD::CondCode CC = 10266 cast<CondCodeSDNode>(N->getOperand( 10267 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 10268 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 10269 10270 if (ISD::isSignedIntSetCC(CC)) { 10271 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 10272 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 10273 return SDValue(); 10274 } else if (ISD::isUnsignedIntSetCC(CC)) { 10275 if (!DAG.MaskedValueIsZero(N->getOperand(0), 10276 APInt::getHighBitsSet(OpBits, OpBits-1)) || 10277 !DAG.MaskedValueIsZero(N->getOperand(1), 10278 APInt::getHighBitsSet(OpBits, OpBits-1))) 10279 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 10280 : SDValue()); 10281 } else { 10282 // This is neither a signed nor an unsigned comparison, just make sure 10283 // that the high bits are equal. 10284 APInt Op1Zero, Op1One; 10285 APInt Op2Zero, Op2One; 10286 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One); 10287 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One); 10288 10289 // We don't really care about what is known about the first bit (if 10290 // anything), so clear it in all masks prior to comparing them. 10291 Op1Zero.clearBit(0); Op1One.clearBit(0); 10292 Op2Zero.clearBit(0); Op2One.clearBit(0); 10293 10294 if (Op1Zero != Op2Zero || Op1One != Op2One) 10295 return SDValue(); 10296 } 10297 } 10298 10299 // We now know that the higher-order bits are irrelevant, we just need to 10300 // make sure that all of the intermediate operations are bit operations, and 10301 // all inputs are extensions. 10302 if (N->getOperand(0).getOpcode() != ISD::AND && 10303 N->getOperand(0).getOpcode() != ISD::OR && 10304 N->getOperand(0).getOpcode() != ISD::XOR && 10305 N->getOperand(0).getOpcode() != ISD::SELECT && 10306 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 10307 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 10308 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 10309 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 10310 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 10311 return SDValue(); 10312 10313 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 10314 N->getOperand(1).getOpcode() != ISD::AND && 10315 N->getOperand(1).getOpcode() != ISD::OR && 10316 N->getOperand(1).getOpcode() != ISD::XOR && 10317 N->getOperand(1).getOpcode() != ISD::SELECT && 10318 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 10319 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 10320 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 10321 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 10322 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 10323 return SDValue(); 10324 10325 SmallVector<SDValue, 4> Inputs; 10326 SmallVector<SDValue, 8> BinOps, PromOps; 10327 SmallPtrSet<SDNode *, 16> Visited; 10328 10329 for (unsigned i = 0; i < 2; ++i) { 10330 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10331 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10332 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 10333 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 10334 isa<ConstantSDNode>(N->getOperand(i))) 10335 Inputs.push_back(N->getOperand(i)); 10336 else 10337 BinOps.push_back(N->getOperand(i)); 10338 10339 if (N->getOpcode() == ISD::TRUNCATE) 10340 break; 10341 } 10342 10343 // Visit all inputs, collect all binary operations (and, or, xor and 10344 // select) that are all fed by extensions. 10345 while (!BinOps.empty()) { 10346 SDValue BinOp = BinOps.back(); 10347 BinOps.pop_back(); 10348 10349 if (!Visited.insert(BinOp.getNode()).second) 10350 continue; 10351 10352 PromOps.push_back(BinOp); 10353 10354 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 10355 // The condition of the select is not promoted. 10356 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 10357 continue; 10358 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 10359 continue; 10360 10361 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10362 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10363 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 10364 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 10365 isa<ConstantSDNode>(BinOp.getOperand(i))) { 10366 Inputs.push_back(BinOp.getOperand(i)); 10367 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 10368 BinOp.getOperand(i).getOpcode() == ISD::OR || 10369 BinOp.getOperand(i).getOpcode() == ISD::XOR || 10370 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 10371 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 10372 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 10373 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10374 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10375 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 10376 BinOps.push_back(BinOp.getOperand(i)); 10377 } else { 10378 // We have an input that is not an extension or another binary 10379 // operation; we'll abort this transformation. 10380 return SDValue(); 10381 } 10382 } 10383 } 10384 10385 // Make sure that this is a self-contained cluster of operations (which 10386 // is not quite the same thing as saying that everything has only one 10387 // use). 10388 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10389 if (isa<ConstantSDNode>(Inputs[i])) 10390 continue; 10391 10392 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 10393 UE = Inputs[i].getNode()->use_end(); 10394 UI != UE; ++UI) { 10395 SDNode *User = *UI; 10396 if (User != N && !Visited.count(User)) 10397 return SDValue(); 10398 10399 // Make sure that we're not going to promote the non-output-value 10400 // operand(s) or SELECT or SELECT_CC. 10401 // FIXME: Although we could sometimes handle this, and it does occur in 10402 // practice that one of the condition inputs to the select is also one of 10403 // the outputs, we currently can't deal with this. 10404 if (User->getOpcode() == ISD::SELECT) { 10405 if (User->getOperand(0) == Inputs[i]) 10406 return SDValue(); 10407 } else if (User->getOpcode() == ISD::SELECT_CC) { 10408 if (User->getOperand(0) == Inputs[i] || 10409 User->getOperand(1) == Inputs[i]) 10410 return SDValue(); 10411 } 10412 } 10413 } 10414 10415 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 10416 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 10417 UE = PromOps[i].getNode()->use_end(); 10418 UI != UE; ++UI) { 10419 SDNode *User = *UI; 10420 if (User != N && !Visited.count(User)) 10421 return SDValue(); 10422 10423 // Make sure that we're not going to promote the non-output-value 10424 // operand(s) or SELECT or SELECT_CC. 10425 // FIXME: Although we could sometimes handle this, and it does occur in 10426 // practice that one of the condition inputs to the select is also one of 10427 // the outputs, we currently can't deal with this. 10428 if (User->getOpcode() == ISD::SELECT) { 10429 if (User->getOperand(0) == PromOps[i]) 10430 return SDValue(); 10431 } else if (User->getOpcode() == ISD::SELECT_CC) { 10432 if (User->getOperand(0) == PromOps[i] || 10433 User->getOperand(1) == PromOps[i]) 10434 return SDValue(); 10435 } 10436 } 10437 } 10438 10439 // Replace all inputs with the extension operand. 10440 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10441 // Constants may have users outside the cluster of to-be-promoted nodes, 10442 // and so we need to replace those as we do the promotions. 10443 if (isa<ConstantSDNode>(Inputs[i])) 10444 continue; 10445 else 10446 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 10447 } 10448 10449 std::list<HandleSDNode> PromOpHandles; 10450 for (auto &PromOp : PromOps) 10451 PromOpHandles.emplace_back(PromOp); 10452 10453 // Replace all operations (these are all the same, but have a different 10454 // (i1) return type). DAG.getNode will validate that the types of 10455 // a binary operator match, so go through the list in reverse so that 10456 // we've likely promoted both operands first. Any intermediate truncations or 10457 // extensions disappear. 10458 while (!PromOpHandles.empty()) { 10459 SDValue PromOp = PromOpHandles.back().getValue(); 10460 PromOpHandles.pop_back(); 10461 10462 if (PromOp.getOpcode() == ISD::TRUNCATE || 10463 PromOp.getOpcode() == ISD::SIGN_EXTEND || 10464 PromOp.getOpcode() == ISD::ZERO_EXTEND || 10465 PromOp.getOpcode() == ISD::ANY_EXTEND) { 10466 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 10467 PromOp.getOperand(0).getValueType() != MVT::i1) { 10468 // The operand is not yet ready (see comment below). 10469 PromOpHandles.emplace_front(PromOp); 10470 continue; 10471 } 10472 10473 SDValue RepValue = PromOp.getOperand(0); 10474 if (isa<ConstantSDNode>(RepValue)) 10475 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 10476 10477 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 10478 continue; 10479 } 10480 10481 unsigned C; 10482 switch (PromOp.getOpcode()) { 10483 default: C = 0; break; 10484 case ISD::SELECT: C = 1; break; 10485 case ISD::SELECT_CC: C = 2; break; 10486 } 10487 10488 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 10489 PromOp.getOperand(C).getValueType() != MVT::i1) || 10490 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 10491 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 10492 // The to-be-promoted operands of this node have not yet been 10493 // promoted (this should be rare because we're going through the 10494 // list backward, but if one of the operands has several users in 10495 // this cluster of to-be-promoted nodes, it is possible). 10496 PromOpHandles.emplace_front(PromOp); 10497 continue; 10498 } 10499 10500 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 10501 PromOp.getNode()->op_end()); 10502 10503 // If there are any constant inputs, make sure they're replaced now. 10504 for (unsigned i = 0; i < 2; ++i) 10505 if (isa<ConstantSDNode>(Ops[C+i])) 10506 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 10507 10508 DAG.ReplaceAllUsesOfValueWith(PromOp, 10509 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 10510 } 10511 10512 // Now we're left with the initial truncation itself. 10513 if (N->getOpcode() == ISD::TRUNCATE) 10514 return N->getOperand(0); 10515 10516 // Otherwise, this is a comparison. The operands to be compared have just 10517 // changed type (to i1), but everything else is the same. 10518 return SDValue(N, 0); 10519 } 10520 10521 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 10522 DAGCombinerInfo &DCI) const { 10523 SelectionDAG &DAG = DCI.DAG; 10524 SDLoc dl(N); 10525 10526 // If we're tracking CR bits, we need to be careful that we don't have: 10527 // zext(binary-ops(trunc(x), trunc(y))) 10528 // or 10529 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 10530 // such that we're unnecessarily moving things into CR bits that can more 10531 // efficiently stay in GPRs. Note that if we're not certain that the high 10532 // bits are set as required by the final extension, we still may need to do 10533 // some masking to get the proper behavior. 10534 10535 // This same functionality is important on PPC64 when dealing with 10536 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 10537 // the return values of functions. Because it is so similar, it is handled 10538 // here as well. 10539 10540 if (N->getValueType(0) != MVT::i32 && 10541 N->getValueType(0) != MVT::i64) 10542 return SDValue(); 10543 10544 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 10545 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 10546 return SDValue(); 10547 10548 if (N->getOperand(0).getOpcode() != ISD::AND && 10549 N->getOperand(0).getOpcode() != ISD::OR && 10550 N->getOperand(0).getOpcode() != ISD::XOR && 10551 N->getOperand(0).getOpcode() != ISD::SELECT && 10552 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 10553 return SDValue(); 10554 10555 SmallVector<SDValue, 4> Inputs; 10556 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 10557 SmallPtrSet<SDNode *, 16> Visited; 10558 10559 // Visit all inputs, collect all binary operations (and, or, xor and 10560 // select) that are all fed by truncations. 10561 while (!BinOps.empty()) { 10562 SDValue BinOp = BinOps.back(); 10563 BinOps.pop_back(); 10564 10565 if (!Visited.insert(BinOp.getNode()).second) 10566 continue; 10567 10568 PromOps.push_back(BinOp); 10569 10570 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 10571 // The condition of the select is not promoted. 10572 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 10573 continue; 10574 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 10575 continue; 10576 10577 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 10578 isa<ConstantSDNode>(BinOp.getOperand(i))) { 10579 Inputs.push_back(BinOp.getOperand(i)); 10580 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 10581 BinOp.getOperand(i).getOpcode() == ISD::OR || 10582 BinOp.getOperand(i).getOpcode() == ISD::XOR || 10583 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 10584 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 10585 BinOps.push_back(BinOp.getOperand(i)); 10586 } else { 10587 // We have an input that is not a truncation or another binary 10588 // operation; we'll abort this transformation. 10589 return SDValue(); 10590 } 10591 } 10592 } 10593 10594 // The operands of a select that must be truncated when the select is 10595 // promoted because the operand is actually part of the to-be-promoted set. 10596 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 10597 10598 // Make sure that this is a self-contained cluster of operations (which 10599 // is not quite the same thing as saying that everything has only one 10600 // use). 10601 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10602 if (isa<ConstantSDNode>(Inputs[i])) 10603 continue; 10604 10605 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 10606 UE = Inputs[i].getNode()->use_end(); 10607 UI != UE; ++UI) { 10608 SDNode *User = *UI; 10609 if (User != N && !Visited.count(User)) 10610 return SDValue(); 10611 10612 // If we're going to promote the non-output-value operand(s) or SELECT or 10613 // SELECT_CC, record them for truncation. 10614 if (User->getOpcode() == ISD::SELECT) { 10615 if (User->getOperand(0) == Inputs[i]) 10616 SelectTruncOp[0].insert(std::make_pair(User, 10617 User->getOperand(0).getValueType())); 10618 } else if (User->getOpcode() == ISD::SELECT_CC) { 10619 if (User->getOperand(0) == Inputs[i]) 10620 SelectTruncOp[0].insert(std::make_pair(User, 10621 User->getOperand(0).getValueType())); 10622 if (User->getOperand(1) == Inputs[i]) 10623 SelectTruncOp[1].insert(std::make_pair(User, 10624 User->getOperand(1).getValueType())); 10625 } 10626 } 10627 } 10628 10629 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 10630 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 10631 UE = PromOps[i].getNode()->use_end(); 10632 UI != UE; ++UI) { 10633 SDNode *User = *UI; 10634 if (User != N && !Visited.count(User)) 10635 return SDValue(); 10636 10637 // If we're going to promote the non-output-value operand(s) or SELECT or 10638 // SELECT_CC, record them for truncation. 10639 if (User->getOpcode() == ISD::SELECT) { 10640 if (User->getOperand(0) == PromOps[i]) 10641 SelectTruncOp[0].insert(std::make_pair(User, 10642 User->getOperand(0).getValueType())); 10643 } else if (User->getOpcode() == ISD::SELECT_CC) { 10644 if (User->getOperand(0) == PromOps[i]) 10645 SelectTruncOp[0].insert(std::make_pair(User, 10646 User->getOperand(0).getValueType())); 10647 if (User->getOperand(1) == PromOps[i]) 10648 SelectTruncOp[1].insert(std::make_pair(User, 10649 User->getOperand(1).getValueType())); 10650 } 10651 } 10652 } 10653 10654 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 10655 bool ReallyNeedsExt = false; 10656 if (N->getOpcode() != ISD::ANY_EXTEND) { 10657 // If all of the inputs are not already sign/zero extended, then 10658 // we'll still need to do that at the end. 10659 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10660 if (isa<ConstantSDNode>(Inputs[i])) 10661 continue; 10662 10663 unsigned OpBits = 10664 Inputs[i].getOperand(0).getValueSizeInBits(); 10665 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 10666 10667 if ((N->getOpcode() == ISD::ZERO_EXTEND && 10668 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 10669 APInt::getHighBitsSet(OpBits, 10670 OpBits-PromBits))) || 10671 (N->getOpcode() == ISD::SIGN_EXTEND && 10672 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 10673 (OpBits-(PromBits-1)))) { 10674 ReallyNeedsExt = true; 10675 break; 10676 } 10677 } 10678 } 10679 10680 // Replace all inputs, either with the truncation operand, or a 10681 // truncation or extension to the final output type. 10682 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10683 // Constant inputs need to be replaced with the to-be-promoted nodes that 10684 // use them because they might have users outside of the cluster of 10685 // promoted nodes. 10686 if (isa<ConstantSDNode>(Inputs[i])) 10687 continue; 10688 10689 SDValue InSrc = Inputs[i].getOperand(0); 10690 if (Inputs[i].getValueType() == N->getValueType(0)) 10691 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 10692 else if (N->getOpcode() == ISD::SIGN_EXTEND) 10693 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 10694 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 10695 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10696 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 10697 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 10698 else 10699 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 10700 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 10701 } 10702 10703 std::list<HandleSDNode> PromOpHandles; 10704 for (auto &PromOp : PromOps) 10705 PromOpHandles.emplace_back(PromOp); 10706 10707 // Replace all operations (these are all the same, but have a different 10708 // (promoted) return type). DAG.getNode will validate that the types of 10709 // a binary operator match, so go through the list in reverse so that 10710 // we've likely promoted both operands first. 10711 while (!PromOpHandles.empty()) { 10712 SDValue PromOp = PromOpHandles.back().getValue(); 10713 PromOpHandles.pop_back(); 10714 10715 unsigned C; 10716 switch (PromOp.getOpcode()) { 10717 default: C = 0; break; 10718 case ISD::SELECT: C = 1; break; 10719 case ISD::SELECT_CC: C = 2; break; 10720 } 10721 10722 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 10723 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 10724 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 10725 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 10726 // The to-be-promoted operands of this node have not yet been 10727 // promoted (this should be rare because we're going through the 10728 // list backward, but if one of the operands has several users in 10729 // this cluster of to-be-promoted nodes, it is possible). 10730 PromOpHandles.emplace_front(PromOp); 10731 continue; 10732 } 10733 10734 // For SELECT and SELECT_CC nodes, we do a similar check for any 10735 // to-be-promoted comparison inputs. 10736 if (PromOp.getOpcode() == ISD::SELECT || 10737 PromOp.getOpcode() == ISD::SELECT_CC) { 10738 if ((SelectTruncOp[0].count(PromOp.getNode()) && 10739 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 10740 (SelectTruncOp[1].count(PromOp.getNode()) && 10741 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 10742 PromOpHandles.emplace_front(PromOp); 10743 continue; 10744 } 10745 } 10746 10747 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 10748 PromOp.getNode()->op_end()); 10749 10750 // If this node has constant inputs, then they'll need to be promoted here. 10751 for (unsigned i = 0; i < 2; ++i) { 10752 if (!isa<ConstantSDNode>(Ops[C+i])) 10753 continue; 10754 if (Ops[C+i].getValueType() == N->getValueType(0)) 10755 continue; 10756 10757 if (N->getOpcode() == ISD::SIGN_EXTEND) 10758 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 10759 else if (N->getOpcode() == ISD::ZERO_EXTEND) 10760 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 10761 else 10762 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 10763 } 10764 10765 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 10766 // truncate them again to the original value type. 10767 if (PromOp.getOpcode() == ISD::SELECT || 10768 PromOp.getOpcode() == ISD::SELECT_CC) { 10769 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 10770 if (SI0 != SelectTruncOp[0].end()) 10771 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 10772 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 10773 if (SI1 != SelectTruncOp[1].end()) 10774 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 10775 } 10776 10777 DAG.ReplaceAllUsesOfValueWith(PromOp, 10778 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 10779 } 10780 10781 // Now we're left with the initial extension itself. 10782 if (!ReallyNeedsExt) 10783 return N->getOperand(0); 10784 10785 // To zero extend, just mask off everything except for the first bit (in the 10786 // i1 case). 10787 if (N->getOpcode() == ISD::ZERO_EXTEND) 10788 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 10789 DAG.getConstant(APInt::getLowBitsSet( 10790 N->getValueSizeInBits(0), PromBits), 10791 dl, N->getValueType(0))); 10792 10793 assert(N->getOpcode() == ISD::SIGN_EXTEND && 10794 "Invalid extension type"); 10795 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 10796 SDValue ShiftCst = 10797 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 10798 return DAG.getNode( 10799 ISD::SRA, dl, N->getValueType(0), 10800 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 10801 ShiftCst); 10802 } 10803 10804 /// \brief Reduces the number of fp-to-int conversion when building a vector. 10805 /// 10806 /// If this vector is built out of floating to integer conversions, 10807 /// transform it to a vector built out of floating point values followed by a 10808 /// single floating to integer conversion of the vector. 10809 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 10810 /// becomes (fptosi (build_vector ($A, $B, ...))) 10811 SDValue PPCTargetLowering:: 10812 combineElementTruncationToVectorTruncation(SDNode *N, 10813 DAGCombinerInfo &DCI) const { 10814 assert(N->getOpcode() == ISD::BUILD_VECTOR && 10815 "Should be called with a BUILD_VECTOR node"); 10816 10817 SelectionDAG &DAG = DCI.DAG; 10818 SDLoc dl(N); 10819 10820 SDValue FirstInput = N->getOperand(0); 10821 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 10822 "The input operand must be an fp-to-int conversion."); 10823 10824 // This combine happens after legalization so the fp_to_[su]i nodes are 10825 // already converted to PPCSISD nodes. 10826 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 10827 if (FirstConversion == PPCISD::FCTIDZ || 10828 FirstConversion == PPCISD::FCTIDUZ || 10829 FirstConversion == PPCISD::FCTIWZ || 10830 FirstConversion == PPCISD::FCTIWUZ) { 10831 bool IsSplat = true; 10832 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 10833 FirstConversion == PPCISD::FCTIWUZ; 10834 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 10835 SmallVector<SDValue, 4> Ops; 10836 EVT TargetVT = N->getValueType(0); 10837 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 10838 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR) 10839 return SDValue(); 10840 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode(); 10841 if (NextConversion != FirstConversion) 10842 return SDValue(); 10843 if (N->getOperand(i) != FirstInput) 10844 IsSplat = false; 10845 } 10846 10847 // If this is a splat, we leave it as-is since there will be only a single 10848 // fp-to-int conversion followed by a splat of the integer. This is better 10849 // for 32-bit and smaller ints and neutral for 64-bit ints. 10850 if (IsSplat) 10851 return SDValue(); 10852 10853 // Now that we know we have the right type of node, get its operands 10854 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 10855 SDValue In = N->getOperand(i).getOperand(0); 10856 // For 32-bit values, we need to add an FP_ROUND node. 10857 if (Is32Bit) { 10858 if (In.isUndef()) 10859 Ops.push_back(DAG.getUNDEF(SrcVT)); 10860 else { 10861 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 10862 MVT::f32, In.getOperand(0), 10863 DAG.getIntPtrConstant(1, dl)); 10864 Ops.push_back(Trunc); 10865 } 10866 } else 10867 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 10868 } 10869 10870 unsigned Opcode; 10871 if (FirstConversion == PPCISD::FCTIDZ || 10872 FirstConversion == PPCISD::FCTIWZ) 10873 Opcode = ISD::FP_TO_SINT; 10874 else 10875 Opcode = ISD::FP_TO_UINT; 10876 10877 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 10878 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 10879 return DAG.getNode(Opcode, dl, TargetVT, BV); 10880 } 10881 return SDValue(); 10882 } 10883 10884 /// \brief Reduce the number of loads when building a vector. 10885 /// 10886 /// Building a vector out of multiple loads can be converted to a load 10887 /// of the vector type if the loads are consecutive. If the loads are 10888 /// consecutive but in descending order, a shuffle is added at the end 10889 /// to reorder the vector. 10890 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 10891 assert(N->getOpcode() == ISD::BUILD_VECTOR && 10892 "Should be called with a BUILD_VECTOR node"); 10893 10894 SDLoc dl(N); 10895 bool InputsAreConsecutiveLoads = true; 10896 bool InputsAreReverseConsecutive = true; 10897 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 10898 SDValue FirstInput = N->getOperand(0); 10899 bool IsRoundOfExtLoad = false; 10900 10901 if (FirstInput.getOpcode() == ISD::FP_ROUND && 10902 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 10903 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 10904 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 10905 } 10906 // Not a build vector of (possibly fp_rounded) loads. 10907 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) 10908 return SDValue(); 10909 10910 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 10911 // If any inputs are fp_round(extload), they all must be. 10912 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 10913 return SDValue(); 10914 10915 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 10916 N->getOperand(i); 10917 if (NextInput.getOpcode() != ISD::LOAD) 10918 return SDValue(); 10919 10920 SDValue PreviousInput = 10921 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 10922 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 10923 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 10924 10925 // If any inputs are fp_round(extload), they all must be. 10926 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 10927 return SDValue(); 10928 10929 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 10930 InputsAreConsecutiveLoads = false; 10931 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 10932 InputsAreReverseConsecutive = false; 10933 10934 // Exit early if the loads are neither consecutive nor reverse consecutive. 10935 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 10936 return SDValue(); 10937 } 10938 10939 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 10940 "The loads cannot be both consecutive and reverse consecutive."); 10941 10942 SDValue FirstLoadOp = 10943 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 10944 SDValue LastLoadOp = 10945 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 10946 N->getOperand(N->getNumOperands()-1); 10947 10948 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 10949 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 10950 if (InputsAreConsecutiveLoads) { 10951 assert(LD1 && "Input needs to be a LoadSDNode."); 10952 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 10953 LD1->getBasePtr(), LD1->getPointerInfo(), 10954 LD1->getAlignment()); 10955 } 10956 if (InputsAreReverseConsecutive) { 10957 assert(LDL && "Input needs to be a LoadSDNode."); 10958 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 10959 LDL->getBasePtr(), LDL->getPointerInfo(), 10960 LDL->getAlignment()); 10961 SmallVector<int, 16> Ops; 10962 for (int i = N->getNumOperands() - 1; i >= 0; i--) 10963 Ops.push_back(i); 10964 10965 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 10966 DAG.getUNDEF(N->getValueType(0)), Ops); 10967 } 10968 return SDValue(); 10969 } 10970 10971 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 10972 DAGCombinerInfo &DCI) const { 10973 assert(N->getOpcode() == ISD::BUILD_VECTOR && 10974 "Should be called with a BUILD_VECTOR node"); 10975 10976 SelectionDAG &DAG = DCI.DAG; 10977 SDLoc dl(N); 10978 10979 if (!Subtarget.hasVSX()) 10980 return SDValue(); 10981 10982 // The target independent DAG combiner will leave a build_vector of 10983 // float-to-int conversions intact. We can generate MUCH better code for 10984 // a float-to-int conversion of a vector of floats. 10985 SDValue FirstInput = N->getOperand(0); 10986 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 10987 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 10988 if (Reduced) 10989 return Reduced; 10990 } 10991 10992 // If we're building a vector out of consecutive loads, just load that 10993 // vector type. 10994 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 10995 if (Reduced) 10996 return Reduced; 10997 10998 if (N->getValueType(0) != MVT::v2f64) 10999 return SDValue(); 11000 11001 // Looking for: 11002 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 11003 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 11004 FirstInput.getOpcode() != ISD::UINT_TO_FP) 11005 return SDValue(); 11006 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 11007 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 11008 return SDValue(); 11009 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 11010 return SDValue(); 11011 11012 SDValue Ext1 = FirstInput.getOperand(0); 11013 SDValue Ext2 = N->getOperand(1).getOperand(0); 11014 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11015 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11016 return SDValue(); 11017 11018 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 11019 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 11020 if (!Ext1Op || !Ext2Op) 11021 return SDValue(); 11022 if (Ext1.getValueType() != MVT::i32 || 11023 Ext2.getValueType() != MVT::i32) 11024 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 11025 return SDValue(); 11026 11027 int FirstElem = Ext1Op->getZExtValue(); 11028 int SecondElem = Ext2Op->getZExtValue(); 11029 int SubvecIdx; 11030 if (FirstElem == 0 && SecondElem == 1) 11031 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 11032 else if (FirstElem == 2 && SecondElem == 3) 11033 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 11034 else 11035 return SDValue(); 11036 11037 SDValue SrcVec = Ext1.getOperand(0); 11038 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 11039 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 11040 return DAG.getNode(NodeType, dl, MVT::v2f64, 11041 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 11042 } 11043 11044 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 11045 DAGCombinerInfo &DCI) const { 11046 assert((N->getOpcode() == ISD::SINT_TO_FP || 11047 N->getOpcode() == ISD::UINT_TO_FP) && 11048 "Need an int -> FP conversion node here"); 11049 11050 if (useSoftFloat() || !Subtarget.has64BitSupport()) 11051 return SDValue(); 11052 11053 SelectionDAG &DAG = DCI.DAG; 11054 SDLoc dl(N); 11055 SDValue Op(N, 0); 11056 11057 SDValue FirstOperand(Op.getOperand(0)); 11058 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 11059 (FirstOperand.getValueType() == MVT::i8 || 11060 FirstOperand.getValueType() == MVT::i16); 11061 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 11062 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 11063 bool DstDouble = Op.getValueType() == MVT::f64; 11064 unsigned ConvOp = Signed ? 11065 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 11066 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 11067 SDValue WidthConst = 11068 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 11069 dl, false); 11070 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 11071 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 11072 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 11073 DAG.getVTList(MVT::f64, MVT::Other), 11074 Ops, MVT::i8, LDN->getMemOperand()); 11075 11076 // For signed conversion, we need to sign-extend the value in the VSR 11077 if (Signed) { 11078 SDValue ExtOps[] = { Ld, WidthConst }; 11079 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 11080 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 11081 } else 11082 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 11083 } 11084 11085 // Don't handle ppc_fp128 here or i1 conversions. 11086 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 11087 return SDValue(); 11088 if (Op.getOperand(0).getValueType() == MVT::i1) 11089 return SDValue(); 11090 11091 // For i32 intermediate values, unfortunately, the conversion functions 11092 // leave the upper 32 bits of the value are undefined. Within the set of 11093 // scalar instructions, we have no method for zero- or sign-extending the 11094 // value. Thus, we cannot handle i32 intermediate values here. 11095 if (Op.getOperand(0).getValueType() == MVT::i32) 11096 return SDValue(); 11097 11098 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 11099 "UINT_TO_FP is supported only with FPCVT"); 11100 11101 // If we have FCFIDS, then use it when converting to single-precision. 11102 // Otherwise, convert to double-precision and then round. 11103 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11104 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 11105 : PPCISD::FCFIDS) 11106 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 11107 : PPCISD::FCFID); 11108 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11109 ? MVT::f32 11110 : MVT::f64; 11111 11112 // If we're converting from a float, to an int, and back to a float again, 11113 // then we don't need the store/load pair at all. 11114 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 11115 Subtarget.hasFPCVT()) || 11116 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 11117 SDValue Src = Op.getOperand(0).getOperand(0); 11118 if (Src.getValueType() == MVT::f32) { 11119 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 11120 DCI.AddToWorklist(Src.getNode()); 11121 } else if (Src.getValueType() != MVT::f64) { 11122 // Make sure that we don't pick up a ppc_fp128 source value. 11123 return SDValue(); 11124 } 11125 11126 unsigned FCTOp = 11127 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 11128 PPCISD::FCTIDUZ; 11129 11130 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 11131 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 11132 11133 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 11134 FP = DAG.getNode(ISD::FP_ROUND, dl, 11135 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 11136 DCI.AddToWorklist(FP.getNode()); 11137 } 11138 11139 return FP; 11140 } 11141 11142 return SDValue(); 11143 } 11144 11145 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 11146 // builtins) into loads with swaps. 11147 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 11148 DAGCombinerInfo &DCI) const { 11149 SelectionDAG &DAG = DCI.DAG; 11150 SDLoc dl(N); 11151 SDValue Chain; 11152 SDValue Base; 11153 MachineMemOperand *MMO; 11154 11155 switch (N->getOpcode()) { 11156 default: 11157 llvm_unreachable("Unexpected opcode for little endian VSX load"); 11158 case ISD::LOAD: { 11159 LoadSDNode *LD = cast<LoadSDNode>(N); 11160 Chain = LD->getChain(); 11161 Base = LD->getBasePtr(); 11162 MMO = LD->getMemOperand(); 11163 // If the MMO suggests this isn't a load of a full vector, leave 11164 // things alone. For a built-in, we have to make the change for 11165 // correctness, so if there is a size problem that will be a bug. 11166 if (MMO->getSize() < 16) 11167 return SDValue(); 11168 break; 11169 } 11170 case ISD::INTRINSIC_W_CHAIN: { 11171 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11172 Chain = Intrin->getChain(); 11173 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 11174 // us what we want. Get operand 2 instead. 11175 Base = Intrin->getOperand(2); 11176 MMO = Intrin->getMemOperand(); 11177 break; 11178 } 11179 } 11180 11181 MVT VecTy = N->getValueType(0).getSimpleVT(); 11182 SDValue LoadOps[] = { Chain, Base }; 11183 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 11184 DAG.getVTList(MVT::v2f64, MVT::Other), 11185 LoadOps, MVT::v2f64, MMO); 11186 11187 DCI.AddToWorklist(Load.getNode()); 11188 Chain = Load.getValue(1); 11189 SDValue Swap = DAG.getNode( 11190 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 11191 DCI.AddToWorklist(Swap.getNode()); 11192 11193 // Add a bitcast if the resulting load type doesn't match v2f64. 11194 if (VecTy != MVT::v2f64) { 11195 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 11196 DCI.AddToWorklist(N.getNode()); 11197 // Package {bitcast value, swap's chain} to match Load's shape. 11198 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 11199 N, Swap.getValue(1)); 11200 } 11201 11202 return Swap; 11203 } 11204 11205 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 11206 // builtins) into stores with swaps. 11207 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 11208 DAGCombinerInfo &DCI) const { 11209 SelectionDAG &DAG = DCI.DAG; 11210 SDLoc dl(N); 11211 SDValue Chain; 11212 SDValue Base; 11213 unsigned SrcOpnd; 11214 MachineMemOperand *MMO; 11215 11216 switch (N->getOpcode()) { 11217 default: 11218 llvm_unreachable("Unexpected opcode for little endian VSX store"); 11219 case ISD::STORE: { 11220 StoreSDNode *ST = cast<StoreSDNode>(N); 11221 Chain = ST->getChain(); 11222 Base = ST->getBasePtr(); 11223 MMO = ST->getMemOperand(); 11224 SrcOpnd = 1; 11225 // If the MMO suggests this isn't a store of a full vector, leave 11226 // things alone. For a built-in, we have to make the change for 11227 // correctness, so if there is a size problem that will be a bug. 11228 if (MMO->getSize() < 16) 11229 return SDValue(); 11230 break; 11231 } 11232 case ISD::INTRINSIC_VOID: { 11233 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11234 Chain = Intrin->getChain(); 11235 // Intrin->getBasePtr() oddly does not get what we want. 11236 Base = Intrin->getOperand(3); 11237 MMO = Intrin->getMemOperand(); 11238 SrcOpnd = 2; 11239 break; 11240 } 11241 } 11242 11243 SDValue Src = N->getOperand(SrcOpnd); 11244 MVT VecTy = Src.getValueType().getSimpleVT(); 11245 11246 // All stores are done as v2f64 and possible bit cast. 11247 if (VecTy != MVT::v2f64) { 11248 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 11249 DCI.AddToWorklist(Src.getNode()); 11250 } 11251 11252 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 11253 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 11254 DCI.AddToWorklist(Swap.getNode()); 11255 Chain = Swap.getValue(1); 11256 SDValue StoreOps[] = { Chain, Swap, Base }; 11257 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 11258 DAG.getVTList(MVT::Other), 11259 StoreOps, VecTy, MMO); 11260 DCI.AddToWorklist(Store.getNode()); 11261 return Store; 11262 } 11263 11264 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 11265 DAGCombinerInfo &DCI) const { 11266 SelectionDAG &DAG = DCI.DAG; 11267 SDLoc dl(N); 11268 switch (N->getOpcode()) { 11269 default: break; 11270 case PPCISD::SHL: 11271 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 11272 return N->getOperand(0); 11273 break; 11274 case PPCISD::SRL: 11275 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 11276 return N->getOperand(0); 11277 break; 11278 case PPCISD::SRA: 11279 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11280 if (C->isNullValue() || // 0 >>s V -> 0. 11281 C->isAllOnesValue()) // -1 >>s V -> -1. 11282 return N->getOperand(0); 11283 } 11284 break; 11285 case ISD::SIGN_EXTEND: 11286 case ISD::ZERO_EXTEND: 11287 case ISD::ANY_EXTEND: 11288 return DAGCombineExtBoolTrunc(N, DCI); 11289 case ISD::TRUNCATE: 11290 case ISD::SETCC: 11291 case ISD::SELECT_CC: 11292 return DAGCombineTruncBoolExt(N, DCI); 11293 case ISD::SINT_TO_FP: 11294 case ISD::UINT_TO_FP: 11295 return combineFPToIntToFP(N, DCI); 11296 case ISD::STORE: { 11297 EVT Op1VT = N->getOperand(1).getValueType(); 11298 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) || 11299 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16)); 11300 11301 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 11302 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 11303 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 11304 ValidTypeForStoreFltAsInt && 11305 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 11306 SDValue Val = N->getOperand(1).getOperand(0); 11307 if (Val.getValueType() == MVT::f32) { 11308 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 11309 DCI.AddToWorklist(Val.getNode()); 11310 } 11311 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 11312 DCI.AddToWorklist(Val.getNode()); 11313 11314 if (Op1VT == MVT::i32) { 11315 SDValue Ops[] = { 11316 N->getOperand(0), Val, N->getOperand(2), 11317 DAG.getValueType(N->getOperand(1).getValueType()) 11318 }; 11319 11320 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 11321 DAG.getVTList(MVT::Other), Ops, 11322 cast<StoreSDNode>(N)->getMemoryVT(), 11323 cast<StoreSDNode>(N)->getMemOperand()); 11324 } else { 11325 unsigned WidthInBytes = 11326 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2; 11327 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false); 11328 11329 SDValue Ops[] = { 11330 N->getOperand(0), Val, N->getOperand(2), WidthConst, 11331 DAG.getValueType(N->getOperand(1).getValueType()) 11332 }; 11333 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl, 11334 DAG.getVTList(MVT::Other), Ops, 11335 cast<StoreSDNode>(N)->getMemoryVT(), 11336 cast<StoreSDNode>(N)->getMemOperand()); 11337 } 11338 11339 DCI.AddToWorklist(Val.getNode()); 11340 return Val; 11341 } 11342 11343 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 11344 if (cast<StoreSDNode>(N)->isUnindexed() && 11345 N->getOperand(1).getOpcode() == ISD::BSWAP && 11346 N->getOperand(1).getNode()->hasOneUse() && 11347 (N->getOperand(1).getValueType() == MVT::i32 || 11348 N->getOperand(1).getValueType() == MVT::i16 || 11349 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 11350 N->getOperand(1).getValueType() == MVT::i64))) { 11351 SDValue BSwapOp = N->getOperand(1).getOperand(0); 11352 // Do an any-extend to 32-bits if this is a half-word input. 11353 if (BSwapOp.getValueType() == MVT::i16) 11354 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 11355 11356 SDValue Ops[] = { 11357 N->getOperand(0), BSwapOp, N->getOperand(2), 11358 DAG.getValueType(N->getOperand(1).getValueType()) 11359 }; 11360 return 11361 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 11362 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 11363 cast<StoreSDNode>(N)->getMemOperand()); 11364 } 11365 11366 // For little endian, VSX stores require generating xxswapd/lxvd2x. 11367 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 11368 EVT VT = N->getOperand(1).getValueType(); 11369 if (VT.isSimple()) { 11370 MVT StoreVT = VT.getSimpleVT(); 11371 if (Subtarget.needsSwapsForVSXMemOps() && 11372 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 11373 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 11374 return expandVSXStoreForLE(N, DCI); 11375 } 11376 break; 11377 } 11378 case ISD::LOAD: { 11379 LoadSDNode *LD = cast<LoadSDNode>(N); 11380 EVT VT = LD->getValueType(0); 11381 11382 // For little endian, VSX loads require generating lxvd2x/xxswapd. 11383 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 11384 if (VT.isSimple()) { 11385 MVT LoadVT = VT.getSimpleVT(); 11386 if (Subtarget.needsSwapsForVSXMemOps() && 11387 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 11388 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 11389 return expandVSXLoadForLE(N, DCI); 11390 } 11391 11392 // We sometimes end up with a 64-bit integer load, from which we extract 11393 // two single-precision floating-point numbers. This happens with 11394 // std::complex<float>, and other similar structures, because of the way we 11395 // canonicalize structure copies. However, if we lack direct moves, 11396 // then the final bitcasts from the extracted integer values to the 11397 // floating-point numbers turn into store/load pairs. Even with direct moves, 11398 // just loading the two floating-point numbers is likely better. 11399 auto ReplaceTwoFloatLoad = [&]() { 11400 if (VT != MVT::i64) 11401 return false; 11402 11403 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 11404 LD->isVolatile()) 11405 return false; 11406 11407 // We're looking for a sequence like this: 11408 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 11409 // t16: i64 = srl t13, Constant:i32<32> 11410 // t17: i32 = truncate t16 11411 // t18: f32 = bitcast t17 11412 // t19: i32 = truncate t13 11413 // t20: f32 = bitcast t19 11414 11415 if (!LD->hasNUsesOfValue(2, 0)) 11416 return false; 11417 11418 auto UI = LD->use_begin(); 11419 while (UI.getUse().getResNo() != 0) ++UI; 11420 SDNode *Trunc = *UI++; 11421 while (UI.getUse().getResNo() != 0) ++UI; 11422 SDNode *RightShift = *UI; 11423 if (Trunc->getOpcode() != ISD::TRUNCATE) 11424 std::swap(Trunc, RightShift); 11425 11426 if (Trunc->getOpcode() != ISD::TRUNCATE || 11427 Trunc->getValueType(0) != MVT::i32 || 11428 !Trunc->hasOneUse()) 11429 return false; 11430 if (RightShift->getOpcode() != ISD::SRL || 11431 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 11432 RightShift->getConstantOperandVal(1) != 32 || 11433 !RightShift->hasOneUse()) 11434 return false; 11435 11436 SDNode *Trunc2 = *RightShift->use_begin(); 11437 if (Trunc2->getOpcode() != ISD::TRUNCATE || 11438 Trunc2->getValueType(0) != MVT::i32 || 11439 !Trunc2->hasOneUse()) 11440 return false; 11441 11442 SDNode *Bitcast = *Trunc->use_begin(); 11443 SDNode *Bitcast2 = *Trunc2->use_begin(); 11444 11445 if (Bitcast->getOpcode() != ISD::BITCAST || 11446 Bitcast->getValueType(0) != MVT::f32) 11447 return false; 11448 if (Bitcast2->getOpcode() != ISD::BITCAST || 11449 Bitcast2->getValueType(0) != MVT::f32) 11450 return false; 11451 11452 if (Subtarget.isLittleEndian()) 11453 std::swap(Bitcast, Bitcast2); 11454 11455 // Bitcast has the second float (in memory-layout order) and Bitcast2 11456 // has the first one. 11457 11458 SDValue BasePtr = LD->getBasePtr(); 11459 if (LD->isIndexed()) { 11460 assert(LD->getAddressingMode() == ISD::PRE_INC && 11461 "Non-pre-inc AM on PPC?"); 11462 BasePtr = 11463 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 11464 LD->getOffset()); 11465 } 11466 11467 auto MMOFlags = 11468 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 11469 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 11470 LD->getPointerInfo(), LD->getAlignment(), 11471 MMOFlags, LD->getAAInfo()); 11472 SDValue AddPtr = 11473 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 11474 BasePtr, DAG.getIntPtrConstant(4, dl)); 11475 SDValue FloatLoad2 = DAG.getLoad( 11476 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 11477 LD->getPointerInfo().getWithOffset(4), 11478 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 11479 11480 if (LD->isIndexed()) { 11481 // Note that DAGCombine should re-form any pre-increment load(s) from 11482 // what is produced here if that makes sense. 11483 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 11484 } 11485 11486 DCI.CombineTo(Bitcast2, FloatLoad); 11487 DCI.CombineTo(Bitcast, FloatLoad2); 11488 11489 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 11490 SDValue(FloatLoad2.getNode(), 1)); 11491 return true; 11492 }; 11493 11494 if (ReplaceTwoFloatLoad()) 11495 return SDValue(N, 0); 11496 11497 EVT MemVT = LD->getMemoryVT(); 11498 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 11499 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 11500 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 11501 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 11502 if (LD->isUnindexed() && VT.isVector() && 11503 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 11504 // P8 and later hardware should just use LOAD. 11505 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 11506 VT == MVT::v4i32 || VT == MVT::v4f32)) || 11507 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 11508 LD->getAlignment() >= ScalarABIAlignment)) && 11509 LD->getAlignment() < ABIAlignment) { 11510 // This is a type-legal unaligned Altivec or QPX load. 11511 SDValue Chain = LD->getChain(); 11512 SDValue Ptr = LD->getBasePtr(); 11513 bool isLittleEndian = Subtarget.isLittleEndian(); 11514 11515 // This implements the loading of unaligned vectors as described in 11516 // the venerable Apple Velocity Engine overview. Specifically: 11517 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 11518 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 11519 // 11520 // The general idea is to expand a sequence of one or more unaligned 11521 // loads into an alignment-based permutation-control instruction (lvsl 11522 // or lvsr), a series of regular vector loads (which always truncate 11523 // their input address to an aligned address), and a series of 11524 // permutations. The results of these permutations are the requested 11525 // loaded values. The trick is that the last "extra" load is not taken 11526 // from the address you might suspect (sizeof(vector) bytes after the 11527 // last requested load), but rather sizeof(vector) - 1 bytes after the 11528 // last requested vector. The point of this is to avoid a page fault if 11529 // the base address happened to be aligned. This works because if the 11530 // base address is aligned, then adding less than a full vector length 11531 // will cause the last vector in the sequence to be (re)loaded. 11532 // Otherwise, the next vector will be fetched as you might suspect was 11533 // necessary. 11534 11535 // We might be able to reuse the permutation generation from 11536 // a different base address offset from this one by an aligned amount. 11537 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 11538 // optimization later. 11539 Intrinsic::ID Intr, IntrLD, IntrPerm; 11540 MVT PermCntlTy, PermTy, LDTy; 11541 if (Subtarget.hasAltivec()) { 11542 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 11543 Intrinsic::ppc_altivec_lvsl; 11544 IntrLD = Intrinsic::ppc_altivec_lvx; 11545 IntrPerm = Intrinsic::ppc_altivec_vperm; 11546 PermCntlTy = MVT::v16i8; 11547 PermTy = MVT::v4i32; 11548 LDTy = MVT::v4i32; 11549 } else { 11550 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 11551 Intrinsic::ppc_qpx_qvlpcls; 11552 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 11553 Intrinsic::ppc_qpx_qvlfs; 11554 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 11555 PermCntlTy = MVT::v4f64; 11556 PermTy = MVT::v4f64; 11557 LDTy = MemVT.getSimpleVT(); 11558 } 11559 11560 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 11561 11562 // Create the new MMO for the new base load. It is like the original MMO, 11563 // but represents an area in memory almost twice the vector size centered 11564 // on the original address. If the address is unaligned, we might start 11565 // reading up to (sizeof(vector)-1) bytes below the address of the 11566 // original unaligned load. 11567 MachineFunction &MF = DAG.getMachineFunction(); 11568 MachineMemOperand *BaseMMO = 11569 MF.getMachineMemOperand(LD->getMemOperand(), 11570 -(long)MemVT.getStoreSize()+1, 11571 2*MemVT.getStoreSize()-1); 11572 11573 // Create the new base load. 11574 SDValue LDXIntID = 11575 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 11576 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 11577 SDValue BaseLoad = 11578 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 11579 DAG.getVTList(PermTy, MVT::Other), 11580 BaseLoadOps, LDTy, BaseMMO); 11581 11582 // Note that the value of IncOffset (which is provided to the next 11583 // load's pointer info offset value, and thus used to calculate the 11584 // alignment), and the value of IncValue (which is actually used to 11585 // increment the pointer value) are different! This is because we 11586 // require the next load to appear to be aligned, even though it 11587 // is actually offset from the base pointer by a lesser amount. 11588 int IncOffset = VT.getSizeInBits() / 8; 11589 int IncValue = IncOffset; 11590 11591 // Walk (both up and down) the chain looking for another load at the real 11592 // (aligned) offset (the alignment of the other load does not matter in 11593 // this case). If found, then do not use the offset reduction trick, as 11594 // that will prevent the loads from being later combined (as they would 11595 // otherwise be duplicates). 11596 if (!findConsecutiveLoad(LD, DAG)) 11597 --IncValue; 11598 11599 SDValue Increment = 11600 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 11601 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 11602 11603 MachineMemOperand *ExtraMMO = 11604 MF.getMachineMemOperand(LD->getMemOperand(), 11605 1, 2*MemVT.getStoreSize()-1); 11606 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 11607 SDValue ExtraLoad = 11608 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 11609 DAG.getVTList(PermTy, MVT::Other), 11610 ExtraLoadOps, LDTy, ExtraMMO); 11611 11612 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 11613 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 11614 11615 // Because vperm has a big-endian bias, we must reverse the order 11616 // of the input vectors and complement the permute control vector 11617 // when generating little endian code. We have already handled the 11618 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 11619 // and ExtraLoad here. 11620 SDValue Perm; 11621 if (isLittleEndian) 11622 Perm = BuildIntrinsicOp(IntrPerm, 11623 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 11624 else 11625 Perm = BuildIntrinsicOp(IntrPerm, 11626 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 11627 11628 if (VT != PermTy) 11629 Perm = Subtarget.hasAltivec() ? 11630 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 11631 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 11632 DAG.getTargetConstant(1, dl, MVT::i64)); 11633 // second argument is 1 because this rounding 11634 // is always exact. 11635 11636 // The output of the permutation is our loaded result, the TokenFactor is 11637 // our new chain. 11638 DCI.CombineTo(N, Perm, TF); 11639 return SDValue(N, 0); 11640 } 11641 } 11642 break; 11643 case ISD::INTRINSIC_WO_CHAIN: { 11644 bool isLittleEndian = Subtarget.isLittleEndian(); 11645 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11646 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 11647 : Intrinsic::ppc_altivec_lvsl); 11648 if ((IID == Intr || 11649 IID == Intrinsic::ppc_qpx_qvlpcld || 11650 IID == Intrinsic::ppc_qpx_qvlpcls) && 11651 N->getOperand(1)->getOpcode() == ISD::ADD) { 11652 SDValue Add = N->getOperand(1); 11653 11654 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 11655 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 11656 11657 if (DAG.MaskedValueIsZero(Add->getOperand(1), 11658 APInt::getAllOnesValue(Bits /* alignment */) 11659 .zext(Add.getScalarValueSizeInBits()))) { 11660 SDNode *BasePtr = Add->getOperand(0).getNode(); 11661 for (SDNode::use_iterator UI = BasePtr->use_begin(), 11662 UE = BasePtr->use_end(); 11663 UI != UE; ++UI) { 11664 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 11665 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 11666 // We've found another LVSL/LVSR, and this address is an aligned 11667 // multiple of that one. The results will be the same, so use the 11668 // one we've just found instead. 11669 11670 return SDValue(*UI, 0); 11671 } 11672 } 11673 } 11674 11675 if (isa<ConstantSDNode>(Add->getOperand(1))) { 11676 SDNode *BasePtr = Add->getOperand(0).getNode(); 11677 for (SDNode::use_iterator UI = BasePtr->use_begin(), 11678 UE = BasePtr->use_end(); UI != UE; ++UI) { 11679 if (UI->getOpcode() == ISD::ADD && 11680 isa<ConstantSDNode>(UI->getOperand(1)) && 11681 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 11682 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 11683 (1ULL << Bits) == 0) { 11684 SDNode *OtherAdd = *UI; 11685 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 11686 VE = OtherAdd->use_end(); VI != VE; ++VI) { 11687 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 11688 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 11689 return SDValue(*VI, 0); 11690 } 11691 } 11692 } 11693 } 11694 } 11695 } 11696 } 11697 11698 break; 11699 case ISD::INTRINSIC_W_CHAIN: 11700 // For little endian, VSX loads require generating lxvd2x/xxswapd. 11701 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 11702 if (Subtarget.needsSwapsForVSXMemOps()) { 11703 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11704 default: 11705 break; 11706 case Intrinsic::ppc_vsx_lxvw4x: 11707 case Intrinsic::ppc_vsx_lxvd2x: 11708 return expandVSXLoadForLE(N, DCI); 11709 } 11710 } 11711 break; 11712 case ISD::INTRINSIC_VOID: 11713 // For little endian, VSX stores require generating xxswapd/stxvd2x. 11714 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 11715 if (Subtarget.needsSwapsForVSXMemOps()) { 11716 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11717 default: 11718 break; 11719 case Intrinsic::ppc_vsx_stxvw4x: 11720 case Intrinsic::ppc_vsx_stxvd2x: 11721 return expandVSXStoreForLE(N, DCI); 11722 } 11723 } 11724 break; 11725 case ISD::BSWAP: 11726 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 11727 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 11728 N->getOperand(0).hasOneUse() && 11729 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 11730 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 11731 N->getValueType(0) == MVT::i64))) { 11732 SDValue Load = N->getOperand(0); 11733 LoadSDNode *LD = cast<LoadSDNode>(Load); 11734 // Create the byte-swapping load. 11735 SDValue Ops[] = { 11736 LD->getChain(), // Chain 11737 LD->getBasePtr(), // Ptr 11738 DAG.getValueType(N->getValueType(0)) // VT 11739 }; 11740 SDValue BSLoad = 11741 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 11742 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 11743 MVT::i64 : MVT::i32, MVT::Other), 11744 Ops, LD->getMemoryVT(), LD->getMemOperand()); 11745 11746 // If this is an i16 load, insert the truncate. 11747 SDValue ResVal = BSLoad; 11748 if (N->getValueType(0) == MVT::i16) 11749 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 11750 11751 // First, combine the bswap away. This makes the value produced by the 11752 // load dead. 11753 DCI.CombineTo(N, ResVal); 11754 11755 // Next, combine the load away, we give it a bogus result value but a real 11756 // chain result. The result value is dead because the bswap is dead. 11757 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 11758 11759 // Return N so it doesn't get rechecked! 11760 return SDValue(N, 0); 11761 } 11762 break; 11763 case PPCISD::VCMP: 11764 // If a VCMPo node already exists with exactly the same operands as this 11765 // node, use its result instead of this node (VCMPo computes both a CR6 and 11766 // a normal output). 11767 // 11768 if (!N->getOperand(0).hasOneUse() && 11769 !N->getOperand(1).hasOneUse() && 11770 !N->getOperand(2).hasOneUse()) { 11771 11772 // Scan all of the users of the LHS, looking for VCMPo's that match. 11773 SDNode *VCMPoNode = nullptr; 11774 11775 SDNode *LHSN = N->getOperand(0).getNode(); 11776 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 11777 UI != E; ++UI) 11778 if (UI->getOpcode() == PPCISD::VCMPo && 11779 UI->getOperand(1) == N->getOperand(1) && 11780 UI->getOperand(2) == N->getOperand(2) && 11781 UI->getOperand(0) == N->getOperand(0)) { 11782 VCMPoNode = *UI; 11783 break; 11784 } 11785 11786 // If there is no VCMPo node, or if the flag value has a single use, don't 11787 // transform this. 11788 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 11789 break; 11790 11791 // Look at the (necessarily single) use of the flag value. If it has a 11792 // chain, this transformation is more complex. Note that multiple things 11793 // could use the value result, which we should ignore. 11794 SDNode *FlagUser = nullptr; 11795 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 11796 FlagUser == nullptr; ++UI) { 11797 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 11798 SDNode *User = *UI; 11799 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 11800 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 11801 FlagUser = User; 11802 break; 11803 } 11804 } 11805 } 11806 11807 // If the user is a MFOCRF instruction, we know this is safe. 11808 // Otherwise we give up for right now. 11809 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 11810 return SDValue(VCMPoNode, 0); 11811 } 11812 break; 11813 case ISD::BRCOND: { 11814 SDValue Cond = N->getOperand(1); 11815 SDValue Target = N->getOperand(2); 11816 11817 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 11818 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 11819 Intrinsic::ppc_is_decremented_ctr_nonzero) { 11820 11821 // We now need to make the intrinsic dead (it cannot be instruction 11822 // selected). 11823 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 11824 assert(Cond.getNode()->hasOneUse() && 11825 "Counter decrement has more than one use"); 11826 11827 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 11828 N->getOperand(0), Target); 11829 } 11830 } 11831 break; 11832 case ISD::BR_CC: { 11833 // If this is a branch on an altivec predicate comparison, lower this so 11834 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 11835 // lowering is done pre-legalize, because the legalizer lowers the predicate 11836 // compare down to code that is difficult to reassemble. 11837 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 11838 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 11839 11840 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 11841 // value. If so, pass-through the AND to get to the intrinsic. 11842 if (LHS.getOpcode() == ISD::AND && 11843 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 11844 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 11845 Intrinsic::ppc_is_decremented_ctr_nonzero && 11846 isa<ConstantSDNode>(LHS.getOperand(1)) && 11847 !isNullConstant(LHS.getOperand(1))) 11848 LHS = LHS.getOperand(0); 11849 11850 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 11851 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 11852 Intrinsic::ppc_is_decremented_ctr_nonzero && 11853 isa<ConstantSDNode>(RHS)) { 11854 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 11855 "Counter decrement comparison is not EQ or NE"); 11856 11857 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 11858 bool isBDNZ = (CC == ISD::SETEQ && Val) || 11859 (CC == ISD::SETNE && !Val); 11860 11861 // We now need to make the intrinsic dead (it cannot be instruction 11862 // selected). 11863 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 11864 assert(LHS.getNode()->hasOneUse() && 11865 "Counter decrement has more than one use"); 11866 11867 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 11868 N->getOperand(0), N->getOperand(4)); 11869 } 11870 11871 int CompareOpc; 11872 bool isDot; 11873 11874 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 11875 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 11876 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 11877 assert(isDot && "Can't compare against a vector result!"); 11878 11879 // If this is a comparison against something other than 0/1, then we know 11880 // that the condition is never/always true. 11881 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 11882 if (Val != 0 && Val != 1) { 11883 if (CC == ISD::SETEQ) // Cond never true, remove branch. 11884 return N->getOperand(0); 11885 // Always !=, turn it into an unconditional branch. 11886 return DAG.getNode(ISD::BR, dl, MVT::Other, 11887 N->getOperand(0), N->getOperand(4)); 11888 } 11889 11890 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 11891 11892 // Create the PPCISD altivec 'dot' comparison node. 11893 SDValue Ops[] = { 11894 LHS.getOperand(2), // LHS of compare 11895 LHS.getOperand(3), // RHS of compare 11896 DAG.getConstant(CompareOpc, dl, MVT::i32) 11897 }; 11898 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 11899 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 11900 11901 // Unpack the result based on how the target uses it. 11902 PPC::Predicate CompOpc; 11903 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 11904 default: // Can't happen, don't crash on invalid number though. 11905 case 0: // Branch on the value of the EQ bit of CR6. 11906 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 11907 break; 11908 case 1: // Branch on the inverted value of the EQ bit of CR6. 11909 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 11910 break; 11911 case 2: // Branch on the value of the LT bit of CR6. 11912 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 11913 break; 11914 case 3: // Branch on the inverted value of the LT bit of CR6. 11915 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 11916 break; 11917 } 11918 11919 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 11920 DAG.getConstant(CompOpc, dl, MVT::i32), 11921 DAG.getRegister(PPC::CR6, MVT::i32), 11922 N->getOperand(4), CompNode.getValue(1)); 11923 } 11924 break; 11925 } 11926 case ISD::BUILD_VECTOR: 11927 return DAGCombineBuildVector(N, DCI); 11928 } 11929 11930 return SDValue(); 11931 } 11932 11933 SDValue 11934 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11935 SelectionDAG &DAG, 11936 std::vector<SDNode *> *Created) const { 11937 // fold (sdiv X, pow2) 11938 EVT VT = N->getValueType(0); 11939 if (VT == MVT::i64 && !Subtarget.isPPC64()) 11940 return SDValue(); 11941 if ((VT != MVT::i32 && VT != MVT::i64) || 11942 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 11943 return SDValue(); 11944 11945 SDLoc DL(N); 11946 SDValue N0 = N->getOperand(0); 11947 11948 bool IsNegPow2 = (-Divisor).isPowerOf2(); 11949 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 11950 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 11951 11952 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 11953 if (Created) 11954 Created->push_back(Op.getNode()); 11955 11956 if (IsNegPow2) { 11957 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 11958 if (Created) 11959 Created->push_back(Op.getNode()); 11960 } 11961 11962 return Op; 11963 } 11964 11965 //===----------------------------------------------------------------------===// 11966 // Inline Assembly Support 11967 //===----------------------------------------------------------------------===// 11968 11969 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 11970 APInt &KnownZero, 11971 APInt &KnownOne, 11972 const SelectionDAG &DAG, 11973 unsigned Depth) const { 11974 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0); 11975 switch (Op.getOpcode()) { 11976 default: break; 11977 case PPCISD::LBRX: { 11978 // lhbrx is known to have the top bits cleared out. 11979 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 11980 KnownZero = 0xFFFF0000; 11981 break; 11982 } 11983 case ISD::INTRINSIC_WO_CHAIN: { 11984 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 11985 default: break; 11986 case Intrinsic::ppc_altivec_vcmpbfp_p: 11987 case Intrinsic::ppc_altivec_vcmpeqfp_p: 11988 case Intrinsic::ppc_altivec_vcmpequb_p: 11989 case Intrinsic::ppc_altivec_vcmpequh_p: 11990 case Intrinsic::ppc_altivec_vcmpequw_p: 11991 case Intrinsic::ppc_altivec_vcmpequd_p: 11992 case Intrinsic::ppc_altivec_vcmpgefp_p: 11993 case Intrinsic::ppc_altivec_vcmpgtfp_p: 11994 case Intrinsic::ppc_altivec_vcmpgtsb_p: 11995 case Intrinsic::ppc_altivec_vcmpgtsh_p: 11996 case Intrinsic::ppc_altivec_vcmpgtsw_p: 11997 case Intrinsic::ppc_altivec_vcmpgtsd_p: 11998 case Intrinsic::ppc_altivec_vcmpgtub_p: 11999 case Intrinsic::ppc_altivec_vcmpgtuh_p: 12000 case Intrinsic::ppc_altivec_vcmpgtuw_p: 12001 case Intrinsic::ppc_altivec_vcmpgtud_p: 12002 KnownZero = ~1U; // All bits but the low one are known to be zero. 12003 break; 12004 } 12005 } 12006 } 12007 } 12008 12009 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12010 switch (Subtarget.getDarwinDirective()) { 12011 default: break; 12012 case PPC::DIR_970: 12013 case PPC::DIR_PWR4: 12014 case PPC::DIR_PWR5: 12015 case PPC::DIR_PWR5X: 12016 case PPC::DIR_PWR6: 12017 case PPC::DIR_PWR6X: 12018 case PPC::DIR_PWR7: 12019 case PPC::DIR_PWR8: 12020 case PPC::DIR_PWR9: { 12021 if (!ML) 12022 break; 12023 12024 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 12025 12026 // For small loops (between 5 and 8 instructions), align to a 32-byte 12027 // boundary so that the entire loop fits in one instruction-cache line. 12028 uint64_t LoopSize = 0; 12029 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 12030 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 12031 LoopSize += TII->getInstSizeInBytes(*J); 12032 if (LoopSize > 32) 12033 break; 12034 } 12035 12036 if (LoopSize > 16 && LoopSize <= 32) 12037 return 5; 12038 12039 break; 12040 } 12041 } 12042 12043 return TargetLowering::getPrefLoopAlignment(ML); 12044 } 12045 12046 /// getConstraintType - Given a constraint, return the type of 12047 /// constraint it is for this target. 12048 PPCTargetLowering::ConstraintType 12049 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 12050 if (Constraint.size() == 1) { 12051 switch (Constraint[0]) { 12052 default: break; 12053 case 'b': 12054 case 'r': 12055 case 'f': 12056 case 'd': 12057 case 'v': 12058 case 'y': 12059 return C_RegisterClass; 12060 case 'Z': 12061 // FIXME: While Z does indicate a memory constraint, it specifically 12062 // indicates an r+r address (used in conjunction with the 'y' modifier 12063 // in the replacement string). Currently, we're forcing the base 12064 // register to be r0 in the asm printer (which is interpreted as zero) 12065 // and forming the complete address in the second register. This is 12066 // suboptimal. 12067 return C_Memory; 12068 } 12069 } else if (Constraint == "wc") { // individual CR bits. 12070 return C_RegisterClass; 12071 } else if (Constraint == "wa" || Constraint == "wd" || 12072 Constraint == "wf" || Constraint == "ws") { 12073 return C_RegisterClass; // VSX registers. 12074 } 12075 return TargetLowering::getConstraintType(Constraint); 12076 } 12077 12078 /// Examine constraint type and operand type and determine a weight value. 12079 /// This object must already have been set up with the operand type 12080 /// and the current alternative constraint selected. 12081 TargetLowering::ConstraintWeight 12082 PPCTargetLowering::getSingleConstraintMatchWeight( 12083 AsmOperandInfo &info, const char *constraint) const { 12084 ConstraintWeight weight = CW_Invalid; 12085 Value *CallOperandVal = info.CallOperandVal; 12086 // If we don't have a value, we can't do a match, 12087 // but allow it at the lowest weight. 12088 if (!CallOperandVal) 12089 return CW_Default; 12090 Type *type = CallOperandVal->getType(); 12091 12092 // Look at the constraint type. 12093 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 12094 return CW_Register; // an individual CR bit. 12095 else if ((StringRef(constraint) == "wa" || 12096 StringRef(constraint) == "wd" || 12097 StringRef(constraint) == "wf") && 12098 type->isVectorTy()) 12099 return CW_Register; 12100 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 12101 return CW_Register; 12102 12103 switch (*constraint) { 12104 default: 12105 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12106 break; 12107 case 'b': 12108 if (type->isIntegerTy()) 12109 weight = CW_Register; 12110 break; 12111 case 'f': 12112 if (type->isFloatTy()) 12113 weight = CW_Register; 12114 break; 12115 case 'd': 12116 if (type->isDoubleTy()) 12117 weight = CW_Register; 12118 break; 12119 case 'v': 12120 if (type->isVectorTy()) 12121 weight = CW_Register; 12122 break; 12123 case 'y': 12124 weight = CW_Register; 12125 break; 12126 case 'Z': 12127 weight = CW_Memory; 12128 break; 12129 } 12130 return weight; 12131 } 12132 12133 std::pair<unsigned, const TargetRegisterClass *> 12134 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 12135 StringRef Constraint, 12136 MVT VT) const { 12137 if (Constraint.size() == 1) { 12138 // GCC RS6000 Constraint Letters 12139 switch (Constraint[0]) { 12140 case 'b': // R1-R31 12141 if (VT == MVT::i64 && Subtarget.isPPC64()) 12142 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 12143 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 12144 case 'r': // R0-R31 12145 if (VT == MVT::i64 && Subtarget.isPPC64()) 12146 return std::make_pair(0U, &PPC::G8RCRegClass); 12147 return std::make_pair(0U, &PPC::GPRCRegClass); 12148 // 'd' and 'f' constraints are both defined to be "the floating point 12149 // registers", where one is for 32-bit and the other for 64-bit. We don't 12150 // really care overly much here so just give them all the same reg classes. 12151 case 'd': 12152 case 'f': 12153 if (VT == MVT::f32 || VT == MVT::i32) 12154 return std::make_pair(0U, &PPC::F4RCRegClass); 12155 if (VT == MVT::f64 || VT == MVT::i64) 12156 return std::make_pair(0U, &PPC::F8RCRegClass); 12157 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 12158 return std::make_pair(0U, &PPC::QFRCRegClass); 12159 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 12160 return std::make_pair(0U, &PPC::QSRCRegClass); 12161 break; 12162 case 'v': 12163 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 12164 return std::make_pair(0U, &PPC::QFRCRegClass); 12165 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 12166 return std::make_pair(0U, &PPC::QSRCRegClass); 12167 if (Subtarget.hasAltivec()) 12168 return std::make_pair(0U, &PPC::VRRCRegClass); 12169 case 'y': // crrc 12170 return std::make_pair(0U, &PPC::CRRCRegClass); 12171 } 12172 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 12173 // An individual CR bit. 12174 return std::make_pair(0U, &PPC::CRBITRCRegClass); 12175 } else if ((Constraint == "wa" || Constraint == "wd" || 12176 Constraint == "wf") && Subtarget.hasVSX()) { 12177 return std::make_pair(0U, &PPC::VSRCRegClass); 12178 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 12179 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 12180 return std::make_pair(0U, &PPC::VSSRCRegClass); 12181 else 12182 return std::make_pair(0U, &PPC::VSFRCRegClass); 12183 } 12184 12185 std::pair<unsigned, const TargetRegisterClass *> R = 12186 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12187 12188 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 12189 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 12190 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 12191 // register. 12192 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 12193 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 12194 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 12195 PPC::GPRCRegClass.contains(R.first)) 12196 return std::make_pair(TRI->getMatchingSuperReg(R.first, 12197 PPC::sub_32, &PPC::G8RCRegClass), 12198 &PPC::G8RCRegClass); 12199 12200 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 12201 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 12202 R.first = PPC::CR0; 12203 R.second = &PPC::CRRCRegClass; 12204 } 12205 12206 return R; 12207 } 12208 12209 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12210 /// vector. If it is invalid, don't add anything to Ops. 12211 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12212 std::string &Constraint, 12213 std::vector<SDValue>&Ops, 12214 SelectionDAG &DAG) const { 12215 SDValue Result; 12216 12217 // Only support length 1 constraints. 12218 if (Constraint.length() > 1) return; 12219 12220 char Letter = Constraint[0]; 12221 switch (Letter) { 12222 default: break; 12223 case 'I': 12224 case 'J': 12225 case 'K': 12226 case 'L': 12227 case 'M': 12228 case 'N': 12229 case 'O': 12230 case 'P': { 12231 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 12232 if (!CST) return; // Must be an immediate to match. 12233 SDLoc dl(Op); 12234 int64_t Value = CST->getSExtValue(); 12235 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 12236 // numbers are printed as such. 12237 switch (Letter) { 12238 default: llvm_unreachable("Unknown constraint letter!"); 12239 case 'I': // "I" is a signed 16-bit constant. 12240 if (isInt<16>(Value)) 12241 Result = DAG.getTargetConstant(Value, dl, TCVT); 12242 break; 12243 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 12244 if (isShiftedUInt<16, 16>(Value)) 12245 Result = DAG.getTargetConstant(Value, dl, TCVT); 12246 break; 12247 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 12248 if (isShiftedInt<16, 16>(Value)) 12249 Result = DAG.getTargetConstant(Value, dl, TCVT); 12250 break; 12251 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 12252 if (isUInt<16>(Value)) 12253 Result = DAG.getTargetConstant(Value, dl, TCVT); 12254 break; 12255 case 'M': // "M" is a constant that is greater than 31. 12256 if (Value > 31) 12257 Result = DAG.getTargetConstant(Value, dl, TCVT); 12258 break; 12259 case 'N': // "N" is a positive constant that is an exact power of two. 12260 if (Value > 0 && isPowerOf2_64(Value)) 12261 Result = DAG.getTargetConstant(Value, dl, TCVT); 12262 break; 12263 case 'O': // "O" is the constant zero. 12264 if (Value == 0) 12265 Result = DAG.getTargetConstant(Value, dl, TCVT); 12266 break; 12267 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 12268 if (isInt<16>(-Value)) 12269 Result = DAG.getTargetConstant(Value, dl, TCVT); 12270 break; 12271 } 12272 break; 12273 } 12274 } 12275 12276 if (Result.getNode()) { 12277 Ops.push_back(Result); 12278 return; 12279 } 12280 12281 // Handle standard constraint letters. 12282 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12283 } 12284 12285 // isLegalAddressingMode - Return true if the addressing mode represented 12286 // by AM is legal for this target, for a load/store of the specified type. 12287 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12288 const AddrMode &AM, Type *Ty, 12289 unsigned AS) const { 12290 // PPC does not allow r+i addressing modes for vectors! 12291 if (Ty->isVectorTy() && AM.BaseOffs != 0) 12292 return false; 12293 12294 // PPC allows a sign-extended 16-bit immediate field. 12295 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 12296 return false; 12297 12298 // No global is ever allowed as a base. 12299 if (AM.BaseGV) 12300 return false; 12301 12302 // PPC only support r+r, 12303 switch (AM.Scale) { 12304 case 0: // "r+i" or just "i", depending on HasBaseReg. 12305 break; 12306 case 1: 12307 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 12308 return false; 12309 // Otherwise we have r+r or r+i. 12310 break; 12311 case 2: 12312 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 12313 return false; 12314 // Allow 2*r as r+r. 12315 break; 12316 default: 12317 // No other scales are supported. 12318 return false; 12319 } 12320 12321 return true; 12322 } 12323 12324 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 12325 SelectionDAG &DAG) const { 12326 MachineFunction &MF = DAG.getMachineFunction(); 12327 MachineFrameInfo &MFI = MF.getFrameInfo(); 12328 MFI.setReturnAddressIsTaken(true); 12329 12330 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 12331 return SDValue(); 12332 12333 SDLoc dl(Op); 12334 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12335 12336 // Make sure the function does not optimize away the store of the RA to 12337 // the stack. 12338 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 12339 FuncInfo->setLRStoreRequired(); 12340 bool isPPC64 = Subtarget.isPPC64(); 12341 auto PtrVT = getPointerTy(MF.getDataLayout()); 12342 12343 if (Depth > 0) { 12344 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 12345 SDValue Offset = 12346 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 12347 isPPC64 ? MVT::i64 : MVT::i32); 12348 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 12349 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 12350 MachinePointerInfo()); 12351 } 12352 12353 // Just load the return address off the stack. 12354 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 12355 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 12356 MachinePointerInfo()); 12357 } 12358 12359 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 12360 SelectionDAG &DAG) const { 12361 SDLoc dl(Op); 12362 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12363 12364 MachineFunction &MF = DAG.getMachineFunction(); 12365 MachineFrameInfo &MFI = MF.getFrameInfo(); 12366 MFI.setFrameAddressIsTaken(true); 12367 12368 EVT PtrVT = getPointerTy(MF.getDataLayout()); 12369 bool isPPC64 = PtrVT == MVT::i64; 12370 12371 // Naked functions never have a frame pointer, and so we use r1. For all 12372 // other functions, this decision must be delayed until during PEI. 12373 unsigned FrameReg; 12374 if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) 12375 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 12376 else 12377 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 12378 12379 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 12380 PtrVT); 12381 while (Depth--) 12382 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 12383 FrameAddr, MachinePointerInfo()); 12384 return FrameAddr; 12385 } 12386 12387 // FIXME? Maybe this could be a TableGen attribute on some registers and 12388 // this table could be generated automatically from RegInfo. 12389 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 12390 SelectionDAG &DAG) const { 12391 bool isPPC64 = Subtarget.isPPC64(); 12392 bool isDarwinABI = Subtarget.isDarwinABI(); 12393 12394 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 12395 (!isPPC64 && VT != MVT::i32)) 12396 report_fatal_error("Invalid register global variable type"); 12397 12398 bool is64Bit = isPPC64 && VT == MVT::i64; 12399 unsigned Reg = StringSwitch<unsigned>(RegName) 12400 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 12401 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 12402 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 12403 (is64Bit ? PPC::X13 : PPC::R13)) 12404 .Default(0); 12405 12406 if (Reg) 12407 return Reg; 12408 report_fatal_error("Invalid register name global variable"); 12409 } 12410 12411 bool 12412 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12413 // The PowerPC target isn't yet aware of offsets. 12414 return false; 12415 } 12416 12417 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12418 const CallInst &I, 12419 unsigned Intrinsic) const { 12420 switch (Intrinsic) { 12421 case Intrinsic::ppc_qpx_qvlfd: 12422 case Intrinsic::ppc_qpx_qvlfs: 12423 case Intrinsic::ppc_qpx_qvlfcd: 12424 case Intrinsic::ppc_qpx_qvlfcs: 12425 case Intrinsic::ppc_qpx_qvlfiwa: 12426 case Intrinsic::ppc_qpx_qvlfiwz: 12427 case Intrinsic::ppc_altivec_lvx: 12428 case Intrinsic::ppc_altivec_lvxl: 12429 case Intrinsic::ppc_altivec_lvebx: 12430 case Intrinsic::ppc_altivec_lvehx: 12431 case Intrinsic::ppc_altivec_lvewx: 12432 case Intrinsic::ppc_vsx_lxvd2x: 12433 case Intrinsic::ppc_vsx_lxvw4x: { 12434 EVT VT; 12435 switch (Intrinsic) { 12436 case Intrinsic::ppc_altivec_lvebx: 12437 VT = MVT::i8; 12438 break; 12439 case Intrinsic::ppc_altivec_lvehx: 12440 VT = MVT::i16; 12441 break; 12442 case Intrinsic::ppc_altivec_lvewx: 12443 VT = MVT::i32; 12444 break; 12445 case Intrinsic::ppc_vsx_lxvd2x: 12446 VT = MVT::v2f64; 12447 break; 12448 case Intrinsic::ppc_qpx_qvlfd: 12449 VT = MVT::v4f64; 12450 break; 12451 case Intrinsic::ppc_qpx_qvlfs: 12452 VT = MVT::v4f32; 12453 break; 12454 case Intrinsic::ppc_qpx_qvlfcd: 12455 VT = MVT::v2f64; 12456 break; 12457 case Intrinsic::ppc_qpx_qvlfcs: 12458 VT = MVT::v2f32; 12459 break; 12460 default: 12461 VT = MVT::v4i32; 12462 break; 12463 } 12464 12465 Info.opc = ISD::INTRINSIC_W_CHAIN; 12466 Info.memVT = VT; 12467 Info.ptrVal = I.getArgOperand(0); 12468 Info.offset = -VT.getStoreSize()+1; 12469 Info.size = 2*VT.getStoreSize()-1; 12470 Info.align = 1; 12471 Info.vol = false; 12472 Info.readMem = true; 12473 Info.writeMem = false; 12474 return true; 12475 } 12476 case Intrinsic::ppc_qpx_qvlfda: 12477 case Intrinsic::ppc_qpx_qvlfsa: 12478 case Intrinsic::ppc_qpx_qvlfcda: 12479 case Intrinsic::ppc_qpx_qvlfcsa: 12480 case Intrinsic::ppc_qpx_qvlfiwaa: 12481 case Intrinsic::ppc_qpx_qvlfiwza: { 12482 EVT VT; 12483 switch (Intrinsic) { 12484 case Intrinsic::ppc_qpx_qvlfda: 12485 VT = MVT::v4f64; 12486 break; 12487 case Intrinsic::ppc_qpx_qvlfsa: 12488 VT = MVT::v4f32; 12489 break; 12490 case Intrinsic::ppc_qpx_qvlfcda: 12491 VT = MVT::v2f64; 12492 break; 12493 case Intrinsic::ppc_qpx_qvlfcsa: 12494 VT = MVT::v2f32; 12495 break; 12496 default: 12497 VT = MVT::v4i32; 12498 break; 12499 } 12500 12501 Info.opc = ISD::INTRINSIC_W_CHAIN; 12502 Info.memVT = VT; 12503 Info.ptrVal = I.getArgOperand(0); 12504 Info.offset = 0; 12505 Info.size = VT.getStoreSize(); 12506 Info.align = 1; 12507 Info.vol = false; 12508 Info.readMem = true; 12509 Info.writeMem = false; 12510 return true; 12511 } 12512 case Intrinsic::ppc_qpx_qvstfd: 12513 case Intrinsic::ppc_qpx_qvstfs: 12514 case Intrinsic::ppc_qpx_qvstfcd: 12515 case Intrinsic::ppc_qpx_qvstfcs: 12516 case Intrinsic::ppc_qpx_qvstfiw: 12517 case Intrinsic::ppc_altivec_stvx: 12518 case Intrinsic::ppc_altivec_stvxl: 12519 case Intrinsic::ppc_altivec_stvebx: 12520 case Intrinsic::ppc_altivec_stvehx: 12521 case Intrinsic::ppc_altivec_stvewx: 12522 case Intrinsic::ppc_vsx_stxvd2x: 12523 case Intrinsic::ppc_vsx_stxvw4x: { 12524 EVT VT; 12525 switch (Intrinsic) { 12526 case Intrinsic::ppc_altivec_stvebx: 12527 VT = MVT::i8; 12528 break; 12529 case Intrinsic::ppc_altivec_stvehx: 12530 VT = MVT::i16; 12531 break; 12532 case Intrinsic::ppc_altivec_stvewx: 12533 VT = MVT::i32; 12534 break; 12535 case Intrinsic::ppc_vsx_stxvd2x: 12536 VT = MVT::v2f64; 12537 break; 12538 case Intrinsic::ppc_qpx_qvstfd: 12539 VT = MVT::v4f64; 12540 break; 12541 case Intrinsic::ppc_qpx_qvstfs: 12542 VT = MVT::v4f32; 12543 break; 12544 case Intrinsic::ppc_qpx_qvstfcd: 12545 VT = MVT::v2f64; 12546 break; 12547 case Intrinsic::ppc_qpx_qvstfcs: 12548 VT = MVT::v2f32; 12549 break; 12550 default: 12551 VT = MVT::v4i32; 12552 break; 12553 } 12554 12555 Info.opc = ISD::INTRINSIC_VOID; 12556 Info.memVT = VT; 12557 Info.ptrVal = I.getArgOperand(1); 12558 Info.offset = -VT.getStoreSize()+1; 12559 Info.size = 2*VT.getStoreSize()-1; 12560 Info.align = 1; 12561 Info.vol = false; 12562 Info.readMem = false; 12563 Info.writeMem = true; 12564 return true; 12565 } 12566 case Intrinsic::ppc_qpx_qvstfda: 12567 case Intrinsic::ppc_qpx_qvstfsa: 12568 case Intrinsic::ppc_qpx_qvstfcda: 12569 case Intrinsic::ppc_qpx_qvstfcsa: 12570 case Intrinsic::ppc_qpx_qvstfiwa: { 12571 EVT VT; 12572 switch (Intrinsic) { 12573 case Intrinsic::ppc_qpx_qvstfda: 12574 VT = MVT::v4f64; 12575 break; 12576 case Intrinsic::ppc_qpx_qvstfsa: 12577 VT = MVT::v4f32; 12578 break; 12579 case Intrinsic::ppc_qpx_qvstfcda: 12580 VT = MVT::v2f64; 12581 break; 12582 case Intrinsic::ppc_qpx_qvstfcsa: 12583 VT = MVT::v2f32; 12584 break; 12585 default: 12586 VT = MVT::v4i32; 12587 break; 12588 } 12589 12590 Info.opc = ISD::INTRINSIC_VOID; 12591 Info.memVT = VT; 12592 Info.ptrVal = I.getArgOperand(1); 12593 Info.offset = 0; 12594 Info.size = VT.getStoreSize(); 12595 Info.align = 1; 12596 Info.vol = false; 12597 Info.readMem = false; 12598 Info.writeMem = true; 12599 return true; 12600 } 12601 default: 12602 break; 12603 } 12604 12605 return false; 12606 } 12607 12608 /// getOptimalMemOpType - Returns the target specific optimal type for load 12609 /// and store operations as a result of memset, memcpy, and memmove 12610 /// lowering. If DstAlign is zero that means it's safe to destination 12611 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 12612 /// means there isn't a need to check it against alignment requirement, 12613 /// probably because the source does not need to be loaded. If 'IsMemset' is 12614 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 12615 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 12616 /// source is constant so it does not need to be loaded. 12617 /// It returns EVT::Other if the type should be determined using generic 12618 /// target-independent logic. 12619 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 12620 unsigned DstAlign, unsigned SrcAlign, 12621 bool IsMemset, bool ZeroMemset, 12622 bool MemcpyStrSrc, 12623 MachineFunction &MF) const { 12624 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 12625 const Function *F = MF.getFunction(); 12626 // When expanding a memset, require at least two QPX instructions to cover 12627 // the cost of loading the value to be stored from the constant pool. 12628 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 12629 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 12630 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 12631 return MVT::v4f64; 12632 } 12633 12634 // We should use Altivec/VSX loads and stores when available. For unaligned 12635 // addresses, unaligned VSX loads are only fast starting with the P8. 12636 if (Subtarget.hasAltivec() && Size >= 16 && 12637 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 12638 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 12639 return MVT::v4i32; 12640 } 12641 12642 if (Subtarget.isPPC64()) { 12643 return MVT::i64; 12644 } 12645 12646 return MVT::i32; 12647 } 12648 12649 /// \brief Returns true if it is beneficial to convert a load of a constant 12650 /// to just the constant itself. 12651 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12652 Type *Ty) const { 12653 assert(Ty->isIntegerTy()); 12654 12655 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 12656 return !(BitSize == 0 || BitSize > 64); 12657 } 12658 12659 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 12660 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12661 return false; 12662 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 12663 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 12664 return NumBits1 == 64 && NumBits2 == 32; 12665 } 12666 12667 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 12668 if (!VT1.isInteger() || !VT2.isInteger()) 12669 return false; 12670 unsigned NumBits1 = VT1.getSizeInBits(); 12671 unsigned NumBits2 = VT2.getSizeInBits(); 12672 return NumBits1 == 64 && NumBits2 == 32; 12673 } 12674 12675 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12676 // Generally speaking, zexts are not free, but they are free when they can be 12677 // folded with other operations. 12678 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 12679 EVT MemVT = LD->getMemoryVT(); 12680 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 12681 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 12682 (LD->getExtensionType() == ISD::NON_EXTLOAD || 12683 LD->getExtensionType() == ISD::ZEXTLOAD)) 12684 return true; 12685 } 12686 12687 // FIXME: Add other cases... 12688 // - 32-bit shifts with a zext to i64 12689 // - zext after ctlz, bswap, etc. 12690 // - zext after and by a constant mask 12691 12692 return TargetLowering::isZExtFree(Val, VT2); 12693 } 12694 12695 bool PPCTargetLowering::isFPExtFree(EVT VT) const { 12696 assert(VT.isFloatingPoint()); 12697 return true; 12698 } 12699 12700 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12701 return isInt<16>(Imm) || isUInt<16>(Imm); 12702 } 12703 12704 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12705 return isInt<16>(Imm) || isUInt<16>(Imm); 12706 } 12707 12708 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12709 unsigned, 12710 unsigned, 12711 bool *Fast) const { 12712 if (DisablePPCUnaligned) 12713 return false; 12714 12715 // PowerPC supports unaligned memory access for simple non-vector types. 12716 // Although accessing unaligned addresses is not as efficient as accessing 12717 // aligned addresses, it is generally more efficient than manual expansion, 12718 // and generally only traps for software emulation when crossing page 12719 // boundaries. 12720 12721 if (!VT.isSimple()) 12722 return false; 12723 12724 if (VT.getSimpleVT().isVector()) { 12725 if (Subtarget.hasVSX()) { 12726 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 12727 VT != MVT::v4f32 && VT != MVT::v4i32) 12728 return false; 12729 } else { 12730 return false; 12731 } 12732 } 12733 12734 if (VT == MVT::ppcf128) 12735 return false; 12736 12737 if (Fast) 12738 *Fast = true; 12739 12740 return true; 12741 } 12742 12743 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 12744 VT = VT.getScalarType(); 12745 12746 if (!VT.isSimple()) 12747 return false; 12748 12749 switch (VT.getSimpleVT().SimpleTy) { 12750 case MVT::f32: 12751 case MVT::f64: 12752 return true; 12753 default: 12754 break; 12755 } 12756 12757 return false; 12758 } 12759 12760 const MCPhysReg * 12761 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 12762 // LR is a callee-save register, but we must treat it as clobbered by any call 12763 // site. Hence we include LR in the scratch registers, which are in turn added 12764 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 12765 // to CTR, which is used by any indirect call. 12766 static const MCPhysReg ScratchRegs[] = { 12767 PPC::X12, PPC::LR8, PPC::CTR8, 0 12768 }; 12769 12770 return ScratchRegs; 12771 } 12772 12773 unsigned PPCTargetLowering::getExceptionPointerRegister( 12774 const Constant *PersonalityFn) const { 12775 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 12776 } 12777 12778 unsigned PPCTargetLowering::getExceptionSelectorRegister( 12779 const Constant *PersonalityFn) const { 12780 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 12781 } 12782 12783 bool 12784 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 12785 EVT VT , unsigned DefinedValues) const { 12786 if (VT == MVT::v2i64) 12787 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 12788 12789 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 12790 return true; 12791 12792 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 12793 } 12794 12795 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 12796 if (DisableILPPref || Subtarget.enableMachineScheduler()) 12797 return TargetLowering::getSchedulingPreference(N); 12798 12799 return Sched::ILP; 12800 } 12801 12802 // Create a fast isel object. 12803 FastISel * 12804 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 12805 const TargetLibraryInfo *LibInfo) const { 12806 return PPC::createFastISel(FuncInfo, LibInfo); 12807 } 12808 12809 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12810 if (Subtarget.isDarwinABI()) return; 12811 if (!Subtarget.isPPC64()) return; 12812 12813 // Update IsSplitCSR in PPCFunctionInfo 12814 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 12815 PFI->setIsSplitCSR(true); 12816 } 12817 12818 void PPCTargetLowering::insertCopiesSplitCSR( 12819 MachineBasicBlock *Entry, 12820 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12821 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 12822 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12823 if (!IStart) 12824 return; 12825 12826 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12827 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12828 MachineBasicBlock::iterator MBBI = Entry->begin(); 12829 for (const MCPhysReg *I = IStart; *I; ++I) { 12830 const TargetRegisterClass *RC = nullptr; 12831 if (PPC::G8RCRegClass.contains(*I)) 12832 RC = &PPC::G8RCRegClass; 12833 else if (PPC::F8RCRegClass.contains(*I)) 12834 RC = &PPC::F8RCRegClass; 12835 else if (PPC::CRRCRegClass.contains(*I)) 12836 RC = &PPC::CRRCRegClass; 12837 else if (PPC::VRRCRegClass.contains(*I)) 12838 RC = &PPC::VRRCRegClass; 12839 else 12840 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12841 12842 unsigned NewVR = MRI->createVirtualRegister(RC); 12843 // Create copy from CSR to a virtual register. 12844 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12845 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12846 // nounwind. If we want to generalize this later, we may need to emit 12847 // CFI pseudo-instructions. 12848 assert(Entry->getParent()->getFunction()->hasFnAttribute( 12849 Attribute::NoUnwind) && 12850 "Function should be nounwind in insertCopiesSplitCSR!"); 12851 Entry->addLiveIn(*I); 12852 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12853 .addReg(*I); 12854 12855 // Insert the copy-back instructions right before the terminator 12856 for (auto *Exit : Exits) 12857 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12858 TII->get(TargetOpcode::COPY), *I) 12859 .addReg(NewVR); 12860 } 12861 } 12862 12863 // Override to enable LOAD_STACK_GUARD lowering on Linux. 12864 bool PPCTargetLowering::useLoadStackGuardNode() const { 12865 if (!Subtarget.isTargetLinux()) 12866 return TargetLowering::useLoadStackGuardNode(); 12867 return true; 12868 } 12869 12870 // Override to disable global variable loading on Linux. 12871 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 12872 if (!Subtarget.isTargetLinux()) 12873 return TargetLowering::insertSSPDeclarations(M); 12874 } 12875 12876 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 12877 if (!VT.isSimple() || !Subtarget.hasVSX()) 12878 return false; 12879 12880 switch(VT.getSimpleVT().SimpleTy) { 12881 default: 12882 // For FP types that are currently not supported by PPC backend, return 12883 // false. Examples: f16, f80. 12884 return false; 12885 case MVT::f32: 12886 case MVT::f64: 12887 case MVT::ppcf128: 12888 return Imm.isPosZero(); 12889 } 12890 } 12891