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 "PPCISelLowering.h" 15 #include "MCTargetDesc/PPCPredicates.h" 16 #include "PPC.h" 17 #include "PPCCCState.h" 18 #include "PPCCallingConv.h" 19 #include "PPCFrameLowering.h" 20 #include "PPCInstrInfo.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/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.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/CallSite.h" 56 #include "llvm/IR/CallingConv.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/IRBuilder.h" 65 #include "llvm/IR/Instructions.h" 66 #include "llvm/IR/Intrinsics.h" 67 #include "llvm/IR/Module.h" 68 #include "llvm/IR/Type.h" 69 #include "llvm/IR/Use.h" 70 #include "llvm/IR/Value.h" 71 #include "llvm/MC/MCExpr.h" 72 #include "llvm/MC/MCRegisterInfo.h" 73 #include "llvm/Support/AtomicOrdering.h" 74 #include "llvm/Support/BranchProbability.h" 75 #include "llvm/Support/Casting.h" 76 #include "llvm/Support/CodeGen.h" 77 #include "llvm/Support/CommandLine.h" 78 #include "llvm/Support/Compiler.h" 79 #include "llvm/Support/Debug.h" 80 #include "llvm/Support/ErrorHandling.h" 81 #include "llvm/Support/Format.h" 82 #include "llvm/Support/KnownBits.h" 83 #include "llvm/Support/MathExtras.h" 84 #include "llvm/Support/raw_ostream.h" 85 #include "llvm/Target/TargetInstrInfo.h" 86 #include "llvm/Target/TargetLowering.h" 87 #include "llvm/Target/TargetMachine.h" 88 #include "llvm/Target/TargetOptions.h" 89 #include "llvm/Target/TargetRegisterInfo.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <list> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 100 #define DEBUG_TYPE "ppc-lowering" 101 102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 104 105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisableSCO("disable-ppc-sco", 112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 113 114 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 116 117 // FIXME: Remove this once the bug has been fixed! 118 extern cl::opt<bool> ANDIGlueBug; 119 120 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 121 const PPCSubtarget &STI) 122 : TargetLowering(TM), Subtarget(STI) { 123 // Use _setjmp/_longjmp instead of setjmp/longjmp. 124 setUseUnderscoreSetJmp(true); 125 setUseUnderscoreLongJmp(true); 126 127 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 128 // arguments are at least 4/8 bytes aligned. 129 bool isPPC64 = Subtarget.isPPC64(); 130 setMinStackArgumentAlignment(isPPC64 ? 8:4); 131 132 // Set up the register classes. 133 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 134 if (!useSoftFloat()) { 135 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 136 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 137 } 138 139 // Match BITREVERSE to customized fast code sequence in the td file. 140 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 141 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 142 143 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 144 for (MVT VT : MVT::integer_valuetypes()) { 145 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 146 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 147 } 148 149 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 150 151 // PowerPC has pre-inc load and store's. 152 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 153 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 154 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 155 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 156 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 157 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 158 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 159 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 160 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 161 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 162 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 163 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 164 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 165 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 166 167 if (Subtarget.useCRBits()) { 168 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 169 170 if (isPPC64 || Subtarget.hasFPCVT()) { 171 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 172 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 173 isPPC64 ? MVT::i64 : MVT::i32); 174 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 175 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 176 isPPC64 ? MVT::i64 : MVT::i32); 177 } else { 178 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 179 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 180 } 181 182 // PowerPC does not support direct load/store of condition registers. 183 setOperationAction(ISD::LOAD, MVT::i1, Custom); 184 setOperationAction(ISD::STORE, MVT::i1, Custom); 185 186 // FIXME: Remove this once the ANDI glue bug is fixed: 187 if (ANDIGlueBug) 188 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 189 190 for (MVT VT : MVT::integer_valuetypes()) { 191 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 192 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 193 setTruncStoreAction(VT, MVT::i1, Expand); 194 } 195 196 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 197 } 198 199 // This is used in the ppcf128->int sequence. Note it has different semantics 200 // from FP_ROUND: that rounds to nearest, this rounds to zero. 201 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 202 203 // We do not currently implement these libm ops for PowerPC. 204 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 205 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 206 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 207 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 208 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 209 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 210 211 // PowerPC has no SREM/UREM instructions unless we are on P9 212 // On P9 we may use a hardware instruction to compute the remainder. 213 // The instructions are not legalized directly because in the cases where the 214 // result of both the remainder and the division is required it is more 215 // efficient to compute the remainder from the result of the division rather 216 // than use the remainder instruction. 217 if (Subtarget.isISA3_0()) { 218 setOperationAction(ISD::SREM, MVT::i32, Custom); 219 setOperationAction(ISD::UREM, MVT::i32, Custom); 220 setOperationAction(ISD::SREM, MVT::i64, Custom); 221 setOperationAction(ISD::UREM, MVT::i64, Custom); 222 } else { 223 setOperationAction(ISD::SREM, MVT::i32, Expand); 224 setOperationAction(ISD::UREM, MVT::i32, Expand); 225 setOperationAction(ISD::SREM, MVT::i64, Expand); 226 setOperationAction(ISD::UREM, MVT::i64, Expand); 227 } 228 229 if (Subtarget.hasP9Vector()) { 230 setOperationAction(ISD::ABS, MVT::v4i32, Legal); 231 setOperationAction(ISD::ABS, MVT::v8i16, Legal); 232 setOperationAction(ISD::ABS, MVT::v16i8, Legal); 233 } 234 235 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 236 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 237 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 238 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 239 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 240 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 241 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 242 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 243 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 244 245 // We don't support sin/cos/sqrt/fmod/pow 246 setOperationAction(ISD::FSIN , MVT::f64, Expand); 247 setOperationAction(ISD::FCOS , MVT::f64, Expand); 248 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 249 setOperationAction(ISD::FREM , MVT::f64, Expand); 250 setOperationAction(ISD::FPOW , MVT::f64, Expand); 251 setOperationAction(ISD::FMA , MVT::f64, Legal); 252 setOperationAction(ISD::FSIN , MVT::f32, Expand); 253 setOperationAction(ISD::FCOS , MVT::f32, Expand); 254 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 255 setOperationAction(ISD::FREM , MVT::f32, Expand); 256 setOperationAction(ISD::FPOW , MVT::f32, Expand); 257 setOperationAction(ISD::FMA , MVT::f32, Legal); 258 259 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 260 261 // If we're enabling GP optimizations, use hardware square root 262 if (!Subtarget.hasFSQRT() && 263 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 264 Subtarget.hasFRE())) 265 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 266 267 if (!Subtarget.hasFSQRT() && 268 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 269 Subtarget.hasFRES())) 270 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 271 272 if (Subtarget.hasFCPSGN()) { 273 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 274 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 275 } else { 276 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 277 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 278 } 279 280 if (Subtarget.hasFPRND()) { 281 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 282 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 283 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 284 setOperationAction(ISD::FROUND, MVT::f64, Legal); 285 286 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 287 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 288 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 289 setOperationAction(ISD::FROUND, MVT::f32, Legal); 290 } 291 292 // PowerPC does not have BSWAP 293 // CTPOP or CTTZ were introduced in P8/P9 respectivelly 294 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 295 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 296 if (Subtarget.isISA3_0()) { 297 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 298 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 299 } else { 300 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 301 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 302 } 303 304 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 305 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 306 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 307 } else { 308 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 309 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 310 } 311 312 // PowerPC does not have ROTR 313 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 314 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 315 316 if (!Subtarget.useCRBits()) { 317 // PowerPC does not have Select 318 setOperationAction(ISD::SELECT, MVT::i32, Expand); 319 setOperationAction(ISD::SELECT, MVT::i64, Expand); 320 setOperationAction(ISD::SELECT, MVT::f32, Expand); 321 setOperationAction(ISD::SELECT, MVT::f64, Expand); 322 } 323 324 // PowerPC wants to turn select_cc of FP into fsel when possible. 325 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 326 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 327 328 // PowerPC wants to optimize integer setcc a bit 329 if (!Subtarget.useCRBits()) 330 setOperationAction(ISD::SETCC, MVT::i32, Custom); 331 332 // PowerPC does not have BRCOND which requires SetCC 333 if (!Subtarget.useCRBits()) 334 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 335 336 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 337 338 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 339 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 340 341 // PowerPC does not have [U|S]INT_TO_FP 342 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 343 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 344 345 if (Subtarget.hasDirectMove() && isPPC64) { 346 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 347 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 348 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 349 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 350 } else { 351 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 352 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 353 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 354 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 355 } 356 357 // We cannot sextinreg(i1). Expand to shifts. 358 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 359 360 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 361 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 362 // support continuation, user-level threading, and etc.. As a result, no 363 // other SjLj exception interfaces are implemented and please don't build 364 // your own exception handling based on them. 365 // LLVM/Clang supports zero-cost DWARF exception handling. 366 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 367 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 368 369 // We want to legalize GlobalAddress and ConstantPool nodes into the 370 // appropriate instructions to materialize the address. 371 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 372 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 373 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 374 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 375 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 376 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 377 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 378 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 379 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 380 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 381 382 // TRAP is legal. 383 setOperationAction(ISD::TRAP, MVT::Other, Legal); 384 385 // TRAMPOLINE is custom lowered. 386 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 387 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 388 389 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 390 setOperationAction(ISD::VASTART , MVT::Other, Custom); 391 392 if (Subtarget.isSVR4ABI()) { 393 if (isPPC64) { 394 // VAARG always uses double-word chunks, so promote anything smaller. 395 setOperationAction(ISD::VAARG, MVT::i1, Promote); 396 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 397 setOperationAction(ISD::VAARG, MVT::i8, Promote); 398 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 399 setOperationAction(ISD::VAARG, MVT::i16, Promote); 400 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 401 setOperationAction(ISD::VAARG, MVT::i32, Promote); 402 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 403 setOperationAction(ISD::VAARG, MVT::Other, Expand); 404 } else { 405 // VAARG is custom lowered with the 32-bit SVR4 ABI. 406 setOperationAction(ISD::VAARG, MVT::Other, Custom); 407 setOperationAction(ISD::VAARG, MVT::i64, Custom); 408 } 409 } else 410 setOperationAction(ISD::VAARG, MVT::Other, Expand); 411 412 if (Subtarget.isSVR4ABI() && !isPPC64) 413 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 414 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 415 else 416 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 417 418 // Use the default implementation. 419 setOperationAction(ISD::VAEND , MVT::Other, Expand); 420 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 421 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 422 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 423 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 424 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 425 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 426 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 427 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 428 429 // We want to custom lower some of our intrinsics. 430 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 431 432 // To handle counter-based loop conditions. 433 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 434 435 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 436 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 437 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 438 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 439 440 // Comparisons that require checking two conditions. 441 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 442 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 443 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 444 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 445 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 446 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 447 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 448 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 449 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 450 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 451 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 452 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 453 454 if (Subtarget.has64BitSupport()) { 455 // They also have instructions for converting between i64 and fp. 456 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 457 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 458 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 459 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 460 // This is just the low 32 bits of a (signed) fp->i64 conversion. 461 // We cannot do this with Promote because i64 is not a legal type. 462 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 463 464 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 465 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 466 } else { 467 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 468 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 469 } 470 471 // With the instructions enabled under FPCVT, we can do everything. 472 if (Subtarget.hasFPCVT()) { 473 if (Subtarget.has64BitSupport()) { 474 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 475 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 476 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 477 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 478 } 479 480 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 481 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 482 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 483 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 484 } 485 486 if (Subtarget.use64BitRegs()) { 487 // 64-bit PowerPC implementations can support i64 types directly 488 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 489 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 490 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 491 // 64-bit PowerPC wants to expand i128 shifts itself. 492 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 493 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 494 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 495 } else { 496 // 32-bit PowerPC wants to expand i64 shifts itself. 497 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 498 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 499 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 500 } 501 502 if (Subtarget.hasAltivec()) { 503 // First set operation action for all vector types to expand. Then we 504 // will selectively turn on ones that can be effectively codegen'd. 505 for (MVT VT : MVT::vector_valuetypes()) { 506 // add/sub are legal for all supported vector VT's. 507 setOperationAction(ISD::ADD, VT, Legal); 508 setOperationAction(ISD::SUB, VT, Legal); 509 510 // Vector instructions introduced in P8 511 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 512 setOperationAction(ISD::CTPOP, VT, Legal); 513 setOperationAction(ISD::CTLZ, VT, Legal); 514 } 515 else { 516 setOperationAction(ISD::CTPOP, VT, Expand); 517 setOperationAction(ISD::CTLZ, VT, Expand); 518 } 519 520 // Vector instructions introduced in P9 521 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 522 setOperationAction(ISD::CTTZ, VT, Legal); 523 else 524 setOperationAction(ISD::CTTZ, VT, Expand); 525 526 // We promote all shuffles to v16i8. 527 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 528 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 529 530 // We promote all non-typed operations to v4i32. 531 setOperationAction(ISD::AND , VT, Promote); 532 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 533 setOperationAction(ISD::OR , VT, Promote); 534 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 535 setOperationAction(ISD::XOR , VT, Promote); 536 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 537 setOperationAction(ISD::LOAD , VT, Promote); 538 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 539 setOperationAction(ISD::SELECT, VT, Promote); 540 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 541 setOperationAction(ISD::SELECT_CC, VT, Promote); 542 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 543 setOperationAction(ISD::STORE, VT, Promote); 544 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 545 546 // No other operations are legal. 547 setOperationAction(ISD::MUL , VT, Expand); 548 setOperationAction(ISD::SDIV, VT, Expand); 549 setOperationAction(ISD::SREM, VT, Expand); 550 setOperationAction(ISD::UDIV, VT, Expand); 551 setOperationAction(ISD::UREM, VT, Expand); 552 setOperationAction(ISD::FDIV, VT, Expand); 553 setOperationAction(ISD::FREM, VT, Expand); 554 setOperationAction(ISD::FNEG, VT, Expand); 555 setOperationAction(ISD::FSQRT, VT, Expand); 556 setOperationAction(ISD::FLOG, VT, Expand); 557 setOperationAction(ISD::FLOG10, VT, Expand); 558 setOperationAction(ISD::FLOG2, VT, Expand); 559 setOperationAction(ISD::FEXP, VT, Expand); 560 setOperationAction(ISD::FEXP2, VT, Expand); 561 setOperationAction(ISD::FSIN, VT, Expand); 562 setOperationAction(ISD::FCOS, VT, Expand); 563 setOperationAction(ISD::FABS, VT, Expand); 564 setOperationAction(ISD::FFLOOR, VT, Expand); 565 setOperationAction(ISD::FCEIL, VT, Expand); 566 setOperationAction(ISD::FTRUNC, VT, Expand); 567 setOperationAction(ISD::FRINT, VT, Expand); 568 setOperationAction(ISD::FNEARBYINT, VT, Expand); 569 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 570 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 571 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 572 setOperationAction(ISD::MULHU, VT, Expand); 573 setOperationAction(ISD::MULHS, VT, Expand); 574 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 575 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 576 setOperationAction(ISD::UDIVREM, VT, Expand); 577 setOperationAction(ISD::SDIVREM, VT, Expand); 578 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 579 setOperationAction(ISD::FPOW, VT, Expand); 580 setOperationAction(ISD::BSWAP, VT, Expand); 581 setOperationAction(ISD::VSELECT, VT, Expand); 582 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 583 setOperationAction(ISD::ROTL, VT, Expand); 584 setOperationAction(ISD::ROTR, VT, Expand); 585 586 for (MVT InnerVT : MVT::vector_valuetypes()) { 587 setTruncStoreAction(VT, InnerVT, Expand); 588 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 589 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 590 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 591 } 592 } 593 594 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 595 // with merges, splats, etc. 596 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 597 598 setOperationAction(ISD::AND , MVT::v4i32, Legal); 599 setOperationAction(ISD::OR , MVT::v4i32, Legal); 600 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 601 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 602 setOperationAction(ISD::SELECT, MVT::v4i32, 603 Subtarget.useCRBits() ? Legal : Expand); 604 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 605 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 606 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 607 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 608 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 609 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 610 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 611 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 612 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 613 614 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 615 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 616 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 617 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 618 619 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 620 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 621 622 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 623 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 624 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 625 } 626 627 if (Subtarget.hasP8Altivec()) 628 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 629 else 630 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 631 632 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 633 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 634 635 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 637 638 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 639 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 640 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 641 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 642 643 // Altivec does not contain unordered floating-point compare instructions 644 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 645 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 646 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 647 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 648 649 if (Subtarget.hasVSX()) { 650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 652 if (Subtarget.hasP8Vector()) { 653 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 654 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 655 } 656 if (Subtarget.hasDirectMove() && isPPC64) { 657 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 658 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 659 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 660 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 661 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 664 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 665 } 666 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 667 668 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 669 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 670 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 671 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 672 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 673 674 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 675 676 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 677 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 678 679 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 680 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 681 682 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 683 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 684 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 685 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 686 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 687 688 // Share the Altivec comparison restrictions. 689 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 690 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 691 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 692 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 693 694 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 695 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 696 697 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 698 699 if (Subtarget.hasP8Vector()) 700 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 701 702 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 703 704 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 705 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 706 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 707 708 if (Subtarget.hasP8Altivec()) { 709 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 710 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 711 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 712 713 // 128 bit shifts can be accomplished via 3 instructions for SHL and 714 // SRL, but not for SRA because of the instructions available: 715 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 716 // doing 717 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 718 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 719 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 720 721 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 722 } 723 else { 724 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 725 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 726 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 727 728 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 729 730 // VSX v2i64 only supports non-arithmetic operations. 731 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 732 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 733 } 734 735 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 736 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 737 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 738 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 739 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 741 742 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 743 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 744 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 745 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 746 747 // Vector operation legalization checks the result type of 748 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 749 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 750 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 751 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 752 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 753 754 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 755 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 756 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 757 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 758 759 if (Subtarget.hasDirectMove()) 760 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 761 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 762 763 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 764 } 765 766 if (Subtarget.hasP8Altivec()) { 767 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 768 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 769 } 770 771 if (Subtarget.hasP9Vector()) { 772 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 774 775 // 128 bit shifts can be accomplished via 3 instructions for SHL and 776 // SRL, but not for SRA because of the instructions available: 777 // VS{RL} and VS{RL}O. 778 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 779 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 780 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 781 } 782 } 783 784 if (Subtarget.hasQPX()) { 785 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 786 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 787 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 788 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 789 790 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 791 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 792 793 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 794 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 795 796 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 797 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 798 799 if (!Subtarget.useCRBits()) 800 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 801 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 802 803 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 804 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 805 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 806 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 807 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 808 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 809 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 810 811 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 812 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 813 814 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 815 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 816 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 817 818 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 819 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 820 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 821 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 822 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 823 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 824 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 825 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 826 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 827 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 828 829 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 830 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 831 832 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 833 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 834 835 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 836 837 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 838 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 839 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 840 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 841 842 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 843 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 844 845 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 846 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 847 848 if (!Subtarget.useCRBits()) 849 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 850 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 851 852 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 853 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 854 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 855 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 856 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 857 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 858 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 859 860 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 861 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 862 863 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 864 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 865 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 866 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 867 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 868 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 869 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 870 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 871 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 872 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 873 874 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 875 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 876 877 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 878 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 879 880 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 881 882 setOperationAction(ISD::AND , MVT::v4i1, Legal); 883 setOperationAction(ISD::OR , MVT::v4i1, Legal); 884 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 885 886 if (!Subtarget.useCRBits()) 887 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 888 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 889 890 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 891 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 892 893 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 894 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 895 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 896 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 897 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 899 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 900 901 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 902 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 903 904 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 905 906 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 907 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 908 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 909 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 910 911 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 912 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 913 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 914 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 915 916 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 917 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 918 919 // These need to set FE_INEXACT, and so cannot be vectorized here. 920 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 921 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 922 923 if (TM.Options.UnsafeFPMath) { 924 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 925 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 926 927 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 928 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 929 } else { 930 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 931 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 932 933 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 934 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 935 } 936 } 937 938 if (Subtarget.has64BitSupport()) 939 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 940 941 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 942 943 if (!isPPC64) { 944 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 945 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 946 } 947 948 setBooleanContents(ZeroOrOneBooleanContent); 949 950 if (Subtarget.hasAltivec()) { 951 // Altivec instructions set fields to all zeros or all ones. 952 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 953 } 954 955 if (!isPPC64) { 956 // These libcalls are not available in 32-bit. 957 setLibcallName(RTLIB::SHL_I128, nullptr); 958 setLibcallName(RTLIB::SRL_I128, nullptr); 959 setLibcallName(RTLIB::SRA_I128, nullptr); 960 } 961 962 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 963 964 // We have target-specific dag combine patterns for the following nodes: 965 setTargetDAGCombine(ISD::SHL); 966 setTargetDAGCombine(ISD::SRA); 967 setTargetDAGCombine(ISD::SRL); 968 setTargetDAGCombine(ISD::SINT_TO_FP); 969 setTargetDAGCombine(ISD::BUILD_VECTOR); 970 if (Subtarget.hasFPCVT()) 971 setTargetDAGCombine(ISD::UINT_TO_FP); 972 setTargetDAGCombine(ISD::LOAD); 973 setTargetDAGCombine(ISD::STORE); 974 setTargetDAGCombine(ISD::BR_CC); 975 if (Subtarget.useCRBits()) 976 setTargetDAGCombine(ISD::BRCOND); 977 setTargetDAGCombine(ISD::BSWAP); 978 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 979 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 980 setTargetDAGCombine(ISD::INTRINSIC_VOID); 981 982 setTargetDAGCombine(ISD::SIGN_EXTEND); 983 setTargetDAGCombine(ISD::ZERO_EXTEND); 984 setTargetDAGCombine(ISD::ANY_EXTEND); 985 986 if (Subtarget.useCRBits()) { 987 setTargetDAGCombine(ISD::TRUNCATE); 988 setTargetDAGCombine(ISD::SETCC); 989 setTargetDAGCombine(ISD::SELECT_CC); 990 } 991 992 // Use reciprocal estimates. 993 if (TM.Options.UnsafeFPMath) { 994 setTargetDAGCombine(ISD::FDIV); 995 setTargetDAGCombine(ISD::FSQRT); 996 } 997 998 // Darwin long double math library functions have $LDBL128 appended. 999 if (Subtarget.isDarwin()) { 1000 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1001 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1002 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1003 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1004 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1005 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1006 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1007 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1008 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1009 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1010 } 1011 1012 // With 32 condition bits, we don't need to sink (and duplicate) compares 1013 // aggressively in CodeGenPrep. 1014 if (Subtarget.useCRBits()) { 1015 setHasMultipleConditionRegisters(); 1016 setJumpIsExpensive(); 1017 } 1018 1019 setMinFunctionAlignment(2); 1020 if (Subtarget.isDarwin()) 1021 setPrefFunctionAlignment(4); 1022 1023 switch (Subtarget.getDarwinDirective()) { 1024 default: break; 1025 case PPC::DIR_970: 1026 case PPC::DIR_A2: 1027 case PPC::DIR_E500mc: 1028 case PPC::DIR_E5500: 1029 case PPC::DIR_PWR4: 1030 case PPC::DIR_PWR5: 1031 case PPC::DIR_PWR5X: 1032 case PPC::DIR_PWR6: 1033 case PPC::DIR_PWR6X: 1034 case PPC::DIR_PWR7: 1035 case PPC::DIR_PWR8: 1036 case PPC::DIR_PWR9: 1037 setPrefFunctionAlignment(4); 1038 setPrefLoopAlignment(4); 1039 break; 1040 } 1041 1042 if (Subtarget.enableMachineScheduler()) 1043 setSchedulingPreference(Sched::Source); 1044 else 1045 setSchedulingPreference(Sched::Hybrid); 1046 1047 computeRegisterProperties(STI.getRegisterInfo()); 1048 1049 // The Freescale cores do better with aggressive inlining of memcpy and 1050 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1051 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1052 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1053 MaxStoresPerMemset = 32; 1054 MaxStoresPerMemsetOptSize = 16; 1055 MaxStoresPerMemcpy = 32; 1056 MaxStoresPerMemcpyOptSize = 8; 1057 MaxStoresPerMemmove = 32; 1058 MaxStoresPerMemmoveOptSize = 8; 1059 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1060 // The A2 also benefits from (very) aggressive inlining of memcpy and 1061 // friends. The overhead of a the function call, even when warm, can be 1062 // over one hundred cycles. 1063 MaxStoresPerMemset = 128; 1064 MaxStoresPerMemcpy = 128; 1065 MaxStoresPerMemmove = 128; 1066 MaxLoadsPerMemcmp = 128; 1067 } else { 1068 MaxLoadsPerMemcmp = 8; 1069 MaxLoadsPerMemcmpOptSize = 4; 1070 } 1071 } 1072 1073 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1074 /// the desired ByVal argument alignment. 1075 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1076 unsigned MaxMaxAlign) { 1077 if (MaxAlign == MaxMaxAlign) 1078 return; 1079 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1080 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1081 MaxAlign = 32; 1082 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1083 MaxAlign = 16; 1084 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1085 unsigned EltAlign = 0; 1086 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1087 if (EltAlign > MaxAlign) 1088 MaxAlign = EltAlign; 1089 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1090 for (auto *EltTy : STy->elements()) { 1091 unsigned EltAlign = 0; 1092 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1093 if (EltAlign > MaxAlign) 1094 MaxAlign = EltAlign; 1095 if (MaxAlign == MaxMaxAlign) 1096 break; 1097 } 1098 } 1099 } 1100 1101 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1102 /// function arguments in the caller parameter area. 1103 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1104 const DataLayout &DL) const { 1105 // Darwin passes everything on 4 byte boundary. 1106 if (Subtarget.isDarwin()) 1107 return 4; 1108 1109 // 16byte and wider vectors are passed on 16byte boundary. 1110 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1111 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1112 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1113 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1114 return Align; 1115 } 1116 1117 bool PPCTargetLowering::useSoftFloat() const { 1118 return Subtarget.useSoftFloat(); 1119 } 1120 1121 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1122 switch ((PPCISD::NodeType)Opcode) { 1123 case PPCISD::FIRST_NUMBER: break; 1124 case PPCISD::FSEL: return "PPCISD::FSEL"; 1125 case PPCISD::FCFID: return "PPCISD::FCFID"; 1126 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1127 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1128 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1129 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1130 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1131 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1132 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1133 case PPCISD::FRE: return "PPCISD::FRE"; 1134 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1135 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1136 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1137 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1138 case PPCISD::VPERM: return "PPCISD::VPERM"; 1139 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1140 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1141 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1142 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1143 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1144 case PPCISD::CMPB: return "PPCISD::CMPB"; 1145 case PPCISD::Hi: return "PPCISD::Hi"; 1146 case PPCISD::Lo: return "PPCISD::Lo"; 1147 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1148 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1149 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1150 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1151 case PPCISD::SRL: return "PPCISD::SRL"; 1152 case PPCISD::SRA: return "PPCISD::SRA"; 1153 case PPCISD::SHL: return "PPCISD::SHL"; 1154 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1155 case PPCISD::CALL: return "PPCISD::CALL"; 1156 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1157 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1158 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1159 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1160 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1161 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1162 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1163 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1164 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1165 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1166 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1167 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1168 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1169 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1170 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1171 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1172 case PPCISD::VCMP: return "PPCISD::VCMP"; 1173 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1174 case PPCISD::LBRX: return "PPCISD::LBRX"; 1175 case PPCISD::STBRX: return "PPCISD::STBRX"; 1176 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1177 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1178 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1179 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1180 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1181 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1182 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1183 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1184 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1185 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1186 case PPCISD::BDZ: return "PPCISD::BDZ"; 1187 case PPCISD::MFFS: return "PPCISD::MFFS"; 1188 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1189 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1190 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1191 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1192 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1193 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1194 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1195 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1196 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1197 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1198 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1199 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1200 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1201 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1202 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1203 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1204 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1205 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1206 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1207 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1208 case PPCISD::SC: return "PPCISD::SC"; 1209 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1210 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1211 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1212 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1213 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1214 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1215 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1216 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1217 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1218 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1219 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1220 } 1221 return nullptr; 1222 } 1223 1224 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1225 EVT VT) const { 1226 if (!VT.isVector()) 1227 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1228 1229 if (Subtarget.hasQPX()) 1230 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1231 1232 return VT.changeVectorElementTypeToInteger(); 1233 } 1234 1235 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1236 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1237 return true; 1238 } 1239 1240 //===----------------------------------------------------------------------===// 1241 // Node matching predicates, for use by the tblgen matching code. 1242 //===----------------------------------------------------------------------===// 1243 1244 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1245 static bool isFloatingPointZero(SDValue Op) { 1246 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1247 return CFP->getValueAPF().isZero(); 1248 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1249 // Maybe this has already been legalized into the constant pool? 1250 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1251 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1252 return CFP->getValueAPF().isZero(); 1253 } 1254 return false; 1255 } 1256 1257 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1258 /// true if Op is undef or if it matches the specified value. 1259 static bool isConstantOrUndef(int Op, int Val) { 1260 return Op < 0 || Op == Val; 1261 } 1262 1263 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1264 /// VPKUHUM instruction. 1265 /// The ShuffleKind distinguishes between big-endian operations with 1266 /// two different inputs (0), either-endian operations with two identical 1267 /// inputs (1), and little-endian operations with two different inputs (2). 1268 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1269 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1270 SelectionDAG &DAG) { 1271 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1272 if (ShuffleKind == 0) { 1273 if (IsLE) 1274 return false; 1275 for (unsigned i = 0; i != 16; ++i) 1276 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1277 return false; 1278 } else if (ShuffleKind == 2) { 1279 if (!IsLE) 1280 return false; 1281 for (unsigned i = 0; i != 16; ++i) 1282 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1283 return false; 1284 } else if (ShuffleKind == 1) { 1285 unsigned j = IsLE ? 0 : 1; 1286 for (unsigned i = 0; i != 8; ++i) 1287 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1288 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1289 return false; 1290 } 1291 return true; 1292 } 1293 1294 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1295 /// VPKUWUM instruction. 1296 /// The ShuffleKind distinguishes between big-endian operations with 1297 /// two different inputs (0), either-endian operations with two identical 1298 /// inputs (1), and little-endian operations with two different inputs (2). 1299 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1300 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1301 SelectionDAG &DAG) { 1302 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1303 if (ShuffleKind == 0) { 1304 if (IsLE) 1305 return false; 1306 for (unsigned i = 0; i != 16; i += 2) 1307 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1308 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1309 return false; 1310 } else if (ShuffleKind == 2) { 1311 if (!IsLE) 1312 return false; 1313 for (unsigned i = 0; i != 16; i += 2) 1314 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1315 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1316 return false; 1317 } else if (ShuffleKind == 1) { 1318 unsigned j = IsLE ? 0 : 2; 1319 for (unsigned i = 0; i != 8; i += 2) 1320 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1321 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1322 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1323 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1324 return false; 1325 } 1326 return true; 1327 } 1328 1329 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1330 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1331 /// current subtarget. 1332 /// 1333 /// The ShuffleKind distinguishes between big-endian operations with 1334 /// two different inputs (0), either-endian operations with two identical 1335 /// inputs (1), and little-endian operations with two different inputs (2). 1336 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1337 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1338 SelectionDAG &DAG) { 1339 const PPCSubtarget& Subtarget = 1340 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1341 if (!Subtarget.hasP8Vector()) 1342 return false; 1343 1344 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1345 if (ShuffleKind == 0) { 1346 if (IsLE) 1347 return false; 1348 for (unsigned i = 0; i != 16; i += 4) 1349 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1350 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1351 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1352 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1353 return false; 1354 } else if (ShuffleKind == 2) { 1355 if (!IsLE) 1356 return false; 1357 for (unsigned i = 0; i != 16; i += 4) 1358 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1359 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1360 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1361 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1362 return false; 1363 } else if (ShuffleKind == 1) { 1364 unsigned j = IsLE ? 0 : 4; 1365 for (unsigned i = 0; i != 8; i += 4) 1366 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1367 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1368 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1369 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1370 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1371 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1372 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1373 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1374 return false; 1375 } 1376 return true; 1377 } 1378 1379 /// isVMerge - Common function, used to match vmrg* shuffles. 1380 /// 1381 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1382 unsigned LHSStart, unsigned RHSStart) { 1383 if (N->getValueType(0) != MVT::v16i8) 1384 return false; 1385 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1386 "Unsupported merge size!"); 1387 1388 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1389 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1390 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1391 LHSStart+j+i*UnitSize) || 1392 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1393 RHSStart+j+i*UnitSize)) 1394 return false; 1395 } 1396 return true; 1397 } 1398 1399 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1400 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1401 /// The ShuffleKind distinguishes between big-endian merges with two 1402 /// different inputs (0), either-endian merges with two identical inputs (1), 1403 /// and little-endian merges with two different inputs (2). For the latter, 1404 /// the input operands are swapped (see PPCInstrAltivec.td). 1405 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1406 unsigned ShuffleKind, SelectionDAG &DAG) { 1407 if (DAG.getDataLayout().isLittleEndian()) { 1408 if (ShuffleKind == 1) // unary 1409 return isVMerge(N, UnitSize, 0, 0); 1410 else if (ShuffleKind == 2) // swapped 1411 return isVMerge(N, UnitSize, 0, 16); 1412 else 1413 return false; 1414 } else { 1415 if (ShuffleKind == 1) // unary 1416 return isVMerge(N, UnitSize, 8, 8); 1417 else if (ShuffleKind == 0) // normal 1418 return isVMerge(N, UnitSize, 8, 24); 1419 else 1420 return false; 1421 } 1422 } 1423 1424 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1425 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1426 /// The ShuffleKind distinguishes between big-endian merges with two 1427 /// different inputs (0), either-endian merges with two identical inputs (1), 1428 /// and little-endian merges with two different inputs (2). For the latter, 1429 /// the input operands are swapped (see PPCInstrAltivec.td). 1430 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1431 unsigned ShuffleKind, SelectionDAG &DAG) { 1432 if (DAG.getDataLayout().isLittleEndian()) { 1433 if (ShuffleKind == 1) // unary 1434 return isVMerge(N, UnitSize, 8, 8); 1435 else if (ShuffleKind == 2) // swapped 1436 return isVMerge(N, UnitSize, 8, 24); 1437 else 1438 return false; 1439 } else { 1440 if (ShuffleKind == 1) // unary 1441 return isVMerge(N, UnitSize, 0, 0); 1442 else if (ShuffleKind == 0) // normal 1443 return isVMerge(N, UnitSize, 0, 16); 1444 else 1445 return false; 1446 } 1447 } 1448 1449 /** 1450 * \brief Common function used to match vmrgew and vmrgow shuffles 1451 * 1452 * The indexOffset determines whether to look for even or odd words in 1453 * the shuffle mask. This is based on the of the endianness of the target 1454 * machine. 1455 * - Little Endian: 1456 * - Use offset of 0 to check for odd elements 1457 * - Use offset of 4 to check for even elements 1458 * - Big Endian: 1459 * - Use offset of 0 to check for even elements 1460 * - Use offset of 4 to check for odd elements 1461 * A detailed description of the vector element ordering for little endian and 1462 * big endian can be found at 1463 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1464 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1465 * compiler differences mean to you 1466 * 1467 * The mask to the shuffle vector instruction specifies the indices of the 1468 * elements from the two input vectors to place in the result. The elements are 1469 * numbered in array-access order, starting with the first vector. These vectors 1470 * are always of type v16i8, thus each vector will contain 16 elements of size 1471 * 8. More info on the shuffle vector can be found in the 1472 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1473 * Language Reference. 1474 * 1475 * The RHSStartValue indicates whether the same input vectors are used (unary) 1476 * or two different input vectors are used, based on the following: 1477 * - If the instruction uses the same vector for both inputs, the range of the 1478 * indices will be 0 to 15. In this case, the RHSStart value passed should 1479 * be 0. 1480 * - If the instruction has two different vectors then the range of the 1481 * indices will be 0 to 31. In this case, the RHSStart value passed should 1482 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1483 * to 31 specify elements in the second vector). 1484 * 1485 * \param[in] N The shuffle vector SD Node to analyze 1486 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1487 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1488 * vector to the shuffle_vector instruction 1489 * \return true iff this shuffle vector represents an even or odd word merge 1490 */ 1491 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1492 unsigned RHSStartValue) { 1493 if (N->getValueType(0) != MVT::v16i8) 1494 return false; 1495 1496 for (unsigned i = 0; i < 2; ++i) 1497 for (unsigned j = 0; j < 4; ++j) 1498 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1499 i*RHSStartValue+j+IndexOffset) || 1500 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1501 i*RHSStartValue+j+IndexOffset+8)) 1502 return false; 1503 return true; 1504 } 1505 1506 /** 1507 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or 1508 * vmrgow instructions. 1509 * 1510 * \param[in] N The shuffle vector SD Node to analyze 1511 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1512 * \param[in] ShuffleKind Identify the type of merge: 1513 * - 0 = big-endian merge with two different inputs; 1514 * - 1 = either-endian merge with two identical inputs; 1515 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1516 * little-endian merges). 1517 * \param[in] DAG The current SelectionDAG 1518 * \return true iff this shuffle mask 1519 */ 1520 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1521 unsigned ShuffleKind, SelectionDAG &DAG) { 1522 if (DAG.getDataLayout().isLittleEndian()) { 1523 unsigned indexOffset = CheckEven ? 4 : 0; 1524 if (ShuffleKind == 1) // Unary 1525 return isVMerge(N, indexOffset, 0); 1526 else if (ShuffleKind == 2) // swapped 1527 return isVMerge(N, indexOffset, 16); 1528 else 1529 return false; 1530 } 1531 else { 1532 unsigned indexOffset = CheckEven ? 0 : 4; 1533 if (ShuffleKind == 1) // Unary 1534 return isVMerge(N, indexOffset, 0); 1535 else if (ShuffleKind == 0) // Normal 1536 return isVMerge(N, indexOffset, 16); 1537 else 1538 return false; 1539 } 1540 return false; 1541 } 1542 1543 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1544 /// amount, otherwise return -1. 1545 /// The ShuffleKind distinguishes between big-endian operations with two 1546 /// different inputs (0), either-endian operations with two identical inputs 1547 /// (1), and little-endian operations with two different inputs (2). For the 1548 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1549 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1550 SelectionDAG &DAG) { 1551 if (N->getValueType(0) != MVT::v16i8) 1552 return -1; 1553 1554 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1555 1556 // Find the first non-undef value in the shuffle mask. 1557 unsigned i; 1558 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1559 /*search*/; 1560 1561 if (i == 16) return -1; // all undef. 1562 1563 // Otherwise, check to see if the rest of the elements are consecutively 1564 // numbered from this value. 1565 unsigned ShiftAmt = SVOp->getMaskElt(i); 1566 if (ShiftAmt < i) return -1; 1567 1568 ShiftAmt -= i; 1569 bool isLE = DAG.getDataLayout().isLittleEndian(); 1570 1571 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1572 // Check the rest of the elements to see if they are consecutive. 1573 for (++i; i != 16; ++i) 1574 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1575 return -1; 1576 } else if (ShuffleKind == 1) { 1577 // Check the rest of the elements to see if they are consecutive. 1578 for (++i; i != 16; ++i) 1579 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1580 return -1; 1581 } else 1582 return -1; 1583 1584 if (isLE) 1585 ShiftAmt = 16 - ShiftAmt; 1586 1587 return ShiftAmt; 1588 } 1589 1590 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1591 /// specifies a splat of a single element that is suitable for input to 1592 /// VSPLTB/VSPLTH/VSPLTW. 1593 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1594 assert(N->getValueType(0) == MVT::v16i8 && 1595 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1596 1597 // The consecutive indices need to specify an element, not part of two 1598 // different elements. So abandon ship early if this isn't the case. 1599 if (N->getMaskElt(0) % EltSize != 0) 1600 return false; 1601 1602 // This is a splat operation if each element of the permute is the same, and 1603 // if the value doesn't reference the second vector. 1604 unsigned ElementBase = N->getMaskElt(0); 1605 1606 // FIXME: Handle UNDEF elements too! 1607 if (ElementBase >= 16) 1608 return false; 1609 1610 // Check that the indices are consecutive, in the case of a multi-byte element 1611 // splatted with a v16i8 mask. 1612 for (unsigned i = 1; i != EltSize; ++i) 1613 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1614 return false; 1615 1616 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1617 if (N->getMaskElt(i) < 0) continue; 1618 for (unsigned j = 0; j != EltSize; ++j) 1619 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1620 return false; 1621 } 1622 return true; 1623 } 1624 1625 /// Check that the mask is shuffling N byte elements. Within each N byte 1626 /// element of the mask, the indices could be either in increasing or 1627 /// decreasing order as long as they are consecutive. 1628 /// \param[in] N the shuffle vector SD Node to analyze 1629 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1630 /// Word/DoubleWord/QuadWord). 1631 /// \param[in] StepLen the delta indices number among the N byte element, if 1632 /// the mask is in increasing/decreasing order then it is 1/-1. 1633 /// \return true iff the mask is shuffling N byte elements. 1634 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1635 int StepLen) { 1636 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1637 "Unexpected element width."); 1638 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1639 1640 unsigned NumOfElem = 16 / Width; 1641 unsigned MaskVal[16]; // Width is never greater than 16 1642 for (unsigned i = 0; i < NumOfElem; ++i) { 1643 MaskVal[0] = N->getMaskElt(i * Width); 1644 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1645 return false; 1646 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1647 return false; 1648 } 1649 1650 for (unsigned int j = 1; j < Width; ++j) { 1651 MaskVal[j] = N->getMaskElt(i * Width + j); 1652 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1653 return false; 1654 } 1655 } 1656 } 1657 1658 return true; 1659 } 1660 1661 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1662 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1663 if (!isNByteElemShuffleMask(N, 4, 1)) 1664 return false; 1665 1666 // Now we look at mask elements 0,4,8,12 1667 unsigned M0 = N->getMaskElt(0) / 4; 1668 unsigned M1 = N->getMaskElt(4) / 4; 1669 unsigned M2 = N->getMaskElt(8) / 4; 1670 unsigned M3 = N->getMaskElt(12) / 4; 1671 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1672 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1673 1674 // Below, let H and L be arbitrary elements of the shuffle mask 1675 // where H is in the range [4,7] and L is in the range [0,3]. 1676 // H, 1, 2, 3 or L, 5, 6, 7 1677 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1678 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1679 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1680 InsertAtByte = IsLE ? 12 : 0; 1681 Swap = M0 < 4; 1682 return true; 1683 } 1684 // 0, H, 2, 3 or 4, L, 6, 7 1685 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1686 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1687 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1688 InsertAtByte = IsLE ? 8 : 4; 1689 Swap = M1 < 4; 1690 return true; 1691 } 1692 // 0, 1, H, 3 or 4, 5, L, 7 1693 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1694 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1695 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1696 InsertAtByte = IsLE ? 4 : 8; 1697 Swap = M2 < 4; 1698 return true; 1699 } 1700 // 0, 1, 2, H or 4, 5, 6, L 1701 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1702 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1703 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1704 InsertAtByte = IsLE ? 0 : 12; 1705 Swap = M3 < 4; 1706 return true; 1707 } 1708 1709 // If both vector operands for the shuffle are the same vector, the mask will 1710 // contain only elements from the first one and the second one will be undef. 1711 if (N->getOperand(1).isUndef()) { 1712 ShiftElts = 0; 1713 Swap = true; 1714 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1715 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1716 InsertAtByte = IsLE ? 12 : 0; 1717 return true; 1718 } 1719 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1720 InsertAtByte = IsLE ? 8 : 4; 1721 return true; 1722 } 1723 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1724 InsertAtByte = IsLE ? 4 : 8; 1725 return true; 1726 } 1727 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1728 InsertAtByte = IsLE ? 0 : 12; 1729 return true; 1730 } 1731 } 1732 1733 return false; 1734 } 1735 1736 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1737 bool &Swap, bool IsLE) { 1738 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1739 // Ensure each byte index of the word is consecutive. 1740 if (!isNByteElemShuffleMask(N, 4, 1)) 1741 return false; 1742 1743 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1744 unsigned M0 = N->getMaskElt(0) / 4; 1745 unsigned M1 = N->getMaskElt(4) / 4; 1746 unsigned M2 = N->getMaskElt(8) / 4; 1747 unsigned M3 = N->getMaskElt(12) / 4; 1748 1749 // If both vector operands for the shuffle are the same vector, the mask will 1750 // contain only elements from the first one and the second one will be undef. 1751 if (N->getOperand(1).isUndef()) { 1752 assert(M0 < 4 && "Indexing into an undef vector?"); 1753 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1754 return false; 1755 1756 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1757 Swap = false; 1758 return true; 1759 } 1760 1761 // Ensure each word index of the ShuffleVector Mask is consecutive. 1762 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1763 return false; 1764 1765 if (IsLE) { 1766 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1767 // Input vectors don't need to be swapped if the leading element 1768 // of the result is one of the 3 left elements of the second vector 1769 // (or if there is no shift to be done at all). 1770 Swap = false; 1771 ShiftElts = (8 - M0) % 8; 1772 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1773 // Input vectors need to be swapped if the leading element 1774 // of the result is one of the 3 left elements of the first vector 1775 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1776 Swap = true; 1777 ShiftElts = (4 - M0) % 4; 1778 } 1779 1780 return true; 1781 } else { // BE 1782 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1783 // Input vectors don't need to be swapped if the leading element 1784 // of the result is one of the 4 elements of the first vector. 1785 Swap = false; 1786 ShiftElts = M0; 1787 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1788 // Input vectors need to be swapped if the leading element 1789 // of the result is one of the 4 elements of the right vector. 1790 Swap = true; 1791 ShiftElts = M0 - 4; 1792 } 1793 1794 return true; 1795 } 1796 } 1797 1798 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1799 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1800 1801 if (!isNByteElemShuffleMask(N, Width, -1)) 1802 return false; 1803 1804 for (int i = 0; i < 16; i += Width) 1805 if (N->getMaskElt(i) != i + Width - 1) 1806 return false; 1807 1808 return true; 1809 } 1810 1811 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1812 return isXXBRShuffleMaskHelper(N, 2); 1813 } 1814 1815 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1816 return isXXBRShuffleMaskHelper(N, 4); 1817 } 1818 1819 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1820 return isXXBRShuffleMaskHelper(N, 8); 1821 } 1822 1823 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1824 return isXXBRShuffleMaskHelper(N, 16); 1825 } 1826 1827 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1828 /// if the inputs to the instruction should be swapped and set \p DM to the 1829 /// value for the immediate. 1830 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1831 /// AND element 0 of the result comes from the first input (LE) or second input 1832 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1833 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1834 /// mask. 1835 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1836 bool &Swap, bool IsLE) { 1837 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1838 1839 // Ensure each byte index of the double word is consecutive. 1840 if (!isNByteElemShuffleMask(N, 8, 1)) 1841 return false; 1842 1843 unsigned M0 = N->getMaskElt(0) / 8; 1844 unsigned M1 = N->getMaskElt(8) / 8; 1845 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1846 1847 // If both vector operands for the shuffle are the same vector, the mask will 1848 // contain only elements from the first one and the second one will be undef. 1849 if (N->getOperand(1).isUndef()) { 1850 if ((M0 | M1) < 2) { 1851 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1852 Swap = false; 1853 return true; 1854 } else 1855 return false; 1856 } 1857 1858 if (IsLE) { 1859 if (M0 > 1 && M1 < 2) { 1860 Swap = false; 1861 } else if (M0 < 2 && M1 > 1) { 1862 M0 = (M0 + 2) % 4; 1863 M1 = (M1 + 2) % 4; 1864 Swap = true; 1865 } else 1866 return false; 1867 1868 // Note: if control flow comes here that means Swap is already set above 1869 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 1870 return true; 1871 } else { // BE 1872 if (M0 < 2 && M1 > 1) { 1873 Swap = false; 1874 } else if (M0 > 1 && M1 < 2) { 1875 M0 = (M0 + 2) % 4; 1876 M1 = (M1 + 2) % 4; 1877 Swap = true; 1878 } else 1879 return false; 1880 1881 // Note: if control flow comes here that means Swap is already set above 1882 DM = (M0 << 1) + (M1 & 1); 1883 return true; 1884 } 1885 } 1886 1887 1888 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1889 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1890 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1891 SelectionDAG &DAG) { 1892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1893 assert(isSplatShuffleMask(SVOp, EltSize)); 1894 if (DAG.getDataLayout().isLittleEndian()) 1895 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1896 else 1897 return SVOp->getMaskElt(0) / EltSize; 1898 } 1899 1900 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1901 /// by using a vspltis[bhw] instruction of the specified element size, return 1902 /// the constant being splatted. The ByteSize field indicates the number of 1903 /// bytes of each element [124] -> [bhw]. 1904 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1905 SDValue OpVal(nullptr, 0); 1906 1907 // If ByteSize of the splat is bigger than the element size of the 1908 // build_vector, then we have a case where we are checking for a splat where 1909 // multiple elements of the buildvector are folded together into a single 1910 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1911 unsigned EltSize = 16/N->getNumOperands(); 1912 if (EltSize < ByteSize) { 1913 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1914 SDValue UniquedVals[4]; 1915 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1916 1917 // See if all of the elements in the buildvector agree across. 1918 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1919 if (N->getOperand(i).isUndef()) continue; 1920 // If the element isn't a constant, bail fully out. 1921 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1922 1923 if (!UniquedVals[i&(Multiple-1)].getNode()) 1924 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1925 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1926 return SDValue(); // no match. 1927 } 1928 1929 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1930 // either constant or undef values that are identical for each chunk. See 1931 // if these chunks can form into a larger vspltis*. 1932 1933 // Check to see if all of the leading entries are either 0 or -1. If 1934 // neither, then this won't fit into the immediate field. 1935 bool LeadingZero = true; 1936 bool LeadingOnes = true; 1937 for (unsigned i = 0; i != Multiple-1; ++i) { 1938 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1939 1940 LeadingZero &= isNullConstant(UniquedVals[i]); 1941 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 1942 } 1943 // Finally, check the least significant entry. 1944 if (LeadingZero) { 1945 if (!UniquedVals[Multiple-1].getNode()) 1946 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 1947 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1948 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 1949 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1950 } 1951 if (LeadingOnes) { 1952 if (!UniquedVals[Multiple-1].getNode()) 1953 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 1954 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1955 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1956 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1957 } 1958 1959 return SDValue(); 1960 } 1961 1962 // Check to see if this buildvec has a single non-undef value in its elements. 1963 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1964 if (N->getOperand(i).isUndef()) continue; 1965 if (!OpVal.getNode()) 1966 OpVal = N->getOperand(i); 1967 else if (OpVal != N->getOperand(i)) 1968 return SDValue(); 1969 } 1970 1971 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1972 1973 unsigned ValSizeInBytes = EltSize; 1974 uint64_t Value = 0; 1975 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1976 Value = CN->getZExtValue(); 1977 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 1978 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 1979 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 1980 } 1981 1982 // If the splat value is larger than the element value, then we can never do 1983 // this splat. The only case that we could fit the replicated bits into our 1984 // immediate field for would be zero, and we prefer to use vxor for it. 1985 if (ValSizeInBytes < ByteSize) return SDValue(); 1986 1987 // If the element value is larger than the splat value, check if it consists 1988 // of a repeated bit pattern of size ByteSize. 1989 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 1990 return SDValue(); 1991 1992 // Properly sign extend the value. 1993 int MaskVal = SignExtend32(Value, ByteSize * 8); 1994 1995 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 1996 if (MaskVal == 0) return SDValue(); 1997 1998 // Finally, if this value fits in a 5 bit sext field, return it 1999 if (SignExtend32<5>(MaskVal) == MaskVal) 2000 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2001 return SDValue(); 2002 } 2003 2004 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2005 /// amount, otherwise return -1. 2006 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2007 EVT VT = N->getValueType(0); 2008 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2009 return -1; 2010 2011 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2012 2013 // Find the first non-undef value in the shuffle mask. 2014 unsigned i; 2015 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2016 /*search*/; 2017 2018 if (i == 4) return -1; // all undef. 2019 2020 // Otherwise, check to see if the rest of the elements are consecutively 2021 // numbered from this value. 2022 unsigned ShiftAmt = SVOp->getMaskElt(i); 2023 if (ShiftAmt < i) return -1; 2024 ShiftAmt -= i; 2025 2026 // Check the rest of the elements to see if they are consecutive. 2027 for (++i; i != 4; ++i) 2028 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2029 return -1; 2030 2031 return ShiftAmt; 2032 } 2033 2034 //===----------------------------------------------------------------------===// 2035 // Addressing Mode Selection 2036 //===----------------------------------------------------------------------===// 2037 2038 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2039 /// or 64-bit immediate, and if the value can be accurately represented as a 2040 /// sign extension from a 16-bit value. If so, this returns true and the 2041 /// immediate. 2042 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2043 if (!isa<ConstantSDNode>(N)) 2044 return false; 2045 2046 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2047 if (N->getValueType(0) == MVT::i32) 2048 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2049 else 2050 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2051 } 2052 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2053 return isIntS16Immediate(Op.getNode(), Imm); 2054 } 2055 2056 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2057 /// can be represented as an indexed [r+r] operation. Returns false if it 2058 /// can be more efficiently represented with [r+imm]. 2059 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2060 SDValue &Index, 2061 SelectionDAG &DAG) const { 2062 int16_t imm = 0; 2063 if (N.getOpcode() == ISD::ADD) { 2064 if (isIntS16Immediate(N.getOperand(1), imm)) 2065 return false; // r+i 2066 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2067 return false; // r+i 2068 2069 Base = N.getOperand(0); 2070 Index = N.getOperand(1); 2071 return true; 2072 } else if (N.getOpcode() == ISD::OR) { 2073 if (isIntS16Immediate(N.getOperand(1), imm)) 2074 return false; // r+i can fold it if we can. 2075 2076 // If this is an or of disjoint bitfields, we can codegen this as an add 2077 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2078 // disjoint. 2079 KnownBits LHSKnown, RHSKnown; 2080 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2081 2082 if (LHSKnown.Zero.getBoolValue()) { 2083 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2084 // If all of the bits are known zero on the LHS or RHS, the add won't 2085 // carry. 2086 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2087 Base = N.getOperand(0); 2088 Index = N.getOperand(1); 2089 return true; 2090 } 2091 } 2092 } 2093 2094 return false; 2095 } 2096 2097 // If we happen to be doing an i64 load or store into a stack slot that has 2098 // less than a 4-byte alignment, then the frame-index elimination may need to 2099 // use an indexed load or store instruction (because the offset may not be a 2100 // multiple of 4). The extra register needed to hold the offset comes from the 2101 // register scavenger, and it is possible that the scavenger will need to use 2102 // an emergency spill slot. As a result, we need to make sure that a spill slot 2103 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2104 // stack slot. 2105 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2106 // FIXME: This does not handle the LWA case. 2107 if (VT != MVT::i64) 2108 return; 2109 2110 // NOTE: We'll exclude negative FIs here, which come from argument 2111 // lowering, because there are no known test cases triggering this problem 2112 // using packed structures (or similar). We can remove this exclusion if 2113 // we find such a test case. The reason why this is so test-case driven is 2114 // because this entire 'fixup' is only to prevent crashes (from the 2115 // register scavenger) on not-really-valid inputs. For example, if we have: 2116 // %a = alloca i1 2117 // %b = bitcast i1* %a to i64* 2118 // store i64* a, i64 b 2119 // then the store should really be marked as 'align 1', but is not. If it 2120 // were marked as 'align 1' then the indexed form would have been 2121 // instruction-selected initially, and the problem this 'fixup' is preventing 2122 // won't happen regardless. 2123 if (FrameIdx < 0) 2124 return; 2125 2126 MachineFunction &MF = DAG.getMachineFunction(); 2127 MachineFrameInfo &MFI = MF.getFrameInfo(); 2128 2129 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2130 if (Align >= 4) 2131 return; 2132 2133 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2134 FuncInfo->setHasNonRISpills(); 2135 } 2136 2137 /// Returns true if the address N can be represented by a base register plus 2138 /// a signed 16-bit displacement [r+imm], and if it is not better 2139 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2140 /// displacements that are multiples of that value. 2141 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2142 SDValue &Base, 2143 SelectionDAG &DAG, 2144 unsigned Alignment) const { 2145 // FIXME dl should come from parent load or store, not from address 2146 SDLoc dl(N); 2147 // If this can be more profitably realized as r+r, fail. 2148 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2149 return false; 2150 2151 if (N.getOpcode() == ISD::ADD) { 2152 int16_t imm = 0; 2153 if (isIntS16Immediate(N.getOperand(1), imm) && 2154 (!Alignment || (imm % Alignment) == 0)) { 2155 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2156 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2157 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2158 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2159 } else { 2160 Base = N.getOperand(0); 2161 } 2162 return true; // [r+i] 2163 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2164 // Match LOAD (ADD (X, Lo(G))). 2165 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2166 && "Cannot handle constant offsets yet!"); 2167 Disp = N.getOperand(1).getOperand(0); // The global address. 2168 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2169 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2170 Disp.getOpcode() == ISD::TargetConstantPool || 2171 Disp.getOpcode() == ISD::TargetJumpTable); 2172 Base = N.getOperand(0); 2173 return true; // [&g+r] 2174 } 2175 } else if (N.getOpcode() == ISD::OR) { 2176 int16_t imm = 0; 2177 if (isIntS16Immediate(N.getOperand(1), imm) && 2178 (!Alignment || (imm % Alignment) == 0)) { 2179 // If this is an or of disjoint bitfields, we can codegen this as an add 2180 // (for better address arithmetic) if the LHS and RHS of the OR are 2181 // provably disjoint. 2182 KnownBits LHSKnown; 2183 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2184 2185 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2186 // If all of the bits are known zero on the LHS or RHS, the add won't 2187 // carry. 2188 if (FrameIndexSDNode *FI = 2189 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2190 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2191 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2192 } else { 2193 Base = N.getOperand(0); 2194 } 2195 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2196 return true; 2197 } 2198 } 2199 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2200 // Loading from a constant address. 2201 2202 // If this address fits entirely in a 16-bit sext immediate field, codegen 2203 // this as "d, 0" 2204 int16_t Imm; 2205 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2206 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2207 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2208 CN->getValueType(0)); 2209 return true; 2210 } 2211 2212 // Handle 32-bit sext immediates with LIS + addr mode. 2213 if ((CN->getValueType(0) == MVT::i32 || 2214 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2215 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2216 int Addr = (int)CN->getZExtValue(); 2217 2218 // Otherwise, break this down into an LIS + disp. 2219 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2220 2221 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2222 MVT::i32); 2223 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2224 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2225 return true; 2226 } 2227 } 2228 2229 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2230 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2231 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2232 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2233 } else 2234 Base = N; 2235 return true; // [r+0] 2236 } 2237 2238 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2239 /// represented as an indexed [r+r] operation. 2240 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2241 SDValue &Index, 2242 SelectionDAG &DAG) const { 2243 // Check to see if we can easily represent this as an [r+r] address. This 2244 // will fail if it thinks that the address is more profitably represented as 2245 // reg+imm, e.g. where imm = 0. 2246 if (SelectAddressRegReg(N, Base, Index, DAG)) 2247 return true; 2248 2249 // If the address is the result of an add, we will utilize the fact that the 2250 // address calculation includes an implicit add. However, we can reduce 2251 // register pressure if we do not materialize a constant just for use as the 2252 // index register. We only get rid of the add if it is not an add of a 2253 // value and a 16-bit signed constant and both have a single use. 2254 int16_t imm = 0; 2255 if (N.getOpcode() == ISD::ADD && 2256 (!isIntS16Immediate(N.getOperand(1), imm) || 2257 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2258 Base = N.getOperand(0); 2259 Index = N.getOperand(1); 2260 return true; 2261 } 2262 2263 // Otherwise, do it the hard way, using R0 as the base register. 2264 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2265 N.getValueType()); 2266 Index = N; 2267 return true; 2268 } 2269 2270 /// getPreIndexedAddressParts - returns true by value, base pointer and 2271 /// offset pointer and addressing mode by reference if the node's address 2272 /// can be legally represented as pre-indexed load / store address. 2273 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2274 SDValue &Offset, 2275 ISD::MemIndexedMode &AM, 2276 SelectionDAG &DAG) const { 2277 if (DisablePPCPreinc) return false; 2278 2279 bool isLoad = true; 2280 SDValue Ptr; 2281 EVT VT; 2282 unsigned Alignment; 2283 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2284 Ptr = LD->getBasePtr(); 2285 VT = LD->getMemoryVT(); 2286 Alignment = LD->getAlignment(); 2287 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2288 Ptr = ST->getBasePtr(); 2289 VT = ST->getMemoryVT(); 2290 Alignment = ST->getAlignment(); 2291 isLoad = false; 2292 } else 2293 return false; 2294 2295 // PowerPC doesn't have preinc load/store instructions for vectors (except 2296 // for QPX, which does have preinc r+r forms). 2297 if (VT.isVector()) { 2298 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2299 return false; 2300 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2301 AM = ISD::PRE_INC; 2302 return true; 2303 } 2304 } 2305 2306 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2307 // Common code will reject creating a pre-inc form if the base pointer 2308 // is a frame index, or if N is a store and the base pointer is either 2309 // the same as or a predecessor of the value being stored. Check for 2310 // those situations here, and try with swapped Base/Offset instead. 2311 bool Swap = false; 2312 2313 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2314 Swap = true; 2315 else if (!isLoad) { 2316 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2317 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2318 Swap = true; 2319 } 2320 2321 if (Swap) 2322 std::swap(Base, Offset); 2323 2324 AM = ISD::PRE_INC; 2325 return true; 2326 } 2327 2328 // LDU/STU can only handle immediates that are a multiple of 4. 2329 if (VT != MVT::i64) { 2330 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2331 return false; 2332 } else { 2333 // LDU/STU need an address with at least 4-byte alignment. 2334 if (Alignment < 4) 2335 return false; 2336 2337 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2338 return false; 2339 } 2340 2341 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2342 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2343 // sext i32 to i64 when addr mode is r+i. 2344 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2345 LD->getExtensionType() == ISD::SEXTLOAD && 2346 isa<ConstantSDNode>(Offset)) 2347 return false; 2348 } 2349 2350 AM = ISD::PRE_INC; 2351 return true; 2352 } 2353 2354 //===----------------------------------------------------------------------===// 2355 // LowerOperation implementation 2356 //===----------------------------------------------------------------------===// 2357 2358 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2359 /// and LoOpFlags to the target MO flags. 2360 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2361 unsigned &HiOpFlags, unsigned &LoOpFlags, 2362 const GlobalValue *GV = nullptr) { 2363 HiOpFlags = PPCII::MO_HA; 2364 LoOpFlags = PPCII::MO_LO; 2365 2366 // Don't use the pic base if not in PIC relocation model. 2367 if (IsPIC) { 2368 HiOpFlags |= PPCII::MO_PIC_FLAG; 2369 LoOpFlags |= PPCII::MO_PIC_FLAG; 2370 } 2371 2372 // If this is a reference to a global value that requires a non-lazy-ptr, make 2373 // sure that instruction lowering adds it. 2374 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2375 HiOpFlags |= PPCII::MO_NLP_FLAG; 2376 LoOpFlags |= PPCII::MO_NLP_FLAG; 2377 2378 if (GV->hasHiddenVisibility()) { 2379 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2380 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2381 } 2382 } 2383 } 2384 2385 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2386 SelectionDAG &DAG) { 2387 SDLoc DL(HiPart); 2388 EVT PtrVT = HiPart.getValueType(); 2389 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2390 2391 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2392 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2393 2394 // With PIC, the first instruction is actually "GR+hi(&G)". 2395 if (isPIC) 2396 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2397 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2398 2399 // Generate non-pic code that has direct accesses to the constant pool. 2400 // The address of the global is just (hi(&g)+lo(&g)). 2401 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2402 } 2403 2404 static void setUsesTOCBasePtr(MachineFunction &MF) { 2405 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2406 FuncInfo->setUsesTOCBasePtr(); 2407 } 2408 2409 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2410 setUsesTOCBasePtr(DAG.getMachineFunction()); 2411 } 2412 2413 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2414 SDValue GA) { 2415 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2416 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2417 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2418 2419 SDValue Ops[] = { GA, Reg }; 2420 return DAG.getMemIntrinsicNode( 2421 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2422 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true, 2423 false, 0); 2424 } 2425 2426 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2427 SelectionDAG &DAG) const { 2428 EVT PtrVT = Op.getValueType(); 2429 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2430 const Constant *C = CP->getConstVal(); 2431 2432 // 64-bit SVR4 ABI code is always position-independent. 2433 // The actual address of the GlobalValue is stored in the TOC. 2434 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2435 setUsesTOCBasePtr(DAG); 2436 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2437 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2438 } 2439 2440 unsigned MOHiFlag, MOLoFlag; 2441 bool IsPIC = isPositionIndependent(); 2442 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2443 2444 if (IsPIC && Subtarget.isSVR4ABI()) { 2445 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2446 PPCII::MO_PIC_FLAG); 2447 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2448 } 2449 2450 SDValue CPIHi = 2451 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2452 SDValue CPILo = 2453 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2454 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2455 } 2456 2457 // For 64-bit PowerPC, prefer the more compact relative encodings. 2458 // This trades 32 bits per jump table entry for one or two instructions 2459 // on the jump site. 2460 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2461 if (isJumpTableRelative()) 2462 return MachineJumpTableInfo::EK_LabelDifference32; 2463 2464 return TargetLowering::getJumpTableEncoding(); 2465 } 2466 2467 bool PPCTargetLowering::isJumpTableRelative() const { 2468 if (Subtarget.isPPC64()) 2469 return true; 2470 return TargetLowering::isJumpTableRelative(); 2471 } 2472 2473 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2474 SelectionDAG &DAG) const { 2475 if (!Subtarget.isPPC64()) 2476 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2477 2478 switch (getTargetMachine().getCodeModel()) { 2479 case CodeModel::Small: 2480 case CodeModel::Medium: 2481 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2482 default: 2483 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2484 getPointerTy(DAG.getDataLayout())); 2485 } 2486 } 2487 2488 const MCExpr * 2489 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2490 unsigned JTI, 2491 MCContext &Ctx) const { 2492 if (!Subtarget.isPPC64()) 2493 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2494 2495 switch (getTargetMachine().getCodeModel()) { 2496 case CodeModel::Small: 2497 case CodeModel::Medium: 2498 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2499 default: 2500 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2501 } 2502 } 2503 2504 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2505 EVT PtrVT = Op.getValueType(); 2506 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2507 2508 // 64-bit SVR4 ABI code is always position-independent. 2509 // The actual address of the GlobalValue is stored in the TOC. 2510 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2511 setUsesTOCBasePtr(DAG); 2512 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2513 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2514 } 2515 2516 unsigned MOHiFlag, MOLoFlag; 2517 bool IsPIC = isPositionIndependent(); 2518 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2519 2520 if (IsPIC && Subtarget.isSVR4ABI()) { 2521 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2522 PPCII::MO_PIC_FLAG); 2523 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2524 } 2525 2526 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2527 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2528 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2529 } 2530 2531 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2532 SelectionDAG &DAG) const { 2533 EVT PtrVT = Op.getValueType(); 2534 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2535 const BlockAddress *BA = BASDN->getBlockAddress(); 2536 2537 // 64-bit SVR4 ABI code is always position-independent. 2538 // The actual BlockAddress is stored in the TOC. 2539 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2540 setUsesTOCBasePtr(DAG); 2541 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2542 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 2543 } 2544 2545 unsigned MOHiFlag, MOLoFlag; 2546 bool IsPIC = isPositionIndependent(); 2547 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2548 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2549 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2550 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2551 } 2552 2553 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2554 SelectionDAG &DAG) const { 2555 // FIXME: TLS addresses currently use medium model code sequences, 2556 // which is the most useful form. Eventually support for small and 2557 // large models could be added if users need it, at the cost of 2558 // additional complexity. 2559 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2560 if (DAG.getTarget().Options.EmulatedTLS) 2561 return LowerToTLSEmulatedModel(GA, DAG); 2562 2563 SDLoc dl(GA); 2564 const GlobalValue *GV = GA->getGlobal(); 2565 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2566 bool is64bit = Subtarget.isPPC64(); 2567 const Module *M = DAG.getMachineFunction().getFunction()->getParent(); 2568 PICLevel::Level picLevel = M->getPICLevel(); 2569 2570 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2571 2572 if (Model == TLSModel::LocalExec) { 2573 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2574 PPCII::MO_TPREL_HA); 2575 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2576 PPCII::MO_TPREL_LO); 2577 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2578 : DAG.getRegister(PPC::R2, MVT::i32); 2579 2580 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2581 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2582 } 2583 2584 if (Model == TLSModel::InitialExec) { 2585 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2586 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2587 PPCII::MO_TLS); 2588 SDValue GOTPtr; 2589 if (is64bit) { 2590 setUsesTOCBasePtr(DAG); 2591 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2592 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2593 PtrVT, GOTReg, TGA); 2594 } else 2595 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2596 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2597 PtrVT, TGA, GOTPtr); 2598 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2599 } 2600 2601 if (Model == TLSModel::GeneralDynamic) { 2602 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2603 SDValue GOTPtr; 2604 if (is64bit) { 2605 setUsesTOCBasePtr(DAG); 2606 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2607 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2608 GOTReg, TGA); 2609 } else { 2610 if (picLevel == PICLevel::SmallPIC) 2611 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2612 else 2613 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2614 } 2615 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2616 GOTPtr, TGA, TGA); 2617 } 2618 2619 if (Model == TLSModel::LocalDynamic) { 2620 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2621 SDValue GOTPtr; 2622 if (is64bit) { 2623 setUsesTOCBasePtr(DAG); 2624 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2625 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2626 GOTReg, TGA); 2627 } else { 2628 if (picLevel == PICLevel::SmallPIC) 2629 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2630 else 2631 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2632 } 2633 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2634 PtrVT, GOTPtr, TGA, TGA); 2635 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2636 PtrVT, TLSAddr, TGA); 2637 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2638 } 2639 2640 llvm_unreachable("Unknown TLS model!"); 2641 } 2642 2643 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2644 SelectionDAG &DAG) const { 2645 EVT PtrVT = Op.getValueType(); 2646 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2647 SDLoc DL(GSDN); 2648 const GlobalValue *GV = GSDN->getGlobal(); 2649 2650 // 64-bit SVR4 ABI code is always position-independent. 2651 // The actual address of the GlobalValue is stored in the TOC. 2652 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2653 setUsesTOCBasePtr(DAG); 2654 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2655 return getTOCEntry(DAG, DL, true, GA); 2656 } 2657 2658 unsigned MOHiFlag, MOLoFlag; 2659 bool IsPIC = isPositionIndependent(); 2660 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2661 2662 if (IsPIC && Subtarget.isSVR4ABI()) { 2663 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2664 GSDN->getOffset(), 2665 PPCII::MO_PIC_FLAG); 2666 return getTOCEntry(DAG, DL, false, GA); 2667 } 2668 2669 SDValue GAHi = 2670 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2671 SDValue GALo = 2672 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2673 2674 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2675 2676 // If the global reference is actually to a non-lazy-pointer, we have to do an 2677 // extra load to get the address of the global. 2678 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2679 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2680 return Ptr; 2681 } 2682 2683 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2684 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2685 SDLoc dl(Op); 2686 2687 if (Op.getValueType() == MVT::v2i64) { 2688 // When the operands themselves are v2i64 values, we need to do something 2689 // special because VSX has no underlying comparison operations for these. 2690 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2691 // Equality can be handled by casting to the legal type for Altivec 2692 // comparisons, everything else needs to be expanded. 2693 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2694 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2695 DAG.getSetCC(dl, MVT::v4i32, 2696 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2697 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2698 CC)); 2699 } 2700 2701 return SDValue(); 2702 } 2703 2704 // We handle most of these in the usual way. 2705 return Op; 2706 } 2707 2708 // If we're comparing for equality to zero, expose the fact that this is 2709 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2710 // fold the new nodes. 2711 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2712 return V; 2713 2714 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2715 // Leave comparisons against 0 and -1 alone for now, since they're usually 2716 // optimized. FIXME: revisit this when we can custom lower all setcc 2717 // optimizations. 2718 if (C->isAllOnesValue() || C->isNullValue()) 2719 return SDValue(); 2720 } 2721 2722 // If we have an integer seteq/setne, turn it into a compare against zero 2723 // by xor'ing the rhs with the lhs, which is faster than setting a 2724 // condition register, reading it back out, and masking the correct bit. The 2725 // normal approach here uses sub to do this instead of xor. Using xor exposes 2726 // the result to other bit-twiddling opportunities. 2727 EVT LHSVT = Op.getOperand(0).getValueType(); 2728 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2729 EVT VT = Op.getValueType(); 2730 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2731 Op.getOperand(1)); 2732 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2733 } 2734 return SDValue(); 2735 } 2736 2737 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2738 SDNode *Node = Op.getNode(); 2739 EVT VT = Node->getValueType(0); 2740 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2741 SDValue InChain = Node->getOperand(0); 2742 SDValue VAListPtr = Node->getOperand(1); 2743 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2744 SDLoc dl(Node); 2745 2746 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2747 2748 // gpr_index 2749 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2750 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2751 InChain = GprIndex.getValue(1); 2752 2753 if (VT == MVT::i64) { 2754 // Check if GprIndex is even 2755 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2756 DAG.getConstant(1, dl, MVT::i32)); 2757 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2758 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2759 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2760 DAG.getConstant(1, dl, MVT::i32)); 2761 // Align GprIndex to be even if it isn't 2762 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2763 GprIndex); 2764 } 2765 2766 // fpr index is 1 byte after gpr 2767 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2768 DAG.getConstant(1, dl, MVT::i32)); 2769 2770 // fpr 2771 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2772 FprPtr, MachinePointerInfo(SV), MVT::i8); 2773 InChain = FprIndex.getValue(1); 2774 2775 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2776 DAG.getConstant(8, dl, MVT::i32)); 2777 2778 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2779 DAG.getConstant(4, dl, MVT::i32)); 2780 2781 // areas 2782 SDValue OverflowArea = 2783 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2784 InChain = OverflowArea.getValue(1); 2785 2786 SDValue RegSaveArea = 2787 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2788 InChain = RegSaveArea.getValue(1); 2789 2790 // select overflow_area if index > 8 2791 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2792 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2793 2794 // adjustment constant gpr_index * 4/8 2795 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2796 VT.isInteger() ? GprIndex : FprIndex, 2797 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2798 MVT::i32)); 2799 2800 // OurReg = RegSaveArea + RegConstant 2801 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2802 RegConstant); 2803 2804 // Floating types are 32 bytes into RegSaveArea 2805 if (VT.isFloatingPoint()) 2806 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2807 DAG.getConstant(32, dl, MVT::i32)); 2808 2809 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2810 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2811 VT.isInteger() ? GprIndex : FprIndex, 2812 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2813 MVT::i32)); 2814 2815 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2816 VT.isInteger() ? VAListPtr : FprPtr, 2817 MachinePointerInfo(SV), MVT::i8); 2818 2819 // determine if we should load from reg_save_area or overflow_area 2820 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2821 2822 // increase overflow_area by 4/8 if gpr/fpr > 8 2823 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2824 DAG.getConstant(VT.isInteger() ? 4 : 8, 2825 dl, MVT::i32)); 2826 2827 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2828 OverflowAreaPlusN); 2829 2830 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2831 MachinePointerInfo(), MVT::i32); 2832 2833 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2834 } 2835 2836 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 2837 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2838 2839 // We have to copy the entire va_list struct: 2840 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2841 return DAG.getMemcpy(Op.getOperand(0), Op, 2842 Op.getOperand(1), Op.getOperand(2), 2843 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 2844 false, MachinePointerInfo(), MachinePointerInfo()); 2845 } 2846 2847 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2848 SelectionDAG &DAG) const { 2849 return Op.getOperand(0); 2850 } 2851 2852 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2853 SelectionDAG &DAG) const { 2854 SDValue Chain = Op.getOperand(0); 2855 SDValue Trmp = Op.getOperand(1); // trampoline 2856 SDValue FPtr = Op.getOperand(2); // nested function 2857 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2858 SDLoc dl(Op); 2859 2860 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2861 bool isPPC64 = (PtrVT == MVT::i64); 2862 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 2863 2864 TargetLowering::ArgListTy Args; 2865 TargetLowering::ArgListEntry Entry; 2866 2867 Entry.Ty = IntPtrTy; 2868 Entry.Node = Trmp; Args.push_back(Entry); 2869 2870 // TrampSize == (isPPC64 ? 48 : 40); 2871 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 2872 isPPC64 ? MVT::i64 : MVT::i32); 2873 Args.push_back(Entry); 2874 2875 Entry.Node = FPtr; Args.push_back(Entry); 2876 Entry.Node = Nest; Args.push_back(Entry); 2877 2878 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2879 TargetLowering::CallLoweringInfo CLI(DAG); 2880 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2881 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2882 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 2883 2884 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2885 return CallResult.second; 2886 } 2887 2888 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2889 MachineFunction &MF = DAG.getMachineFunction(); 2890 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2891 EVT PtrVT = getPointerTy(MF.getDataLayout()); 2892 2893 SDLoc dl(Op); 2894 2895 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2896 // vastart just stores the address of the VarArgsFrameIndex slot into the 2897 // memory location argument. 2898 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2899 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2900 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2901 MachinePointerInfo(SV)); 2902 } 2903 2904 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2905 // We suppose the given va_list is already allocated. 2906 // 2907 // typedef struct { 2908 // char gpr; /* index into the array of 8 GPRs 2909 // * stored in the register save area 2910 // * gpr=0 corresponds to r3, 2911 // * gpr=1 to r4, etc. 2912 // */ 2913 // char fpr; /* index into the array of 8 FPRs 2914 // * stored in the register save area 2915 // * fpr=0 corresponds to f1, 2916 // * fpr=1 to f2, etc. 2917 // */ 2918 // char *overflow_arg_area; 2919 // /* location on stack that holds 2920 // * the next overflow argument 2921 // */ 2922 // char *reg_save_area; 2923 // /* where r3:r10 and f1:f8 (if saved) 2924 // * are stored 2925 // */ 2926 // } va_list[1]; 2927 2928 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 2929 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 2930 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2931 PtrVT); 2932 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2933 PtrVT); 2934 2935 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2936 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 2937 2938 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2939 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 2940 2941 uint64_t FPROffset = 1; 2942 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 2943 2944 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2945 2946 // Store first byte : number of int regs 2947 SDValue firstStore = 2948 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 2949 MachinePointerInfo(SV), MVT::i8); 2950 uint64_t nextOffset = FPROffset; 2951 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2952 ConstFPROffset); 2953 2954 // Store second byte : number of float regs 2955 SDValue secondStore = 2956 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2957 MachinePointerInfo(SV, nextOffset), MVT::i8); 2958 nextOffset += StackOffset; 2959 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2960 2961 // Store second word : arguments given on stack 2962 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2963 MachinePointerInfo(SV, nextOffset)); 2964 nextOffset += FrameOffset; 2965 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2966 2967 // Store third word : arguments given in registers 2968 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2969 MachinePointerInfo(SV, nextOffset)); 2970 } 2971 2972 #include "PPCGenCallingConv.inc" 2973 2974 // Function whose sole purpose is to kill compiler warnings 2975 // stemming from unused functions included from PPCGenCallingConv.inc. 2976 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2977 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 2978 } 2979 2980 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 2981 CCValAssign::LocInfo &LocInfo, 2982 ISD::ArgFlagsTy &ArgFlags, 2983 CCState &State) { 2984 return true; 2985 } 2986 2987 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 2988 MVT &LocVT, 2989 CCValAssign::LocInfo &LocInfo, 2990 ISD::ArgFlagsTy &ArgFlags, 2991 CCState &State) { 2992 static const MCPhysReg ArgRegs[] = { 2993 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2994 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2995 }; 2996 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2997 2998 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2999 3000 // Skip one register if the first unallocated register has an even register 3001 // number and there are still argument registers available which have not been 3002 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3003 // need to skip a register if RegNum is odd. 3004 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3005 State.AllocateReg(ArgRegs[RegNum]); 3006 } 3007 3008 // Always return false here, as this function only makes sure that the first 3009 // unallocated register has an odd register number and does not actually 3010 // allocate a register for the current argument. 3011 return false; 3012 } 3013 3014 bool 3015 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3016 MVT &LocVT, 3017 CCValAssign::LocInfo &LocInfo, 3018 ISD::ArgFlagsTy &ArgFlags, 3019 CCState &State) { 3020 static const MCPhysReg ArgRegs[] = { 3021 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3022 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3023 }; 3024 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3025 3026 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3027 int RegsLeft = NumArgRegs - RegNum; 3028 3029 // Skip if there is not enough registers left for long double type (4 gpr regs 3030 // in soft float mode) and put long double argument on the stack. 3031 if (RegNum != NumArgRegs && RegsLeft < 4) { 3032 for (int i = 0; i < RegsLeft; i++) { 3033 State.AllocateReg(ArgRegs[RegNum + i]); 3034 } 3035 } 3036 3037 return false; 3038 } 3039 3040 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3041 MVT &LocVT, 3042 CCValAssign::LocInfo &LocInfo, 3043 ISD::ArgFlagsTy &ArgFlags, 3044 CCState &State) { 3045 static const MCPhysReg ArgRegs[] = { 3046 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3047 PPC::F8 3048 }; 3049 3050 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3051 3052 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3053 3054 // If there is only one Floating-point register left we need to put both f64 3055 // values of a split ppc_fp128 value on the stack. 3056 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3057 State.AllocateReg(ArgRegs[RegNum]); 3058 } 3059 3060 // Always return false here, as this function only makes sure that the two f64 3061 // values a ppc_fp128 value is split into are both passed in registers or both 3062 // passed on the stack and does not actually allocate a register for the 3063 // current argument. 3064 return false; 3065 } 3066 3067 /// FPR - The set of FP registers that should be allocated for arguments, 3068 /// on Darwin. 3069 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3070 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3071 PPC::F11, PPC::F12, PPC::F13}; 3072 3073 /// QFPR - The set of QPX registers that should be allocated for arguments. 3074 static const MCPhysReg QFPR[] = { 3075 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3076 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3077 3078 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3079 /// the stack. 3080 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3081 unsigned PtrByteSize) { 3082 unsigned ArgSize = ArgVT.getStoreSize(); 3083 if (Flags.isByVal()) 3084 ArgSize = Flags.getByValSize(); 3085 3086 // Round up to multiples of the pointer size, except for array members, 3087 // which are always packed. 3088 if (!Flags.isInConsecutiveRegs()) 3089 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3090 3091 return ArgSize; 3092 } 3093 3094 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3095 /// on the stack. 3096 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3097 ISD::ArgFlagsTy Flags, 3098 unsigned PtrByteSize) { 3099 unsigned Align = PtrByteSize; 3100 3101 // Altivec parameters are padded to a 16 byte boundary. 3102 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3103 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3104 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3105 ArgVT == MVT::v1i128) 3106 Align = 16; 3107 // QPX vector types stored in double-precision are padded to a 32 byte 3108 // boundary. 3109 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3110 Align = 32; 3111 3112 // ByVal parameters are aligned as requested. 3113 if (Flags.isByVal()) { 3114 unsigned BVAlign = Flags.getByValAlign(); 3115 if (BVAlign > PtrByteSize) { 3116 if (BVAlign % PtrByteSize != 0) 3117 llvm_unreachable( 3118 "ByVal alignment is not a multiple of the pointer size"); 3119 3120 Align = BVAlign; 3121 } 3122 } 3123 3124 // Array members are always packed to their original alignment. 3125 if (Flags.isInConsecutiveRegs()) { 3126 // If the array member was split into multiple registers, the first 3127 // needs to be aligned to the size of the full type. (Except for 3128 // ppcf128, which is only aligned as its f64 components.) 3129 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3130 Align = OrigVT.getStoreSize(); 3131 else 3132 Align = ArgVT.getStoreSize(); 3133 } 3134 3135 return Align; 3136 } 3137 3138 /// CalculateStackSlotUsed - Return whether this argument will use its 3139 /// stack slot (instead of being passed in registers). ArgOffset, 3140 /// AvailableFPRs, and AvailableVRs must hold the current argument 3141 /// position, and will be updated to account for this argument. 3142 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3143 ISD::ArgFlagsTy Flags, 3144 unsigned PtrByteSize, 3145 unsigned LinkageSize, 3146 unsigned ParamAreaSize, 3147 unsigned &ArgOffset, 3148 unsigned &AvailableFPRs, 3149 unsigned &AvailableVRs, bool HasQPX) { 3150 bool UseMemory = false; 3151 3152 // Respect alignment of argument on the stack. 3153 unsigned Align = 3154 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3155 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3156 // If there's no space left in the argument save area, we must 3157 // use memory (this check also catches zero-sized arguments). 3158 if (ArgOffset >= LinkageSize + ParamAreaSize) 3159 UseMemory = true; 3160 3161 // Allocate argument on the stack. 3162 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3163 if (Flags.isInConsecutiveRegsLast()) 3164 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3165 // If we overran the argument save area, we must use memory 3166 // (this check catches arguments passed partially in memory) 3167 if (ArgOffset > LinkageSize + ParamAreaSize) 3168 UseMemory = true; 3169 3170 // However, if the argument is actually passed in an FPR or a VR, 3171 // we don't use memory after all. 3172 if (!Flags.isByVal()) { 3173 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3174 // QPX registers overlap with the scalar FP registers. 3175 (HasQPX && (ArgVT == MVT::v4f32 || 3176 ArgVT == MVT::v4f64 || 3177 ArgVT == MVT::v4i1))) 3178 if (AvailableFPRs > 0) { 3179 --AvailableFPRs; 3180 return false; 3181 } 3182 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3183 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3184 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3185 ArgVT == MVT::v1i128) 3186 if (AvailableVRs > 0) { 3187 --AvailableVRs; 3188 return false; 3189 } 3190 } 3191 3192 return UseMemory; 3193 } 3194 3195 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3196 /// ensure minimum alignment required for target. 3197 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3198 unsigned NumBytes) { 3199 unsigned TargetAlign = Lowering->getStackAlignment(); 3200 unsigned AlignMask = TargetAlign - 1; 3201 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3202 return NumBytes; 3203 } 3204 3205 SDValue PPCTargetLowering::LowerFormalArguments( 3206 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3207 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3208 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3209 if (Subtarget.isSVR4ABI()) { 3210 if (Subtarget.isPPC64()) 3211 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3212 dl, DAG, InVals); 3213 else 3214 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3215 dl, DAG, InVals); 3216 } else { 3217 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3218 dl, DAG, InVals); 3219 } 3220 } 3221 3222 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3223 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3224 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3225 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3226 3227 // 32-bit SVR4 ABI Stack Frame Layout: 3228 // +-----------------------------------+ 3229 // +--> | Back chain | 3230 // | +-----------------------------------+ 3231 // | | Floating-point register save area | 3232 // | +-----------------------------------+ 3233 // | | General register save area | 3234 // | +-----------------------------------+ 3235 // | | CR save word | 3236 // | +-----------------------------------+ 3237 // | | VRSAVE save word | 3238 // | +-----------------------------------+ 3239 // | | Alignment padding | 3240 // | +-----------------------------------+ 3241 // | | Vector register save area | 3242 // | +-----------------------------------+ 3243 // | | Local variable space | 3244 // | +-----------------------------------+ 3245 // | | Parameter list area | 3246 // | +-----------------------------------+ 3247 // | | LR save word | 3248 // | +-----------------------------------+ 3249 // SP--> +--- | Back chain | 3250 // +-----------------------------------+ 3251 // 3252 // Specifications: 3253 // System V Application Binary Interface PowerPC Processor Supplement 3254 // AltiVec Technology Programming Interface Manual 3255 3256 MachineFunction &MF = DAG.getMachineFunction(); 3257 MachineFrameInfo &MFI = MF.getFrameInfo(); 3258 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3259 3260 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3261 // Potential tail calls could cause overwriting of argument stack slots. 3262 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3263 (CallConv == CallingConv::Fast)); 3264 unsigned PtrByteSize = 4; 3265 3266 // Assign locations to all of the incoming arguments. 3267 SmallVector<CCValAssign, 16> ArgLocs; 3268 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3269 *DAG.getContext()); 3270 3271 // Reserve space for the linkage area on the stack. 3272 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3273 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3274 if (useSoftFloat()) 3275 CCInfo.PreAnalyzeFormalArguments(Ins); 3276 3277 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3278 CCInfo.clearWasPPCF128(); 3279 3280 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3281 CCValAssign &VA = ArgLocs[i]; 3282 3283 // Arguments stored in registers. 3284 if (VA.isRegLoc()) { 3285 const TargetRegisterClass *RC; 3286 EVT ValVT = VA.getValVT(); 3287 3288 switch (ValVT.getSimpleVT().SimpleTy) { 3289 default: 3290 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3291 case MVT::i1: 3292 case MVT::i32: 3293 RC = &PPC::GPRCRegClass; 3294 break; 3295 case MVT::f32: 3296 if (Subtarget.hasP8Vector()) 3297 RC = &PPC::VSSRCRegClass; 3298 else 3299 RC = &PPC::F4RCRegClass; 3300 break; 3301 case MVT::f64: 3302 if (Subtarget.hasVSX()) 3303 RC = &PPC::VSFRCRegClass; 3304 else 3305 RC = &PPC::F8RCRegClass; 3306 break; 3307 case MVT::v16i8: 3308 case MVT::v8i16: 3309 case MVT::v4i32: 3310 RC = &PPC::VRRCRegClass; 3311 break; 3312 case MVT::v4f32: 3313 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3314 break; 3315 case MVT::v2f64: 3316 case MVT::v2i64: 3317 RC = &PPC::VRRCRegClass; 3318 break; 3319 case MVT::v4f64: 3320 RC = &PPC::QFRCRegClass; 3321 break; 3322 case MVT::v4i1: 3323 RC = &PPC::QBRCRegClass; 3324 break; 3325 } 3326 3327 // Transform the arguments stored in physical registers into virtual ones. 3328 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3329 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3330 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3331 3332 if (ValVT == MVT::i1) 3333 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3334 3335 InVals.push_back(ArgValue); 3336 } else { 3337 // Argument stored in memory. 3338 assert(VA.isMemLoc()); 3339 3340 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3341 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(), 3342 isImmutable); 3343 3344 // Create load nodes to retrieve arguments from the stack. 3345 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3346 InVals.push_back( 3347 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3348 } 3349 } 3350 3351 // Assign locations to all of the incoming aggregate by value arguments. 3352 // Aggregates passed by value are stored in the local variable space of the 3353 // caller's stack frame, right above the parameter list area. 3354 SmallVector<CCValAssign, 16> ByValArgLocs; 3355 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3356 ByValArgLocs, *DAG.getContext()); 3357 3358 // Reserve stack space for the allocations in CCInfo. 3359 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3360 3361 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3362 3363 // Area that is at least reserved in the caller of this function. 3364 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3365 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3366 3367 // Set the size that is at least reserved in caller of this function. Tail 3368 // call optimized function's reserved stack space needs to be aligned so that 3369 // taking the difference between two stack areas will result in an aligned 3370 // stack. 3371 MinReservedArea = 3372 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3373 FuncInfo->setMinReservedArea(MinReservedArea); 3374 3375 SmallVector<SDValue, 8> MemOps; 3376 3377 // If the function takes variable number of arguments, make a frame index for 3378 // the start of the first vararg value... for expansion of llvm.va_start. 3379 if (isVarArg) { 3380 static const MCPhysReg GPArgRegs[] = { 3381 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3382 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3383 }; 3384 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3385 3386 static const MCPhysReg FPArgRegs[] = { 3387 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3388 PPC::F8 3389 }; 3390 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3391 3392 if (useSoftFloat()) 3393 NumFPArgRegs = 0; 3394 3395 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3396 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3397 3398 // Make room for NumGPArgRegs and NumFPArgRegs. 3399 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3400 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3401 3402 FuncInfo->setVarArgsStackOffset( 3403 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3404 CCInfo.getNextStackOffset(), true)); 3405 3406 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3407 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3408 3409 // The fixed integer arguments of a variadic function are stored to the 3410 // VarArgsFrameIndex on the stack so that they may be loaded by 3411 // dereferencing the result of va_next. 3412 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3413 // Get an existing live-in vreg, or add a new one. 3414 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3415 if (!VReg) 3416 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3417 3418 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3419 SDValue Store = 3420 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3421 MemOps.push_back(Store); 3422 // Increment the address by four for the next argument to store 3423 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3424 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3425 } 3426 3427 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3428 // is set. 3429 // The double arguments are stored to the VarArgsFrameIndex 3430 // on the stack. 3431 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3432 // Get an existing live-in vreg, or add a new one. 3433 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3434 if (!VReg) 3435 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3436 3437 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3438 SDValue Store = 3439 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3440 MemOps.push_back(Store); 3441 // Increment the address by eight for the next argument to store 3442 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3443 PtrVT); 3444 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3445 } 3446 } 3447 3448 if (!MemOps.empty()) 3449 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3450 3451 return Chain; 3452 } 3453 3454 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3455 // value to MVT::i64 and then truncate to the correct register size. 3456 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3457 EVT ObjectVT, SelectionDAG &DAG, 3458 SDValue ArgVal, 3459 const SDLoc &dl) const { 3460 if (Flags.isSExt()) 3461 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3462 DAG.getValueType(ObjectVT)); 3463 else if (Flags.isZExt()) 3464 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3465 DAG.getValueType(ObjectVT)); 3466 3467 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3468 } 3469 3470 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3471 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3472 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3473 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3474 // TODO: add description of PPC stack frame format, or at least some docs. 3475 // 3476 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3477 bool isLittleEndian = Subtarget.isLittleEndian(); 3478 MachineFunction &MF = DAG.getMachineFunction(); 3479 MachineFrameInfo &MFI = MF.getFrameInfo(); 3480 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3481 3482 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3483 "fastcc not supported on varargs functions"); 3484 3485 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3486 // Potential tail calls could cause overwriting of argument stack slots. 3487 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3488 (CallConv == CallingConv::Fast)); 3489 unsigned PtrByteSize = 8; 3490 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3491 3492 static const MCPhysReg GPR[] = { 3493 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3494 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3495 }; 3496 static const MCPhysReg VR[] = { 3497 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3498 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3499 }; 3500 3501 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3502 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3503 const unsigned Num_VR_Regs = array_lengthof(VR); 3504 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3505 3506 // Do a first pass over the arguments to determine whether the ABI 3507 // guarantees that our caller has allocated the parameter save area 3508 // on its stack frame. In the ELFv1 ABI, this is always the case; 3509 // in the ELFv2 ABI, it is true if this is a vararg function or if 3510 // any parameter is located in a stack slot. 3511 3512 bool HasParameterArea = !isELFv2ABI || isVarArg; 3513 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3514 unsigned NumBytes = LinkageSize; 3515 unsigned AvailableFPRs = Num_FPR_Regs; 3516 unsigned AvailableVRs = Num_VR_Regs; 3517 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3518 if (Ins[i].Flags.isNest()) 3519 continue; 3520 3521 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3522 PtrByteSize, LinkageSize, ParamAreaSize, 3523 NumBytes, AvailableFPRs, AvailableVRs, 3524 Subtarget.hasQPX())) 3525 HasParameterArea = true; 3526 } 3527 3528 // Add DAG nodes to load the arguments or copy them out of registers. On 3529 // entry to a function on PPC, the arguments start after the linkage area, 3530 // although the first ones are often in registers. 3531 3532 unsigned ArgOffset = LinkageSize; 3533 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3534 unsigned &QFPR_idx = FPR_idx; 3535 SmallVector<SDValue, 8> MemOps; 3536 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3537 unsigned CurArgIdx = 0; 3538 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3539 SDValue ArgVal; 3540 bool needsLoad = false; 3541 EVT ObjectVT = Ins[ArgNo].VT; 3542 EVT OrigVT = Ins[ArgNo].ArgVT; 3543 unsigned ObjSize = ObjectVT.getStoreSize(); 3544 unsigned ArgSize = ObjSize; 3545 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3546 if (Ins[ArgNo].isOrigArg()) { 3547 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3548 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3549 } 3550 // We re-align the argument offset for each argument, except when using the 3551 // fast calling convention, when we need to make sure we do that only when 3552 // we'll actually use a stack slot. 3553 unsigned CurArgOffset, Align; 3554 auto ComputeArgOffset = [&]() { 3555 /* Respect alignment of argument on the stack. */ 3556 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3557 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3558 CurArgOffset = ArgOffset; 3559 }; 3560 3561 if (CallConv != CallingConv::Fast) { 3562 ComputeArgOffset(); 3563 3564 /* Compute GPR index associated with argument offset. */ 3565 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3566 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3567 } 3568 3569 // FIXME the codegen can be much improved in some cases. 3570 // We do not have to keep everything in memory. 3571 if (Flags.isByVal()) { 3572 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3573 3574 if (CallConv == CallingConv::Fast) 3575 ComputeArgOffset(); 3576 3577 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3578 ObjSize = Flags.getByValSize(); 3579 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3580 // Empty aggregate parameters do not take up registers. Examples: 3581 // struct { } a; 3582 // union { } b; 3583 // int c[0]; 3584 // etc. However, we have to provide a place-holder in InVals, so 3585 // pretend we have an 8-byte item at the current address for that 3586 // purpose. 3587 if (!ObjSize) { 3588 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3589 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3590 InVals.push_back(FIN); 3591 continue; 3592 } 3593 3594 // Create a stack object covering all stack doublewords occupied 3595 // by the argument. If the argument is (fully or partially) on 3596 // the stack, or if the argument is fully in registers but the 3597 // caller has allocated the parameter save anyway, we can refer 3598 // directly to the caller's stack frame. Otherwise, create a 3599 // local copy in our own frame. 3600 int FI; 3601 if (HasParameterArea || 3602 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3603 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3604 else 3605 FI = MFI.CreateStackObject(ArgSize, Align, false); 3606 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3607 3608 // Handle aggregates smaller than 8 bytes. 3609 if (ObjSize < PtrByteSize) { 3610 // The value of the object is its address, which differs from the 3611 // address of the enclosing doubleword on big-endian systems. 3612 SDValue Arg = FIN; 3613 if (!isLittleEndian) { 3614 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3615 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3616 } 3617 InVals.push_back(Arg); 3618 3619 if (GPR_idx != Num_GPR_Regs) { 3620 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3621 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3622 SDValue Store; 3623 3624 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3625 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3626 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3627 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3628 MachinePointerInfo(&*FuncArg), ObjType); 3629 } else { 3630 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3631 // store the whole register as-is to the parameter save area 3632 // slot. 3633 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3634 MachinePointerInfo(&*FuncArg)); 3635 } 3636 3637 MemOps.push_back(Store); 3638 } 3639 // Whether we copied from a register or not, advance the offset 3640 // into the parameter save area by a full doubleword. 3641 ArgOffset += PtrByteSize; 3642 continue; 3643 } 3644 3645 // The value of the object is its address, which is the address of 3646 // its first stack doubleword. 3647 InVals.push_back(FIN); 3648 3649 // Store whatever pieces of the object are in registers to memory. 3650 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3651 if (GPR_idx == Num_GPR_Regs) 3652 break; 3653 3654 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3655 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3656 SDValue Addr = FIN; 3657 if (j) { 3658 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3659 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3660 } 3661 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3662 MachinePointerInfo(&*FuncArg, j)); 3663 MemOps.push_back(Store); 3664 ++GPR_idx; 3665 } 3666 ArgOffset += ArgSize; 3667 continue; 3668 } 3669 3670 switch (ObjectVT.getSimpleVT().SimpleTy) { 3671 default: llvm_unreachable("Unhandled argument type!"); 3672 case MVT::i1: 3673 case MVT::i32: 3674 case MVT::i64: 3675 if (Flags.isNest()) { 3676 // The 'nest' parameter, if any, is passed in R11. 3677 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3678 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3679 3680 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3681 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3682 3683 break; 3684 } 3685 3686 // These can be scalar arguments or elements of an integer array type 3687 // passed directly. Clang may use those instead of "byval" aggregate 3688 // types to avoid forcing arguments to memory unnecessarily. 3689 if (GPR_idx != Num_GPR_Regs) { 3690 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3691 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3692 3693 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3694 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3695 // value to MVT::i64 and then truncate to the correct register size. 3696 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3697 } else { 3698 if (CallConv == CallingConv::Fast) 3699 ComputeArgOffset(); 3700 3701 needsLoad = true; 3702 ArgSize = PtrByteSize; 3703 } 3704 if (CallConv != CallingConv::Fast || needsLoad) 3705 ArgOffset += 8; 3706 break; 3707 3708 case MVT::f32: 3709 case MVT::f64: 3710 // These can be scalar arguments or elements of a float array type 3711 // passed directly. The latter are used to implement ELFv2 homogenous 3712 // float aggregates. 3713 if (FPR_idx != Num_FPR_Regs) { 3714 unsigned VReg; 3715 3716 if (ObjectVT == MVT::f32) 3717 VReg = MF.addLiveIn(FPR[FPR_idx], 3718 Subtarget.hasP8Vector() 3719 ? &PPC::VSSRCRegClass 3720 : &PPC::F4RCRegClass); 3721 else 3722 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3723 ? &PPC::VSFRCRegClass 3724 : &PPC::F8RCRegClass); 3725 3726 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3727 ++FPR_idx; 3728 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3729 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3730 // once we support fp <-> gpr moves. 3731 3732 // This can only ever happen in the presence of f32 array types, 3733 // since otherwise we never run out of FPRs before running out 3734 // of GPRs. 3735 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3736 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3737 3738 if (ObjectVT == MVT::f32) { 3739 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3740 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3741 DAG.getConstant(32, dl, MVT::i32)); 3742 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3743 } 3744 3745 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3746 } else { 3747 if (CallConv == CallingConv::Fast) 3748 ComputeArgOffset(); 3749 3750 needsLoad = true; 3751 } 3752 3753 // When passing an array of floats, the array occupies consecutive 3754 // space in the argument area; only round up to the next doubleword 3755 // at the end of the array. Otherwise, each float takes 8 bytes. 3756 if (CallConv != CallingConv::Fast || needsLoad) { 3757 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3758 ArgOffset += ArgSize; 3759 if (Flags.isInConsecutiveRegsLast()) 3760 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3761 } 3762 break; 3763 case MVT::v4f32: 3764 case MVT::v4i32: 3765 case MVT::v8i16: 3766 case MVT::v16i8: 3767 case MVT::v2f64: 3768 case MVT::v2i64: 3769 case MVT::v1i128: 3770 if (!Subtarget.hasQPX()) { 3771 // These can be scalar arguments or elements of a vector array type 3772 // passed directly. The latter are used to implement ELFv2 homogenous 3773 // vector aggregates. 3774 if (VR_idx != Num_VR_Regs) { 3775 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3776 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3777 ++VR_idx; 3778 } else { 3779 if (CallConv == CallingConv::Fast) 3780 ComputeArgOffset(); 3781 3782 needsLoad = true; 3783 } 3784 if (CallConv != CallingConv::Fast || needsLoad) 3785 ArgOffset += 16; 3786 break; 3787 } // not QPX 3788 3789 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3790 "Invalid QPX parameter type"); 3791 /* fall through */ 3792 3793 case MVT::v4f64: 3794 case MVT::v4i1: 3795 // QPX vectors are treated like their scalar floating-point subregisters 3796 // (except that they're larger). 3797 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3798 if (QFPR_idx != Num_QFPR_Regs) { 3799 const TargetRegisterClass *RC; 3800 switch (ObjectVT.getSimpleVT().SimpleTy) { 3801 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3802 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3803 default: RC = &PPC::QBRCRegClass; break; 3804 } 3805 3806 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3807 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3808 ++QFPR_idx; 3809 } else { 3810 if (CallConv == CallingConv::Fast) 3811 ComputeArgOffset(); 3812 needsLoad = true; 3813 } 3814 if (CallConv != CallingConv::Fast || needsLoad) 3815 ArgOffset += Sz; 3816 break; 3817 } 3818 3819 // We need to load the argument to a virtual register if we determined 3820 // above that we ran out of physical registers of the appropriate type. 3821 if (needsLoad) { 3822 if (ObjSize < ArgSize && !isLittleEndian) 3823 CurArgOffset += ArgSize - ObjSize; 3824 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3825 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3826 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3827 } 3828 3829 InVals.push_back(ArgVal); 3830 } 3831 3832 // Area that is at least reserved in the caller of this function. 3833 unsigned MinReservedArea; 3834 if (HasParameterArea) 3835 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3836 else 3837 MinReservedArea = LinkageSize; 3838 3839 // Set the size that is at least reserved in caller of this function. Tail 3840 // call optimized functions' reserved stack space needs to be aligned so that 3841 // taking the difference between two stack areas will result in an aligned 3842 // stack. 3843 MinReservedArea = 3844 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3845 FuncInfo->setMinReservedArea(MinReservedArea); 3846 3847 // If the function takes variable number of arguments, make a frame index for 3848 // the start of the first vararg value... for expansion of llvm.va_start. 3849 if (isVarArg) { 3850 int Depth = ArgOffset; 3851 3852 FuncInfo->setVarArgsFrameIndex( 3853 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3854 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3855 3856 // If this function is vararg, store any remaining integer argument regs 3857 // to their spots on the stack so that they may be loaded by dereferencing 3858 // the result of va_next. 3859 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3860 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3861 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3862 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3863 SDValue Store = 3864 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3865 MemOps.push_back(Store); 3866 // Increment the address by four for the next argument to store 3867 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3868 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3869 } 3870 } 3871 3872 if (!MemOps.empty()) 3873 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3874 3875 return Chain; 3876 } 3877 3878 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3879 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3880 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3881 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3882 // TODO: add description of PPC stack frame format, or at least some docs. 3883 // 3884 MachineFunction &MF = DAG.getMachineFunction(); 3885 MachineFrameInfo &MFI = MF.getFrameInfo(); 3886 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3887 3888 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3889 bool isPPC64 = PtrVT == MVT::i64; 3890 // Potential tail calls could cause overwriting of argument stack slots. 3891 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3892 (CallConv == CallingConv::Fast)); 3893 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3894 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3895 unsigned ArgOffset = LinkageSize; 3896 // Area that is at least reserved in caller of this function. 3897 unsigned MinReservedArea = ArgOffset; 3898 3899 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3900 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3901 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3902 }; 3903 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3904 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3905 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3906 }; 3907 static const MCPhysReg VR[] = { 3908 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3909 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3910 }; 3911 3912 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3913 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3914 const unsigned Num_VR_Regs = array_lengthof( VR); 3915 3916 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3917 3918 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3919 3920 // In 32-bit non-varargs functions, the stack space for vectors is after the 3921 // stack space for non-vectors. We do not use this space unless we have 3922 // too many vectors to fit in registers, something that only occurs in 3923 // constructed examples:), but we have to walk the arglist to figure 3924 // that out...for the pathological case, compute VecArgOffset as the 3925 // start of the vector parameter area. Computing VecArgOffset is the 3926 // entire point of the following loop. 3927 unsigned VecArgOffset = ArgOffset; 3928 if (!isVarArg && !isPPC64) { 3929 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3930 ++ArgNo) { 3931 EVT ObjectVT = Ins[ArgNo].VT; 3932 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3933 3934 if (Flags.isByVal()) { 3935 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3936 unsigned ObjSize = Flags.getByValSize(); 3937 unsigned ArgSize = 3938 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3939 VecArgOffset += ArgSize; 3940 continue; 3941 } 3942 3943 switch(ObjectVT.getSimpleVT().SimpleTy) { 3944 default: llvm_unreachable("Unhandled argument type!"); 3945 case MVT::i1: 3946 case MVT::i32: 3947 case MVT::f32: 3948 VecArgOffset += 4; 3949 break; 3950 case MVT::i64: // PPC64 3951 case MVT::f64: 3952 // FIXME: We are guaranteed to be !isPPC64 at this point. 3953 // Does MVT::i64 apply? 3954 VecArgOffset += 8; 3955 break; 3956 case MVT::v4f32: 3957 case MVT::v4i32: 3958 case MVT::v8i16: 3959 case MVT::v16i8: 3960 // Nothing to do, we're only looking at Nonvector args here. 3961 break; 3962 } 3963 } 3964 } 3965 // We've found where the vector parameter area in memory is. Skip the 3966 // first 12 parameters; these don't use that memory. 3967 VecArgOffset = ((VecArgOffset+15)/16)*16; 3968 VecArgOffset += 12*16; 3969 3970 // Add DAG nodes to load the arguments or copy them out of registers. On 3971 // entry to a function on PPC, the arguments start after the linkage area, 3972 // although the first ones are often in registers. 3973 3974 SmallVector<SDValue, 8> MemOps; 3975 unsigned nAltivecParamsAtEnd = 0; 3976 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3977 unsigned CurArgIdx = 0; 3978 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3979 SDValue ArgVal; 3980 bool needsLoad = false; 3981 EVT ObjectVT = Ins[ArgNo].VT; 3982 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 3983 unsigned ArgSize = ObjSize; 3984 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3985 if (Ins[ArgNo].isOrigArg()) { 3986 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3987 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3988 } 3989 unsigned CurArgOffset = ArgOffset; 3990 3991 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 3992 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 3993 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 3994 if (isVarArg || isPPC64) { 3995 MinReservedArea = ((MinReservedArea+15)/16)*16; 3996 MinReservedArea += CalculateStackSlotSize(ObjectVT, 3997 Flags, 3998 PtrByteSize); 3999 } else nAltivecParamsAtEnd++; 4000 } else 4001 // Calculate min reserved area. 4002 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4003 Flags, 4004 PtrByteSize); 4005 4006 // FIXME the codegen can be much improved in some cases. 4007 // We do not have to keep everything in memory. 4008 if (Flags.isByVal()) { 4009 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4010 4011 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4012 ObjSize = Flags.getByValSize(); 4013 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4014 // Objects of size 1 and 2 are right justified, everything else is 4015 // left justified. This means the memory address is adjusted forwards. 4016 if (ObjSize==1 || ObjSize==2) { 4017 CurArgOffset = CurArgOffset + (4 - ObjSize); 4018 } 4019 // The value of the object is its address. 4020 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4021 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4022 InVals.push_back(FIN); 4023 if (ObjSize==1 || ObjSize==2) { 4024 if (GPR_idx != Num_GPR_Regs) { 4025 unsigned VReg; 4026 if (isPPC64) 4027 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4028 else 4029 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4030 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4031 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4032 SDValue Store = 4033 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4034 MachinePointerInfo(&*FuncArg), ObjType); 4035 MemOps.push_back(Store); 4036 ++GPR_idx; 4037 } 4038 4039 ArgOffset += PtrByteSize; 4040 4041 continue; 4042 } 4043 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4044 // Store whatever pieces of the object are in registers 4045 // to memory. ArgOffset will be the address of the beginning 4046 // of the object. 4047 if (GPR_idx != Num_GPR_Regs) { 4048 unsigned VReg; 4049 if (isPPC64) 4050 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4051 else 4052 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4053 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4054 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4055 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4056 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4057 MachinePointerInfo(&*FuncArg, j)); 4058 MemOps.push_back(Store); 4059 ++GPR_idx; 4060 ArgOffset += PtrByteSize; 4061 } else { 4062 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4063 break; 4064 } 4065 } 4066 continue; 4067 } 4068 4069 switch (ObjectVT.getSimpleVT().SimpleTy) { 4070 default: llvm_unreachable("Unhandled argument type!"); 4071 case MVT::i1: 4072 case MVT::i32: 4073 if (!isPPC64) { 4074 if (GPR_idx != Num_GPR_Regs) { 4075 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4076 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4077 4078 if (ObjectVT == MVT::i1) 4079 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4080 4081 ++GPR_idx; 4082 } else { 4083 needsLoad = true; 4084 ArgSize = PtrByteSize; 4085 } 4086 // All int arguments reserve stack space in the Darwin ABI. 4087 ArgOffset += PtrByteSize; 4088 break; 4089 } 4090 LLVM_FALLTHROUGH; 4091 case MVT::i64: // PPC64 4092 if (GPR_idx != Num_GPR_Regs) { 4093 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4094 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4095 4096 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4097 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4098 // value to MVT::i64 and then truncate to the correct register size. 4099 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4100 4101 ++GPR_idx; 4102 } else { 4103 needsLoad = true; 4104 ArgSize = PtrByteSize; 4105 } 4106 // All int arguments reserve stack space in the Darwin ABI. 4107 ArgOffset += 8; 4108 break; 4109 4110 case MVT::f32: 4111 case MVT::f64: 4112 // Every 4 bytes of argument space consumes one of the GPRs available for 4113 // argument passing. 4114 if (GPR_idx != Num_GPR_Regs) { 4115 ++GPR_idx; 4116 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4117 ++GPR_idx; 4118 } 4119 if (FPR_idx != Num_FPR_Regs) { 4120 unsigned VReg; 4121 4122 if (ObjectVT == MVT::f32) 4123 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4124 else 4125 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4126 4127 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4128 ++FPR_idx; 4129 } else { 4130 needsLoad = true; 4131 } 4132 4133 // All FP arguments reserve stack space in the Darwin ABI. 4134 ArgOffset += isPPC64 ? 8 : ObjSize; 4135 break; 4136 case MVT::v4f32: 4137 case MVT::v4i32: 4138 case MVT::v8i16: 4139 case MVT::v16i8: 4140 // Note that vector arguments in registers don't reserve stack space, 4141 // except in varargs functions. 4142 if (VR_idx != Num_VR_Regs) { 4143 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4144 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4145 if (isVarArg) { 4146 while ((ArgOffset % 16) != 0) { 4147 ArgOffset += PtrByteSize; 4148 if (GPR_idx != Num_GPR_Regs) 4149 GPR_idx++; 4150 } 4151 ArgOffset += 16; 4152 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4153 } 4154 ++VR_idx; 4155 } else { 4156 if (!isVarArg && !isPPC64) { 4157 // Vectors go after all the nonvectors. 4158 CurArgOffset = VecArgOffset; 4159 VecArgOffset += 16; 4160 } else { 4161 // Vectors are aligned. 4162 ArgOffset = ((ArgOffset+15)/16)*16; 4163 CurArgOffset = ArgOffset; 4164 ArgOffset += 16; 4165 } 4166 needsLoad = true; 4167 } 4168 break; 4169 } 4170 4171 // We need to load the argument to a virtual register if we determined above 4172 // that we ran out of physical registers of the appropriate type. 4173 if (needsLoad) { 4174 int FI = MFI.CreateFixedObject(ObjSize, 4175 CurArgOffset + (ArgSize - ObjSize), 4176 isImmutable); 4177 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4178 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4179 } 4180 4181 InVals.push_back(ArgVal); 4182 } 4183 4184 // Allow for Altivec parameters at the end, if needed. 4185 if (nAltivecParamsAtEnd) { 4186 MinReservedArea = ((MinReservedArea+15)/16)*16; 4187 MinReservedArea += 16*nAltivecParamsAtEnd; 4188 } 4189 4190 // Area that is at least reserved in the caller of this function. 4191 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4192 4193 // Set the size that is at least reserved in caller of this function. Tail 4194 // call optimized functions' reserved stack space needs to be aligned so that 4195 // taking the difference between two stack areas will result in an aligned 4196 // stack. 4197 MinReservedArea = 4198 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4199 FuncInfo->setMinReservedArea(MinReservedArea); 4200 4201 // If the function takes variable number of arguments, make a frame index for 4202 // the start of the first vararg value... for expansion of llvm.va_start. 4203 if (isVarArg) { 4204 int Depth = ArgOffset; 4205 4206 FuncInfo->setVarArgsFrameIndex( 4207 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4208 Depth, true)); 4209 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4210 4211 // If this function is vararg, store any remaining integer argument regs 4212 // to their spots on the stack so that they may be loaded by dereferencing 4213 // the result of va_next. 4214 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4215 unsigned VReg; 4216 4217 if (isPPC64) 4218 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4219 else 4220 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4221 4222 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4223 SDValue Store = 4224 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4225 MemOps.push_back(Store); 4226 // Increment the address by four for the next argument to store 4227 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4228 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4229 } 4230 } 4231 4232 if (!MemOps.empty()) 4233 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4234 4235 return Chain; 4236 } 4237 4238 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4239 /// adjusted to accommodate the arguments for the tailcall. 4240 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4241 unsigned ParamSize) { 4242 4243 if (!isTailCall) return 0; 4244 4245 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4246 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4247 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4248 // Remember only if the new adjustement is bigger. 4249 if (SPDiff < FI->getTailCallSPDelta()) 4250 FI->setTailCallSPDelta(SPDiff); 4251 4252 return SPDiff; 4253 } 4254 4255 static bool isFunctionGlobalAddress(SDValue Callee); 4256 4257 static bool 4258 callsShareTOCBase(const Function *Caller, SDValue Callee, 4259 const TargetMachine &TM) { 4260 // If !G, Callee can be an external symbol. 4261 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4262 if (!G) 4263 return false; 4264 4265 // The medium and large code models are expected to provide a sufficiently 4266 // large TOC to provide all data addressing needs of a module with a 4267 // single TOC. Since each module will be addressed with a single TOC then we 4268 // only need to check that caller and callee don't cross dso boundaries. 4269 if (CodeModel::Medium == TM.getCodeModel() || 4270 CodeModel::Large == TM.getCodeModel()) 4271 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4272 4273 // Otherwise we need to ensure callee and caller are in the same section, 4274 // since the linker may allocate multiple TOCs, and we don't know which 4275 // sections will belong to the same TOC base. 4276 4277 const GlobalValue *GV = G->getGlobal(); 4278 if (!GV->isStrongDefinitionForLinker()) 4279 return false; 4280 4281 // Any explicitly-specified sections and section prefixes must also match. 4282 // Also, if we're using -ffunction-sections, then each function is always in 4283 // a different section (the same is true for COMDAT functions). 4284 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4285 GV->getSection() != Caller->getSection()) 4286 return false; 4287 if (const auto *F = dyn_cast<Function>(GV)) { 4288 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4289 return false; 4290 } 4291 4292 // If the callee might be interposed, then we can't assume the ultimate call 4293 // target will be in the same section. Even in cases where we can assume that 4294 // interposition won't happen, in any case where the linker might insert a 4295 // stub to allow for interposition, we must generate code as though 4296 // interposition might occur. To understand why this matters, consider a 4297 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4298 // in the same section, but a is in a different module (i.e. has a different 4299 // TOC base pointer). If the linker allows for interposition between b and c, 4300 // then it will generate a stub for the call edge between b and c which will 4301 // save the TOC pointer into the designated stack slot allocated by b. If we 4302 // return true here, and therefore allow a tail call between b and c, that 4303 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4304 // pointer into the stack slot allocated by a (where the a -> b stub saved 4305 // a's TOC base pointer). If we're not considering a tail call, but rather, 4306 // whether a nop is needed after the call instruction in b, because the linker 4307 // will insert a stub, it might complain about a missing nop if we omit it 4308 // (although many don't complain in this case). 4309 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4310 return false; 4311 4312 return true; 4313 } 4314 4315 static bool 4316 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4317 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4318 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4319 4320 const unsigned PtrByteSize = 8; 4321 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4322 4323 static const MCPhysReg GPR[] = { 4324 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4325 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4326 }; 4327 static const MCPhysReg VR[] = { 4328 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4329 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4330 }; 4331 4332 const unsigned NumGPRs = array_lengthof(GPR); 4333 const unsigned NumFPRs = 13; 4334 const unsigned NumVRs = array_lengthof(VR); 4335 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4336 4337 unsigned NumBytes = LinkageSize; 4338 unsigned AvailableFPRs = NumFPRs; 4339 unsigned AvailableVRs = NumVRs; 4340 4341 for (const ISD::OutputArg& Param : Outs) { 4342 if (Param.Flags.isNest()) continue; 4343 4344 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4345 PtrByteSize, LinkageSize, ParamAreaSize, 4346 NumBytes, AvailableFPRs, AvailableVRs, 4347 Subtarget.hasQPX())) 4348 return true; 4349 } 4350 return false; 4351 } 4352 4353 static bool 4354 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4355 if (CS.arg_size() != CallerFn->arg_size()) 4356 return false; 4357 4358 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4359 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4360 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4361 4362 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4363 const Value* CalleeArg = *CalleeArgIter; 4364 const Value* CallerArg = &(*CallerArgIter); 4365 if (CalleeArg == CallerArg) 4366 continue; 4367 4368 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4369 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4370 // } 4371 // 1st argument of callee is undef and has the same type as caller. 4372 if (CalleeArg->getType() == CallerArg->getType() && 4373 isa<UndefValue>(CalleeArg)) 4374 continue; 4375 4376 return false; 4377 } 4378 4379 return true; 4380 } 4381 4382 bool 4383 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4384 SDValue Callee, 4385 CallingConv::ID CalleeCC, 4386 ImmutableCallSite CS, 4387 bool isVarArg, 4388 const SmallVectorImpl<ISD::OutputArg> &Outs, 4389 const SmallVectorImpl<ISD::InputArg> &Ins, 4390 SelectionDAG& DAG) const { 4391 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4392 4393 if (DisableSCO && !TailCallOpt) return false; 4394 4395 // Variadic argument functions are not supported. 4396 if (isVarArg) return false; 4397 4398 MachineFunction &MF = DAG.getMachineFunction(); 4399 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4400 4401 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has 4402 // the same calling convention 4403 if (CallerCC != CalleeCC) return false; 4404 4405 // SCO support C calling convention 4406 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C) 4407 return false; 4408 4409 // Caller contains any byval parameter is not supported. 4410 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4411 return false; 4412 4413 // Callee contains any byval parameter is not supported, too. 4414 // Note: This is a quick work around, because in some cases, e.g. 4415 // caller's stack size > callee's stack size, we are still able to apply 4416 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574 4417 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4418 return false; 4419 4420 // No TCO/SCO on indirect call because Caller have to restore its TOC 4421 if (!isFunctionGlobalAddress(Callee) && 4422 !isa<ExternalSymbolSDNode>(Callee)) 4423 return false; 4424 4425 // If the caller and callee potentially have different TOC bases then we 4426 // cannot tail call since we need to restore the TOC pointer after the call. 4427 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4428 if (!callsShareTOCBase(MF.getFunction(), Callee, getTargetMachine())) 4429 return false; 4430 4431 // TCO allows altering callee ABI, so we don't have to check further. 4432 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4433 return true; 4434 4435 if (DisableSCO) return false; 4436 4437 // If callee use the same argument list that caller is using, then we can 4438 // apply SCO on this case. If it is not, then we need to check if callee needs 4439 // stack for passing arguments. 4440 if (!hasSameArgumentList(MF.getFunction(), CS) && 4441 needStackSlotPassParameters(Subtarget, Outs)) { 4442 return false; 4443 } 4444 4445 return true; 4446 } 4447 4448 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4449 /// for tail call optimization. Targets which want to do tail call 4450 /// optimization should implement this function. 4451 bool 4452 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4453 CallingConv::ID CalleeCC, 4454 bool isVarArg, 4455 const SmallVectorImpl<ISD::InputArg> &Ins, 4456 SelectionDAG& DAG) const { 4457 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4458 return false; 4459 4460 // Variable argument functions are not supported. 4461 if (isVarArg) 4462 return false; 4463 4464 MachineFunction &MF = DAG.getMachineFunction(); 4465 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4466 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4467 // Functions containing by val parameters are not supported. 4468 for (unsigned i = 0; i != Ins.size(); i++) { 4469 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4470 if (Flags.isByVal()) return false; 4471 } 4472 4473 // Non-PIC/GOT tail calls are supported. 4474 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4475 return true; 4476 4477 // At the moment we can only do local tail calls (in same module, hidden 4478 // or protected) if we are generating PIC. 4479 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4480 return G->getGlobal()->hasHiddenVisibility() 4481 || G->getGlobal()->hasProtectedVisibility(); 4482 } 4483 4484 return false; 4485 } 4486 4487 /// isCallCompatibleAddress - Return the immediate to use if the specified 4488 /// 32-bit value is representable in the immediate field of a BxA instruction. 4489 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4490 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4491 if (!C) return nullptr; 4492 4493 int Addr = C->getZExtValue(); 4494 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4495 SignExtend32<26>(Addr) != Addr) 4496 return nullptr; // Top 6 bits have to be sext of immediate. 4497 4498 return DAG 4499 .getConstant( 4500 (int)C->getZExtValue() >> 2, SDLoc(Op), 4501 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4502 .getNode(); 4503 } 4504 4505 namespace { 4506 4507 struct TailCallArgumentInfo { 4508 SDValue Arg; 4509 SDValue FrameIdxOp; 4510 int FrameIdx = 0; 4511 4512 TailCallArgumentInfo() = default; 4513 }; 4514 4515 } // end anonymous namespace 4516 4517 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4518 static void StoreTailCallArgumentsToStackSlot( 4519 SelectionDAG &DAG, SDValue Chain, 4520 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4521 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4522 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4523 SDValue Arg = TailCallArgs[i].Arg; 4524 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4525 int FI = TailCallArgs[i].FrameIdx; 4526 // Store relative to framepointer. 4527 MemOpChains.push_back(DAG.getStore( 4528 Chain, dl, Arg, FIN, 4529 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4530 } 4531 } 4532 4533 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4534 /// the appropriate stack slot for the tail call optimized function call. 4535 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4536 SDValue OldRetAddr, SDValue OldFP, 4537 int SPDiff, const SDLoc &dl) { 4538 if (SPDiff) { 4539 // Calculate the new stack slot for the return address. 4540 MachineFunction &MF = DAG.getMachineFunction(); 4541 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4542 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4543 bool isPPC64 = Subtarget.isPPC64(); 4544 int SlotSize = isPPC64 ? 8 : 4; 4545 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4546 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4547 NewRetAddrLoc, true); 4548 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4549 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4550 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4551 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4552 4553 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4554 // slot as the FP is never overwritten. 4555 if (Subtarget.isDarwinABI()) { 4556 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4557 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4558 true); 4559 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4560 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4561 MachinePointerInfo::getFixedStack( 4562 DAG.getMachineFunction(), NewFPIdx)); 4563 } 4564 } 4565 return Chain; 4566 } 4567 4568 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4569 /// the position of the argument. 4570 static void 4571 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4572 SDValue Arg, int SPDiff, unsigned ArgOffset, 4573 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4574 int Offset = ArgOffset + SPDiff; 4575 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4576 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4577 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4578 SDValue FIN = DAG.getFrameIndex(FI, VT); 4579 TailCallArgumentInfo Info; 4580 Info.Arg = Arg; 4581 Info.FrameIdxOp = FIN; 4582 Info.FrameIdx = FI; 4583 TailCallArguments.push_back(Info); 4584 } 4585 4586 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4587 /// stack slot. Returns the chain as result and the loaded frame pointers in 4588 /// LROpOut/FPOpout. Used when tail calling. 4589 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4590 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4591 SDValue &FPOpOut, const SDLoc &dl) const { 4592 if (SPDiff) { 4593 // Load the LR and FP stack slot for later adjusting. 4594 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4595 LROpOut = getReturnAddrFrameIndex(DAG); 4596 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4597 Chain = SDValue(LROpOut.getNode(), 1); 4598 4599 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4600 // slot as the FP is never overwritten. 4601 if (Subtarget.isDarwinABI()) { 4602 FPOpOut = getFramePointerFrameIndex(DAG); 4603 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4604 Chain = SDValue(FPOpOut.getNode(), 1); 4605 } 4606 } 4607 return Chain; 4608 } 4609 4610 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4611 /// by "Src" to address "Dst" of size "Size". Alignment information is 4612 /// specified by the specific parameter attribute. The copy will be passed as 4613 /// a byval function parameter. 4614 /// Sometimes what we are copying is the end of a larger object, the part that 4615 /// does not fit in registers. 4616 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4617 SDValue Chain, ISD::ArgFlagsTy Flags, 4618 SelectionDAG &DAG, const SDLoc &dl) { 4619 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4620 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4621 false, false, false, MachinePointerInfo(), 4622 MachinePointerInfo()); 4623 } 4624 4625 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4626 /// tail calls. 4627 static void LowerMemOpCallTo( 4628 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4629 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4630 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4631 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4632 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4633 if (!isTailCall) { 4634 if (isVector) { 4635 SDValue StackPtr; 4636 if (isPPC64) 4637 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4638 else 4639 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4640 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4641 DAG.getConstant(ArgOffset, dl, PtrVT)); 4642 } 4643 MemOpChains.push_back( 4644 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4645 // Calculate and remember argument location. 4646 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4647 TailCallArguments); 4648 } 4649 4650 static void 4651 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4652 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4653 SDValue FPOp, 4654 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4655 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4656 // might overwrite each other in case of tail call optimization. 4657 SmallVector<SDValue, 8> MemOpChains2; 4658 // Do not flag preceding copytoreg stuff together with the following stuff. 4659 InFlag = SDValue(); 4660 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4661 MemOpChains2, dl); 4662 if (!MemOpChains2.empty()) 4663 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4664 4665 // Store the return address to the appropriate stack slot. 4666 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4667 4668 // Emit callseq_end just before tailcall node. 4669 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4670 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4671 InFlag = Chain.getValue(1); 4672 } 4673 4674 // Is this global address that of a function that can be called by name? (as 4675 // opposed to something that must hold a descriptor for an indirect call). 4676 static bool isFunctionGlobalAddress(SDValue Callee) { 4677 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4678 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4679 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4680 return false; 4681 4682 return G->getGlobal()->getValueType()->isFunctionTy(); 4683 } 4684 4685 return false; 4686 } 4687 4688 static unsigned 4689 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4690 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4691 bool isPatchPoint, bool hasNest, 4692 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4693 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4694 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4695 bool isPPC64 = Subtarget.isPPC64(); 4696 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4697 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4698 4699 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4700 NodeTys.push_back(MVT::Other); // Returns a chain 4701 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4702 4703 unsigned CallOpc = PPCISD::CALL; 4704 4705 bool needIndirectCall = true; 4706 if (!isSVR4ABI || !isPPC64) 4707 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4708 // If this is an absolute destination address, use the munged value. 4709 Callee = SDValue(Dest, 0); 4710 needIndirectCall = false; 4711 } 4712 4713 // PC-relative references to external symbols should go through $stub, unless 4714 // we're building with the leopard linker or later, which automatically 4715 // synthesizes these stubs. 4716 const TargetMachine &TM = DAG.getTarget(); 4717 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent(); 4718 const GlobalValue *GV = nullptr; 4719 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4720 GV = G->getGlobal(); 4721 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4722 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4723 4724 if (isFunctionGlobalAddress(Callee)) { 4725 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4726 // A call to a TLS address is actually an indirect call to a 4727 // thread-specific pointer. 4728 unsigned OpFlags = 0; 4729 if (UsePlt) 4730 OpFlags = PPCII::MO_PLT; 4731 4732 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4733 // every direct call is) turn it into a TargetGlobalAddress / 4734 // TargetExternalSymbol node so that legalize doesn't hack it. 4735 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4736 Callee.getValueType(), 0, OpFlags); 4737 needIndirectCall = false; 4738 } 4739 4740 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4741 unsigned char OpFlags = 0; 4742 4743 if (UsePlt) 4744 OpFlags = PPCII::MO_PLT; 4745 4746 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4747 OpFlags); 4748 needIndirectCall = false; 4749 } 4750 4751 if (isPatchPoint) { 4752 // We'll form an invalid direct call when lowering a patchpoint; the full 4753 // sequence for an indirect call is complicated, and many of the 4754 // instructions introduced might have side effects (and, thus, can't be 4755 // removed later). The call itself will be removed as soon as the 4756 // argument/return lowering is complete, so the fact that it has the wrong 4757 // kind of operands should not really matter. 4758 needIndirectCall = false; 4759 } 4760 4761 if (needIndirectCall) { 4762 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4763 // to do the call, we can't use PPCISD::CALL. 4764 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4765 4766 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4767 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4768 // entry point, but to the function descriptor (the function entry point 4769 // address is part of the function descriptor though). 4770 // The function descriptor is a three doubleword structure with the 4771 // following fields: function entry point, TOC base address and 4772 // environment pointer. 4773 // Thus for a call through a function pointer, the following actions need 4774 // to be performed: 4775 // 1. Save the TOC of the caller in the TOC save area of its stack 4776 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4777 // 2. Load the address of the function entry point from the function 4778 // descriptor. 4779 // 3. Load the TOC of the callee from the function descriptor into r2. 4780 // 4. Load the environment pointer from the function descriptor into 4781 // r11. 4782 // 5. Branch to the function entry point address. 4783 // 6. On return of the callee, the TOC of the caller needs to be 4784 // restored (this is done in FinishCall()). 4785 // 4786 // The loads are scheduled at the beginning of the call sequence, and the 4787 // register copies are flagged together to ensure that no other 4788 // operations can be scheduled in between. E.g. without flagging the 4789 // copies together, a TOC access in the caller could be scheduled between 4790 // the assignment of the callee TOC and the branch to the callee, which 4791 // results in the TOC access going through the TOC of the callee instead 4792 // of going through the TOC of the caller, which leads to incorrect code. 4793 4794 // Load the address of the function entry point from the function 4795 // descriptor. 4796 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4797 if (LDChain.getValueType() == MVT::Glue) 4798 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4799 4800 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4801 ? (MachineMemOperand::MODereferenceable | 4802 MachineMemOperand::MOInvariant) 4803 : MachineMemOperand::MONone; 4804 4805 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4806 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4807 /* Alignment = */ 8, MMOFlags); 4808 4809 // Load environment pointer into r11. 4810 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4811 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4812 SDValue LoadEnvPtr = 4813 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4814 /* Alignment = */ 8, MMOFlags); 4815 4816 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4817 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4818 SDValue TOCPtr = 4819 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4820 /* Alignment = */ 8, MMOFlags); 4821 4822 setUsesTOCBasePtr(DAG); 4823 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4824 InFlag); 4825 Chain = TOCVal.getValue(0); 4826 InFlag = TOCVal.getValue(1); 4827 4828 // If the function call has an explicit 'nest' parameter, it takes the 4829 // place of the environment pointer. 4830 if (!hasNest) { 4831 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4832 InFlag); 4833 4834 Chain = EnvVal.getValue(0); 4835 InFlag = EnvVal.getValue(1); 4836 } 4837 4838 MTCTROps[0] = Chain; 4839 MTCTROps[1] = LoadFuncPtr; 4840 MTCTROps[2] = InFlag; 4841 } 4842 4843 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4844 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4845 InFlag = Chain.getValue(1); 4846 4847 NodeTys.clear(); 4848 NodeTys.push_back(MVT::Other); 4849 NodeTys.push_back(MVT::Glue); 4850 Ops.push_back(Chain); 4851 CallOpc = PPCISD::BCTRL; 4852 Callee.setNode(nullptr); 4853 // Add use of X11 (holding environment pointer) 4854 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4855 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4856 // Add CTR register as callee so a bctr can be emitted later. 4857 if (isTailCall) 4858 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4859 } 4860 4861 // If this is a direct call, pass the chain and the callee. 4862 if (Callee.getNode()) { 4863 Ops.push_back(Chain); 4864 Ops.push_back(Callee); 4865 } 4866 // If this is a tail call add stack pointer delta. 4867 if (isTailCall) 4868 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 4869 4870 // Add argument registers to the end of the list so that they are known live 4871 // into the call. 4872 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4873 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4874 RegsToPass[i].second.getValueType())); 4875 4876 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4877 // into the call. 4878 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 4879 setUsesTOCBasePtr(DAG); 4880 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4881 } 4882 4883 return CallOpc; 4884 } 4885 4886 SDValue PPCTargetLowering::LowerCallResult( 4887 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4888 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4889 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4890 SmallVector<CCValAssign, 16> RVLocs; 4891 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4892 *DAG.getContext()); 4893 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 4894 4895 // Copy all of the result registers out of their specified physreg. 4896 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4897 CCValAssign &VA = RVLocs[i]; 4898 assert(VA.isRegLoc() && "Can only return in registers!"); 4899 4900 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4901 VA.getLocReg(), VA.getLocVT(), InFlag); 4902 Chain = Val.getValue(1); 4903 InFlag = Val.getValue(2); 4904 4905 switch (VA.getLocInfo()) { 4906 default: llvm_unreachable("Unknown loc info!"); 4907 case CCValAssign::Full: break; 4908 case CCValAssign::AExt: 4909 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4910 break; 4911 case CCValAssign::ZExt: 4912 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4913 DAG.getValueType(VA.getValVT())); 4914 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4915 break; 4916 case CCValAssign::SExt: 4917 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4918 DAG.getValueType(VA.getValVT())); 4919 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4920 break; 4921 } 4922 4923 InVals.push_back(Val); 4924 } 4925 4926 return Chain; 4927 } 4928 4929 SDValue PPCTargetLowering::FinishCall( 4930 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 4931 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 4932 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 4933 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 4934 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 4935 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 4936 std::vector<EVT> NodeTys; 4937 SmallVector<SDValue, 8> Ops; 4938 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 4939 SPDiff, isTailCall, isPatchPoint, hasNest, 4940 RegsToPass, Ops, NodeTys, CS, Subtarget); 4941 4942 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 4943 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 4944 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 4945 4946 // When performing tail call optimization the callee pops its arguments off 4947 // the stack. Account for this here so these bytes can be pushed back on in 4948 // PPCFrameLowering::eliminateCallFramePseudoInstr. 4949 int BytesCalleePops = 4950 (CallConv == CallingConv::Fast && 4951 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 4952 4953 // Add a register mask operand representing the call-preserved registers. 4954 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4955 const uint32_t *Mask = 4956 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 4957 assert(Mask && "Missing call preserved mask for calling convention"); 4958 Ops.push_back(DAG.getRegisterMask(Mask)); 4959 4960 if (InFlag.getNode()) 4961 Ops.push_back(InFlag); 4962 4963 // Emit tail call. 4964 if (isTailCall) { 4965 assert(((Callee.getOpcode() == ISD::Register && 4966 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 4967 Callee.getOpcode() == ISD::TargetExternalSymbol || 4968 Callee.getOpcode() == ISD::TargetGlobalAddress || 4969 isa<ConstantSDNode>(Callee)) && 4970 "Expecting an global address, external symbol, absolute value or register"); 4971 4972 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 4973 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 4974 } 4975 4976 // Add a NOP immediately after the branch instruction when using the 64-bit 4977 // SVR4 ABI. At link time, if caller and callee are in a different module and 4978 // thus have a different TOC, the call will be replaced with a call to a stub 4979 // function which saves the current TOC, loads the TOC of the callee and 4980 // branches to the callee. The NOP will be replaced with a load instruction 4981 // which restores the TOC of the caller from the TOC save slot of the current 4982 // stack frame. If caller and callee belong to the same module (and have the 4983 // same TOC), the NOP will remain unchanged. 4984 4985 MachineFunction &MF = DAG.getMachineFunction(); 4986 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 4987 !isPatchPoint) { 4988 if (CallOpc == PPCISD::BCTRL) { 4989 // This is a call through a function pointer. 4990 // Restore the caller TOC from the save area into R2. 4991 // See PrepareCall() for more information about calls through function 4992 // pointers in the 64-bit SVR4 ABI. 4993 // We are using a target-specific load with r2 hard coded, because the 4994 // result of a target-independent load would never go directly into r2, 4995 // since r2 is a reserved register (which prevents the register allocator 4996 // from allocating it), resulting in an additional register being 4997 // allocated and an unnecessary move instruction being generated. 4998 CallOpc = PPCISD::BCTRL_LOAD_TOC; 4999 5000 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5001 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5002 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5003 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5004 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5005 5006 // The address needs to go after the chain input but before the flag (or 5007 // any other variadic arguments). 5008 Ops.insert(std::next(Ops.begin()), AddTOC); 5009 } else if (CallOpc == PPCISD::CALL && 5010 !callsShareTOCBase(MF.getFunction(), Callee, DAG.getTarget())) { 5011 // Otherwise insert NOP for non-local calls. 5012 CallOpc = PPCISD::CALL_NOP; 5013 } 5014 } 5015 5016 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5017 InFlag = Chain.getValue(1); 5018 5019 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5020 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5021 InFlag, dl); 5022 if (!Ins.empty()) 5023 InFlag = Chain.getValue(1); 5024 5025 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5026 Ins, dl, DAG, InVals); 5027 } 5028 5029 SDValue 5030 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5031 SmallVectorImpl<SDValue> &InVals) const { 5032 SelectionDAG &DAG = CLI.DAG; 5033 SDLoc &dl = CLI.DL; 5034 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5035 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5036 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5037 SDValue Chain = CLI.Chain; 5038 SDValue Callee = CLI.Callee; 5039 bool &isTailCall = CLI.IsTailCall; 5040 CallingConv::ID CallConv = CLI.CallConv; 5041 bool isVarArg = CLI.IsVarArg; 5042 bool isPatchPoint = CLI.IsPatchPoint; 5043 ImmutableCallSite CS = CLI.CS; 5044 5045 if (isTailCall) { 5046 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5047 isTailCall = false; 5048 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5049 isTailCall = 5050 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5051 isVarArg, Outs, Ins, DAG); 5052 else 5053 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5054 Ins, DAG); 5055 if (isTailCall) { 5056 ++NumTailCalls; 5057 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5058 ++NumSiblingCalls; 5059 5060 assert(isa<GlobalAddressSDNode>(Callee) && 5061 "Callee should be an llvm::Function object."); 5062 DEBUG( 5063 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5064 const unsigned Width = 80 - strlen("TCO caller: ") 5065 - strlen(", callee linkage: 0, 0"); 5066 dbgs() << "TCO caller: " 5067 << left_justify(DAG.getMachineFunction().getName(), Width) 5068 << ", callee linkage: " 5069 << GV->getVisibility() << ", " << GV->getLinkage() << "\n" 5070 ); 5071 } 5072 } 5073 5074 if (!isTailCall && CS && CS.isMustTailCall()) 5075 report_fatal_error("failed to perform tail call elimination on a call " 5076 "site marked musttail"); 5077 5078 // When long calls (i.e. indirect calls) are always used, calls are always 5079 // made via function pointer. If we have a function name, first translate it 5080 // into a pointer. 5081 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5082 !isTailCall) 5083 Callee = LowerGlobalAddress(Callee, DAG); 5084 5085 if (Subtarget.isSVR4ABI()) { 5086 if (Subtarget.isPPC64()) 5087 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5088 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5089 dl, DAG, InVals, CS); 5090 else 5091 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5092 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5093 dl, DAG, InVals, CS); 5094 } 5095 5096 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5097 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5098 dl, DAG, InVals, CS); 5099 } 5100 5101 SDValue PPCTargetLowering::LowerCall_32SVR4( 5102 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5103 bool isTailCall, bool isPatchPoint, 5104 const SmallVectorImpl<ISD::OutputArg> &Outs, 5105 const SmallVectorImpl<SDValue> &OutVals, 5106 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5107 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5108 ImmutableCallSite CS) const { 5109 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5110 // of the 32-bit SVR4 ABI stack frame layout. 5111 5112 assert((CallConv == CallingConv::C || 5113 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5114 5115 unsigned PtrByteSize = 4; 5116 5117 MachineFunction &MF = DAG.getMachineFunction(); 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 // Count how many bytes are to be pushed on the stack, including the linkage 5129 // area, parameter list area and the part of the local variable space which 5130 // contains copies of aggregates which are passed by value. 5131 5132 // Assign locations to all of the outgoing arguments. 5133 SmallVector<CCValAssign, 16> ArgLocs; 5134 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5135 5136 // Reserve space for the linkage area on the stack. 5137 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5138 PtrByteSize); 5139 if (useSoftFloat()) 5140 CCInfo.PreAnalyzeCallOperands(Outs); 5141 5142 if (isVarArg) { 5143 // Handle fixed and variable vector arguments differently. 5144 // Fixed vector arguments go into registers as long as registers are 5145 // available. Variable vector arguments always go into memory. 5146 unsigned NumArgs = Outs.size(); 5147 5148 for (unsigned i = 0; i != NumArgs; ++i) { 5149 MVT ArgVT = Outs[i].VT; 5150 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5151 bool Result; 5152 5153 if (Outs[i].IsFixed) { 5154 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5155 CCInfo); 5156 } else { 5157 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5158 ArgFlags, CCInfo); 5159 } 5160 5161 if (Result) { 5162 #ifndef NDEBUG 5163 errs() << "Call operand #" << i << " has unhandled type " 5164 << EVT(ArgVT).getEVTString() << "\n"; 5165 #endif 5166 llvm_unreachable(nullptr); 5167 } 5168 } 5169 } else { 5170 // All arguments are treated the same. 5171 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5172 } 5173 CCInfo.clearWasPPCF128(); 5174 5175 // Assign locations to all of the outgoing aggregate by value arguments. 5176 SmallVector<CCValAssign, 16> ByValArgLocs; 5177 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5178 5179 // Reserve stack space for the allocations in CCInfo. 5180 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5181 5182 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5183 5184 // Size of the linkage area, parameter list area and the part of the local 5185 // space variable where copies of aggregates which are passed by value are 5186 // stored. 5187 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5188 5189 // Calculate by how many bytes the stack has to be adjusted in case of tail 5190 // call optimization. 5191 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5192 5193 // Adjust the stack pointer for the new arguments... 5194 // These operations are automatically eliminated by the prolog/epilog pass 5195 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5196 SDValue CallSeqStart = Chain; 5197 5198 // Load the return address and frame pointer so it can be moved somewhere else 5199 // later. 5200 SDValue LROp, FPOp; 5201 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5202 5203 // Set up a copy of the stack pointer for use loading and storing any 5204 // arguments that may not fit in the registers available for argument 5205 // passing. 5206 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5207 5208 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5209 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5210 SmallVector<SDValue, 8> MemOpChains; 5211 5212 bool seenFloatArg = false; 5213 // Walk the register/memloc assignments, inserting copies/loads. 5214 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5215 i != e; 5216 ++i) { 5217 CCValAssign &VA = ArgLocs[i]; 5218 SDValue Arg = OutVals[i]; 5219 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5220 5221 if (Flags.isByVal()) { 5222 // Argument is an aggregate which is passed by value, thus we need to 5223 // create a copy of it in the local variable space of the current stack 5224 // frame (which is the stack frame of the caller) and pass the address of 5225 // this copy to the callee. 5226 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5227 CCValAssign &ByValVA = ByValArgLocs[j++]; 5228 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5229 5230 // Memory reserved in the local variable space of the callers stack frame. 5231 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5232 5233 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5234 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5235 StackPtr, PtrOff); 5236 5237 // Create a copy of the argument in the local area of the current 5238 // stack frame. 5239 SDValue MemcpyCall = 5240 CreateCopyOfByValArgument(Arg, PtrOff, 5241 CallSeqStart.getNode()->getOperand(0), 5242 Flags, DAG, dl); 5243 5244 // This must go outside the CALLSEQ_START..END. 5245 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5246 SDLoc(MemcpyCall)); 5247 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5248 NewCallSeqStart.getNode()); 5249 Chain = CallSeqStart = NewCallSeqStart; 5250 5251 // Pass the address of the aggregate copy on the stack either in a 5252 // physical register or in the parameter list area of the current stack 5253 // frame to the callee. 5254 Arg = PtrOff; 5255 } 5256 5257 if (VA.isRegLoc()) { 5258 if (Arg.getValueType() == MVT::i1) 5259 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 5260 5261 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5262 // Put argument in a physical register. 5263 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5264 } else { 5265 // Put argument in the parameter list area of the current stack frame. 5266 assert(VA.isMemLoc()); 5267 unsigned LocMemOffset = VA.getLocMemOffset(); 5268 5269 if (!isTailCall) { 5270 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5271 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5272 StackPtr, PtrOff); 5273 5274 MemOpChains.push_back( 5275 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5276 } else { 5277 // Calculate and remember argument location. 5278 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5279 TailCallArguments); 5280 } 5281 } 5282 } 5283 5284 if (!MemOpChains.empty()) 5285 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5286 5287 // Build a sequence of copy-to-reg nodes chained together with token chain 5288 // and flag operands which copy the outgoing args into the appropriate regs. 5289 SDValue InFlag; 5290 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5291 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5292 RegsToPass[i].second, InFlag); 5293 InFlag = Chain.getValue(1); 5294 } 5295 5296 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5297 // registers. 5298 if (isVarArg) { 5299 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5300 SDValue Ops[] = { Chain, InFlag }; 5301 5302 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5303 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5304 5305 InFlag = Chain.getValue(1); 5306 } 5307 5308 if (isTailCall) 5309 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5310 TailCallArguments); 5311 5312 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5313 /* unused except on PPC64 ELFv1 */ false, DAG, 5314 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5315 NumBytes, Ins, InVals, CS); 5316 } 5317 5318 // Copy an argument into memory, being careful to do this outside the 5319 // call sequence for the call to which the argument belongs. 5320 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5321 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5322 SelectionDAG &DAG, const SDLoc &dl) const { 5323 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5324 CallSeqStart.getNode()->getOperand(0), 5325 Flags, DAG, dl); 5326 // The MEMCPY must go outside the CALLSEQ_START..END. 5327 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5328 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5329 SDLoc(MemcpyCall)); 5330 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5331 NewCallSeqStart.getNode()); 5332 return NewCallSeqStart; 5333 } 5334 5335 SDValue PPCTargetLowering::LowerCall_64SVR4( 5336 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5337 bool isTailCall, bool isPatchPoint, 5338 const SmallVectorImpl<ISD::OutputArg> &Outs, 5339 const SmallVectorImpl<SDValue> &OutVals, 5340 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5341 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5342 ImmutableCallSite CS) const { 5343 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5344 bool isLittleEndian = Subtarget.isLittleEndian(); 5345 unsigned NumOps = Outs.size(); 5346 bool hasNest = false; 5347 bool IsSibCall = false; 5348 5349 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5350 unsigned PtrByteSize = 8; 5351 5352 MachineFunction &MF = DAG.getMachineFunction(); 5353 5354 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5355 IsSibCall = true; 5356 5357 // Mark this function as potentially containing a function that contains a 5358 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5359 // and restoring the callers stack pointer in this functions epilog. This is 5360 // done because by tail calling the called function might overwrite the value 5361 // in this function's (MF) stack pointer stack slot 0(SP). 5362 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5363 CallConv == CallingConv::Fast) 5364 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5365 5366 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5367 "fastcc not supported on varargs functions"); 5368 5369 // Count how many bytes are to be pushed on the stack, including the linkage 5370 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5371 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5372 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5373 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5374 unsigned NumBytes = LinkageSize; 5375 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5376 unsigned &QFPR_idx = FPR_idx; 5377 5378 static const MCPhysReg GPR[] = { 5379 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5380 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5381 }; 5382 static const MCPhysReg VR[] = { 5383 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5384 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5385 }; 5386 5387 const unsigned NumGPRs = array_lengthof(GPR); 5388 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5389 const unsigned NumVRs = array_lengthof(VR); 5390 const unsigned NumQFPRs = NumFPRs; 5391 5392 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5393 // can be passed to the callee in registers. 5394 // For the fast calling convention, there is another check below. 5395 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5396 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5397 if (!HasParameterArea) { 5398 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5399 unsigned AvailableFPRs = NumFPRs; 5400 unsigned AvailableVRs = NumVRs; 5401 unsigned NumBytesTmp = NumBytes; 5402 for (unsigned i = 0; i != NumOps; ++i) { 5403 if (Outs[i].Flags.isNest()) continue; 5404 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5405 PtrByteSize, LinkageSize, ParamAreaSize, 5406 NumBytesTmp, AvailableFPRs, AvailableVRs, 5407 Subtarget.hasQPX())) 5408 HasParameterArea = true; 5409 } 5410 } 5411 5412 // When using the fast calling convention, we don't provide backing for 5413 // arguments that will be in registers. 5414 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5415 5416 // Add up all the space actually used. 5417 for (unsigned i = 0; i != NumOps; ++i) { 5418 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5419 EVT ArgVT = Outs[i].VT; 5420 EVT OrigVT = Outs[i].ArgVT; 5421 5422 if (Flags.isNest()) 5423 continue; 5424 5425 if (CallConv == CallingConv::Fast) { 5426 if (Flags.isByVal()) 5427 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5428 else 5429 switch (ArgVT.getSimpleVT().SimpleTy) { 5430 default: llvm_unreachable("Unexpected ValueType for argument!"); 5431 case MVT::i1: 5432 case MVT::i32: 5433 case MVT::i64: 5434 if (++NumGPRsUsed <= NumGPRs) 5435 continue; 5436 break; 5437 case MVT::v4i32: 5438 case MVT::v8i16: 5439 case MVT::v16i8: 5440 case MVT::v2f64: 5441 case MVT::v2i64: 5442 case MVT::v1i128: 5443 if (++NumVRsUsed <= NumVRs) 5444 continue; 5445 break; 5446 case MVT::v4f32: 5447 // When using QPX, this is handled like a FP register, otherwise, it 5448 // is an Altivec register. 5449 if (Subtarget.hasQPX()) { 5450 if (++NumFPRsUsed <= NumFPRs) 5451 continue; 5452 } else { 5453 if (++NumVRsUsed <= NumVRs) 5454 continue; 5455 } 5456 break; 5457 case MVT::f32: 5458 case MVT::f64: 5459 case MVT::v4f64: // QPX 5460 case MVT::v4i1: // QPX 5461 if (++NumFPRsUsed <= NumFPRs) 5462 continue; 5463 break; 5464 } 5465 } 5466 5467 /* Respect alignment of argument on the stack. */ 5468 unsigned Align = 5469 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5470 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5471 5472 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5473 if (Flags.isInConsecutiveRegsLast()) 5474 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5475 } 5476 5477 unsigned NumBytesActuallyUsed = NumBytes; 5478 5479 // In the old ELFv1 ABI, 5480 // the prolog code of the callee may store up to 8 GPR argument registers to 5481 // the stack, allowing va_start to index over them in memory if its varargs. 5482 // Because we cannot tell if this is needed on the caller side, we have to 5483 // conservatively assume that it is needed. As such, make sure we have at 5484 // least enough stack space for the caller to store the 8 GPRs. 5485 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5486 // really requires memory operands, e.g. a vararg function. 5487 if (HasParameterArea) 5488 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5489 else 5490 NumBytes = LinkageSize; 5491 5492 // Tail call needs the stack to be aligned. 5493 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5494 CallConv == CallingConv::Fast) 5495 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5496 5497 int SPDiff = 0; 5498 5499 // Calculate by how many bytes the stack has to be adjusted in case of tail 5500 // call optimization. 5501 if (!IsSibCall) 5502 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5503 5504 // To protect arguments on the stack from being clobbered in a tail call, 5505 // force all the loads to happen before doing any other lowering. 5506 if (isTailCall) 5507 Chain = DAG.getStackArgumentTokenFactor(Chain); 5508 5509 // Adjust the stack pointer for the new arguments... 5510 // These operations are automatically eliminated by the prolog/epilog pass 5511 if (!IsSibCall) 5512 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5513 SDValue CallSeqStart = Chain; 5514 5515 // Load the return address and frame pointer so it can be move somewhere else 5516 // later. 5517 SDValue LROp, FPOp; 5518 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5519 5520 // Set up a copy of the stack pointer for use loading and storing any 5521 // arguments that may not fit in the registers available for argument 5522 // passing. 5523 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5524 5525 // Figure out which arguments are going to go in registers, and which in 5526 // memory. Also, if this is a vararg function, floating point operations 5527 // must be stored to our stack, and loaded into integer regs as well, if 5528 // any integer regs are available for argument passing. 5529 unsigned ArgOffset = LinkageSize; 5530 5531 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5532 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5533 5534 SmallVector<SDValue, 8> MemOpChains; 5535 for (unsigned i = 0; i != NumOps; ++i) { 5536 SDValue Arg = OutVals[i]; 5537 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5538 EVT ArgVT = Outs[i].VT; 5539 EVT OrigVT = Outs[i].ArgVT; 5540 5541 // PtrOff will be used to store the current argument to the stack if a 5542 // register cannot be found for it. 5543 SDValue PtrOff; 5544 5545 // We re-align the argument offset for each argument, except when using the 5546 // fast calling convention, when we need to make sure we do that only when 5547 // we'll actually use a stack slot. 5548 auto ComputePtrOff = [&]() { 5549 /* Respect alignment of argument on the stack. */ 5550 unsigned Align = 5551 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5552 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5553 5554 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5555 5556 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5557 }; 5558 5559 if (CallConv != CallingConv::Fast) { 5560 ComputePtrOff(); 5561 5562 /* Compute GPR index associated with argument offset. */ 5563 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5564 GPR_idx = std::min(GPR_idx, NumGPRs); 5565 } 5566 5567 // Promote integers to 64-bit values. 5568 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5569 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5570 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5571 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5572 } 5573 5574 // FIXME memcpy is used way more than necessary. Correctness first. 5575 // Note: "by value" is code for passing a structure by value, not 5576 // basic types. 5577 if (Flags.isByVal()) { 5578 // Note: Size includes alignment padding, so 5579 // struct x { short a; char b; } 5580 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5581 // These are the proper values we need for right-justifying the 5582 // aggregate in a parameter register. 5583 unsigned Size = Flags.getByValSize(); 5584 5585 // An empty aggregate parameter takes up no storage and no 5586 // registers. 5587 if (Size == 0) 5588 continue; 5589 5590 if (CallConv == CallingConv::Fast) 5591 ComputePtrOff(); 5592 5593 // All aggregates smaller than 8 bytes must be passed right-justified. 5594 if (Size==1 || Size==2 || Size==4) { 5595 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5596 if (GPR_idx != NumGPRs) { 5597 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5598 MachinePointerInfo(), VT); 5599 MemOpChains.push_back(Load.getValue(1)); 5600 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5601 5602 ArgOffset += PtrByteSize; 5603 continue; 5604 } 5605 } 5606 5607 if (GPR_idx == NumGPRs && Size < 8) { 5608 SDValue AddPtr = PtrOff; 5609 if (!isLittleEndian) { 5610 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5611 PtrOff.getValueType()); 5612 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5613 } 5614 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5615 CallSeqStart, 5616 Flags, DAG, dl); 5617 ArgOffset += PtrByteSize; 5618 continue; 5619 } 5620 // Copy entire object into memory. There are cases where gcc-generated 5621 // code assumes it is there, even if it could be put entirely into 5622 // registers. (This is not what the doc says.) 5623 5624 // FIXME: The above statement is likely due to a misunderstanding of the 5625 // documents. All arguments must be copied into the parameter area BY 5626 // THE CALLEE in the event that the callee takes the address of any 5627 // formal argument. That has not yet been implemented. However, it is 5628 // reasonable to use the stack area as a staging area for the register 5629 // load. 5630 5631 // Skip this for small aggregates, as we will use the same slot for a 5632 // right-justified copy, below. 5633 if (Size >= 8) 5634 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5635 CallSeqStart, 5636 Flags, DAG, dl); 5637 5638 // When a register is available, pass a small aggregate right-justified. 5639 if (Size < 8 && GPR_idx != NumGPRs) { 5640 // The easiest way to get this right-justified in a register 5641 // is to copy the structure into the rightmost portion of a 5642 // local variable slot, then load the whole slot into the 5643 // register. 5644 // FIXME: The memcpy seems to produce pretty awful code for 5645 // small aggregates, particularly for packed ones. 5646 // FIXME: It would be preferable to use the slot in the 5647 // parameter save area instead of a new local variable. 5648 SDValue AddPtr = PtrOff; 5649 if (!isLittleEndian) { 5650 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5651 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5652 } 5653 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5654 CallSeqStart, 5655 Flags, DAG, dl); 5656 5657 // Load the slot into the register. 5658 SDValue Load = 5659 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5660 MemOpChains.push_back(Load.getValue(1)); 5661 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5662 5663 // Done with this argument. 5664 ArgOffset += PtrByteSize; 5665 continue; 5666 } 5667 5668 // For aggregates larger than PtrByteSize, copy the pieces of the 5669 // object that fit into registers from the parameter save area. 5670 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5671 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5672 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5673 if (GPR_idx != NumGPRs) { 5674 SDValue Load = 5675 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5676 MemOpChains.push_back(Load.getValue(1)); 5677 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5678 ArgOffset += PtrByteSize; 5679 } else { 5680 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5681 break; 5682 } 5683 } 5684 continue; 5685 } 5686 5687 switch (Arg.getSimpleValueType().SimpleTy) { 5688 default: llvm_unreachable("Unexpected ValueType for argument!"); 5689 case MVT::i1: 5690 case MVT::i32: 5691 case MVT::i64: 5692 if (Flags.isNest()) { 5693 // The 'nest' parameter, if any, is passed in R11. 5694 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5695 hasNest = true; 5696 break; 5697 } 5698 5699 // These can be scalar arguments or elements of an integer array type 5700 // passed directly. Clang may use those instead of "byval" aggregate 5701 // types to avoid forcing arguments to memory unnecessarily. 5702 if (GPR_idx != NumGPRs) { 5703 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5704 } else { 5705 if (CallConv == CallingConv::Fast) 5706 ComputePtrOff(); 5707 5708 assert(HasParameterArea && 5709 "Parameter area must exist to pass an argument in memory."); 5710 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5711 true, isTailCall, false, MemOpChains, 5712 TailCallArguments, dl); 5713 if (CallConv == CallingConv::Fast) 5714 ArgOffset += PtrByteSize; 5715 } 5716 if (CallConv != CallingConv::Fast) 5717 ArgOffset += PtrByteSize; 5718 break; 5719 case MVT::f32: 5720 case MVT::f64: { 5721 // These can be scalar arguments or elements of a float array type 5722 // passed directly. The latter are used to implement ELFv2 homogenous 5723 // float aggregates. 5724 5725 // Named arguments go into FPRs first, and once they overflow, the 5726 // remaining arguments go into GPRs and then the parameter save area. 5727 // Unnamed arguments for vararg functions always go to GPRs and 5728 // then the parameter save area. For now, put all arguments to vararg 5729 // routines always in both locations (FPR *and* GPR or stack slot). 5730 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5731 bool NeededLoad = false; 5732 5733 // First load the argument into the next available FPR. 5734 if (FPR_idx != NumFPRs) 5735 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5736 5737 // Next, load the argument into GPR or stack slot if needed. 5738 if (!NeedGPROrStack) 5739 ; 5740 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5741 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5742 // once we support fp <-> gpr moves. 5743 5744 // In the non-vararg case, this can only ever happen in the 5745 // presence of f32 array types, since otherwise we never run 5746 // out of FPRs before running out of GPRs. 5747 SDValue ArgVal; 5748 5749 // Double values are always passed in a single GPR. 5750 if (Arg.getValueType() != MVT::f32) { 5751 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5752 5753 // Non-array float values are extended and passed in a GPR. 5754 } else if (!Flags.isInConsecutiveRegs()) { 5755 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5756 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5757 5758 // If we have an array of floats, we collect every odd element 5759 // together with its predecessor into one GPR. 5760 } else if (ArgOffset % PtrByteSize != 0) { 5761 SDValue Lo, Hi; 5762 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5763 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5764 if (!isLittleEndian) 5765 std::swap(Lo, Hi); 5766 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5767 5768 // The final element, if even, goes into the first half of a GPR. 5769 } else if (Flags.isInConsecutiveRegsLast()) { 5770 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5771 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5772 if (!isLittleEndian) 5773 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5774 DAG.getConstant(32, dl, MVT::i32)); 5775 5776 // Non-final even elements are skipped; they will be handled 5777 // together the with subsequent argument on the next go-around. 5778 } else 5779 ArgVal = SDValue(); 5780 5781 if (ArgVal.getNode()) 5782 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5783 } else { 5784 if (CallConv == CallingConv::Fast) 5785 ComputePtrOff(); 5786 5787 // Single-precision floating-point values are mapped to the 5788 // second (rightmost) word of the stack doubleword. 5789 if (Arg.getValueType() == MVT::f32 && 5790 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5791 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5792 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5793 } 5794 5795 assert(HasParameterArea && 5796 "Parameter area must exist to pass an argument in memory."); 5797 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5798 true, isTailCall, false, MemOpChains, 5799 TailCallArguments, dl); 5800 5801 NeededLoad = true; 5802 } 5803 // When passing an array of floats, the array occupies consecutive 5804 // space in the argument area; only round up to the next doubleword 5805 // at the end of the array. Otherwise, each float takes 8 bytes. 5806 if (CallConv != CallingConv::Fast || NeededLoad) { 5807 ArgOffset += (Arg.getValueType() == MVT::f32 && 5808 Flags.isInConsecutiveRegs()) ? 4 : 8; 5809 if (Flags.isInConsecutiveRegsLast()) 5810 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5811 } 5812 break; 5813 } 5814 case MVT::v4f32: 5815 case MVT::v4i32: 5816 case MVT::v8i16: 5817 case MVT::v16i8: 5818 case MVT::v2f64: 5819 case MVT::v2i64: 5820 case MVT::v1i128: 5821 if (!Subtarget.hasQPX()) { 5822 // These can be scalar arguments or elements of a vector array type 5823 // passed directly. The latter are used to implement ELFv2 homogenous 5824 // vector aggregates. 5825 5826 // For a varargs call, named arguments go into VRs or on the stack as 5827 // usual; unnamed arguments always go to the stack or the corresponding 5828 // GPRs when within range. For now, we always put the value in both 5829 // locations (or even all three). 5830 if (isVarArg) { 5831 assert(HasParameterArea && 5832 "Parameter area must exist if we have a varargs call."); 5833 // We could elide this store in the case where the object fits 5834 // entirely in R registers. Maybe later. 5835 SDValue Store = 5836 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5837 MemOpChains.push_back(Store); 5838 if (VR_idx != NumVRs) { 5839 SDValue Load = 5840 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 5841 MemOpChains.push_back(Load.getValue(1)); 5842 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5843 } 5844 ArgOffset += 16; 5845 for (unsigned i=0; i<16; i+=PtrByteSize) { 5846 if (GPR_idx == NumGPRs) 5847 break; 5848 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5849 DAG.getConstant(i, dl, PtrVT)); 5850 SDValue Load = 5851 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5852 MemOpChains.push_back(Load.getValue(1)); 5853 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5854 } 5855 break; 5856 } 5857 5858 // Non-varargs Altivec params go into VRs or on the stack. 5859 if (VR_idx != NumVRs) { 5860 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5861 } else { 5862 if (CallConv == CallingConv::Fast) 5863 ComputePtrOff(); 5864 5865 assert(HasParameterArea && 5866 "Parameter area must exist to pass an argument in memory."); 5867 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5868 true, isTailCall, true, MemOpChains, 5869 TailCallArguments, dl); 5870 if (CallConv == CallingConv::Fast) 5871 ArgOffset += 16; 5872 } 5873 5874 if (CallConv != CallingConv::Fast) 5875 ArgOffset += 16; 5876 break; 5877 } // not QPX 5878 5879 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5880 "Invalid QPX parameter type"); 5881 5882 /* fall through */ 5883 case MVT::v4f64: 5884 case MVT::v4i1: { 5885 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5886 if (isVarArg) { 5887 assert(HasParameterArea && 5888 "Parameter area must exist if we have a varargs call."); 5889 // We could elide this store in the case where the object fits 5890 // entirely in R registers. Maybe later. 5891 SDValue Store = 5892 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5893 MemOpChains.push_back(Store); 5894 if (QFPR_idx != NumQFPRs) { 5895 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 5896 PtrOff, MachinePointerInfo()); 5897 MemOpChains.push_back(Load.getValue(1)); 5898 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5899 } 5900 ArgOffset += (IsF32 ? 16 : 32); 5901 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5902 if (GPR_idx == NumGPRs) 5903 break; 5904 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5905 DAG.getConstant(i, dl, PtrVT)); 5906 SDValue Load = 5907 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5908 MemOpChains.push_back(Load.getValue(1)); 5909 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5910 } 5911 break; 5912 } 5913 5914 // Non-varargs QPX params go into registers or on the stack. 5915 if (QFPR_idx != NumQFPRs) { 5916 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5917 } else { 5918 if (CallConv == CallingConv::Fast) 5919 ComputePtrOff(); 5920 5921 assert(HasParameterArea && 5922 "Parameter area must exist to pass an argument in memory."); 5923 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5924 true, isTailCall, true, MemOpChains, 5925 TailCallArguments, dl); 5926 if (CallConv == CallingConv::Fast) 5927 ArgOffset += (IsF32 ? 16 : 32); 5928 } 5929 5930 if (CallConv != CallingConv::Fast) 5931 ArgOffset += (IsF32 ? 16 : 32); 5932 break; 5933 } 5934 } 5935 } 5936 5937 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 5938 "mismatch in size of parameter area"); 5939 (void)NumBytesActuallyUsed; 5940 5941 if (!MemOpChains.empty()) 5942 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5943 5944 // Check if this is an indirect call (MTCTR/BCTRL). 5945 // See PrepareCall() for more information about calls through function 5946 // pointers in the 64-bit SVR4 ABI. 5947 if (!isTailCall && !isPatchPoint && 5948 !isFunctionGlobalAddress(Callee) && 5949 !isa<ExternalSymbolSDNode>(Callee)) { 5950 // Load r2 into a virtual register and store it to the TOC save area. 5951 setUsesTOCBasePtr(DAG); 5952 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 5953 // TOC save area offset. 5954 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5955 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5956 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5957 Chain = DAG.getStore( 5958 Val.getValue(1), dl, Val, AddPtr, 5959 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 5960 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 5961 // This does not mean the MTCTR instruction must use R12; it's easier 5962 // to model this as an extra parameter, so do that. 5963 if (isELFv2ABI && !isPatchPoint) 5964 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 5965 } 5966 5967 // Build a sequence of copy-to-reg nodes chained together with token chain 5968 // and flag operands which copy the outgoing args into the appropriate regs. 5969 SDValue InFlag; 5970 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5971 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5972 RegsToPass[i].second, InFlag); 5973 InFlag = Chain.getValue(1); 5974 } 5975 5976 if (isTailCall && !IsSibCall) 5977 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5978 TailCallArguments); 5979 5980 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 5981 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 5982 SPDiff, NumBytes, Ins, InVals, CS); 5983 } 5984 5985 SDValue PPCTargetLowering::LowerCall_Darwin( 5986 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5987 bool isTailCall, bool isPatchPoint, 5988 const SmallVectorImpl<ISD::OutputArg> &Outs, 5989 const SmallVectorImpl<SDValue> &OutVals, 5990 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5991 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5992 ImmutableCallSite CS) const { 5993 unsigned NumOps = Outs.size(); 5994 5995 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5996 bool isPPC64 = PtrVT == MVT::i64; 5997 unsigned PtrByteSize = isPPC64 ? 8 : 4; 5998 5999 MachineFunction &MF = DAG.getMachineFunction(); 6000 6001 // Mark this function as potentially containing a function that contains a 6002 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6003 // and restoring the callers stack pointer in this functions epilog. This is 6004 // done because by tail calling the called function might overwrite the value 6005 // in this function's (MF) stack pointer stack slot 0(SP). 6006 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6007 CallConv == CallingConv::Fast) 6008 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6009 6010 // Count how many bytes are to be pushed on the stack, including the linkage 6011 // area, and parameter passing area. We start with 24/48 bytes, which is 6012 // prereserved space for [SP][CR][LR][3 x unused]. 6013 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6014 unsigned NumBytes = LinkageSize; 6015 6016 // Add up all the space actually used. 6017 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6018 // they all go in registers, but we must reserve stack space for them for 6019 // possible use by the caller. In varargs or 64-bit calls, parameters are 6020 // assigned stack space in order, with padding so Altivec parameters are 6021 // 16-byte aligned. 6022 unsigned nAltivecParamsAtEnd = 0; 6023 for (unsigned i = 0; i != NumOps; ++i) { 6024 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6025 EVT ArgVT = Outs[i].VT; 6026 // Varargs Altivec parameters are padded to a 16 byte boundary. 6027 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6028 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6029 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6030 if (!isVarArg && !isPPC64) { 6031 // Non-varargs Altivec parameters go after all the non-Altivec 6032 // parameters; handle those later so we know how much padding we need. 6033 nAltivecParamsAtEnd++; 6034 continue; 6035 } 6036 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6037 NumBytes = ((NumBytes+15)/16)*16; 6038 } 6039 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6040 } 6041 6042 // Allow for Altivec parameters at the end, if needed. 6043 if (nAltivecParamsAtEnd) { 6044 NumBytes = ((NumBytes+15)/16)*16; 6045 NumBytes += 16*nAltivecParamsAtEnd; 6046 } 6047 6048 // The prolog code of the callee may store up to 8 GPR argument registers to 6049 // the stack, allowing va_start to index over them in memory if its varargs. 6050 // Because we cannot tell if this is needed on the caller side, we have to 6051 // conservatively assume that it is needed. As such, make sure we have at 6052 // least enough stack space for the caller to store the 8 GPRs. 6053 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6054 6055 // Tail call needs the stack to be aligned. 6056 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6057 CallConv == CallingConv::Fast) 6058 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6059 6060 // Calculate by how many bytes the stack has to be adjusted in case of tail 6061 // call optimization. 6062 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6063 6064 // To protect arguments on the stack from being clobbered in a tail call, 6065 // force all the loads to happen before doing any other lowering. 6066 if (isTailCall) 6067 Chain = DAG.getStackArgumentTokenFactor(Chain); 6068 6069 // Adjust the stack pointer for the new arguments... 6070 // These operations are automatically eliminated by the prolog/epilog pass 6071 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6072 SDValue CallSeqStart = Chain; 6073 6074 // Load the return address and frame pointer so it can be move somewhere else 6075 // later. 6076 SDValue LROp, FPOp; 6077 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6078 6079 // Set up a copy of the stack pointer for use loading and storing any 6080 // arguments that may not fit in the registers available for argument 6081 // passing. 6082 SDValue StackPtr; 6083 if (isPPC64) 6084 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6085 else 6086 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6087 6088 // Figure out which arguments are going to go in registers, and which in 6089 // memory. Also, if this is a vararg function, floating point operations 6090 // must be stored to our stack, and loaded into integer regs as well, if 6091 // any integer regs are available for argument passing. 6092 unsigned ArgOffset = LinkageSize; 6093 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6094 6095 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6096 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6097 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6098 }; 6099 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6100 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6101 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6102 }; 6103 static const MCPhysReg VR[] = { 6104 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6105 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6106 }; 6107 const unsigned NumGPRs = array_lengthof(GPR_32); 6108 const unsigned NumFPRs = 13; 6109 const unsigned NumVRs = array_lengthof(VR); 6110 6111 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6112 6113 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6114 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6115 6116 SmallVector<SDValue, 8> MemOpChains; 6117 for (unsigned i = 0; i != NumOps; ++i) { 6118 SDValue Arg = OutVals[i]; 6119 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6120 6121 // PtrOff will be used to store the current argument to the stack if a 6122 // register cannot be found for it. 6123 SDValue PtrOff; 6124 6125 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6126 6127 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6128 6129 // On PPC64, promote integers to 64-bit values. 6130 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6131 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6132 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6133 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6134 } 6135 6136 // FIXME memcpy is used way more than necessary. Correctness first. 6137 // Note: "by value" is code for passing a structure by value, not 6138 // basic types. 6139 if (Flags.isByVal()) { 6140 unsigned Size = Flags.getByValSize(); 6141 // Very small objects are passed right-justified. Everything else is 6142 // passed left-justified. 6143 if (Size==1 || Size==2) { 6144 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6145 if (GPR_idx != NumGPRs) { 6146 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6147 MachinePointerInfo(), VT); 6148 MemOpChains.push_back(Load.getValue(1)); 6149 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6150 6151 ArgOffset += PtrByteSize; 6152 } else { 6153 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6154 PtrOff.getValueType()); 6155 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6156 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6157 CallSeqStart, 6158 Flags, DAG, dl); 6159 ArgOffset += PtrByteSize; 6160 } 6161 continue; 6162 } 6163 // Copy entire object into memory. There are cases where gcc-generated 6164 // code assumes it is there, even if it could be put entirely into 6165 // registers. (This is not what the doc says.) 6166 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6167 CallSeqStart, 6168 Flags, DAG, dl); 6169 6170 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6171 // copy the pieces of the object that fit into registers from the 6172 // parameter save area. 6173 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6174 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6175 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6176 if (GPR_idx != NumGPRs) { 6177 SDValue Load = 6178 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6179 MemOpChains.push_back(Load.getValue(1)); 6180 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6181 ArgOffset += PtrByteSize; 6182 } else { 6183 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6184 break; 6185 } 6186 } 6187 continue; 6188 } 6189 6190 switch (Arg.getSimpleValueType().SimpleTy) { 6191 default: llvm_unreachable("Unexpected ValueType for argument!"); 6192 case MVT::i1: 6193 case MVT::i32: 6194 case MVT::i64: 6195 if (GPR_idx != NumGPRs) { 6196 if (Arg.getValueType() == MVT::i1) 6197 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6198 6199 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6200 } else { 6201 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6202 isPPC64, isTailCall, false, MemOpChains, 6203 TailCallArguments, dl); 6204 } 6205 ArgOffset += PtrByteSize; 6206 break; 6207 case MVT::f32: 6208 case MVT::f64: 6209 if (FPR_idx != NumFPRs) { 6210 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6211 6212 if (isVarArg) { 6213 SDValue Store = 6214 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6215 MemOpChains.push_back(Store); 6216 6217 // Float varargs are always shadowed in available integer registers 6218 if (GPR_idx != NumGPRs) { 6219 SDValue Load = 6220 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6221 MemOpChains.push_back(Load.getValue(1)); 6222 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6223 } 6224 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6225 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6226 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6227 SDValue Load = 6228 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6229 MemOpChains.push_back(Load.getValue(1)); 6230 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6231 } 6232 } else { 6233 // If we have any FPRs remaining, we may also have GPRs remaining. 6234 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6235 // GPRs. 6236 if (GPR_idx != NumGPRs) 6237 ++GPR_idx; 6238 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6239 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6240 ++GPR_idx; 6241 } 6242 } else 6243 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6244 isPPC64, isTailCall, false, MemOpChains, 6245 TailCallArguments, dl); 6246 if (isPPC64) 6247 ArgOffset += 8; 6248 else 6249 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6250 break; 6251 case MVT::v4f32: 6252 case MVT::v4i32: 6253 case MVT::v8i16: 6254 case MVT::v16i8: 6255 if (isVarArg) { 6256 // These go aligned on the stack, or in the corresponding R registers 6257 // when within range. The Darwin PPC ABI doc claims they also go in 6258 // V registers; in fact gcc does this only for arguments that are 6259 // prototyped, not for those that match the ... We do it for all 6260 // arguments, seems to work. 6261 while (ArgOffset % 16 !=0) { 6262 ArgOffset += PtrByteSize; 6263 if (GPR_idx != NumGPRs) 6264 GPR_idx++; 6265 } 6266 // We could elide this store in the case where the object fits 6267 // entirely in R registers. Maybe later. 6268 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6269 DAG.getConstant(ArgOffset, dl, PtrVT)); 6270 SDValue Store = 6271 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6272 MemOpChains.push_back(Store); 6273 if (VR_idx != NumVRs) { 6274 SDValue Load = 6275 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6276 MemOpChains.push_back(Load.getValue(1)); 6277 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6278 } 6279 ArgOffset += 16; 6280 for (unsigned i=0; i<16; i+=PtrByteSize) { 6281 if (GPR_idx == NumGPRs) 6282 break; 6283 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6284 DAG.getConstant(i, dl, PtrVT)); 6285 SDValue Load = 6286 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6287 MemOpChains.push_back(Load.getValue(1)); 6288 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6289 } 6290 break; 6291 } 6292 6293 // Non-varargs Altivec params generally go in registers, but have 6294 // stack space allocated at the end. 6295 if (VR_idx != NumVRs) { 6296 // Doesn't have GPR space allocated. 6297 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6298 } else if (nAltivecParamsAtEnd==0) { 6299 // We are emitting Altivec params in order. 6300 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6301 isPPC64, isTailCall, true, MemOpChains, 6302 TailCallArguments, dl); 6303 ArgOffset += 16; 6304 } 6305 break; 6306 } 6307 } 6308 // If all Altivec parameters fit in registers, as they usually do, 6309 // they get stack space following the non-Altivec parameters. We 6310 // don't track this here because nobody below needs it. 6311 // If there are more Altivec parameters than fit in registers emit 6312 // the stores here. 6313 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6314 unsigned j = 0; 6315 // Offset is aligned; skip 1st 12 params which go in V registers. 6316 ArgOffset = ((ArgOffset+15)/16)*16; 6317 ArgOffset += 12*16; 6318 for (unsigned i = 0; i != NumOps; ++i) { 6319 SDValue Arg = OutVals[i]; 6320 EVT ArgType = Outs[i].VT; 6321 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6322 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6323 if (++j > NumVRs) { 6324 SDValue PtrOff; 6325 // We are emitting Altivec params in order. 6326 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6327 isPPC64, isTailCall, true, MemOpChains, 6328 TailCallArguments, dl); 6329 ArgOffset += 16; 6330 } 6331 } 6332 } 6333 } 6334 6335 if (!MemOpChains.empty()) 6336 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6337 6338 // On Darwin, R12 must contain the address of an indirect callee. This does 6339 // not mean the MTCTR instruction must use R12; it's easier to model this as 6340 // an extra parameter, so do that. 6341 if (!isTailCall && 6342 !isFunctionGlobalAddress(Callee) && 6343 !isa<ExternalSymbolSDNode>(Callee) && 6344 !isBLACompatibleAddress(Callee, DAG)) 6345 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6346 PPC::R12), Callee)); 6347 6348 // Build a sequence of copy-to-reg nodes chained together with token chain 6349 // and flag operands which copy the outgoing args into the appropriate regs. 6350 SDValue InFlag; 6351 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6352 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6353 RegsToPass[i].second, InFlag); 6354 InFlag = Chain.getValue(1); 6355 } 6356 6357 if (isTailCall) 6358 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6359 TailCallArguments); 6360 6361 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6362 /* unused except on PPC64 ELFv1 */ false, DAG, 6363 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6364 NumBytes, Ins, InVals, CS); 6365 } 6366 6367 bool 6368 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6369 MachineFunction &MF, bool isVarArg, 6370 const SmallVectorImpl<ISD::OutputArg> &Outs, 6371 LLVMContext &Context) const { 6372 SmallVector<CCValAssign, 16> RVLocs; 6373 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6374 return CCInfo.CheckReturn(Outs, RetCC_PPC); 6375 } 6376 6377 SDValue 6378 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6379 bool isVarArg, 6380 const SmallVectorImpl<ISD::OutputArg> &Outs, 6381 const SmallVectorImpl<SDValue> &OutVals, 6382 const SDLoc &dl, SelectionDAG &DAG) const { 6383 SmallVector<CCValAssign, 16> RVLocs; 6384 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6385 *DAG.getContext()); 6386 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 6387 6388 SDValue Flag; 6389 SmallVector<SDValue, 4> RetOps(1, Chain); 6390 6391 // Copy the result values into the output registers. 6392 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6393 CCValAssign &VA = RVLocs[i]; 6394 assert(VA.isRegLoc() && "Can only return in registers!"); 6395 6396 SDValue Arg = OutVals[i]; 6397 6398 switch (VA.getLocInfo()) { 6399 default: llvm_unreachable("Unknown loc info!"); 6400 case CCValAssign::Full: break; 6401 case CCValAssign::AExt: 6402 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6403 break; 6404 case CCValAssign::ZExt: 6405 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6406 break; 6407 case CCValAssign::SExt: 6408 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6409 break; 6410 } 6411 6412 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6413 Flag = Chain.getValue(1); 6414 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6415 } 6416 6417 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6418 const MCPhysReg *I = 6419 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6420 if (I) { 6421 for (; *I; ++I) { 6422 6423 if (PPC::G8RCRegClass.contains(*I)) 6424 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6425 else if (PPC::F8RCRegClass.contains(*I)) 6426 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6427 else if (PPC::CRRCRegClass.contains(*I)) 6428 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6429 else if (PPC::VRRCRegClass.contains(*I)) 6430 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6431 else 6432 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6433 } 6434 } 6435 6436 RetOps[0] = Chain; // Update chain. 6437 6438 // Add the flag if we have it. 6439 if (Flag.getNode()) 6440 RetOps.push_back(Flag); 6441 6442 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6443 } 6444 6445 SDValue 6446 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6447 SelectionDAG &DAG) const { 6448 SDLoc dl(Op); 6449 6450 // Get the correct type for integers. 6451 EVT IntVT = Op.getValueType(); 6452 6453 // Get the inputs. 6454 SDValue Chain = Op.getOperand(0); 6455 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6456 // Build a DYNAREAOFFSET node. 6457 SDValue Ops[2] = {Chain, FPSIdx}; 6458 SDVTList VTs = DAG.getVTList(IntVT); 6459 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6460 } 6461 6462 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6463 SelectionDAG &DAG) const { 6464 // When we pop the dynamic allocation we need to restore the SP link. 6465 SDLoc dl(Op); 6466 6467 // Get the correct type for pointers. 6468 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6469 6470 // Construct the stack pointer operand. 6471 bool isPPC64 = Subtarget.isPPC64(); 6472 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6473 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6474 6475 // Get the operands for the STACKRESTORE. 6476 SDValue Chain = Op.getOperand(0); 6477 SDValue SaveSP = Op.getOperand(1); 6478 6479 // Load the old link SP. 6480 SDValue LoadLinkSP = 6481 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6482 6483 // Restore the stack pointer. 6484 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6485 6486 // Store the old link SP. 6487 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6488 } 6489 6490 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6491 MachineFunction &MF = DAG.getMachineFunction(); 6492 bool isPPC64 = Subtarget.isPPC64(); 6493 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6494 6495 // Get current frame pointer save index. The users of this index will be 6496 // primarily DYNALLOC instructions. 6497 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6498 int RASI = FI->getReturnAddrSaveIndex(); 6499 6500 // If the frame pointer save index hasn't been defined yet. 6501 if (!RASI) { 6502 // Find out what the fix offset of the frame pointer save area. 6503 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6504 // Allocate the frame index for frame pointer save area. 6505 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6506 // Save the result. 6507 FI->setReturnAddrSaveIndex(RASI); 6508 } 6509 return DAG.getFrameIndex(RASI, PtrVT); 6510 } 6511 6512 SDValue 6513 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6514 MachineFunction &MF = DAG.getMachineFunction(); 6515 bool isPPC64 = Subtarget.isPPC64(); 6516 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6517 6518 // Get current frame pointer save index. The users of this index will be 6519 // primarily DYNALLOC instructions. 6520 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6521 int FPSI = FI->getFramePointerSaveIndex(); 6522 6523 // If the frame pointer save index hasn't been defined yet. 6524 if (!FPSI) { 6525 // Find out what the fix offset of the frame pointer save area. 6526 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6527 // Allocate the frame index for frame pointer save area. 6528 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6529 // Save the result. 6530 FI->setFramePointerSaveIndex(FPSI); 6531 } 6532 return DAG.getFrameIndex(FPSI, PtrVT); 6533 } 6534 6535 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6536 SelectionDAG &DAG) const { 6537 // Get the inputs. 6538 SDValue Chain = Op.getOperand(0); 6539 SDValue Size = Op.getOperand(1); 6540 SDLoc dl(Op); 6541 6542 // Get the correct type for pointers. 6543 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6544 // Negate the size. 6545 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6546 DAG.getConstant(0, dl, PtrVT), Size); 6547 // Construct a node for the frame pointer save index. 6548 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6549 // Build a DYNALLOC node. 6550 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6551 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6552 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6553 } 6554 6555 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6556 SelectionDAG &DAG) const { 6557 MachineFunction &MF = DAG.getMachineFunction(); 6558 6559 bool isPPC64 = Subtarget.isPPC64(); 6560 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6561 6562 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6563 return DAG.getFrameIndex(FI, PtrVT); 6564 } 6565 6566 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6567 SelectionDAG &DAG) const { 6568 SDLoc DL(Op); 6569 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6570 DAG.getVTList(MVT::i32, MVT::Other), 6571 Op.getOperand(0), Op.getOperand(1)); 6572 } 6573 6574 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6575 SelectionDAG &DAG) const { 6576 SDLoc DL(Op); 6577 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6578 Op.getOperand(0), Op.getOperand(1)); 6579 } 6580 6581 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6582 if (Op.getValueType().isVector()) 6583 return LowerVectorLoad(Op, DAG); 6584 6585 assert(Op.getValueType() == MVT::i1 && 6586 "Custom lowering only for i1 loads"); 6587 6588 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6589 6590 SDLoc dl(Op); 6591 LoadSDNode *LD = cast<LoadSDNode>(Op); 6592 6593 SDValue Chain = LD->getChain(); 6594 SDValue BasePtr = LD->getBasePtr(); 6595 MachineMemOperand *MMO = LD->getMemOperand(); 6596 6597 SDValue NewLD = 6598 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6599 BasePtr, MVT::i8, MMO); 6600 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6601 6602 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6603 return DAG.getMergeValues(Ops, dl); 6604 } 6605 6606 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6607 if (Op.getOperand(1).getValueType().isVector()) 6608 return LowerVectorStore(Op, DAG); 6609 6610 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6611 "Custom lowering only for i1 stores"); 6612 6613 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6614 6615 SDLoc dl(Op); 6616 StoreSDNode *ST = cast<StoreSDNode>(Op); 6617 6618 SDValue Chain = ST->getChain(); 6619 SDValue BasePtr = ST->getBasePtr(); 6620 SDValue Value = ST->getValue(); 6621 MachineMemOperand *MMO = ST->getMemOperand(); 6622 6623 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6624 Value); 6625 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6626 } 6627 6628 // FIXME: Remove this once the ANDI glue bug is fixed: 6629 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6630 assert(Op.getValueType() == MVT::i1 && 6631 "Custom lowering only for i1 results"); 6632 6633 SDLoc DL(Op); 6634 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6635 Op.getOperand(0)); 6636 } 6637 6638 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6639 /// possible. 6640 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6641 // Not FP? Not a fsel. 6642 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6643 !Op.getOperand(2).getValueType().isFloatingPoint()) 6644 return Op; 6645 6646 // We might be able to do better than this under some circumstances, but in 6647 // general, fsel-based lowering of select is a finite-math-only optimization. 6648 // For more information, see section F.3 of the 2.06 ISA specification. 6649 if (!DAG.getTarget().Options.NoInfsFPMath || 6650 !DAG.getTarget().Options.NoNaNsFPMath) 6651 return Op; 6652 // TODO: Propagate flags from the select rather than global settings. 6653 SDNodeFlags Flags; 6654 Flags.setNoInfs(true); 6655 Flags.setNoNaNs(true); 6656 6657 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6658 6659 EVT ResVT = Op.getValueType(); 6660 EVT CmpVT = Op.getOperand(0).getValueType(); 6661 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6662 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6663 SDLoc dl(Op); 6664 6665 // If the RHS of the comparison is a 0.0, we don't need to do the 6666 // subtraction at all. 6667 SDValue Sel1; 6668 if (isFloatingPointZero(RHS)) 6669 switch (CC) { 6670 default: break; // SETUO etc aren't handled by fsel. 6671 case ISD::SETNE: 6672 std::swap(TV, FV); 6673 LLVM_FALLTHROUGH; 6674 case ISD::SETEQ: 6675 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6676 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6677 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6678 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6679 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6680 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6681 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6682 case ISD::SETULT: 6683 case ISD::SETLT: 6684 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6685 LLVM_FALLTHROUGH; 6686 case ISD::SETOGE: 6687 case ISD::SETGE: 6688 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6689 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6690 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6691 case ISD::SETUGT: 6692 case ISD::SETGT: 6693 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6694 LLVM_FALLTHROUGH; 6695 case ISD::SETOLE: 6696 case ISD::SETLE: 6697 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6698 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6699 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6700 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6701 } 6702 6703 SDValue Cmp; 6704 switch (CC) { 6705 default: break; // SETUO etc aren't handled by fsel. 6706 case ISD::SETNE: 6707 std::swap(TV, FV); 6708 LLVM_FALLTHROUGH; 6709 case ISD::SETEQ: 6710 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6711 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6712 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6713 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6714 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6715 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6716 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6717 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6718 case ISD::SETULT: 6719 case ISD::SETLT: 6720 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6721 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6722 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6723 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6724 case ISD::SETOGE: 6725 case ISD::SETGE: 6726 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6727 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6728 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6729 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6730 case ISD::SETUGT: 6731 case ISD::SETGT: 6732 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6733 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6734 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6735 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6736 case ISD::SETOLE: 6737 case ISD::SETLE: 6738 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6739 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6740 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6741 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6742 } 6743 return Op; 6744 } 6745 6746 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6747 SelectionDAG &DAG, 6748 const SDLoc &dl) const { 6749 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6750 SDValue Src = Op.getOperand(0); 6751 if (Src.getValueType() == MVT::f32) 6752 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6753 6754 SDValue Tmp; 6755 switch (Op.getSimpleValueType().SimpleTy) { 6756 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6757 case MVT::i32: 6758 Tmp = DAG.getNode( 6759 Op.getOpcode() == ISD::FP_TO_SINT 6760 ? PPCISD::FCTIWZ 6761 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6762 dl, MVT::f64, Src); 6763 break; 6764 case MVT::i64: 6765 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6766 "i64 FP_TO_UINT is supported only with FPCVT"); 6767 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6768 PPCISD::FCTIDUZ, 6769 dl, MVT::f64, Src); 6770 break; 6771 } 6772 6773 // Convert the FP value to an int value through memory. 6774 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 6775 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 6776 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 6777 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 6778 MachinePointerInfo MPI = 6779 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 6780 6781 // Emit a store to the stack slot. 6782 SDValue Chain; 6783 if (i32Stack) { 6784 MachineFunction &MF = DAG.getMachineFunction(); 6785 MachineMemOperand *MMO = 6786 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 6787 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 6788 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 6789 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 6790 } else 6791 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 6792 6793 // Result is a load from the stack slot. If loading 4 bytes, make sure to 6794 // add in a bias on big endian. 6795 if (Op.getValueType() == MVT::i32 && !i32Stack) { 6796 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 6797 DAG.getConstant(4, dl, FIPtr.getValueType())); 6798 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 6799 } 6800 6801 RLI.Chain = Chain; 6802 RLI.Ptr = FIPtr; 6803 RLI.MPI = MPI; 6804 } 6805 6806 /// \brief Custom lowers floating point to integer conversions to use 6807 /// the direct move instructions available in ISA 2.07 to avoid the 6808 /// need for load/store combinations. 6809 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 6810 SelectionDAG &DAG, 6811 const SDLoc &dl) const { 6812 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6813 SDValue Src = Op.getOperand(0); 6814 6815 if (Src.getValueType() == MVT::f32) 6816 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6817 6818 SDValue Tmp; 6819 switch (Op.getSimpleValueType().SimpleTy) { 6820 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6821 case MVT::i32: 6822 Tmp = DAG.getNode( 6823 Op.getOpcode() == ISD::FP_TO_SINT 6824 ? PPCISD::FCTIWZ 6825 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6826 dl, MVT::f64, Src); 6827 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 6828 break; 6829 case MVT::i64: 6830 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6831 "i64 FP_TO_UINT is supported only with FPCVT"); 6832 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6833 PPCISD::FCTIDUZ, 6834 dl, MVT::f64, Src); 6835 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 6836 break; 6837 } 6838 return Tmp; 6839 } 6840 6841 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 6842 const SDLoc &dl) const { 6843 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 6844 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 6845 6846 ReuseLoadInfo RLI; 6847 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6848 6849 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6850 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6851 } 6852 6853 // We're trying to insert a regular store, S, and then a load, L. If the 6854 // incoming value, O, is a load, we might just be able to have our load use the 6855 // address used by O. However, we don't know if anything else will store to 6856 // that address before we can load from it. To prevent this situation, we need 6857 // to insert our load, L, into the chain as a peer of O. To do this, we give L 6858 // the same chain operand as O, we create a token factor from the chain results 6859 // of O and L, and we replace all uses of O's chain result with that token 6860 // factor (see spliceIntoChain below for this last part). 6861 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 6862 ReuseLoadInfo &RLI, 6863 SelectionDAG &DAG, 6864 ISD::LoadExtType ET) const { 6865 SDLoc dl(Op); 6866 if (ET == ISD::NON_EXTLOAD && 6867 (Op.getOpcode() == ISD::FP_TO_UINT || 6868 Op.getOpcode() == ISD::FP_TO_SINT) && 6869 isOperationLegalOrCustom(Op.getOpcode(), 6870 Op.getOperand(0).getValueType())) { 6871 6872 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6873 return true; 6874 } 6875 6876 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 6877 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 6878 LD->isNonTemporal()) 6879 return false; 6880 if (LD->getMemoryVT() != MemVT) 6881 return false; 6882 6883 RLI.Ptr = LD->getBasePtr(); 6884 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 6885 assert(LD->getAddressingMode() == ISD::PRE_INC && 6886 "Non-pre-inc AM on PPC?"); 6887 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 6888 LD->getOffset()); 6889 } 6890 6891 RLI.Chain = LD->getChain(); 6892 RLI.MPI = LD->getPointerInfo(); 6893 RLI.IsDereferenceable = LD->isDereferenceable(); 6894 RLI.IsInvariant = LD->isInvariant(); 6895 RLI.Alignment = LD->getAlignment(); 6896 RLI.AAInfo = LD->getAAInfo(); 6897 RLI.Ranges = LD->getRanges(); 6898 6899 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 6900 return true; 6901 } 6902 6903 // Given the head of the old chain, ResChain, insert a token factor containing 6904 // it and NewResChain, and make users of ResChain now be users of that token 6905 // factor. 6906 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 6907 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 6908 SDValue NewResChain, 6909 SelectionDAG &DAG) const { 6910 if (!ResChain) 6911 return; 6912 6913 SDLoc dl(NewResChain); 6914 6915 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6916 NewResChain, DAG.getUNDEF(MVT::Other)); 6917 assert(TF.getNode() != NewResChain.getNode() && 6918 "A new TF really is required here"); 6919 6920 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 6921 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 6922 } 6923 6924 /// \brief Analyze profitability of direct move 6925 /// prefer float load to int load plus direct move 6926 /// when there is no integer use of int load 6927 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 6928 SDNode *Origin = Op.getOperand(0).getNode(); 6929 if (Origin->getOpcode() != ISD::LOAD) 6930 return true; 6931 6932 // If there is no LXSIBZX/LXSIHZX, like Power8, 6933 // prefer direct move if the memory size is 1 or 2 bytes. 6934 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 6935 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 6936 return true; 6937 6938 for (SDNode::use_iterator UI = Origin->use_begin(), 6939 UE = Origin->use_end(); 6940 UI != UE; ++UI) { 6941 6942 // Only look at the users of the loaded value. 6943 if (UI.getUse().get().getResNo() != 0) 6944 continue; 6945 6946 if (UI->getOpcode() != ISD::SINT_TO_FP && 6947 UI->getOpcode() != ISD::UINT_TO_FP) 6948 return true; 6949 } 6950 6951 return false; 6952 } 6953 6954 /// \brief Custom lowers integer to floating point conversions to use 6955 /// the direct move instructions available in ISA 2.07 to avoid the 6956 /// need for load/store combinations. 6957 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 6958 SelectionDAG &DAG, 6959 const SDLoc &dl) const { 6960 assert((Op.getValueType() == MVT::f32 || 6961 Op.getValueType() == MVT::f64) && 6962 "Invalid floating point type as target of conversion"); 6963 assert(Subtarget.hasFPCVT() && 6964 "Int to FP conversions with direct moves require FPCVT"); 6965 SDValue FP; 6966 SDValue Src = Op.getOperand(0); 6967 bool SinglePrec = Op.getValueType() == MVT::f32; 6968 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 6969 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 6970 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 6971 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 6972 6973 if (WordInt) { 6974 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 6975 dl, MVT::f64, Src); 6976 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6977 } 6978 else { 6979 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 6980 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6981 } 6982 6983 return FP; 6984 } 6985 6986 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 6987 SelectionDAG &DAG) const { 6988 SDLoc dl(Op); 6989 6990 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 6991 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 6992 return SDValue(); 6993 6994 SDValue Value = Op.getOperand(0); 6995 // The values are now known to be -1 (false) or 1 (true). To convert this 6996 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 6997 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 6998 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 6999 7000 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7001 7002 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7003 7004 if (Op.getValueType() != MVT::v4f64) 7005 Value = DAG.getNode(ISD::FP_ROUND, dl, 7006 Op.getValueType(), Value, 7007 DAG.getIntPtrConstant(1, dl)); 7008 return Value; 7009 } 7010 7011 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7012 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7013 return SDValue(); 7014 7015 if (Op.getOperand(0).getValueType() == MVT::i1) 7016 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7017 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7018 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7019 7020 // If we have direct moves, we can do all the conversion, skip the store/load 7021 // however, without FPCVT we can't do most conversions. 7022 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7023 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7024 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7025 7026 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7027 "UINT_TO_FP is supported only with FPCVT"); 7028 7029 // If we have FCFIDS, then use it when converting to single-precision. 7030 // Otherwise, convert to double-precision and then round. 7031 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7032 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7033 : PPCISD::FCFIDS) 7034 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7035 : PPCISD::FCFID); 7036 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7037 ? MVT::f32 7038 : MVT::f64; 7039 7040 if (Op.getOperand(0).getValueType() == MVT::i64) { 7041 SDValue SINT = Op.getOperand(0); 7042 // When converting to single-precision, we actually need to convert 7043 // to double-precision first and then round to single-precision. 7044 // To avoid double-rounding effects during that operation, we have 7045 // to prepare the input operand. Bits that might be truncated when 7046 // converting to double-precision are replaced by a bit that won't 7047 // be lost at this stage, but is below the single-precision rounding 7048 // position. 7049 // 7050 // However, if -enable-unsafe-fp-math is in effect, accept double 7051 // rounding to avoid the extra overhead. 7052 if (Op.getValueType() == MVT::f32 && 7053 !Subtarget.hasFPCVT() && 7054 !DAG.getTarget().Options.UnsafeFPMath) { 7055 7056 // Twiddle input to make sure the low 11 bits are zero. (If this 7057 // is the case, we are guaranteed the value will fit into the 53 bit 7058 // mantissa of an IEEE double-precision value without rounding.) 7059 // If any of those low 11 bits were not zero originally, make sure 7060 // bit 12 (value 2048) is set instead, so that the final rounding 7061 // to single-precision gets the correct result. 7062 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7063 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7064 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7065 Round, DAG.getConstant(2047, dl, MVT::i64)); 7066 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7067 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7068 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7069 7070 // However, we cannot use that value unconditionally: if the magnitude 7071 // of the input value is small, the bit-twiddling we did above might 7072 // end up visibly changing the output. Fortunately, in that case, we 7073 // don't need to twiddle bits since the original input will convert 7074 // exactly to double-precision floating-point already. Therefore, 7075 // construct a conditional to use the original value if the top 11 7076 // bits are all sign-bit copies, and use the rounded value computed 7077 // above otherwise. 7078 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7079 SINT, DAG.getConstant(53, dl, MVT::i32)); 7080 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7081 Cond, DAG.getConstant(1, dl, MVT::i64)); 7082 Cond = DAG.getSetCC(dl, MVT::i32, 7083 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7084 7085 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7086 } 7087 7088 ReuseLoadInfo RLI; 7089 SDValue Bits; 7090 7091 MachineFunction &MF = DAG.getMachineFunction(); 7092 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7093 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7094 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7095 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7096 } else if (Subtarget.hasLFIWAX() && 7097 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7098 MachineMemOperand *MMO = 7099 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7100 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7101 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7102 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7103 DAG.getVTList(MVT::f64, MVT::Other), 7104 Ops, MVT::i32, MMO); 7105 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7106 } else if (Subtarget.hasFPCVT() && 7107 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7108 MachineMemOperand *MMO = 7109 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7110 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7111 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7112 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7113 DAG.getVTList(MVT::f64, MVT::Other), 7114 Ops, MVT::i32, MMO); 7115 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7116 } else if (((Subtarget.hasLFIWAX() && 7117 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7118 (Subtarget.hasFPCVT() && 7119 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7120 SINT.getOperand(0).getValueType() == MVT::i32) { 7121 MachineFrameInfo &MFI = MF.getFrameInfo(); 7122 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7123 7124 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7125 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7126 7127 SDValue Store = 7128 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7129 MachinePointerInfo::getFixedStack( 7130 DAG.getMachineFunction(), FrameIdx)); 7131 7132 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7133 "Expected an i32 store"); 7134 7135 RLI.Ptr = FIdx; 7136 RLI.Chain = Store; 7137 RLI.MPI = 7138 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7139 RLI.Alignment = 4; 7140 7141 MachineMemOperand *MMO = 7142 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7143 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7144 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7145 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7146 PPCISD::LFIWZX : PPCISD::LFIWAX, 7147 dl, DAG.getVTList(MVT::f64, MVT::Other), 7148 Ops, MVT::i32, MMO); 7149 } else 7150 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7151 7152 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7153 7154 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7155 FP = DAG.getNode(ISD::FP_ROUND, dl, 7156 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7157 return FP; 7158 } 7159 7160 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7161 "Unhandled INT_TO_FP type in custom expander!"); 7162 // Since we only generate this in 64-bit mode, we can take advantage of 7163 // 64-bit registers. In particular, sign extend the input value into the 7164 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7165 // then lfd it and fcfid it. 7166 MachineFunction &MF = DAG.getMachineFunction(); 7167 MachineFrameInfo &MFI = MF.getFrameInfo(); 7168 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7169 7170 SDValue Ld; 7171 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7172 ReuseLoadInfo RLI; 7173 bool ReusingLoad; 7174 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7175 DAG))) { 7176 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7177 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7178 7179 SDValue Store = 7180 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7181 MachinePointerInfo::getFixedStack( 7182 DAG.getMachineFunction(), FrameIdx)); 7183 7184 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7185 "Expected an i32 store"); 7186 7187 RLI.Ptr = FIdx; 7188 RLI.Chain = Store; 7189 RLI.MPI = 7190 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7191 RLI.Alignment = 4; 7192 } 7193 7194 MachineMemOperand *MMO = 7195 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7196 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7197 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7198 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7199 PPCISD::LFIWZX : PPCISD::LFIWAX, 7200 dl, DAG.getVTList(MVT::f64, MVT::Other), 7201 Ops, MVT::i32, MMO); 7202 if (ReusingLoad) 7203 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7204 } else { 7205 assert(Subtarget.isPPC64() && 7206 "i32->FP without LFIWAX supported only on PPC64"); 7207 7208 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7209 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7210 7211 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7212 Op.getOperand(0)); 7213 7214 // STD the extended value into the stack slot. 7215 SDValue Store = DAG.getStore( 7216 DAG.getEntryNode(), dl, Ext64, FIdx, 7217 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7218 7219 // Load the value as a double. 7220 Ld = DAG.getLoad( 7221 MVT::f64, dl, Store, FIdx, 7222 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7223 } 7224 7225 // FCFID it and return it. 7226 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7227 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7228 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7229 DAG.getIntPtrConstant(0, dl)); 7230 return FP; 7231 } 7232 7233 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7234 SelectionDAG &DAG) const { 7235 SDLoc dl(Op); 7236 /* 7237 The rounding mode is in bits 30:31 of FPSR, and has the following 7238 settings: 7239 00 Round to nearest 7240 01 Round to 0 7241 10 Round to +inf 7242 11 Round to -inf 7243 7244 FLT_ROUNDS, on the other hand, expects the following: 7245 -1 Undefined 7246 0 Round to 0 7247 1 Round to nearest 7248 2 Round to +inf 7249 3 Round to -inf 7250 7251 To perform the conversion, we do: 7252 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7253 */ 7254 7255 MachineFunction &MF = DAG.getMachineFunction(); 7256 EVT VT = Op.getValueType(); 7257 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7258 7259 // Save FP Control Word to register 7260 EVT NodeTys[] = { 7261 MVT::f64, // return register 7262 MVT::Glue // unused in this context 7263 }; 7264 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7265 7266 // Save FP register to stack slot 7267 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7268 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7269 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7270 MachinePointerInfo()); 7271 7272 // Load FP Control Word from low 32 bits of stack slot. 7273 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7274 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7275 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7276 7277 // Transform as necessary 7278 SDValue CWD1 = 7279 DAG.getNode(ISD::AND, dl, MVT::i32, 7280 CWD, DAG.getConstant(3, dl, MVT::i32)); 7281 SDValue CWD2 = 7282 DAG.getNode(ISD::SRL, dl, MVT::i32, 7283 DAG.getNode(ISD::AND, dl, MVT::i32, 7284 DAG.getNode(ISD::XOR, dl, MVT::i32, 7285 CWD, DAG.getConstant(3, dl, MVT::i32)), 7286 DAG.getConstant(3, dl, MVT::i32)), 7287 DAG.getConstant(1, dl, MVT::i32)); 7288 7289 SDValue RetVal = 7290 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7291 7292 return DAG.getNode((VT.getSizeInBits() < 16 ? 7293 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7294 } 7295 7296 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7297 EVT VT = Op.getValueType(); 7298 unsigned BitWidth = VT.getSizeInBits(); 7299 SDLoc dl(Op); 7300 assert(Op.getNumOperands() == 3 && 7301 VT == Op.getOperand(1).getValueType() && 7302 "Unexpected SHL!"); 7303 7304 // Expand into a bunch of logical ops. Note that these ops 7305 // depend on the PPC behavior for oversized shift amounts. 7306 SDValue Lo = Op.getOperand(0); 7307 SDValue Hi = Op.getOperand(1); 7308 SDValue Amt = Op.getOperand(2); 7309 EVT AmtVT = Amt.getValueType(); 7310 7311 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7312 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7313 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7314 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7315 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7316 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7317 DAG.getConstant(-BitWidth, dl, AmtVT)); 7318 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7319 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7320 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7321 SDValue OutOps[] = { OutLo, OutHi }; 7322 return DAG.getMergeValues(OutOps, dl); 7323 } 7324 7325 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7326 EVT VT = Op.getValueType(); 7327 SDLoc dl(Op); 7328 unsigned BitWidth = VT.getSizeInBits(); 7329 assert(Op.getNumOperands() == 3 && 7330 VT == Op.getOperand(1).getValueType() && 7331 "Unexpected SRL!"); 7332 7333 // Expand into a bunch of logical ops. Note that these ops 7334 // depend on the PPC behavior for oversized shift amounts. 7335 SDValue Lo = Op.getOperand(0); 7336 SDValue Hi = Op.getOperand(1); 7337 SDValue Amt = Op.getOperand(2); 7338 EVT AmtVT = Amt.getValueType(); 7339 7340 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7341 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7342 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7343 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7344 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7345 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7346 DAG.getConstant(-BitWidth, dl, AmtVT)); 7347 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7348 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7349 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7350 SDValue OutOps[] = { OutLo, OutHi }; 7351 return DAG.getMergeValues(OutOps, dl); 7352 } 7353 7354 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7355 SDLoc dl(Op); 7356 EVT VT = Op.getValueType(); 7357 unsigned BitWidth = VT.getSizeInBits(); 7358 assert(Op.getNumOperands() == 3 && 7359 VT == Op.getOperand(1).getValueType() && 7360 "Unexpected SRA!"); 7361 7362 // Expand into a bunch of logical ops, followed by a select_cc. 7363 SDValue Lo = Op.getOperand(0); 7364 SDValue Hi = Op.getOperand(1); 7365 SDValue Amt = Op.getOperand(2); 7366 EVT AmtVT = Amt.getValueType(); 7367 7368 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7369 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7370 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7371 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7372 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7373 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7374 DAG.getConstant(-BitWidth, dl, AmtVT)); 7375 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7376 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7377 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7378 Tmp4, Tmp6, ISD::SETLE); 7379 SDValue OutOps[] = { OutLo, OutHi }; 7380 return DAG.getMergeValues(OutOps, dl); 7381 } 7382 7383 //===----------------------------------------------------------------------===// 7384 // Vector related lowering. 7385 // 7386 7387 /// BuildSplatI - Build a canonical splati of Val with an element size of 7388 /// SplatSize. Cast the result to VT. 7389 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7390 SelectionDAG &DAG, const SDLoc &dl) { 7391 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7392 7393 static const MVT VTys[] = { // canonical VT to use for each size. 7394 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7395 }; 7396 7397 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7398 7399 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7400 if (Val == -1) 7401 SplatSize = 1; 7402 7403 EVT CanonicalVT = VTys[SplatSize-1]; 7404 7405 // Build a canonical splat for this value. 7406 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7407 } 7408 7409 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7410 /// specified intrinsic ID. 7411 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7412 const SDLoc &dl, EVT DestVT = MVT::Other) { 7413 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7414 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7415 DAG.getConstant(IID, dl, MVT::i32), Op); 7416 } 7417 7418 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7419 /// specified intrinsic ID. 7420 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7421 SelectionDAG &DAG, const SDLoc &dl, 7422 EVT DestVT = MVT::Other) { 7423 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7424 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7425 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7426 } 7427 7428 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7429 /// specified intrinsic ID. 7430 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7431 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7432 EVT DestVT = MVT::Other) { 7433 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7434 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7435 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7436 } 7437 7438 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7439 /// amount. The result has the specified value type. 7440 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7441 SelectionDAG &DAG, const SDLoc &dl) { 7442 // Force LHS/RHS to be the right type. 7443 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7444 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7445 7446 int Ops[16]; 7447 for (unsigned i = 0; i != 16; ++i) 7448 Ops[i] = i + Amt; 7449 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7450 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7451 } 7452 7453 /// Do we have an efficient pattern in a .td file for this node? 7454 /// 7455 /// \param V - pointer to the BuildVectorSDNode being matched 7456 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7457 /// 7458 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7459 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7460 /// the opposite is true (expansion is beneficial) are: 7461 /// - The node builds a vector out of integers that are not 32 or 64-bits 7462 /// - The node builds a vector out of constants 7463 /// - The node is a "load-and-splat" 7464 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7465 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7466 bool HasDirectMove, 7467 bool HasP8Vector) { 7468 EVT VecVT = V->getValueType(0); 7469 bool RightType = VecVT == MVT::v2f64 || 7470 (HasP8Vector && VecVT == MVT::v4f32) || 7471 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7472 if (!RightType) 7473 return false; 7474 7475 bool IsSplat = true; 7476 bool IsLoad = false; 7477 SDValue Op0 = V->getOperand(0); 7478 7479 // This function is called in a block that confirms the node is not a constant 7480 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7481 // different constants. 7482 if (V->isConstant()) 7483 return false; 7484 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7485 if (V->getOperand(i).isUndef()) 7486 return false; 7487 // We want to expand nodes that represent load-and-splat even if the 7488 // loaded value is a floating point truncation or conversion to int. 7489 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7490 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7491 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7492 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7493 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7494 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7495 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7496 IsLoad = true; 7497 // If the operands are different or the input is not a load and has more 7498 // uses than just this BV node, then it isn't a splat. 7499 if (V->getOperand(i) != Op0 || 7500 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7501 IsSplat = false; 7502 } 7503 return !(IsSplat && IsLoad); 7504 } 7505 7506 // If this is a case we can't handle, return null and let the default 7507 // expansion code take care of it. If we CAN select this case, and if it 7508 // selects to a single instruction, return Op. Otherwise, if we can codegen 7509 // this case more efficiently than a constant pool load, lower it to the 7510 // sequence of ops that should be used. 7511 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7512 SelectionDAG &DAG) const { 7513 SDLoc dl(Op); 7514 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7515 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7516 7517 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7518 // We first build an i32 vector, load it into a QPX register, 7519 // then convert it to a floating-point vector and compare it 7520 // to a zero vector to get the boolean result. 7521 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7522 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7523 MachinePointerInfo PtrInfo = 7524 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7525 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7526 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7527 7528 assert(BVN->getNumOperands() == 4 && 7529 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7530 7531 bool IsConst = true; 7532 for (unsigned i = 0; i < 4; ++i) { 7533 if (BVN->getOperand(i).isUndef()) continue; 7534 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7535 IsConst = false; 7536 break; 7537 } 7538 } 7539 7540 if (IsConst) { 7541 Constant *One = 7542 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7543 Constant *NegOne = 7544 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7545 7546 Constant *CV[4]; 7547 for (unsigned i = 0; i < 4; ++i) { 7548 if (BVN->getOperand(i).isUndef()) 7549 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7550 else if (isNullConstant(BVN->getOperand(i))) 7551 CV[i] = NegOne; 7552 else 7553 CV[i] = One; 7554 } 7555 7556 Constant *CP = ConstantVector::get(CV); 7557 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7558 16 /* alignment */); 7559 7560 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7561 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7562 return DAG.getMemIntrinsicNode( 7563 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7564 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7565 } 7566 7567 SmallVector<SDValue, 4> Stores; 7568 for (unsigned i = 0; i < 4; ++i) { 7569 if (BVN->getOperand(i).isUndef()) continue; 7570 7571 unsigned Offset = 4*i; 7572 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7573 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7574 7575 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7576 if (StoreSize > 4) { 7577 Stores.push_back( 7578 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7579 PtrInfo.getWithOffset(Offset), MVT::i32)); 7580 } else { 7581 SDValue StoreValue = BVN->getOperand(i); 7582 if (StoreSize < 4) 7583 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7584 7585 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7586 PtrInfo.getWithOffset(Offset))); 7587 } 7588 } 7589 7590 SDValue StoreChain; 7591 if (!Stores.empty()) 7592 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7593 else 7594 StoreChain = DAG.getEntryNode(); 7595 7596 // Now load from v4i32 into the QPX register; this will extend it to 7597 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7598 // is typed as v4f64 because the QPX register integer states are not 7599 // explicitly represented. 7600 7601 SDValue Ops[] = {StoreChain, 7602 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7603 FIdx}; 7604 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7605 7606 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7607 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7608 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7609 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7610 LoadedVect); 7611 7612 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7613 7614 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7615 } 7616 7617 // All other QPX vectors are handled by generic code. 7618 if (Subtarget.hasQPX()) 7619 return SDValue(); 7620 7621 // Check if this is a splat of a constant value. 7622 APInt APSplatBits, APSplatUndef; 7623 unsigned SplatBitSize; 7624 bool HasAnyUndefs; 7625 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7626 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7627 SplatBitSize > 32) { 7628 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7629 // lowered to VSX instructions under certain conditions. 7630 // Without VSX, there is no pattern more efficient than expanding the node. 7631 if (Subtarget.hasVSX() && 7632 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 7633 Subtarget.hasP8Vector())) 7634 return Op; 7635 return SDValue(); 7636 } 7637 7638 unsigned SplatBits = APSplatBits.getZExtValue(); 7639 unsigned SplatUndef = APSplatUndef.getZExtValue(); 7640 unsigned SplatSize = SplatBitSize / 8; 7641 7642 // First, handle single instruction cases. 7643 7644 // All zeros? 7645 if (SplatBits == 0) { 7646 // Canonicalize all zero vectors to be v4i32. 7647 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 7648 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 7649 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 7650 } 7651 return Op; 7652 } 7653 7654 // We have XXSPLTIB for constant splats one byte wide 7655 if (Subtarget.hasP9Vector() && SplatSize == 1) { 7656 // This is a splat of 1-byte elements with some elements potentially undef. 7657 // Rather than trying to match undef in the SDAG patterns, ensure that all 7658 // elements are the same constant. 7659 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 7660 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 7661 dl, MVT::i32)); 7662 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 7663 if (Op.getValueType() != MVT::v16i8) 7664 return DAG.getBitcast(Op.getValueType(), NewBV); 7665 return NewBV; 7666 } 7667 7668 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 7669 // detect that constant splats like v8i16: 0xABAB are really just splats 7670 // of a 1-byte constant. In this case, we need to convert the node to a 7671 // splat of v16i8 and a bitcast. 7672 if (Op.getValueType() != MVT::v16i8) 7673 return DAG.getBitcast(Op.getValueType(), 7674 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 7675 7676 return Op; 7677 } 7678 7679 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 7680 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 7681 (32-SplatBitSize)); 7682 if (SextVal >= -16 && SextVal <= 15) 7683 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 7684 7685 // Two instruction sequences. 7686 7687 // If this value is in the range [-32,30] and is even, use: 7688 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 7689 // If this value is in the range [17,31] and is odd, use: 7690 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 7691 // If this value is in the range [-31,-17] and is odd, use: 7692 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 7693 // Note the last two are three-instruction sequences. 7694 if (SextVal >= -32 && SextVal <= 31) { 7695 // To avoid having these optimizations undone by constant folding, 7696 // we convert to a pseudo that will be expanded later into one of 7697 // the above forms. 7698 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 7699 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 7700 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 7701 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 7702 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 7703 if (VT == Op.getValueType()) 7704 return RetVal; 7705 else 7706 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 7707 } 7708 7709 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 7710 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 7711 // for fneg/fabs. 7712 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 7713 // Make -1 and vspltisw -1: 7714 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 7715 7716 // Make the VSLW intrinsic, computing 0x8000_0000. 7717 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 7718 OnesV, DAG, dl); 7719 7720 // xor by OnesV to invert it. 7721 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 7722 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7723 } 7724 7725 // Check to see if this is a wide variety of vsplti*, binop self cases. 7726 static const signed char SplatCsts[] = { 7727 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 7728 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 7729 }; 7730 7731 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 7732 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 7733 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 7734 int i = SplatCsts[idx]; 7735 7736 // Figure out what shift amount will be used by altivec if shifted by i in 7737 // this splat size. 7738 unsigned TypeShiftAmt = i & (SplatBitSize-1); 7739 7740 // vsplti + shl self. 7741 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 7742 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7743 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7744 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 7745 Intrinsic::ppc_altivec_vslw 7746 }; 7747 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7748 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7749 } 7750 7751 // vsplti + srl self. 7752 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7753 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7754 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7755 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 7756 Intrinsic::ppc_altivec_vsrw 7757 }; 7758 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7759 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7760 } 7761 7762 // vsplti + sra self. 7763 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7764 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7765 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7766 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 7767 Intrinsic::ppc_altivec_vsraw 7768 }; 7769 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7770 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7771 } 7772 7773 // vsplti + rol self. 7774 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 7775 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 7776 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7777 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7778 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 7779 Intrinsic::ppc_altivec_vrlw 7780 }; 7781 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7782 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7783 } 7784 7785 // t = vsplti c, result = vsldoi t, t, 1 7786 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 7787 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7788 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 7789 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7790 } 7791 // t = vsplti c, result = vsldoi t, t, 2 7792 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 7793 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7794 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 7795 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7796 } 7797 // t = vsplti c, result = vsldoi t, t, 3 7798 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 7799 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7800 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 7801 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7802 } 7803 } 7804 7805 return SDValue(); 7806 } 7807 7808 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7809 /// the specified operations to build the shuffle. 7810 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7811 SDValue RHS, SelectionDAG &DAG, 7812 const SDLoc &dl) { 7813 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7814 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7815 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7816 7817 enum { 7818 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7819 OP_VMRGHW, 7820 OP_VMRGLW, 7821 OP_VSPLTISW0, 7822 OP_VSPLTISW1, 7823 OP_VSPLTISW2, 7824 OP_VSPLTISW3, 7825 OP_VSLDOI4, 7826 OP_VSLDOI8, 7827 OP_VSLDOI12 7828 }; 7829 7830 if (OpNum == OP_COPY) { 7831 if (LHSID == (1*9+2)*9+3) return LHS; 7832 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7833 return RHS; 7834 } 7835 7836 SDValue OpLHS, OpRHS; 7837 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7838 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7839 7840 int ShufIdxs[16]; 7841 switch (OpNum) { 7842 default: llvm_unreachable("Unknown i32 permute!"); 7843 case OP_VMRGHW: 7844 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 7845 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 7846 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 7847 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 7848 break; 7849 case OP_VMRGLW: 7850 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 7851 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 7852 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 7853 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 7854 break; 7855 case OP_VSPLTISW0: 7856 for (unsigned i = 0; i != 16; ++i) 7857 ShufIdxs[i] = (i&3)+0; 7858 break; 7859 case OP_VSPLTISW1: 7860 for (unsigned i = 0; i != 16; ++i) 7861 ShufIdxs[i] = (i&3)+4; 7862 break; 7863 case OP_VSPLTISW2: 7864 for (unsigned i = 0; i != 16; ++i) 7865 ShufIdxs[i] = (i&3)+8; 7866 break; 7867 case OP_VSPLTISW3: 7868 for (unsigned i = 0; i != 16; ++i) 7869 ShufIdxs[i] = (i&3)+12; 7870 break; 7871 case OP_VSLDOI4: 7872 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 7873 case OP_VSLDOI8: 7874 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 7875 case OP_VSLDOI12: 7876 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 7877 } 7878 EVT VT = OpLHS.getValueType(); 7879 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 7880 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 7881 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 7882 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7883 } 7884 7885 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 7886 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 7887 /// return the code it can be lowered into. Worst case, it can always be 7888 /// lowered into a vperm. 7889 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 7890 SelectionDAG &DAG) const { 7891 SDLoc dl(Op); 7892 SDValue V1 = Op.getOperand(0); 7893 SDValue V2 = Op.getOperand(1); 7894 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 7895 EVT VT = Op.getValueType(); 7896 bool isLittleEndian = Subtarget.isLittleEndian(); 7897 7898 unsigned ShiftElts, InsertAtByte; 7899 bool Swap = false; 7900 if (Subtarget.hasP9Vector() && 7901 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 7902 isLittleEndian)) { 7903 if (Swap) 7904 std::swap(V1, V2); 7905 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7906 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 7907 if (ShiftElts) { 7908 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 7909 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7910 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 7911 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7912 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 7913 } 7914 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 7915 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7916 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 7917 } 7918 7919 7920 if (Subtarget.hasVSX() && 7921 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 7922 if (Swap) 7923 std::swap(V1, V2); 7924 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7925 SDValue Conv2 = 7926 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 7927 7928 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 7929 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7930 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 7931 } 7932 7933 if (Subtarget.hasVSX() && 7934 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 7935 if (Swap) 7936 std::swap(V1, V2); 7937 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 7938 SDValue Conv2 = 7939 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 7940 7941 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 7942 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7943 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 7944 } 7945 7946 if (Subtarget.hasP9Vector()) { 7947 if (PPC::isXXBRHShuffleMask(SVOp)) { 7948 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 7949 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 7950 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 7951 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 7952 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7953 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 7954 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 7955 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 7956 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 7957 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 7958 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 7959 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 7960 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 7961 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 7962 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 7963 } 7964 } 7965 7966 if (Subtarget.hasVSX()) { 7967 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 7968 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 7969 7970 // If the source for the shuffle is a scalar_to_vector that came from a 7971 // 32-bit load, it will have used LXVWSX so we don't need to splat again. 7972 if (Subtarget.hasP9Vector() && 7973 ((isLittleEndian && SplatIdx == 3) || 7974 (!isLittleEndian && SplatIdx == 0))) { 7975 SDValue Src = V1.getOperand(0); 7976 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR && 7977 Src.getOperand(0).getOpcode() == ISD::LOAD && 7978 Src.getOperand(0).hasOneUse()) 7979 return V1; 7980 } 7981 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7982 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 7983 DAG.getConstant(SplatIdx, dl, MVT::i32)); 7984 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 7985 } 7986 7987 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 7988 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 7989 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 7990 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 7991 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 7992 } 7993 } 7994 7995 if (Subtarget.hasQPX()) { 7996 if (VT.getVectorNumElements() != 4) 7997 return SDValue(); 7998 7999 if (V2.isUndef()) V2 = V1; 8000 8001 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8002 if (AlignIdx != -1) { 8003 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8004 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8005 } else if (SVOp->isSplat()) { 8006 int SplatIdx = SVOp->getSplatIndex(); 8007 if (SplatIdx >= 4) { 8008 std::swap(V1, V2); 8009 SplatIdx -= 4; 8010 } 8011 8012 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8013 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8014 } 8015 8016 // Lower this into a qvgpci/qvfperm pair. 8017 8018 // Compute the qvgpci literal 8019 unsigned idx = 0; 8020 for (unsigned i = 0; i < 4; ++i) { 8021 int m = SVOp->getMaskElt(i); 8022 unsigned mm = m >= 0 ? (unsigned) m : i; 8023 idx |= mm << (3-i)*3; 8024 } 8025 8026 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8027 DAG.getConstant(idx, dl, MVT::i32)); 8028 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8029 } 8030 8031 // Cases that are handled by instructions that take permute immediates 8032 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8033 // selected by the instruction selector. 8034 if (V2.isUndef()) { 8035 if (PPC::isSplatShuffleMask(SVOp, 1) || 8036 PPC::isSplatShuffleMask(SVOp, 2) || 8037 PPC::isSplatShuffleMask(SVOp, 4) || 8038 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8039 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8040 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8041 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8042 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8043 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8044 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8045 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8046 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8047 (Subtarget.hasP8Altivec() && ( 8048 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8049 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8050 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8051 return Op; 8052 } 8053 } 8054 8055 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8056 // and produce a fixed permutation. If any of these match, do not lower to 8057 // VPERM. 8058 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8059 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8060 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8061 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8062 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8063 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8064 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8065 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8066 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8067 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8068 (Subtarget.hasP8Altivec() && ( 8069 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8070 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8071 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8072 return Op; 8073 8074 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8075 // perfect shuffle table to emit an optimal matching sequence. 8076 ArrayRef<int> PermMask = SVOp->getMask(); 8077 8078 unsigned PFIndexes[4]; 8079 bool isFourElementShuffle = true; 8080 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8081 unsigned EltNo = 8; // Start out undef. 8082 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8083 if (PermMask[i*4+j] < 0) 8084 continue; // Undef, ignore it. 8085 8086 unsigned ByteSource = PermMask[i*4+j]; 8087 if ((ByteSource & 3) != j) { 8088 isFourElementShuffle = false; 8089 break; 8090 } 8091 8092 if (EltNo == 8) { 8093 EltNo = ByteSource/4; 8094 } else if (EltNo != ByteSource/4) { 8095 isFourElementShuffle = false; 8096 break; 8097 } 8098 } 8099 PFIndexes[i] = EltNo; 8100 } 8101 8102 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8103 // perfect shuffle vector to determine if it is cost effective to do this as 8104 // discrete instructions, or whether we should use a vperm. 8105 // For now, we skip this for little endian until such time as we have a 8106 // little-endian perfect shuffle table. 8107 if (isFourElementShuffle && !isLittleEndian) { 8108 // Compute the index in the perfect shuffle table. 8109 unsigned PFTableIndex = 8110 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8111 8112 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8113 unsigned Cost = (PFEntry >> 30); 8114 8115 // Determining when to avoid vperm is tricky. Many things affect the cost 8116 // of vperm, particularly how many times the perm mask needs to be computed. 8117 // For example, if the perm mask can be hoisted out of a loop or is already 8118 // used (perhaps because there are multiple permutes with the same shuffle 8119 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8120 // the loop requires an extra register. 8121 // 8122 // As a compromise, we only emit discrete instructions if the shuffle can be 8123 // generated in 3 or fewer operations. When we have loop information 8124 // available, if this block is within a loop, we should avoid using vperm 8125 // for 3-operation perms and use a constant pool load instead. 8126 if (Cost < 3) 8127 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8128 } 8129 8130 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8131 // vector that will get spilled to the constant pool. 8132 if (V2.isUndef()) V2 = V1; 8133 8134 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8135 // that it is in input element units, not in bytes. Convert now. 8136 8137 // For little endian, the order of the input vectors is reversed, and 8138 // the permutation mask is complemented with respect to 31. This is 8139 // necessary to produce proper semantics with the big-endian-biased vperm 8140 // instruction. 8141 EVT EltVT = V1.getValueType().getVectorElementType(); 8142 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8143 8144 SmallVector<SDValue, 16> ResultMask; 8145 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8146 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8147 8148 for (unsigned j = 0; j != BytesPerElement; ++j) 8149 if (isLittleEndian) 8150 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8151 dl, MVT::i32)); 8152 else 8153 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8154 MVT::i32)); 8155 } 8156 8157 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8158 if (isLittleEndian) 8159 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8160 V2, V1, VPermMask); 8161 else 8162 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8163 V1, V2, VPermMask); 8164 } 8165 8166 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8167 /// vector comparison. If it is, return true and fill in Opc/isDot with 8168 /// information about the intrinsic. 8169 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8170 bool &isDot, const PPCSubtarget &Subtarget) { 8171 unsigned IntrinsicID = 8172 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8173 CompareOpc = -1; 8174 isDot = false; 8175 switch (IntrinsicID) { 8176 default: 8177 return false; 8178 // Comparison predicates. 8179 case Intrinsic::ppc_altivec_vcmpbfp_p: 8180 CompareOpc = 966; 8181 isDot = true; 8182 break; 8183 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8184 CompareOpc = 198; 8185 isDot = true; 8186 break; 8187 case Intrinsic::ppc_altivec_vcmpequb_p: 8188 CompareOpc = 6; 8189 isDot = true; 8190 break; 8191 case Intrinsic::ppc_altivec_vcmpequh_p: 8192 CompareOpc = 70; 8193 isDot = true; 8194 break; 8195 case Intrinsic::ppc_altivec_vcmpequw_p: 8196 CompareOpc = 134; 8197 isDot = true; 8198 break; 8199 case Intrinsic::ppc_altivec_vcmpequd_p: 8200 if (Subtarget.hasP8Altivec()) { 8201 CompareOpc = 199; 8202 isDot = true; 8203 } else 8204 return false; 8205 break; 8206 case Intrinsic::ppc_altivec_vcmpneb_p: 8207 case Intrinsic::ppc_altivec_vcmpneh_p: 8208 case Intrinsic::ppc_altivec_vcmpnew_p: 8209 case Intrinsic::ppc_altivec_vcmpnezb_p: 8210 case Intrinsic::ppc_altivec_vcmpnezh_p: 8211 case Intrinsic::ppc_altivec_vcmpnezw_p: 8212 if (Subtarget.hasP9Altivec()) { 8213 switch (IntrinsicID) { 8214 default: 8215 llvm_unreachable("Unknown comparison intrinsic."); 8216 case Intrinsic::ppc_altivec_vcmpneb_p: 8217 CompareOpc = 7; 8218 break; 8219 case Intrinsic::ppc_altivec_vcmpneh_p: 8220 CompareOpc = 71; 8221 break; 8222 case Intrinsic::ppc_altivec_vcmpnew_p: 8223 CompareOpc = 135; 8224 break; 8225 case Intrinsic::ppc_altivec_vcmpnezb_p: 8226 CompareOpc = 263; 8227 break; 8228 case Intrinsic::ppc_altivec_vcmpnezh_p: 8229 CompareOpc = 327; 8230 break; 8231 case Intrinsic::ppc_altivec_vcmpnezw_p: 8232 CompareOpc = 391; 8233 break; 8234 } 8235 isDot = true; 8236 } else 8237 return false; 8238 break; 8239 case Intrinsic::ppc_altivec_vcmpgefp_p: 8240 CompareOpc = 454; 8241 isDot = true; 8242 break; 8243 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8244 CompareOpc = 710; 8245 isDot = true; 8246 break; 8247 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8248 CompareOpc = 774; 8249 isDot = true; 8250 break; 8251 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8252 CompareOpc = 838; 8253 isDot = true; 8254 break; 8255 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8256 CompareOpc = 902; 8257 isDot = true; 8258 break; 8259 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8260 if (Subtarget.hasP8Altivec()) { 8261 CompareOpc = 967; 8262 isDot = true; 8263 } else 8264 return false; 8265 break; 8266 case Intrinsic::ppc_altivec_vcmpgtub_p: 8267 CompareOpc = 518; 8268 isDot = true; 8269 break; 8270 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8271 CompareOpc = 582; 8272 isDot = true; 8273 break; 8274 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8275 CompareOpc = 646; 8276 isDot = true; 8277 break; 8278 case Intrinsic::ppc_altivec_vcmpgtud_p: 8279 if (Subtarget.hasP8Altivec()) { 8280 CompareOpc = 711; 8281 isDot = true; 8282 } else 8283 return false; 8284 break; 8285 8286 // VSX predicate comparisons use the same infrastructure 8287 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8288 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8289 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8290 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8291 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8292 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8293 if (Subtarget.hasVSX()) { 8294 switch (IntrinsicID) { 8295 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8296 CompareOpc = 99; 8297 break; 8298 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8299 CompareOpc = 115; 8300 break; 8301 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8302 CompareOpc = 107; 8303 break; 8304 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8305 CompareOpc = 67; 8306 break; 8307 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8308 CompareOpc = 83; 8309 break; 8310 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8311 CompareOpc = 75; 8312 break; 8313 } 8314 isDot = true; 8315 } else 8316 return false; 8317 break; 8318 8319 // Normal Comparisons. 8320 case Intrinsic::ppc_altivec_vcmpbfp: 8321 CompareOpc = 966; 8322 break; 8323 case Intrinsic::ppc_altivec_vcmpeqfp: 8324 CompareOpc = 198; 8325 break; 8326 case Intrinsic::ppc_altivec_vcmpequb: 8327 CompareOpc = 6; 8328 break; 8329 case Intrinsic::ppc_altivec_vcmpequh: 8330 CompareOpc = 70; 8331 break; 8332 case Intrinsic::ppc_altivec_vcmpequw: 8333 CompareOpc = 134; 8334 break; 8335 case Intrinsic::ppc_altivec_vcmpequd: 8336 if (Subtarget.hasP8Altivec()) 8337 CompareOpc = 199; 8338 else 8339 return false; 8340 break; 8341 case Intrinsic::ppc_altivec_vcmpneb: 8342 case Intrinsic::ppc_altivec_vcmpneh: 8343 case Intrinsic::ppc_altivec_vcmpnew: 8344 case Intrinsic::ppc_altivec_vcmpnezb: 8345 case Intrinsic::ppc_altivec_vcmpnezh: 8346 case Intrinsic::ppc_altivec_vcmpnezw: 8347 if (Subtarget.hasP9Altivec()) 8348 switch (IntrinsicID) { 8349 default: 8350 llvm_unreachable("Unknown comparison intrinsic."); 8351 case Intrinsic::ppc_altivec_vcmpneb: 8352 CompareOpc = 7; 8353 break; 8354 case Intrinsic::ppc_altivec_vcmpneh: 8355 CompareOpc = 71; 8356 break; 8357 case Intrinsic::ppc_altivec_vcmpnew: 8358 CompareOpc = 135; 8359 break; 8360 case Intrinsic::ppc_altivec_vcmpnezb: 8361 CompareOpc = 263; 8362 break; 8363 case Intrinsic::ppc_altivec_vcmpnezh: 8364 CompareOpc = 327; 8365 break; 8366 case Intrinsic::ppc_altivec_vcmpnezw: 8367 CompareOpc = 391; 8368 break; 8369 } 8370 else 8371 return false; 8372 break; 8373 case Intrinsic::ppc_altivec_vcmpgefp: 8374 CompareOpc = 454; 8375 break; 8376 case Intrinsic::ppc_altivec_vcmpgtfp: 8377 CompareOpc = 710; 8378 break; 8379 case Intrinsic::ppc_altivec_vcmpgtsb: 8380 CompareOpc = 774; 8381 break; 8382 case Intrinsic::ppc_altivec_vcmpgtsh: 8383 CompareOpc = 838; 8384 break; 8385 case Intrinsic::ppc_altivec_vcmpgtsw: 8386 CompareOpc = 902; 8387 break; 8388 case Intrinsic::ppc_altivec_vcmpgtsd: 8389 if (Subtarget.hasP8Altivec()) 8390 CompareOpc = 967; 8391 else 8392 return false; 8393 break; 8394 case Intrinsic::ppc_altivec_vcmpgtub: 8395 CompareOpc = 518; 8396 break; 8397 case Intrinsic::ppc_altivec_vcmpgtuh: 8398 CompareOpc = 582; 8399 break; 8400 case Intrinsic::ppc_altivec_vcmpgtuw: 8401 CompareOpc = 646; 8402 break; 8403 case Intrinsic::ppc_altivec_vcmpgtud: 8404 if (Subtarget.hasP8Altivec()) 8405 CompareOpc = 711; 8406 else 8407 return false; 8408 break; 8409 } 8410 return true; 8411 } 8412 8413 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8414 /// lower, do it, otherwise return null. 8415 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8416 SelectionDAG &DAG) const { 8417 unsigned IntrinsicID = 8418 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8419 8420 SDLoc dl(Op); 8421 8422 if (IntrinsicID == Intrinsic::thread_pointer) { 8423 // Reads the thread pointer register, used for __builtin_thread_pointer. 8424 if (Subtarget.isPPC64()) 8425 return DAG.getRegister(PPC::X13, MVT::i64); 8426 return DAG.getRegister(PPC::R2, MVT::i32); 8427 } 8428 8429 // We are looking for absolute values here. 8430 // The idea is to try to fit one of two patterns: 8431 // max (a, (0-a)) OR max ((0-a), a) 8432 if (Subtarget.hasP9Vector() && 8433 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw || 8434 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh || 8435 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) { 8436 SDValue V1 = Op.getOperand(1); 8437 SDValue V2 = Op.getOperand(2); 8438 if (V1.getSimpleValueType() == V2.getSimpleValueType() && 8439 (V1.getSimpleValueType() == MVT::v4i32 || 8440 V1.getSimpleValueType() == MVT::v8i16 || 8441 V1.getSimpleValueType() == MVT::v16i8)) { 8442 if ( V1.getOpcode() == ISD::SUB && 8443 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 8444 V1.getOperand(1) == V2 ) { 8445 // Generate the abs instruction with the operands 8446 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2); 8447 } 8448 8449 if ( V2.getOpcode() == ISD::SUB && 8450 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 8451 V2.getOperand(1) == V1 ) { 8452 // Generate the abs instruction with the operands 8453 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1); 8454 } 8455 } 8456 } 8457 8458 // If this is a lowered altivec predicate compare, CompareOpc is set to the 8459 // opcode number of the comparison. 8460 int CompareOpc; 8461 bool isDot; 8462 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 8463 return SDValue(); // Don't custom lower most intrinsics. 8464 8465 // If this is a non-dot comparison, make the VCMP node and we are done. 8466 if (!isDot) { 8467 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 8468 Op.getOperand(1), Op.getOperand(2), 8469 DAG.getConstant(CompareOpc, dl, MVT::i32)); 8470 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 8471 } 8472 8473 // Create the PPCISD altivec 'dot' comparison node. 8474 SDValue Ops[] = { 8475 Op.getOperand(2), // LHS 8476 Op.getOperand(3), // RHS 8477 DAG.getConstant(CompareOpc, dl, MVT::i32) 8478 }; 8479 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 8480 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8481 8482 // Now that we have the comparison, emit a copy from the CR to a GPR. 8483 // This is flagged to the above dot comparison. 8484 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 8485 DAG.getRegister(PPC::CR6, MVT::i32), 8486 CompNode.getValue(1)); 8487 8488 // Unpack the result based on how the target uses it. 8489 unsigned BitNo; // Bit # of CR6. 8490 bool InvertBit; // Invert result? 8491 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 8492 default: // Can't happen, don't crash on invalid number though. 8493 case 0: // Return the value of the EQ bit of CR6. 8494 BitNo = 0; InvertBit = false; 8495 break; 8496 case 1: // Return the inverted value of the EQ bit of CR6. 8497 BitNo = 0; InvertBit = true; 8498 break; 8499 case 2: // Return the value of the LT bit of CR6. 8500 BitNo = 2; InvertBit = false; 8501 break; 8502 case 3: // Return the inverted value of the LT bit of CR6. 8503 BitNo = 2; InvertBit = true; 8504 break; 8505 } 8506 8507 // Shift the bit into the low position. 8508 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 8509 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 8510 // Isolate the bit. 8511 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 8512 DAG.getConstant(1, dl, MVT::i32)); 8513 8514 // If we are supposed to, toggle the bit. 8515 if (InvertBit) 8516 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 8517 DAG.getConstant(1, dl, MVT::i32)); 8518 return Flags; 8519 } 8520 8521 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 8522 SelectionDAG &DAG) const { 8523 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 8524 // the beginning of the argument list. 8525 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 8526 SDLoc DL(Op); 8527 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 8528 case Intrinsic::ppc_cfence: { 8529 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 8530 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 8531 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 8532 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 8533 Op.getOperand(ArgStart + 1)), 8534 Op.getOperand(0)), 8535 0); 8536 } 8537 default: 8538 break; 8539 } 8540 return SDValue(); 8541 } 8542 8543 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 8544 // Check for a DIV with the same operands as this REM. 8545 for (auto UI : Op.getOperand(1)->uses()) { 8546 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 8547 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 8548 if (UI->getOperand(0) == Op.getOperand(0) && 8549 UI->getOperand(1) == Op.getOperand(1)) 8550 return SDValue(); 8551 } 8552 return Op; 8553 } 8554 8555 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 8556 SelectionDAG &DAG) const { 8557 SDLoc dl(Op); 8558 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 8559 // instructions), but for smaller types, we need to first extend up to v2i32 8560 // before doing going farther. 8561 if (Op.getValueType() == MVT::v2i64) { 8562 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 8563 if (ExtVT != MVT::v2i32) { 8564 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 8565 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 8566 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 8567 ExtVT.getVectorElementType(), 4))); 8568 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 8569 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 8570 DAG.getValueType(MVT::v2i32)); 8571 } 8572 8573 return Op; 8574 } 8575 8576 return SDValue(); 8577 } 8578 8579 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 8580 SelectionDAG &DAG) const { 8581 SDLoc dl(Op); 8582 // Create a stack slot that is 16-byte aligned. 8583 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8584 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8585 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8586 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8587 8588 // Store the input value into Value#0 of the stack slot. 8589 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8590 MachinePointerInfo()); 8591 // Load it out. 8592 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 8593 } 8594 8595 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8596 SelectionDAG &DAG) const { 8597 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 8598 "Should only be called for ISD::INSERT_VECTOR_ELT"); 8599 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8600 // We have legal lowering for constant indices but not for variable ones. 8601 if (C) 8602 return Op; 8603 return SDValue(); 8604 } 8605 8606 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8607 SelectionDAG &DAG) const { 8608 SDLoc dl(Op); 8609 SDNode *N = Op.getNode(); 8610 8611 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 8612 "Unknown extract_vector_elt type"); 8613 8614 SDValue Value = N->getOperand(0); 8615 8616 // The first part of this is like the store lowering except that we don't 8617 // need to track the chain. 8618 8619 // The values are now known to be -1 (false) or 1 (true). To convert this 8620 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8621 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8622 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8623 8624 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8625 // understand how to form the extending load. 8626 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8627 8628 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8629 8630 // Now convert to an integer and store. 8631 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8632 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8633 Value); 8634 8635 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8636 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8637 MachinePointerInfo PtrInfo = 8638 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8639 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8640 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8641 8642 SDValue StoreChain = DAG.getEntryNode(); 8643 SDValue Ops[] = {StoreChain, 8644 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8645 Value, FIdx}; 8646 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8647 8648 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8649 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8650 8651 // Extract the value requested. 8652 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 8653 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8654 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8655 8656 SDValue IntVal = 8657 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 8658 8659 if (!Subtarget.useCRBits()) 8660 return IntVal; 8661 8662 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 8663 } 8664 8665 /// Lowering for QPX v4i1 loads 8666 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 8667 SelectionDAG &DAG) const { 8668 SDLoc dl(Op); 8669 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 8670 SDValue LoadChain = LN->getChain(); 8671 SDValue BasePtr = LN->getBasePtr(); 8672 8673 if (Op.getValueType() == MVT::v4f64 || 8674 Op.getValueType() == MVT::v4f32) { 8675 EVT MemVT = LN->getMemoryVT(); 8676 unsigned Alignment = LN->getAlignment(); 8677 8678 // If this load is properly aligned, then it is legal. 8679 if (Alignment >= MemVT.getStoreSize()) 8680 return Op; 8681 8682 EVT ScalarVT = Op.getValueType().getScalarType(), 8683 ScalarMemVT = MemVT.getScalarType(); 8684 unsigned Stride = ScalarMemVT.getStoreSize(); 8685 8686 SDValue Vals[4], LoadChains[4]; 8687 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8688 SDValue Load; 8689 if (ScalarVT != ScalarMemVT) 8690 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 8691 BasePtr, 8692 LN->getPointerInfo().getWithOffset(Idx * Stride), 8693 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8694 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8695 else 8696 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 8697 LN->getPointerInfo().getWithOffset(Idx * Stride), 8698 MinAlign(Alignment, Idx * Stride), 8699 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8700 8701 if (Idx == 0 && LN->isIndexed()) { 8702 assert(LN->getAddressingMode() == ISD::PRE_INC && 8703 "Unknown addressing mode on vector load"); 8704 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 8705 LN->getAddressingMode()); 8706 } 8707 8708 Vals[Idx] = Load; 8709 LoadChains[Idx] = Load.getValue(1); 8710 8711 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8712 DAG.getConstant(Stride, dl, 8713 BasePtr.getValueType())); 8714 } 8715 8716 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8717 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 8718 8719 if (LN->isIndexed()) { 8720 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 8721 return DAG.getMergeValues(RetOps, dl); 8722 } 8723 8724 SDValue RetOps[] = { Value, TF }; 8725 return DAG.getMergeValues(RetOps, dl); 8726 } 8727 8728 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 8729 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 8730 8731 // To lower v4i1 from a byte array, we load the byte elements of the 8732 // vector and then reuse the BUILD_VECTOR logic. 8733 8734 SDValue VectElmts[4], VectElmtChains[4]; 8735 for (unsigned i = 0; i < 4; ++i) { 8736 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 8737 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 8738 8739 VectElmts[i] = DAG.getExtLoad( 8740 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 8741 LN->getPointerInfo().getWithOffset(i), MVT::i8, 8742 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8743 VectElmtChains[i] = VectElmts[i].getValue(1); 8744 } 8745 8746 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 8747 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 8748 8749 SDValue RVals[] = { Value, LoadChain }; 8750 return DAG.getMergeValues(RVals, dl); 8751 } 8752 8753 /// Lowering for QPX v4i1 stores 8754 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 8755 SelectionDAG &DAG) const { 8756 SDLoc dl(Op); 8757 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 8758 SDValue StoreChain = SN->getChain(); 8759 SDValue BasePtr = SN->getBasePtr(); 8760 SDValue Value = SN->getValue(); 8761 8762 if (Value.getValueType() == MVT::v4f64 || 8763 Value.getValueType() == MVT::v4f32) { 8764 EVT MemVT = SN->getMemoryVT(); 8765 unsigned Alignment = SN->getAlignment(); 8766 8767 // If this store is properly aligned, then it is legal. 8768 if (Alignment >= MemVT.getStoreSize()) 8769 return Op; 8770 8771 EVT ScalarVT = Value.getValueType().getScalarType(), 8772 ScalarMemVT = MemVT.getScalarType(); 8773 unsigned Stride = ScalarMemVT.getStoreSize(); 8774 8775 SDValue Stores[4]; 8776 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8777 SDValue Ex = DAG.getNode( 8778 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 8779 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 8780 SDValue Store; 8781 if (ScalarVT != ScalarMemVT) 8782 Store = 8783 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 8784 SN->getPointerInfo().getWithOffset(Idx * Stride), 8785 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8786 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 8787 else 8788 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 8789 SN->getPointerInfo().getWithOffset(Idx * Stride), 8790 MinAlign(Alignment, Idx * Stride), 8791 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 8792 8793 if (Idx == 0 && SN->isIndexed()) { 8794 assert(SN->getAddressingMode() == ISD::PRE_INC && 8795 "Unknown addressing mode on vector store"); 8796 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 8797 SN->getAddressingMode()); 8798 } 8799 8800 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8801 DAG.getConstant(Stride, dl, 8802 BasePtr.getValueType())); 8803 Stores[Idx] = Store; 8804 } 8805 8806 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8807 8808 if (SN->isIndexed()) { 8809 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 8810 return DAG.getMergeValues(RetOps, dl); 8811 } 8812 8813 return TF; 8814 } 8815 8816 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 8817 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 8818 8819 // The values are now known to be -1 (false) or 1 (true). To convert this 8820 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8821 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8822 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8823 8824 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8825 // understand how to form the extending load. 8826 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8827 8828 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8829 8830 // Now convert to an integer and store. 8831 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8832 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8833 Value); 8834 8835 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8836 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8837 MachinePointerInfo PtrInfo = 8838 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8839 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8840 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8841 8842 SDValue Ops[] = {StoreChain, 8843 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8844 Value, FIdx}; 8845 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8846 8847 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8848 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8849 8850 // Move data into the byte array. 8851 SDValue Loads[4], LoadChains[4]; 8852 for (unsigned i = 0; i < 4; ++i) { 8853 unsigned Offset = 4*i; 8854 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8855 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8856 8857 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 8858 PtrInfo.getWithOffset(Offset)); 8859 LoadChains[i] = Loads[i].getValue(1); 8860 } 8861 8862 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8863 8864 SDValue Stores[4]; 8865 for (unsigned i = 0; i < 4; ++i) { 8866 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 8867 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 8868 8869 Stores[i] = DAG.getTruncStore( 8870 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 8871 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 8872 SN->getAAInfo()); 8873 } 8874 8875 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8876 8877 return StoreChain; 8878 } 8879 8880 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 8881 SDLoc dl(Op); 8882 if (Op.getValueType() == MVT::v4i32) { 8883 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8884 8885 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 8886 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 8887 8888 SDValue RHSSwap = // = vrlw RHS, 16 8889 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 8890 8891 // Shrinkify inputs to v8i16. 8892 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 8893 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 8894 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 8895 8896 // Low parts multiplied together, generating 32-bit results (we ignore the 8897 // top parts). 8898 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 8899 LHS, RHS, DAG, dl, MVT::v4i32); 8900 8901 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 8902 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 8903 // Shift the high parts up 16 bits. 8904 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 8905 Neg16, DAG, dl); 8906 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 8907 } else if (Op.getValueType() == MVT::v8i16) { 8908 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8909 8910 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 8911 8912 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 8913 LHS, RHS, Zero, DAG, dl); 8914 } else if (Op.getValueType() == MVT::v16i8) { 8915 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8916 bool isLittleEndian = Subtarget.isLittleEndian(); 8917 8918 // Multiply the even 8-bit parts, producing 16-bit sums. 8919 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 8920 LHS, RHS, DAG, dl, MVT::v8i16); 8921 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 8922 8923 // Multiply the odd 8-bit parts, producing 16-bit sums. 8924 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 8925 LHS, RHS, DAG, dl, MVT::v8i16); 8926 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 8927 8928 // Merge the results together. Because vmuleub and vmuloub are 8929 // instructions with a big-endian bias, we must reverse the 8930 // element numbering and reverse the meaning of "odd" and "even" 8931 // when generating little endian code. 8932 int Ops[16]; 8933 for (unsigned i = 0; i != 8; ++i) { 8934 if (isLittleEndian) { 8935 Ops[i*2 ] = 2*i; 8936 Ops[i*2+1] = 2*i+16; 8937 } else { 8938 Ops[i*2 ] = 2*i+1; 8939 Ops[i*2+1] = 2*i+1+16; 8940 } 8941 } 8942 if (isLittleEndian) 8943 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 8944 else 8945 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 8946 } else { 8947 llvm_unreachable("Unknown mul to lower!"); 8948 } 8949 } 8950 8951 /// LowerOperation - Provide custom lowering hooks for some operations. 8952 /// 8953 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8954 switch (Op.getOpcode()) { 8955 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 8956 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8957 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8958 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8959 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8960 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 8961 case ISD::SETCC: return LowerSETCC(Op, DAG); 8962 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 8963 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 8964 case ISD::VASTART: 8965 return LowerVASTART(Op, DAG); 8966 8967 case ISD::VAARG: 8968 return LowerVAARG(Op, DAG); 8969 8970 case ISD::VACOPY: 8971 return LowerVACOPY(Op, DAG); 8972 8973 case ISD::STACKRESTORE: 8974 return LowerSTACKRESTORE(Op, DAG); 8975 8976 case ISD::DYNAMIC_STACKALLOC: 8977 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8978 8979 case ISD::GET_DYNAMIC_AREA_OFFSET: 8980 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 8981 8982 case ISD::EH_DWARF_CFA: 8983 return LowerEH_DWARF_CFA(Op, DAG); 8984 8985 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 8986 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 8987 8988 case ISD::LOAD: return LowerLOAD(Op, DAG); 8989 case ISD::STORE: return LowerSTORE(Op, DAG); 8990 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 8991 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8992 case ISD::FP_TO_UINT: 8993 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 8994 SDLoc(Op)); 8995 case ISD::UINT_TO_FP: 8996 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8997 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8998 8999 // Lower 64-bit shifts. 9000 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9001 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9002 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9003 9004 // Vector-related lowering. 9005 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9006 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9007 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9008 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9009 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 9010 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9011 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9012 case ISD::MUL: return LowerMUL(Op, DAG); 9013 9014 // For counter-based loop handling. 9015 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9016 9017 // Frame & Return address. 9018 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9019 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9020 9021 case ISD::INTRINSIC_VOID: 9022 return LowerINTRINSIC_VOID(Op, DAG); 9023 case ISD::SREM: 9024 case ISD::UREM: 9025 return LowerREM(Op, DAG); 9026 } 9027 } 9028 9029 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9030 SmallVectorImpl<SDValue>&Results, 9031 SelectionDAG &DAG) const { 9032 SDLoc dl(N); 9033 switch (N->getOpcode()) { 9034 default: 9035 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9036 case ISD::READCYCLECOUNTER: { 9037 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9038 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9039 9040 Results.push_back(RTB); 9041 Results.push_back(RTB.getValue(1)); 9042 Results.push_back(RTB.getValue(2)); 9043 break; 9044 } 9045 case ISD::INTRINSIC_W_CHAIN: { 9046 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9047 Intrinsic::ppc_is_decremented_ctr_nonzero) 9048 break; 9049 9050 assert(N->getValueType(0) == MVT::i1 && 9051 "Unexpected result type for CTR decrement intrinsic"); 9052 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9053 N->getValueType(0)); 9054 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9055 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9056 N->getOperand(1)); 9057 9058 Results.push_back(NewInt); 9059 Results.push_back(NewInt.getValue(1)); 9060 break; 9061 } 9062 case ISD::VAARG: { 9063 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9064 return; 9065 9066 EVT VT = N->getValueType(0); 9067 9068 if (VT == MVT::i64) { 9069 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9070 9071 Results.push_back(NewNode); 9072 Results.push_back(NewNode.getValue(1)); 9073 } 9074 return; 9075 } 9076 case ISD::FP_ROUND_INREG: { 9077 assert(N->getValueType(0) == MVT::ppcf128); 9078 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 9079 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 9080 MVT::f64, N->getOperand(0), 9081 DAG.getIntPtrConstant(0, dl)); 9082 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 9083 MVT::f64, N->getOperand(0), 9084 DAG.getIntPtrConstant(1, dl)); 9085 9086 // Add the two halves of the long double in round-to-zero mode. 9087 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 9088 9089 // We know the low half is about to be thrown away, so just use something 9090 // convenient. 9091 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 9092 FPreg, FPreg)); 9093 return; 9094 } 9095 case ISD::FP_TO_SINT: 9096 case ISD::FP_TO_UINT: 9097 // LowerFP_TO_INT() can only handle f32 and f64. 9098 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9099 return; 9100 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9101 return; 9102 } 9103 } 9104 9105 //===----------------------------------------------------------------------===// 9106 // Other Lowering Code 9107 //===----------------------------------------------------------------------===// 9108 9109 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9110 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9111 Function *Func = Intrinsic::getDeclaration(M, Id); 9112 return Builder.CreateCall(Func, {}); 9113 } 9114 9115 // The mappings for emitLeading/TrailingFence is taken from 9116 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9117 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9118 Instruction *Inst, 9119 AtomicOrdering Ord) const { 9120 if (Ord == AtomicOrdering::SequentiallyConsistent) 9121 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9122 if (isReleaseOrStronger(Ord)) 9123 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9124 return nullptr; 9125 } 9126 9127 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9128 Instruction *Inst, 9129 AtomicOrdering Ord) const { 9130 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9131 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9132 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9133 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9134 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9135 return Builder.CreateCall( 9136 Intrinsic::getDeclaration( 9137 Builder.GetInsertBlock()->getParent()->getParent(), 9138 Intrinsic::ppc_cfence, {Inst->getType()}), 9139 {Inst}); 9140 // FIXME: Can use isync for rmw operation. 9141 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9142 } 9143 return nullptr; 9144 } 9145 9146 MachineBasicBlock * 9147 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9148 unsigned AtomicSize, 9149 unsigned BinOpcode, 9150 unsigned CmpOpcode, 9151 unsigned CmpPred) const { 9152 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9153 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9154 9155 auto LoadMnemonic = PPC::LDARX; 9156 auto StoreMnemonic = PPC::STDCX; 9157 switch (AtomicSize) { 9158 default: 9159 llvm_unreachable("Unexpected size of atomic entity"); 9160 case 1: 9161 LoadMnemonic = PPC::LBARX; 9162 StoreMnemonic = PPC::STBCX; 9163 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9164 break; 9165 case 2: 9166 LoadMnemonic = PPC::LHARX; 9167 StoreMnemonic = PPC::STHCX; 9168 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9169 break; 9170 case 4: 9171 LoadMnemonic = PPC::LWARX; 9172 StoreMnemonic = PPC::STWCX; 9173 break; 9174 case 8: 9175 LoadMnemonic = PPC::LDARX; 9176 StoreMnemonic = PPC::STDCX; 9177 break; 9178 } 9179 9180 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9181 MachineFunction *F = BB->getParent(); 9182 MachineFunction::iterator It = ++BB->getIterator(); 9183 9184 unsigned dest = MI.getOperand(0).getReg(); 9185 unsigned ptrA = MI.getOperand(1).getReg(); 9186 unsigned ptrB = MI.getOperand(2).getReg(); 9187 unsigned incr = MI.getOperand(3).getReg(); 9188 DebugLoc dl = MI.getDebugLoc(); 9189 9190 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9191 MachineBasicBlock *loop2MBB = 9192 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9193 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9194 F->insert(It, loopMBB); 9195 if (CmpOpcode) 9196 F->insert(It, loop2MBB); 9197 F->insert(It, exitMBB); 9198 exitMBB->splice(exitMBB->begin(), BB, 9199 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9200 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9201 9202 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9203 unsigned TmpReg = (!BinOpcode) ? incr : 9204 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9205 : &PPC::GPRCRegClass); 9206 9207 // thisMBB: 9208 // ... 9209 // fallthrough --> loopMBB 9210 BB->addSuccessor(loopMBB); 9211 9212 // loopMBB: 9213 // l[wd]arx dest, ptr 9214 // add r0, dest, incr 9215 // st[wd]cx. r0, ptr 9216 // bne- loopMBB 9217 // fallthrough --> exitMBB 9218 9219 // For max/min... 9220 // loopMBB: 9221 // l[wd]arx dest, ptr 9222 // cmpl?[wd] incr, dest 9223 // bgt exitMBB 9224 // loop2MBB: 9225 // st[wd]cx. dest, ptr 9226 // bne- loopMBB 9227 // fallthrough --> exitMBB 9228 9229 BB = loopMBB; 9230 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9231 .addReg(ptrA).addReg(ptrB); 9232 if (BinOpcode) 9233 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9234 if (CmpOpcode) { 9235 // Signed comparisons of byte or halfword values must be sign-extended. 9236 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9237 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9238 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9239 ExtReg).addReg(dest); 9240 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9241 .addReg(incr).addReg(ExtReg); 9242 } else 9243 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9244 .addReg(incr).addReg(dest); 9245 9246 BuildMI(BB, dl, TII->get(PPC::BCC)) 9247 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9248 BB->addSuccessor(loop2MBB); 9249 BB->addSuccessor(exitMBB); 9250 BB = loop2MBB; 9251 } 9252 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9253 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9254 BuildMI(BB, dl, TII->get(PPC::BCC)) 9255 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9256 BB->addSuccessor(loopMBB); 9257 BB->addSuccessor(exitMBB); 9258 9259 // exitMBB: 9260 // ... 9261 BB = exitMBB; 9262 return BB; 9263 } 9264 9265 MachineBasicBlock * 9266 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9267 MachineBasicBlock *BB, 9268 bool is8bit, // operation 9269 unsigned BinOpcode, 9270 unsigned CmpOpcode, 9271 unsigned CmpPred) const { 9272 // If we support part-word atomic mnemonics, just use them 9273 if (Subtarget.hasPartwordAtomics()) 9274 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9275 CmpOpcode, CmpPred); 9276 9277 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9278 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9279 // In 64 bit mode we have to use 64 bits for addresses, even though the 9280 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9281 // registers without caring whether they're 32 or 64, but here we're 9282 // doing actual arithmetic on the addresses. 9283 bool is64bit = Subtarget.isPPC64(); 9284 bool isLittleEndian = Subtarget.isLittleEndian(); 9285 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9286 9287 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9288 MachineFunction *F = BB->getParent(); 9289 MachineFunction::iterator It = ++BB->getIterator(); 9290 9291 unsigned dest = MI.getOperand(0).getReg(); 9292 unsigned ptrA = MI.getOperand(1).getReg(); 9293 unsigned ptrB = MI.getOperand(2).getReg(); 9294 unsigned incr = MI.getOperand(3).getReg(); 9295 DebugLoc dl = MI.getDebugLoc(); 9296 9297 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9298 MachineBasicBlock *loop2MBB = 9299 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9300 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9301 F->insert(It, loopMBB); 9302 if (CmpOpcode) 9303 F->insert(It, loop2MBB); 9304 F->insert(It, exitMBB); 9305 exitMBB->splice(exitMBB->begin(), BB, 9306 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9307 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9308 9309 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9310 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9311 : &PPC::GPRCRegClass; 9312 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9313 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9314 unsigned ShiftReg = 9315 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9316 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9317 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9318 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9319 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9320 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9321 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9322 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9323 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9324 unsigned Ptr1Reg; 9325 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9326 9327 // thisMBB: 9328 // ... 9329 // fallthrough --> loopMBB 9330 BB->addSuccessor(loopMBB); 9331 9332 // The 4-byte load must be aligned, while a char or short may be 9333 // anywhere in the word. Hence all this nasty bookkeeping code. 9334 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9335 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9336 // xori shift, shift1, 24 [16] 9337 // rlwinm ptr, ptr1, 0, 0, 29 9338 // slw incr2, incr, shift 9339 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9340 // slw mask, mask2, shift 9341 // loopMBB: 9342 // lwarx tmpDest, ptr 9343 // add tmp, tmpDest, incr2 9344 // andc tmp2, tmpDest, mask 9345 // and tmp3, tmp, mask 9346 // or tmp4, tmp3, tmp2 9347 // stwcx. tmp4, ptr 9348 // bne- loopMBB 9349 // fallthrough --> exitMBB 9350 // srw dest, tmpDest, shift 9351 if (ptrA != ZeroReg) { 9352 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9353 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9354 .addReg(ptrA).addReg(ptrB); 9355 } else { 9356 Ptr1Reg = ptrB; 9357 } 9358 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9359 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9360 if (!isLittleEndian) 9361 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9362 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9363 if (is64bit) 9364 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9365 .addReg(Ptr1Reg).addImm(0).addImm(61); 9366 else 9367 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9368 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9369 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9370 .addReg(incr).addReg(ShiftReg); 9371 if (is8bit) 9372 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9373 else { 9374 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9375 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9376 } 9377 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9378 .addReg(Mask2Reg).addReg(ShiftReg); 9379 9380 BB = loopMBB; 9381 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9382 .addReg(ZeroReg).addReg(PtrReg); 9383 if (BinOpcode) 9384 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9385 .addReg(Incr2Reg).addReg(TmpDestReg); 9386 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9387 .addReg(TmpDestReg).addReg(MaskReg); 9388 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9389 .addReg(TmpReg).addReg(MaskReg); 9390 if (CmpOpcode) { 9391 // For unsigned comparisons, we can directly compare the shifted values. 9392 // For signed comparisons we shift and sign extend. 9393 unsigned SReg = RegInfo.createVirtualRegister(RC); 9394 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 9395 .addReg(TmpDestReg).addReg(MaskReg); 9396 unsigned ValueReg = SReg; 9397 unsigned CmpReg = Incr2Reg; 9398 if (CmpOpcode == PPC::CMPW) { 9399 ValueReg = RegInfo.createVirtualRegister(RC); 9400 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 9401 .addReg(SReg).addReg(ShiftReg); 9402 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 9403 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 9404 .addReg(ValueReg); 9405 ValueReg = ValueSReg; 9406 CmpReg = incr; 9407 } 9408 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9409 .addReg(CmpReg).addReg(ValueReg); 9410 BuildMI(BB, dl, TII->get(PPC::BCC)) 9411 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9412 BB->addSuccessor(loop2MBB); 9413 BB->addSuccessor(exitMBB); 9414 BB = loop2MBB; 9415 } 9416 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 9417 .addReg(Tmp3Reg).addReg(Tmp2Reg); 9418 BuildMI(BB, dl, TII->get(PPC::STWCX)) 9419 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 9420 BuildMI(BB, dl, TII->get(PPC::BCC)) 9421 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9422 BB->addSuccessor(loopMBB); 9423 BB->addSuccessor(exitMBB); 9424 9425 // exitMBB: 9426 // ... 9427 BB = exitMBB; 9428 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 9429 .addReg(ShiftReg); 9430 return BB; 9431 } 9432 9433 llvm::MachineBasicBlock * 9434 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 9435 MachineBasicBlock *MBB) const { 9436 DebugLoc DL = MI.getDebugLoc(); 9437 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9438 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9439 9440 MachineFunction *MF = MBB->getParent(); 9441 MachineRegisterInfo &MRI = MF->getRegInfo(); 9442 9443 const BasicBlock *BB = MBB->getBasicBlock(); 9444 MachineFunction::iterator I = ++MBB->getIterator(); 9445 9446 // Memory Reference 9447 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9448 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9449 9450 unsigned DstReg = MI.getOperand(0).getReg(); 9451 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 9452 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 9453 unsigned mainDstReg = MRI.createVirtualRegister(RC); 9454 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 9455 9456 MVT PVT = getPointerTy(MF->getDataLayout()); 9457 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9458 "Invalid Pointer Size!"); 9459 // For v = setjmp(buf), we generate 9460 // 9461 // thisMBB: 9462 // SjLjSetup mainMBB 9463 // bl mainMBB 9464 // v_restore = 1 9465 // b sinkMBB 9466 // 9467 // mainMBB: 9468 // buf[LabelOffset] = LR 9469 // v_main = 0 9470 // 9471 // sinkMBB: 9472 // v = phi(main, restore) 9473 // 9474 9475 MachineBasicBlock *thisMBB = MBB; 9476 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 9477 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 9478 MF->insert(I, mainMBB); 9479 MF->insert(I, sinkMBB); 9480 9481 MachineInstrBuilder MIB; 9482 9483 // Transfer the remainder of BB and its successor edges to sinkMBB. 9484 sinkMBB->splice(sinkMBB->begin(), MBB, 9485 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9486 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 9487 9488 // Note that the structure of the jmp_buf used here is not compatible 9489 // with that used by libc, and is not designed to be. Specifically, it 9490 // stores only those 'reserved' registers that LLVM does not otherwise 9491 // understand how to spill. Also, by convention, by the time this 9492 // intrinsic is called, Clang has already stored the frame address in the 9493 // first slot of the buffer and stack address in the third. Following the 9494 // X86 target code, we'll store the jump address in the second slot. We also 9495 // need to save the TOC pointer (R2) to handle jumps between shared 9496 // libraries, and that will be stored in the fourth slot. The thread 9497 // identifier (R13) is not affected. 9498 9499 // thisMBB: 9500 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9501 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9502 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9503 9504 // Prepare IP either in reg. 9505 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 9506 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 9507 unsigned BufReg = MI.getOperand(1).getReg(); 9508 9509 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 9510 setUsesTOCBasePtr(*MBB->getParent()); 9511 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 9512 .addReg(PPC::X2) 9513 .addImm(TOCOffset) 9514 .addReg(BufReg); 9515 MIB.setMemRefs(MMOBegin, MMOEnd); 9516 } 9517 9518 // Naked functions never have a base pointer, and so we use r1. For all 9519 // other functions, this decision must be delayed until during PEI. 9520 unsigned BaseReg; 9521 if (MF->getFunction()->hasFnAttribute(Attribute::Naked)) 9522 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 9523 else 9524 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 9525 9526 MIB = BuildMI(*thisMBB, MI, DL, 9527 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 9528 .addReg(BaseReg) 9529 .addImm(BPOffset) 9530 .addReg(BufReg); 9531 MIB.setMemRefs(MMOBegin, MMOEnd); 9532 9533 // Setup 9534 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 9535 MIB.addRegMask(TRI->getNoPreservedMask()); 9536 9537 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 9538 9539 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 9540 .addMBB(mainMBB); 9541 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 9542 9543 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 9544 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 9545 9546 // mainMBB: 9547 // mainDstReg = 0 9548 MIB = 9549 BuildMI(mainMBB, DL, 9550 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 9551 9552 // Store IP 9553 if (Subtarget.isPPC64()) { 9554 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 9555 .addReg(LabelReg) 9556 .addImm(LabelOffset) 9557 .addReg(BufReg); 9558 } else { 9559 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 9560 .addReg(LabelReg) 9561 .addImm(LabelOffset) 9562 .addReg(BufReg); 9563 } 9564 9565 MIB.setMemRefs(MMOBegin, MMOEnd); 9566 9567 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 9568 mainMBB->addSuccessor(sinkMBB); 9569 9570 // sinkMBB: 9571 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 9572 TII->get(PPC::PHI), DstReg) 9573 .addReg(mainDstReg).addMBB(mainMBB) 9574 .addReg(restoreDstReg).addMBB(thisMBB); 9575 9576 MI.eraseFromParent(); 9577 return sinkMBB; 9578 } 9579 9580 MachineBasicBlock * 9581 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 9582 MachineBasicBlock *MBB) const { 9583 DebugLoc DL = MI.getDebugLoc(); 9584 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9585 9586 MachineFunction *MF = MBB->getParent(); 9587 MachineRegisterInfo &MRI = MF->getRegInfo(); 9588 9589 // Memory Reference 9590 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9591 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9592 9593 MVT PVT = getPointerTy(MF->getDataLayout()); 9594 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9595 "Invalid Pointer Size!"); 9596 9597 const TargetRegisterClass *RC = 9598 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9599 unsigned Tmp = MRI.createVirtualRegister(RC); 9600 // Since FP is only updated here but NOT referenced, it's treated as GPR. 9601 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 9602 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 9603 unsigned BP = 9604 (PVT == MVT::i64) 9605 ? PPC::X30 9606 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 9607 : PPC::R30); 9608 9609 MachineInstrBuilder MIB; 9610 9611 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9612 const int64_t SPOffset = 2 * PVT.getStoreSize(); 9613 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9614 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9615 9616 unsigned BufReg = MI.getOperand(0).getReg(); 9617 9618 // Reload FP (the jumped-to function may not have had a 9619 // frame pointer, and if so, then its r31 will be restored 9620 // as necessary). 9621 if (PVT == MVT::i64) { 9622 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 9623 .addImm(0) 9624 .addReg(BufReg); 9625 } else { 9626 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 9627 .addImm(0) 9628 .addReg(BufReg); 9629 } 9630 MIB.setMemRefs(MMOBegin, MMOEnd); 9631 9632 // Reload IP 9633 if (PVT == MVT::i64) { 9634 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 9635 .addImm(LabelOffset) 9636 .addReg(BufReg); 9637 } else { 9638 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 9639 .addImm(LabelOffset) 9640 .addReg(BufReg); 9641 } 9642 MIB.setMemRefs(MMOBegin, MMOEnd); 9643 9644 // Reload SP 9645 if (PVT == MVT::i64) { 9646 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 9647 .addImm(SPOffset) 9648 .addReg(BufReg); 9649 } else { 9650 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 9651 .addImm(SPOffset) 9652 .addReg(BufReg); 9653 } 9654 MIB.setMemRefs(MMOBegin, MMOEnd); 9655 9656 // Reload BP 9657 if (PVT == MVT::i64) { 9658 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 9659 .addImm(BPOffset) 9660 .addReg(BufReg); 9661 } else { 9662 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 9663 .addImm(BPOffset) 9664 .addReg(BufReg); 9665 } 9666 MIB.setMemRefs(MMOBegin, MMOEnd); 9667 9668 // Reload TOC 9669 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 9670 setUsesTOCBasePtr(*MBB->getParent()); 9671 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 9672 .addImm(TOCOffset) 9673 .addReg(BufReg); 9674 9675 MIB.setMemRefs(MMOBegin, MMOEnd); 9676 } 9677 9678 // Jump 9679 BuildMI(*MBB, MI, DL, 9680 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 9681 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 9682 9683 MI.eraseFromParent(); 9684 return MBB; 9685 } 9686 9687 MachineBasicBlock * 9688 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9689 MachineBasicBlock *BB) const { 9690 if (MI.getOpcode() == TargetOpcode::STACKMAP || 9691 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9692 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 9693 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9694 // Call lowering should have added an r2 operand to indicate a dependence 9695 // on the TOC base pointer value. It can't however, because there is no 9696 // way to mark the dependence as implicit there, and so the stackmap code 9697 // will confuse it with a regular operand. Instead, add the dependence 9698 // here. 9699 setUsesTOCBasePtr(*BB->getParent()); 9700 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 9701 } 9702 9703 return emitPatchPoint(MI, BB); 9704 } 9705 9706 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 9707 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 9708 return emitEHSjLjSetJmp(MI, BB); 9709 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 9710 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 9711 return emitEHSjLjLongJmp(MI, BB); 9712 } 9713 9714 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9715 9716 // To "insert" these instructions we actually have to insert their 9717 // control-flow patterns. 9718 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9719 MachineFunction::iterator It = ++BB->getIterator(); 9720 9721 MachineFunction *F = BB->getParent(); 9722 9723 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9724 MI.getOpcode() == PPC::SELECT_CC_I8 || 9725 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 9726 SmallVector<MachineOperand, 2> Cond; 9727 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9728 MI.getOpcode() == PPC::SELECT_CC_I8) 9729 Cond.push_back(MI.getOperand(4)); 9730 else 9731 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 9732 Cond.push_back(MI.getOperand(1)); 9733 9734 DebugLoc dl = MI.getDebugLoc(); 9735 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 9736 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 9737 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9738 MI.getOpcode() == PPC::SELECT_CC_I8 || 9739 MI.getOpcode() == PPC::SELECT_CC_F4 || 9740 MI.getOpcode() == PPC::SELECT_CC_F8 || 9741 MI.getOpcode() == PPC::SELECT_CC_QFRC || 9742 MI.getOpcode() == PPC::SELECT_CC_QSRC || 9743 MI.getOpcode() == PPC::SELECT_CC_QBRC || 9744 MI.getOpcode() == PPC::SELECT_CC_VRRC || 9745 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 9746 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 9747 MI.getOpcode() == PPC::SELECT_CC_VSRC || 9748 MI.getOpcode() == PPC::SELECT_I4 || 9749 MI.getOpcode() == PPC::SELECT_I8 || 9750 MI.getOpcode() == PPC::SELECT_F4 || 9751 MI.getOpcode() == PPC::SELECT_F8 || 9752 MI.getOpcode() == PPC::SELECT_QFRC || 9753 MI.getOpcode() == PPC::SELECT_QSRC || 9754 MI.getOpcode() == PPC::SELECT_QBRC || 9755 MI.getOpcode() == PPC::SELECT_VRRC || 9756 MI.getOpcode() == PPC::SELECT_VSFRC || 9757 MI.getOpcode() == PPC::SELECT_VSSRC || 9758 MI.getOpcode() == PPC::SELECT_VSRC) { 9759 // The incoming instruction knows the destination vreg to set, the 9760 // condition code register to branch on, the true/false values to 9761 // select between, and a branch opcode to use. 9762 9763 // thisMBB: 9764 // ... 9765 // TrueVal = ... 9766 // cmpTY ccX, r1, r2 9767 // bCC copy1MBB 9768 // fallthrough --> copy0MBB 9769 MachineBasicBlock *thisMBB = BB; 9770 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9771 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9772 DebugLoc dl = MI.getDebugLoc(); 9773 F->insert(It, copy0MBB); 9774 F->insert(It, sinkMBB); 9775 9776 // Transfer the remainder of BB and its successor edges to sinkMBB. 9777 sinkMBB->splice(sinkMBB->begin(), BB, 9778 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9779 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9780 9781 // Next, add the true and fallthrough blocks as its successors. 9782 BB->addSuccessor(copy0MBB); 9783 BB->addSuccessor(sinkMBB); 9784 9785 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 9786 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 9787 MI.getOpcode() == PPC::SELECT_QFRC || 9788 MI.getOpcode() == PPC::SELECT_QSRC || 9789 MI.getOpcode() == PPC::SELECT_QBRC || 9790 MI.getOpcode() == PPC::SELECT_VRRC || 9791 MI.getOpcode() == PPC::SELECT_VSFRC || 9792 MI.getOpcode() == PPC::SELECT_VSSRC || 9793 MI.getOpcode() == PPC::SELECT_VSRC) { 9794 BuildMI(BB, dl, TII->get(PPC::BC)) 9795 .addReg(MI.getOperand(1).getReg()) 9796 .addMBB(sinkMBB); 9797 } else { 9798 unsigned SelectPred = MI.getOperand(4).getImm(); 9799 BuildMI(BB, dl, TII->get(PPC::BCC)) 9800 .addImm(SelectPred) 9801 .addReg(MI.getOperand(1).getReg()) 9802 .addMBB(sinkMBB); 9803 } 9804 9805 // copy0MBB: 9806 // %FalseValue = ... 9807 // # fallthrough to sinkMBB 9808 BB = copy0MBB; 9809 9810 // Update machine-CFG edges 9811 BB->addSuccessor(sinkMBB); 9812 9813 // sinkMBB: 9814 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9815 // ... 9816 BB = sinkMBB; 9817 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 9818 .addReg(MI.getOperand(3).getReg()) 9819 .addMBB(copy0MBB) 9820 .addReg(MI.getOperand(2).getReg()) 9821 .addMBB(thisMBB); 9822 } else if (MI.getOpcode() == PPC::ReadTB) { 9823 // To read the 64-bit time-base register on a 32-bit target, we read the 9824 // two halves. Should the counter have wrapped while it was being read, we 9825 // need to try again. 9826 // ... 9827 // readLoop: 9828 // mfspr Rx,TBU # load from TBU 9829 // mfspr Ry,TB # load from TB 9830 // mfspr Rz,TBU # load from TBU 9831 // cmpw crX,Rx,Rz # check if 'old'='new' 9832 // bne readLoop # branch if they're not equal 9833 // ... 9834 9835 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 9836 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9837 DebugLoc dl = MI.getDebugLoc(); 9838 F->insert(It, readMBB); 9839 F->insert(It, sinkMBB); 9840 9841 // Transfer the remainder of BB and its successor edges to sinkMBB. 9842 sinkMBB->splice(sinkMBB->begin(), BB, 9843 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9844 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9845 9846 BB->addSuccessor(readMBB); 9847 BB = readMBB; 9848 9849 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9850 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9851 unsigned LoReg = MI.getOperand(0).getReg(); 9852 unsigned HiReg = MI.getOperand(1).getReg(); 9853 9854 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 9855 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 9856 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 9857 9858 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 9859 9860 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 9861 .addReg(HiReg).addReg(ReadAgainReg); 9862 BuildMI(BB, dl, TII->get(PPC::BCC)) 9863 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 9864 9865 BB->addSuccessor(readMBB); 9866 BB->addSuccessor(sinkMBB); 9867 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 9868 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 9869 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 9870 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 9871 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 9872 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 9873 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 9874 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 9875 9876 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 9877 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 9878 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 9879 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 9880 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 9881 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 9882 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 9883 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 9884 9885 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 9886 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 9887 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 9888 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 9889 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 9890 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 9891 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 9892 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 9893 9894 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 9895 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 9896 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 9897 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 9898 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 9899 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 9900 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 9901 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 9902 9903 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 9904 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 9905 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 9906 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 9907 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 9908 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 9909 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 9910 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 9911 9912 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 9913 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 9914 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 9915 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 9916 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 9917 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 9918 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 9919 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 9920 9921 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 9922 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 9923 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 9924 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 9925 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 9926 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 9927 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 9928 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 9929 9930 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 9931 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 9932 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 9933 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 9934 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 9935 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 9936 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 9937 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 9938 9939 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 9940 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 9941 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 9942 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 9943 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 9944 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 9945 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 9946 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 9947 9948 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 9949 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 9950 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 9951 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 9952 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 9953 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 9954 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 9955 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 9956 9957 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 9958 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 9959 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 9960 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 9961 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 9962 BB = EmitAtomicBinary(MI, BB, 4, 0); 9963 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 9964 BB = EmitAtomicBinary(MI, BB, 8, 0); 9965 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 9966 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 9967 (Subtarget.hasPartwordAtomics() && 9968 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 9969 (Subtarget.hasPartwordAtomics() && 9970 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 9971 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 9972 9973 auto LoadMnemonic = PPC::LDARX; 9974 auto StoreMnemonic = PPC::STDCX; 9975 switch (MI.getOpcode()) { 9976 default: 9977 llvm_unreachable("Compare and swap of unknown size"); 9978 case PPC::ATOMIC_CMP_SWAP_I8: 9979 LoadMnemonic = PPC::LBARX; 9980 StoreMnemonic = PPC::STBCX; 9981 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 9982 break; 9983 case PPC::ATOMIC_CMP_SWAP_I16: 9984 LoadMnemonic = PPC::LHARX; 9985 StoreMnemonic = PPC::STHCX; 9986 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 9987 break; 9988 case PPC::ATOMIC_CMP_SWAP_I32: 9989 LoadMnemonic = PPC::LWARX; 9990 StoreMnemonic = PPC::STWCX; 9991 break; 9992 case PPC::ATOMIC_CMP_SWAP_I64: 9993 LoadMnemonic = PPC::LDARX; 9994 StoreMnemonic = PPC::STDCX; 9995 break; 9996 } 9997 unsigned dest = MI.getOperand(0).getReg(); 9998 unsigned ptrA = MI.getOperand(1).getReg(); 9999 unsigned ptrB = MI.getOperand(2).getReg(); 10000 unsigned oldval = MI.getOperand(3).getReg(); 10001 unsigned newval = MI.getOperand(4).getReg(); 10002 DebugLoc dl = MI.getDebugLoc(); 10003 10004 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10005 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10006 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10007 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10008 F->insert(It, loop1MBB); 10009 F->insert(It, loop2MBB); 10010 F->insert(It, midMBB); 10011 F->insert(It, exitMBB); 10012 exitMBB->splice(exitMBB->begin(), BB, 10013 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10014 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10015 10016 // thisMBB: 10017 // ... 10018 // fallthrough --> loopMBB 10019 BB->addSuccessor(loop1MBB); 10020 10021 // loop1MBB: 10022 // l[bhwd]arx dest, ptr 10023 // cmp[wd] dest, oldval 10024 // bne- midMBB 10025 // loop2MBB: 10026 // st[bhwd]cx. newval, ptr 10027 // bne- loopMBB 10028 // b exitBB 10029 // midMBB: 10030 // st[bhwd]cx. dest, ptr 10031 // exitBB: 10032 BB = loop1MBB; 10033 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10034 .addReg(ptrA).addReg(ptrB); 10035 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10036 .addReg(oldval).addReg(dest); 10037 BuildMI(BB, dl, TII->get(PPC::BCC)) 10038 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10039 BB->addSuccessor(loop2MBB); 10040 BB->addSuccessor(midMBB); 10041 10042 BB = loop2MBB; 10043 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10044 .addReg(newval).addReg(ptrA).addReg(ptrB); 10045 BuildMI(BB, dl, TII->get(PPC::BCC)) 10046 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10047 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10048 BB->addSuccessor(loop1MBB); 10049 BB->addSuccessor(exitMBB); 10050 10051 BB = midMBB; 10052 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10053 .addReg(dest).addReg(ptrA).addReg(ptrB); 10054 BB->addSuccessor(exitMBB); 10055 10056 // exitMBB: 10057 // ... 10058 BB = exitMBB; 10059 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10060 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10061 // We must use 64-bit registers for addresses when targeting 64-bit, 10062 // since we're actually doing arithmetic on them. Other registers 10063 // can be 32-bit. 10064 bool is64bit = Subtarget.isPPC64(); 10065 bool isLittleEndian = Subtarget.isLittleEndian(); 10066 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10067 10068 unsigned dest = MI.getOperand(0).getReg(); 10069 unsigned ptrA = MI.getOperand(1).getReg(); 10070 unsigned ptrB = MI.getOperand(2).getReg(); 10071 unsigned oldval = MI.getOperand(3).getReg(); 10072 unsigned newval = MI.getOperand(4).getReg(); 10073 DebugLoc dl = MI.getDebugLoc(); 10074 10075 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10076 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10077 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10078 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10079 F->insert(It, loop1MBB); 10080 F->insert(It, loop2MBB); 10081 F->insert(It, midMBB); 10082 F->insert(It, exitMBB); 10083 exitMBB->splice(exitMBB->begin(), BB, 10084 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10085 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10086 10087 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10088 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10089 : &PPC::GPRCRegClass; 10090 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10091 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10092 unsigned ShiftReg = 10093 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10094 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10095 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10096 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10097 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10098 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10099 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10100 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10101 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10102 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10103 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10104 unsigned Ptr1Reg; 10105 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10106 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10107 // thisMBB: 10108 // ... 10109 // fallthrough --> loopMBB 10110 BB->addSuccessor(loop1MBB); 10111 10112 // The 4-byte load must be aligned, while a char or short may be 10113 // anywhere in the word. Hence all this nasty bookkeeping code. 10114 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10115 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10116 // xori shift, shift1, 24 [16] 10117 // rlwinm ptr, ptr1, 0, 0, 29 10118 // slw newval2, newval, shift 10119 // slw oldval2, oldval,shift 10120 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10121 // slw mask, mask2, shift 10122 // and newval3, newval2, mask 10123 // and oldval3, oldval2, mask 10124 // loop1MBB: 10125 // lwarx tmpDest, ptr 10126 // and tmp, tmpDest, mask 10127 // cmpw tmp, oldval3 10128 // bne- midMBB 10129 // loop2MBB: 10130 // andc tmp2, tmpDest, mask 10131 // or tmp4, tmp2, newval3 10132 // stwcx. tmp4, ptr 10133 // bne- loop1MBB 10134 // b exitBB 10135 // midMBB: 10136 // stwcx. tmpDest, ptr 10137 // exitBB: 10138 // srw dest, tmpDest, shift 10139 if (ptrA != ZeroReg) { 10140 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10141 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10142 .addReg(ptrA).addReg(ptrB); 10143 } else { 10144 Ptr1Reg = ptrB; 10145 } 10146 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10147 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10148 if (!isLittleEndian) 10149 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10150 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10151 if (is64bit) 10152 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10153 .addReg(Ptr1Reg).addImm(0).addImm(61); 10154 else 10155 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10156 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10157 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10158 .addReg(newval).addReg(ShiftReg); 10159 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10160 .addReg(oldval).addReg(ShiftReg); 10161 if (is8bit) 10162 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10163 else { 10164 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10165 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10166 .addReg(Mask3Reg).addImm(65535); 10167 } 10168 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10169 .addReg(Mask2Reg).addReg(ShiftReg); 10170 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10171 .addReg(NewVal2Reg).addReg(MaskReg); 10172 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10173 .addReg(OldVal2Reg).addReg(MaskReg); 10174 10175 BB = loop1MBB; 10176 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10177 .addReg(ZeroReg).addReg(PtrReg); 10178 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10179 .addReg(TmpDestReg).addReg(MaskReg); 10180 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10181 .addReg(TmpReg).addReg(OldVal3Reg); 10182 BuildMI(BB, dl, TII->get(PPC::BCC)) 10183 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10184 BB->addSuccessor(loop2MBB); 10185 BB->addSuccessor(midMBB); 10186 10187 BB = loop2MBB; 10188 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10189 .addReg(TmpDestReg).addReg(MaskReg); 10190 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10191 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10192 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10193 .addReg(ZeroReg).addReg(PtrReg); 10194 BuildMI(BB, dl, TII->get(PPC::BCC)) 10195 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10196 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10197 BB->addSuccessor(loop1MBB); 10198 BB->addSuccessor(exitMBB); 10199 10200 BB = midMBB; 10201 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10202 .addReg(ZeroReg).addReg(PtrReg); 10203 BB->addSuccessor(exitMBB); 10204 10205 // exitMBB: 10206 // ... 10207 BB = exitMBB; 10208 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10209 .addReg(ShiftReg); 10210 } else if (MI.getOpcode() == PPC::FADDrtz) { 10211 // This pseudo performs an FADD with rounding mode temporarily forced 10212 // to round-to-zero. We emit this via custom inserter since the FPSCR 10213 // is not modeled at the SelectionDAG level. 10214 unsigned Dest = MI.getOperand(0).getReg(); 10215 unsigned Src1 = MI.getOperand(1).getReg(); 10216 unsigned Src2 = MI.getOperand(2).getReg(); 10217 DebugLoc dl = MI.getDebugLoc(); 10218 10219 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10220 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10221 10222 // Save FPSCR value. 10223 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10224 10225 // Set rounding mode to round-to-zero. 10226 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10227 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10228 10229 // Perform addition. 10230 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10231 10232 // Restore FPSCR value. 10233 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10234 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10235 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10236 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10237 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10238 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10239 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10240 ? PPC::ANDIo8 10241 : PPC::ANDIo; 10242 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10243 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10244 10245 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10246 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10247 &PPC::GPRCRegClass : 10248 &PPC::G8RCRegClass); 10249 10250 DebugLoc dl = MI.getDebugLoc(); 10251 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10252 .addReg(MI.getOperand(1).getReg()) 10253 .addImm(1); 10254 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10255 MI.getOperand(0).getReg()) 10256 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10257 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10258 DebugLoc Dl = MI.getDebugLoc(); 10259 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10260 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10261 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10262 return BB; 10263 } else { 10264 llvm_unreachable("Unexpected instr type to insert"); 10265 } 10266 10267 MI.eraseFromParent(); // The pseudo instruction is gone now. 10268 return BB; 10269 } 10270 10271 //===----------------------------------------------------------------------===// 10272 // Target Optimization Hooks 10273 //===----------------------------------------------------------------------===// 10274 10275 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10276 // For the estimates, convergence is quadratic, so we essentially double the 10277 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10278 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10279 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10280 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10281 if (VT.getScalarType() == MVT::f64) 10282 RefinementSteps++; 10283 return RefinementSteps; 10284 } 10285 10286 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10287 int Enabled, int &RefinementSteps, 10288 bool &UseOneConstNR, 10289 bool Reciprocal) const { 10290 EVT VT = Operand.getValueType(); 10291 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10292 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10293 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10294 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10295 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10296 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10297 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10298 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10299 10300 UseOneConstNR = true; 10301 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10302 } 10303 return SDValue(); 10304 } 10305 10306 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10307 int Enabled, 10308 int &RefinementSteps) const { 10309 EVT VT = Operand.getValueType(); 10310 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10311 (VT == MVT::f64 && Subtarget.hasFRE()) || 10312 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10313 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10314 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10315 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10316 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10317 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10318 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10319 } 10320 return SDValue(); 10321 } 10322 10323 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10324 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10325 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10326 // enabled for division), this functionality is redundant with the default 10327 // combiner logic (once the division -> reciprocal/multiply transformation 10328 // has taken place). As a result, this matters more for older cores than for 10329 // newer ones. 10330 10331 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10332 // reciprocal if there are two or more FDIVs (for embedded cores with only 10333 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10334 switch (Subtarget.getDarwinDirective()) { 10335 default: 10336 return 3; 10337 case PPC::DIR_440: 10338 case PPC::DIR_A2: 10339 case PPC::DIR_E500mc: 10340 case PPC::DIR_E5500: 10341 return 2; 10342 } 10343 } 10344 10345 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10346 // collapsed, and so we need to look through chains of them. 10347 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10348 int64_t& Offset, SelectionDAG &DAG) { 10349 if (DAG.isBaseWithConstantOffset(Loc)) { 10350 Base = Loc.getOperand(0); 10351 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10352 10353 // The base might itself be a base plus an offset, and if so, accumulate 10354 // that as well. 10355 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10356 } 10357 } 10358 10359 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10360 unsigned Bytes, int Dist, 10361 SelectionDAG &DAG) { 10362 if (VT.getSizeInBits() / 8 != Bytes) 10363 return false; 10364 10365 SDValue BaseLoc = Base->getBasePtr(); 10366 if (Loc.getOpcode() == ISD::FrameIndex) { 10367 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10368 return false; 10369 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10370 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10371 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10372 int FS = MFI.getObjectSize(FI); 10373 int BFS = MFI.getObjectSize(BFI); 10374 if (FS != BFS || FS != (int)Bytes) return false; 10375 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10376 } 10377 10378 SDValue Base1 = Loc, Base2 = BaseLoc; 10379 int64_t Offset1 = 0, Offset2 = 0; 10380 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 10381 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 10382 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 10383 return true; 10384 10385 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10386 const GlobalValue *GV1 = nullptr; 10387 const GlobalValue *GV2 = nullptr; 10388 Offset1 = 0; 10389 Offset2 = 0; 10390 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10391 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 10392 if (isGA1 && isGA2 && GV1 == GV2) 10393 return Offset1 == (Offset2 + Dist*Bytes); 10394 return false; 10395 } 10396 10397 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 10398 // not enforce equality of the chain operands. 10399 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 10400 unsigned Bytes, int Dist, 10401 SelectionDAG &DAG) { 10402 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 10403 EVT VT = LS->getMemoryVT(); 10404 SDValue Loc = LS->getBasePtr(); 10405 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 10406 } 10407 10408 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 10409 EVT VT; 10410 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10411 default: return false; 10412 case Intrinsic::ppc_qpx_qvlfd: 10413 case Intrinsic::ppc_qpx_qvlfda: 10414 VT = MVT::v4f64; 10415 break; 10416 case Intrinsic::ppc_qpx_qvlfs: 10417 case Intrinsic::ppc_qpx_qvlfsa: 10418 VT = MVT::v4f32; 10419 break; 10420 case Intrinsic::ppc_qpx_qvlfcd: 10421 case Intrinsic::ppc_qpx_qvlfcda: 10422 VT = MVT::v2f64; 10423 break; 10424 case Intrinsic::ppc_qpx_qvlfcs: 10425 case Intrinsic::ppc_qpx_qvlfcsa: 10426 VT = MVT::v2f32; 10427 break; 10428 case Intrinsic::ppc_qpx_qvlfiwa: 10429 case Intrinsic::ppc_qpx_qvlfiwz: 10430 case Intrinsic::ppc_altivec_lvx: 10431 case Intrinsic::ppc_altivec_lvxl: 10432 case Intrinsic::ppc_vsx_lxvw4x: 10433 case Intrinsic::ppc_vsx_lxvw4x_be: 10434 VT = MVT::v4i32; 10435 break; 10436 case Intrinsic::ppc_vsx_lxvd2x: 10437 case Intrinsic::ppc_vsx_lxvd2x_be: 10438 VT = MVT::v2f64; 10439 break; 10440 case Intrinsic::ppc_altivec_lvebx: 10441 VT = MVT::i8; 10442 break; 10443 case Intrinsic::ppc_altivec_lvehx: 10444 VT = MVT::i16; 10445 break; 10446 case Intrinsic::ppc_altivec_lvewx: 10447 VT = MVT::i32; 10448 break; 10449 } 10450 10451 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 10452 } 10453 10454 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 10455 EVT VT; 10456 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10457 default: return false; 10458 case Intrinsic::ppc_qpx_qvstfd: 10459 case Intrinsic::ppc_qpx_qvstfda: 10460 VT = MVT::v4f64; 10461 break; 10462 case Intrinsic::ppc_qpx_qvstfs: 10463 case Intrinsic::ppc_qpx_qvstfsa: 10464 VT = MVT::v4f32; 10465 break; 10466 case Intrinsic::ppc_qpx_qvstfcd: 10467 case Intrinsic::ppc_qpx_qvstfcda: 10468 VT = MVT::v2f64; 10469 break; 10470 case Intrinsic::ppc_qpx_qvstfcs: 10471 case Intrinsic::ppc_qpx_qvstfcsa: 10472 VT = MVT::v2f32; 10473 break; 10474 case Intrinsic::ppc_qpx_qvstfiw: 10475 case Intrinsic::ppc_qpx_qvstfiwa: 10476 case Intrinsic::ppc_altivec_stvx: 10477 case Intrinsic::ppc_altivec_stvxl: 10478 case Intrinsic::ppc_vsx_stxvw4x: 10479 VT = MVT::v4i32; 10480 break; 10481 case Intrinsic::ppc_vsx_stxvd2x: 10482 VT = MVT::v2f64; 10483 break; 10484 case Intrinsic::ppc_vsx_stxvw4x_be: 10485 VT = MVT::v4i32; 10486 break; 10487 case Intrinsic::ppc_vsx_stxvd2x_be: 10488 VT = MVT::v2f64; 10489 break; 10490 case Intrinsic::ppc_altivec_stvebx: 10491 VT = MVT::i8; 10492 break; 10493 case Intrinsic::ppc_altivec_stvehx: 10494 VT = MVT::i16; 10495 break; 10496 case Intrinsic::ppc_altivec_stvewx: 10497 VT = MVT::i32; 10498 break; 10499 } 10500 10501 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 10502 } 10503 10504 return false; 10505 } 10506 10507 // Return true is there is a nearyby consecutive load to the one provided 10508 // (regardless of alignment). We search up and down the chain, looking though 10509 // token factors and other loads (but nothing else). As a result, a true result 10510 // indicates that it is safe to create a new consecutive load adjacent to the 10511 // load provided. 10512 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 10513 SDValue Chain = LD->getChain(); 10514 EVT VT = LD->getMemoryVT(); 10515 10516 SmallSet<SDNode *, 16> LoadRoots; 10517 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 10518 SmallSet<SDNode *, 16> Visited; 10519 10520 // First, search up the chain, branching to follow all token-factor operands. 10521 // If we find a consecutive load, then we're done, otherwise, record all 10522 // nodes just above the top-level loads and token factors. 10523 while (!Queue.empty()) { 10524 SDNode *ChainNext = Queue.pop_back_val(); 10525 if (!Visited.insert(ChainNext).second) 10526 continue; 10527 10528 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 10529 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10530 return true; 10531 10532 if (!Visited.count(ChainLD->getChain().getNode())) 10533 Queue.push_back(ChainLD->getChain().getNode()); 10534 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 10535 for (const SDUse &O : ChainNext->ops()) 10536 if (!Visited.count(O.getNode())) 10537 Queue.push_back(O.getNode()); 10538 } else 10539 LoadRoots.insert(ChainNext); 10540 } 10541 10542 // Second, search down the chain, starting from the top-level nodes recorded 10543 // in the first phase. These top-level nodes are the nodes just above all 10544 // loads and token factors. Starting with their uses, recursively look though 10545 // all loads (just the chain uses) and token factors to find a consecutive 10546 // load. 10547 Visited.clear(); 10548 Queue.clear(); 10549 10550 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 10551 IE = LoadRoots.end(); I != IE; ++I) { 10552 Queue.push_back(*I); 10553 10554 while (!Queue.empty()) { 10555 SDNode *LoadRoot = Queue.pop_back_val(); 10556 if (!Visited.insert(LoadRoot).second) 10557 continue; 10558 10559 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 10560 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10561 return true; 10562 10563 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 10564 UE = LoadRoot->use_end(); UI != UE; ++UI) 10565 if (((isa<MemSDNode>(*UI) && 10566 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 10567 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 10568 Queue.push_back(*UI); 10569 } 10570 } 10571 10572 return false; 10573 } 10574 10575 /// This function is called when we have proved that a SETCC node can be replaced 10576 /// by subtraction (and other supporting instructions) so that the result of 10577 /// comparison is kept in a GPR instead of CR. This function is purely for 10578 /// codegen purposes and has some flags to guide the codegen process. 10579 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 10580 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 10581 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10582 10583 // Zero extend the operands to the largest legal integer. Originally, they 10584 // must be of a strictly smaller size. 10585 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 10586 DAG.getConstant(Size, DL, MVT::i32)); 10587 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 10588 DAG.getConstant(Size, DL, MVT::i32)); 10589 10590 // Swap if needed. Depends on the condition code. 10591 if (Swap) 10592 std::swap(Op0, Op1); 10593 10594 // Subtract extended integers. 10595 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 10596 10597 // Move the sign bit to the least significant position and zero out the rest. 10598 // Now the least significant bit carries the result of original comparison. 10599 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 10600 DAG.getConstant(Size - 1, DL, MVT::i32)); 10601 auto Final = Shifted; 10602 10603 // Complement the result if needed. Based on the condition code. 10604 if (Complement) 10605 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 10606 DAG.getConstant(1, DL, MVT::i64)); 10607 10608 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 10609 } 10610 10611 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 10612 DAGCombinerInfo &DCI) const { 10613 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10614 10615 SelectionDAG &DAG = DCI.DAG; 10616 SDLoc DL(N); 10617 10618 // Size of integers being compared has a critical role in the following 10619 // analysis, so we prefer to do this when all types are legal. 10620 if (!DCI.isAfterLegalizeVectorOps()) 10621 return SDValue(); 10622 10623 // If all users of SETCC extend its value to a legal integer type 10624 // then we replace SETCC with a subtraction 10625 for (SDNode::use_iterator UI = N->use_begin(), 10626 UE = N->use_end(); UI != UE; ++UI) { 10627 if (UI->getOpcode() != ISD::ZERO_EXTEND) 10628 return SDValue(); 10629 } 10630 10631 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10632 auto OpSize = N->getOperand(0).getValueSizeInBits(); 10633 10634 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 10635 10636 if (OpSize < Size) { 10637 switch (CC) { 10638 default: break; 10639 case ISD::SETULT: 10640 return generateEquivalentSub(N, Size, false, false, DL, DAG); 10641 case ISD::SETULE: 10642 return generateEquivalentSub(N, Size, true, true, DL, DAG); 10643 case ISD::SETUGT: 10644 return generateEquivalentSub(N, Size, false, true, DL, DAG); 10645 case ISD::SETUGE: 10646 return generateEquivalentSub(N, Size, true, false, DL, DAG); 10647 } 10648 } 10649 10650 return SDValue(); 10651 } 10652 10653 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 10654 DAGCombinerInfo &DCI) const { 10655 SelectionDAG &DAG = DCI.DAG; 10656 SDLoc dl(N); 10657 10658 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 10659 // If we're tracking CR bits, we need to be careful that we don't have: 10660 // trunc(binary-ops(zext(x), zext(y))) 10661 // or 10662 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 10663 // such that we're unnecessarily moving things into GPRs when it would be 10664 // better to keep them in CR bits. 10665 10666 // Note that trunc here can be an actual i1 trunc, or can be the effective 10667 // truncation that comes from a setcc or select_cc. 10668 if (N->getOpcode() == ISD::TRUNCATE && 10669 N->getValueType(0) != MVT::i1) 10670 return SDValue(); 10671 10672 if (N->getOperand(0).getValueType() != MVT::i32 && 10673 N->getOperand(0).getValueType() != MVT::i64) 10674 return SDValue(); 10675 10676 if (N->getOpcode() == ISD::SETCC || 10677 N->getOpcode() == ISD::SELECT_CC) { 10678 // If we're looking at a comparison, then we need to make sure that the 10679 // high bits (all except for the first) don't matter the result. 10680 ISD::CondCode CC = 10681 cast<CondCodeSDNode>(N->getOperand( 10682 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 10683 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 10684 10685 if (ISD::isSignedIntSetCC(CC)) { 10686 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 10687 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 10688 return SDValue(); 10689 } else if (ISD::isUnsignedIntSetCC(CC)) { 10690 if (!DAG.MaskedValueIsZero(N->getOperand(0), 10691 APInt::getHighBitsSet(OpBits, OpBits-1)) || 10692 !DAG.MaskedValueIsZero(N->getOperand(1), 10693 APInt::getHighBitsSet(OpBits, OpBits-1))) 10694 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 10695 : SDValue()); 10696 } else { 10697 // This is neither a signed nor an unsigned comparison, just make sure 10698 // that the high bits are equal. 10699 KnownBits Op1Known, Op2Known; 10700 DAG.computeKnownBits(N->getOperand(0), Op1Known); 10701 DAG.computeKnownBits(N->getOperand(1), Op2Known); 10702 10703 // We don't really care about what is known about the first bit (if 10704 // anything), so clear it in all masks prior to comparing them. 10705 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 10706 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 10707 10708 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 10709 return SDValue(); 10710 } 10711 } 10712 10713 // We now know that the higher-order bits are irrelevant, we just need to 10714 // make sure that all of the intermediate operations are bit operations, and 10715 // all inputs are extensions. 10716 if (N->getOperand(0).getOpcode() != ISD::AND && 10717 N->getOperand(0).getOpcode() != ISD::OR && 10718 N->getOperand(0).getOpcode() != ISD::XOR && 10719 N->getOperand(0).getOpcode() != ISD::SELECT && 10720 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 10721 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 10722 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 10723 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 10724 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 10725 return SDValue(); 10726 10727 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 10728 N->getOperand(1).getOpcode() != ISD::AND && 10729 N->getOperand(1).getOpcode() != ISD::OR && 10730 N->getOperand(1).getOpcode() != ISD::XOR && 10731 N->getOperand(1).getOpcode() != ISD::SELECT && 10732 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 10733 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 10734 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 10735 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 10736 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 10737 return SDValue(); 10738 10739 SmallVector<SDValue, 4> Inputs; 10740 SmallVector<SDValue, 8> BinOps, PromOps; 10741 SmallPtrSet<SDNode *, 16> Visited; 10742 10743 for (unsigned i = 0; i < 2; ++i) { 10744 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10745 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10746 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 10747 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 10748 isa<ConstantSDNode>(N->getOperand(i))) 10749 Inputs.push_back(N->getOperand(i)); 10750 else 10751 BinOps.push_back(N->getOperand(i)); 10752 10753 if (N->getOpcode() == ISD::TRUNCATE) 10754 break; 10755 } 10756 10757 // Visit all inputs, collect all binary operations (and, or, xor and 10758 // select) that are all fed by extensions. 10759 while (!BinOps.empty()) { 10760 SDValue BinOp = BinOps.back(); 10761 BinOps.pop_back(); 10762 10763 if (!Visited.insert(BinOp.getNode()).second) 10764 continue; 10765 10766 PromOps.push_back(BinOp); 10767 10768 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 10769 // The condition of the select is not promoted. 10770 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 10771 continue; 10772 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 10773 continue; 10774 10775 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10776 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10777 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 10778 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 10779 isa<ConstantSDNode>(BinOp.getOperand(i))) { 10780 Inputs.push_back(BinOp.getOperand(i)); 10781 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 10782 BinOp.getOperand(i).getOpcode() == ISD::OR || 10783 BinOp.getOperand(i).getOpcode() == ISD::XOR || 10784 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 10785 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 10786 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 10787 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10788 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10789 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 10790 BinOps.push_back(BinOp.getOperand(i)); 10791 } else { 10792 // We have an input that is not an extension or another binary 10793 // operation; we'll abort this transformation. 10794 return SDValue(); 10795 } 10796 } 10797 } 10798 10799 // Make sure that this is a self-contained cluster of operations (which 10800 // is not quite the same thing as saying that everything has only one 10801 // use). 10802 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10803 if (isa<ConstantSDNode>(Inputs[i])) 10804 continue; 10805 10806 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 10807 UE = Inputs[i].getNode()->use_end(); 10808 UI != UE; ++UI) { 10809 SDNode *User = *UI; 10810 if (User != N && !Visited.count(User)) 10811 return SDValue(); 10812 10813 // Make sure that we're not going to promote the non-output-value 10814 // operand(s) or SELECT or SELECT_CC. 10815 // FIXME: Although we could sometimes handle this, and it does occur in 10816 // practice that one of the condition inputs to the select is also one of 10817 // the outputs, we currently can't deal with this. 10818 if (User->getOpcode() == ISD::SELECT) { 10819 if (User->getOperand(0) == Inputs[i]) 10820 return SDValue(); 10821 } else if (User->getOpcode() == ISD::SELECT_CC) { 10822 if (User->getOperand(0) == Inputs[i] || 10823 User->getOperand(1) == Inputs[i]) 10824 return SDValue(); 10825 } 10826 } 10827 } 10828 10829 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 10830 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 10831 UE = PromOps[i].getNode()->use_end(); 10832 UI != UE; ++UI) { 10833 SDNode *User = *UI; 10834 if (User != N && !Visited.count(User)) 10835 return SDValue(); 10836 10837 // Make sure that we're not going to promote the non-output-value 10838 // operand(s) or SELECT or SELECT_CC. 10839 // FIXME: Although we could sometimes handle this, and it does occur in 10840 // practice that one of the condition inputs to the select is also one of 10841 // the outputs, we currently can't deal with this. 10842 if (User->getOpcode() == ISD::SELECT) { 10843 if (User->getOperand(0) == PromOps[i]) 10844 return SDValue(); 10845 } else if (User->getOpcode() == ISD::SELECT_CC) { 10846 if (User->getOperand(0) == PromOps[i] || 10847 User->getOperand(1) == PromOps[i]) 10848 return SDValue(); 10849 } 10850 } 10851 } 10852 10853 // Replace all inputs with the extension operand. 10854 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10855 // Constants may have users outside the cluster of to-be-promoted nodes, 10856 // and so we need to replace those as we do the promotions. 10857 if (isa<ConstantSDNode>(Inputs[i])) 10858 continue; 10859 else 10860 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 10861 } 10862 10863 std::list<HandleSDNode> PromOpHandles; 10864 for (auto &PromOp : PromOps) 10865 PromOpHandles.emplace_back(PromOp); 10866 10867 // Replace all operations (these are all the same, but have a different 10868 // (i1) return type). DAG.getNode will validate that the types of 10869 // a binary operator match, so go through the list in reverse so that 10870 // we've likely promoted both operands first. Any intermediate truncations or 10871 // extensions disappear. 10872 while (!PromOpHandles.empty()) { 10873 SDValue PromOp = PromOpHandles.back().getValue(); 10874 PromOpHandles.pop_back(); 10875 10876 if (PromOp.getOpcode() == ISD::TRUNCATE || 10877 PromOp.getOpcode() == ISD::SIGN_EXTEND || 10878 PromOp.getOpcode() == ISD::ZERO_EXTEND || 10879 PromOp.getOpcode() == ISD::ANY_EXTEND) { 10880 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 10881 PromOp.getOperand(0).getValueType() != MVT::i1) { 10882 // The operand is not yet ready (see comment below). 10883 PromOpHandles.emplace_front(PromOp); 10884 continue; 10885 } 10886 10887 SDValue RepValue = PromOp.getOperand(0); 10888 if (isa<ConstantSDNode>(RepValue)) 10889 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 10890 10891 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 10892 continue; 10893 } 10894 10895 unsigned C; 10896 switch (PromOp.getOpcode()) { 10897 default: C = 0; break; 10898 case ISD::SELECT: C = 1; break; 10899 case ISD::SELECT_CC: C = 2; break; 10900 } 10901 10902 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 10903 PromOp.getOperand(C).getValueType() != MVT::i1) || 10904 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 10905 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 10906 // The to-be-promoted operands of this node have not yet been 10907 // promoted (this should be rare because we're going through the 10908 // list backward, but if one of the operands has several users in 10909 // this cluster of to-be-promoted nodes, it is possible). 10910 PromOpHandles.emplace_front(PromOp); 10911 continue; 10912 } 10913 10914 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 10915 PromOp.getNode()->op_end()); 10916 10917 // If there are any constant inputs, make sure they're replaced now. 10918 for (unsigned i = 0; i < 2; ++i) 10919 if (isa<ConstantSDNode>(Ops[C+i])) 10920 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 10921 10922 DAG.ReplaceAllUsesOfValueWith(PromOp, 10923 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 10924 } 10925 10926 // Now we're left with the initial truncation itself. 10927 if (N->getOpcode() == ISD::TRUNCATE) 10928 return N->getOperand(0); 10929 10930 // Otherwise, this is a comparison. The operands to be compared have just 10931 // changed type (to i1), but everything else is the same. 10932 return SDValue(N, 0); 10933 } 10934 10935 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 10936 DAGCombinerInfo &DCI) const { 10937 SelectionDAG &DAG = DCI.DAG; 10938 SDLoc dl(N); 10939 10940 // If we're tracking CR bits, we need to be careful that we don't have: 10941 // zext(binary-ops(trunc(x), trunc(y))) 10942 // or 10943 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 10944 // such that we're unnecessarily moving things into CR bits that can more 10945 // efficiently stay in GPRs. Note that if we're not certain that the high 10946 // bits are set as required by the final extension, we still may need to do 10947 // some masking to get the proper behavior. 10948 10949 // This same functionality is important on PPC64 when dealing with 10950 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 10951 // the return values of functions. Because it is so similar, it is handled 10952 // here as well. 10953 10954 if (N->getValueType(0) != MVT::i32 && 10955 N->getValueType(0) != MVT::i64) 10956 return SDValue(); 10957 10958 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 10959 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 10960 return SDValue(); 10961 10962 if (N->getOperand(0).getOpcode() != ISD::AND && 10963 N->getOperand(0).getOpcode() != ISD::OR && 10964 N->getOperand(0).getOpcode() != ISD::XOR && 10965 N->getOperand(0).getOpcode() != ISD::SELECT && 10966 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 10967 return SDValue(); 10968 10969 SmallVector<SDValue, 4> Inputs; 10970 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 10971 SmallPtrSet<SDNode *, 16> Visited; 10972 10973 // Visit all inputs, collect all binary operations (and, or, xor and 10974 // select) that are all fed by truncations. 10975 while (!BinOps.empty()) { 10976 SDValue BinOp = BinOps.back(); 10977 BinOps.pop_back(); 10978 10979 if (!Visited.insert(BinOp.getNode()).second) 10980 continue; 10981 10982 PromOps.push_back(BinOp); 10983 10984 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 10985 // The condition of the select is not promoted. 10986 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 10987 continue; 10988 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 10989 continue; 10990 10991 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 10992 isa<ConstantSDNode>(BinOp.getOperand(i))) { 10993 Inputs.push_back(BinOp.getOperand(i)); 10994 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 10995 BinOp.getOperand(i).getOpcode() == ISD::OR || 10996 BinOp.getOperand(i).getOpcode() == ISD::XOR || 10997 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 10998 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 10999 BinOps.push_back(BinOp.getOperand(i)); 11000 } else { 11001 // We have an input that is not a truncation or another binary 11002 // operation; we'll abort this transformation. 11003 return SDValue(); 11004 } 11005 } 11006 } 11007 11008 // The operands of a select that must be truncated when the select is 11009 // promoted because the operand is actually part of the to-be-promoted set. 11010 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11011 11012 // Make sure that this is a self-contained cluster of operations (which 11013 // is not quite the same thing as saying that everything has only one 11014 // use). 11015 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11016 if (isa<ConstantSDNode>(Inputs[i])) 11017 continue; 11018 11019 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11020 UE = Inputs[i].getNode()->use_end(); 11021 UI != UE; ++UI) { 11022 SDNode *User = *UI; 11023 if (User != N && !Visited.count(User)) 11024 return SDValue(); 11025 11026 // If we're going to promote the non-output-value operand(s) or SELECT or 11027 // SELECT_CC, record them for truncation. 11028 if (User->getOpcode() == ISD::SELECT) { 11029 if (User->getOperand(0) == Inputs[i]) 11030 SelectTruncOp[0].insert(std::make_pair(User, 11031 User->getOperand(0).getValueType())); 11032 } else if (User->getOpcode() == ISD::SELECT_CC) { 11033 if (User->getOperand(0) == Inputs[i]) 11034 SelectTruncOp[0].insert(std::make_pair(User, 11035 User->getOperand(0).getValueType())); 11036 if (User->getOperand(1) == Inputs[i]) 11037 SelectTruncOp[1].insert(std::make_pair(User, 11038 User->getOperand(1).getValueType())); 11039 } 11040 } 11041 } 11042 11043 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11044 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11045 UE = PromOps[i].getNode()->use_end(); 11046 UI != UE; ++UI) { 11047 SDNode *User = *UI; 11048 if (User != N && !Visited.count(User)) 11049 return SDValue(); 11050 11051 // If we're going to promote the non-output-value operand(s) or SELECT or 11052 // SELECT_CC, record them for truncation. 11053 if (User->getOpcode() == ISD::SELECT) { 11054 if (User->getOperand(0) == PromOps[i]) 11055 SelectTruncOp[0].insert(std::make_pair(User, 11056 User->getOperand(0).getValueType())); 11057 } else if (User->getOpcode() == ISD::SELECT_CC) { 11058 if (User->getOperand(0) == PromOps[i]) 11059 SelectTruncOp[0].insert(std::make_pair(User, 11060 User->getOperand(0).getValueType())); 11061 if (User->getOperand(1) == PromOps[i]) 11062 SelectTruncOp[1].insert(std::make_pair(User, 11063 User->getOperand(1).getValueType())); 11064 } 11065 } 11066 } 11067 11068 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11069 bool ReallyNeedsExt = false; 11070 if (N->getOpcode() != ISD::ANY_EXTEND) { 11071 // If all of the inputs are not already sign/zero extended, then 11072 // we'll still need to do that at the end. 11073 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11074 if (isa<ConstantSDNode>(Inputs[i])) 11075 continue; 11076 11077 unsigned OpBits = 11078 Inputs[i].getOperand(0).getValueSizeInBits(); 11079 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11080 11081 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11082 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11083 APInt::getHighBitsSet(OpBits, 11084 OpBits-PromBits))) || 11085 (N->getOpcode() == ISD::SIGN_EXTEND && 11086 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11087 (OpBits-(PromBits-1)))) { 11088 ReallyNeedsExt = true; 11089 break; 11090 } 11091 } 11092 } 11093 11094 // Replace all inputs, either with the truncation operand, or a 11095 // truncation or extension to the final output type. 11096 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11097 // Constant inputs need to be replaced with the to-be-promoted nodes that 11098 // use them because they might have users outside of the cluster of 11099 // promoted nodes. 11100 if (isa<ConstantSDNode>(Inputs[i])) 11101 continue; 11102 11103 SDValue InSrc = Inputs[i].getOperand(0); 11104 if (Inputs[i].getValueType() == N->getValueType(0)) 11105 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11106 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11107 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11108 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11109 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11110 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11111 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11112 else 11113 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11114 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11115 } 11116 11117 std::list<HandleSDNode> PromOpHandles; 11118 for (auto &PromOp : PromOps) 11119 PromOpHandles.emplace_back(PromOp); 11120 11121 // Replace all operations (these are all the same, but have a different 11122 // (promoted) return type). DAG.getNode will validate that the types of 11123 // a binary operator match, so go through the list in reverse so that 11124 // we've likely promoted both operands first. 11125 while (!PromOpHandles.empty()) { 11126 SDValue PromOp = PromOpHandles.back().getValue(); 11127 PromOpHandles.pop_back(); 11128 11129 unsigned C; 11130 switch (PromOp.getOpcode()) { 11131 default: C = 0; break; 11132 case ISD::SELECT: C = 1; break; 11133 case ISD::SELECT_CC: C = 2; break; 11134 } 11135 11136 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11137 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11138 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11139 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11140 // The to-be-promoted operands of this node have not yet been 11141 // promoted (this should be rare because we're going through the 11142 // list backward, but if one of the operands has several users in 11143 // this cluster of to-be-promoted nodes, it is possible). 11144 PromOpHandles.emplace_front(PromOp); 11145 continue; 11146 } 11147 11148 // For SELECT and SELECT_CC nodes, we do a similar check for any 11149 // to-be-promoted comparison inputs. 11150 if (PromOp.getOpcode() == ISD::SELECT || 11151 PromOp.getOpcode() == ISD::SELECT_CC) { 11152 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11153 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11154 (SelectTruncOp[1].count(PromOp.getNode()) && 11155 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11156 PromOpHandles.emplace_front(PromOp); 11157 continue; 11158 } 11159 } 11160 11161 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11162 PromOp.getNode()->op_end()); 11163 11164 // If this node has constant inputs, then they'll need to be promoted here. 11165 for (unsigned i = 0; i < 2; ++i) { 11166 if (!isa<ConstantSDNode>(Ops[C+i])) 11167 continue; 11168 if (Ops[C+i].getValueType() == N->getValueType(0)) 11169 continue; 11170 11171 if (N->getOpcode() == ISD::SIGN_EXTEND) 11172 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11173 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11174 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11175 else 11176 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11177 } 11178 11179 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11180 // truncate them again to the original value type. 11181 if (PromOp.getOpcode() == ISD::SELECT || 11182 PromOp.getOpcode() == ISD::SELECT_CC) { 11183 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11184 if (SI0 != SelectTruncOp[0].end()) 11185 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11186 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11187 if (SI1 != SelectTruncOp[1].end()) 11188 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11189 } 11190 11191 DAG.ReplaceAllUsesOfValueWith(PromOp, 11192 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11193 } 11194 11195 // Now we're left with the initial extension itself. 11196 if (!ReallyNeedsExt) 11197 return N->getOperand(0); 11198 11199 // To zero extend, just mask off everything except for the first bit (in the 11200 // i1 case). 11201 if (N->getOpcode() == ISD::ZERO_EXTEND) 11202 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11203 DAG.getConstant(APInt::getLowBitsSet( 11204 N->getValueSizeInBits(0), PromBits), 11205 dl, N->getValueType(0))); 11206 11207 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11208 "Invalid extension type"); 11209 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11210 SDValue ShiftCst = 11211 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11212 return DAG.getNode( 11213 ISD::SRA, dl, N->getValueType(0), 11214 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11215 ShiftCst); 11216 } 11217 11218 /// \brief Reduces the number of fp-to-int conversion when building a vector. 11219 /// 11220 /// If this vector is built out of floating to integer conversions, 11221 /// transform it to a vector built out of floating point values followed by a 11222 /// single floating to integer conversion of the vector. 11223 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11224 /// becomes (fptosi (build_vector ($A, $B, ...))) 11225 SDValue PPCTargetLowering:: 11226 combineElementTruncationToVectorTruncation(SDNode *N, 11227 DAGCombinerInfo &DCI) const { 11228 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11229 "Should be called with a BUILD_VECTOR node"); 11230 11231 SelectionDAG &DAG = DCI.DAG; 11232 SDLoc dl(N); 11233 11234 SDValue FirstInput = N->getOperand(0); 11235 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11236 "The input operand must be an fp-to-int conversion."); 11237 11238 // This combine happens after legalization so the fp_to_[su]i nodes are 11239 // already converted to PPCSISD nodes. 11240 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11241 if (FirstConversion == PPCISD::FCTIDZ || 11242 FirstConversion == PPCISD::FCTIDUZ || 11243 FirstConversion == PPCISD::FCTIWZ || 11244 FirstConversion == PPCISD::FCTIWUZ) { 11245 bool IsSplat = true; 11246 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11247 FirstConversion == PPCISD::FCTIWUZ; 11248 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11249 SmallVector<SDValue, 4> Ops; 11250 EVT TargetVT = N->getValueType(0); 11251 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11252 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR) 11253 return SDValue(); 11254 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode(); 11255 if (NextConversion != FirstConversion) 11256 return SDValue(); 11257 if (N->getOperand(i) != FirstInput) 11258 IsSplat = false; 11259 } 11260 11261 // If this is a splat, we leave it as-is since there will be only a single 11262 // fp-to-int conversion followed by a splat of the integer. This is better 11263 // for 32-bit and smaller ints and neutral for 64-bit ints. 11264 if (IsSplat) 11265 return SDValue(); 11266 11267 // Now that we know we have the right type of node, get its operands 11268 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11269 SDValue In = N->getOperand(i).getOperand(0); 11270 // For 32-bit values, we need to add an FP_ROUND node. 11271 if (Is32Bit) { 11272 if (In.isUndef()) 11273 Ops.push_back(DAG.getUNDEF(SrcVT)); 11274 else { 11275 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11276 MVT::f32, In.getOperand(0), 11277 DAG.getIntPtrConstant(1, dl)); 11278 Ops.push_back(Trunc); 11279 } 11280 } else 11281 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11282 } 11283 11284 unsigned Opcode; 11285 if (FirstConversion == PPCISD::FCTIDZ || 11286 FirstConversion == PPCISD::FCTIWZ) 11287 Opcode = ISD::FP_TO_SINT; 11288 else 11289 Opcode = ISD::FP_TO_UINT; 11290 11291 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11292 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11293 return DAG.getNode(Opcode, dl, TargetVT, BV); 11294 } 11295 return SDValue(); 11296 } 11297 11298 /// \brief Reduce the number of loads when building a vector. 11299 /// 11300 /// Building a vector out of multiple loads can be converted to a load 11301 /// of the vector type if the loads are consecutive. If the loads are 11302 /// consecutive but in descending order, a shuffle is added at the end 11303 /// to reorder the vector. 11304 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11305 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11306 "Should be called with a BUILD_VECTOR node"); 11307 11308 SDLoc dl(N); 11309 bool InputsAreConsecutiveLoads = true; 11310 bool InputsAreReverseConsecutive = true; 11311 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11312 SDValue FirstInput = N->getOperand(0); 11313 bool IsRoundOfExtLoad = false; 11314 11315 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11316 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11317 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11318 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11319 } 11320 // Not a build vector of (possibly fp_rounded) loads. 11321 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) 11322 return SDValue(); 11323 11324 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11325 // If any inputs are fp_round(extload), they all must be. 11326 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11327 return SDValue(); 11328 11329 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11330 N->getOperand(i); 11331 if (NextInput.getOpcode() != ISD::LOAD) 11332 return SDValue(); 11333 11334 SDValue PreviousInput = 11335 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 11336 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 11337 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 11338 11339 // If any inputs are fp_round(extload), they all must be. 11340 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 11341 return SDValue(); 11342 11343 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 11344 InputsAreConsecutiveLoads = false; 11345 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 11346 InputsAreReverseConsecutive = false; 11347 11348 // Exit early if the loads are neither consecutive nor reverse consecutive. 11349 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 11350 return SDValue(); 11351 } 11352 11353 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 11354 "The loads cannot be both consecutive and reverse consecutive."); 11355 11356 SDValue FirstLoadOp = 11357 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 11358 SDValue LastLoadOp = 11359 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 11360 N->getOperand(N->getNumOperands()-1); 11361 11362 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 11363 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 11364 if (InputsAreConsecutiveLoads) { 11365 assert(LD1 && "Input needs to be a LoadSDNode."); 11366 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 11367 LD1->getBasePtr(), LD1->getPointerInfo(), 11368 LD1->getAlignment()); 11369 } 11370 if (InputsAreReverseConsecutive) { 11371 assert(LDL && "Input needs to be a LoadSDNode."); 11372 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 11373 LDL->getBasePtr(), LDL->getPointerInfo(), 11374 LDL->getAlignment()); 11375 SmallVector<int, 16> Ops; 11376 for (int i = N->getNumOperands() - 1; i >= 0; i--) 11377 Ops.push_back(i); 11378 11379 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 11380 DAG.getUNDEF(N->getValueType(0)), Ops); 11381 } 11382 return SDValue(); 11383 } 11384 11385 // This function adds the required vector_shuffle needed to get 11386 // the elements of the vector extract in the correct position 11387 // as specified by the CorrectElems encoding. 11388 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 11389 SDValue Input, uint64_t Elems, 11390 uint64_t CorrectElems) { 11391 SDLoc dl(N); 11392 11393 unsigned NumElems = Input.getValueType().getVectorNumElements(); 11394 SmallVector<int, 16> ShuffleMask(NumElems, -1); 11395 11396 // Knowing the element indices being extracted from the original 11397 // vector and the order in which they're being inserted, just put 11398 // them at element indices required for the instruction. 11399 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11400 if (DAG.getDataLayout().isLittleEndian()) 11401 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 11402 else 11403 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 11404 CorrectElems = CorrectElems >> 8; 11405 Elems = Elems >> 8; 11406 } 11407 11408 SDValue Shuffle = 11409 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 11410 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 11411 11412 EVT Ty = N->getValueType(0); 11413 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 11414 return BV; 11415 } 11416 11417 // Look for build vector patterns where input operands come from sign 11418 // extended vector_extract elements of specific indices. If the correct indices 11419 // aren't used, add a vector shuffle to fix up the indices and create a new 11420 // PPCISD:SExtVElems node which selects the vector sign extend instructions 11421 // during instruction selection. 11422 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 11423 // This array encodes the indices that the vector sign extend instructions 11424 // extract from when extending from one type to another for both BE and LE. 11425 // The right nibble of each byte corresponds to the LE incides. 11426 // and the left nibble of each byte corresponds to the BE incides. 11427 // For example: 0x3074B8FC byte->word 11428 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 11429 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 11430 // For example: 0x000070F8 byte->double word 11431 // For LE: the allowed indices are: 0x0,0x8 11432 // For BE: the allowed indices are: 0x7,0xF 11433 uint64_t TargetElems[] = { 11434 0x3074B8FC, // b->w 11435 0x000070F8, // b->d 11436 0x10325476, // h->w 11437 0x00003074, // h->d 11438 0x00001032, // w->d 11439 }; 11440 11441 uint64_t Elems = 0; 11442 int Index; 11443 SDValue Input; 11444 11445 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 11446 if (!Op) 11447 return false; 11448 if (Op.getOpcode() != ISD::SIGN_EXTEND) 11449 return false; 11450 11451 SDValue Extract = Op.getOperand(0); 11452 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11453 return false; 11454 11455 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 11456 if (!ExtOp) 11457 return false; 11458 11459 Index = ExtOp->getZExtValue(); 11460 if (Input && Input != Extract.getOperand(0)) 11461 return false; 11462 11463 if (!Input) 11464 Input = Extract.getOperand(0); 11465 11466 Elems = Elems << 8; 11467 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 11468 Elems |= Index; 11469 11470 return true; 11471 }; 11472 11473 // If the build vector operands aren't sign extended vector extracts, 11474 // of the same input vector, then return. 11475 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11476 if (!isSExtOfVecExtract(N->getOperand(i))) { 11477 return SDValue(); 11478 } 11479 } 11480 11481 // If the vector extract indicies are not correct, add the appropriate 11482 // vector_shuffle. 11483 int TgtElemArrayIdx; 11484 int InputSize = Input.getValueType().getScalarSizeInBits(); 11485 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 11486 if (InputSize + OutputSize == 40) 11487 TgtElemArrayIdx = 0; 11488 else if (InputSize + OutputSize == 72) 11489 TgtElemArrayIdx = 1; 11490 else if (InputSize + OutputSize == 48) 11491 TgtElemArrayIdx = 2; 11492 else if (InputSize + OutputSize == 80) 11493 TgtElemArrayIdx = 3; 11494 else if (InputSize + OutputSize == 96) 11495 TgtElemArrayIdx = 4; 11496 else 11497 return SDValue(); 11498 11499 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 11500 CorrectElems = DAG.getDataLayout().isLittleEndian() 11501 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 11502 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 11503 if (Elems != CorrectElems) { 11504 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 11505 } 11506 11507 // Regular lowering will catch cases where a shuffle is not needed. 11508 return SDValue(); 11509 } 11510 11511 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 11512 DAGCombinerInfo &DCI) const { 11513 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11514 "Should be called with a BUILD_VECTOR node"); 11515 11516 SelectionDAG &DAG = DCI.DAG; 11517 SDLoc dl(N); 11518 11519 if (!Subtarget.hasVSX()) 11520 return SDValue(); 11521 11522 // The target independent DAG combiner will leave a build_vector of 11523 // float-to-int conversions intact. We can generate MUCH better code for 11524 // a float-to-int conversion of a vector of floats. 11525 SDValue FirstInput = N->getOperand(0); 11526 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 11527 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 11528 if (Reduced) 11529 return Reduced; 11530 } 11531 11532 // If we're building a vector out of consecutive loads, just load that 11533 // vector type. 11534 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 11535 if (Reduced) 11536 return Reduced; 11537 11538 // If we're building a vector out of extended elements from another vector 11539 // we have P9 vector integer extend instructions. 11540 if (Subtarget.hasP9Altivec()) { 11541 Reduced = combineBVOfVecSExt(N, DAG); 11542 if (Reduced) 11543 return Reduced; 11544 } 11545 11546 11547 if (N->getValueType(0) != MVT::v2f64) 11548 return SDValue(); 11549 11550 // Looking for: 11551 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 11552 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 11553 FirstInput.getOpcode() != ISD::UINT_TO_FP) 11554 return SDValue(); 11555 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 11556 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 11557 return SDValue(); 11558 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 11559 return SDValue(); 11560 11561 SDValue Ext1 = FirstInput.getOperand(0); 11562 SDValue Ext2 = N->getOperand(1).getOperand(0); 11563 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11564 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11565 return SDValue(); 11566 11567 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 11568 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 11569 if (!Ext1Op || !Ext2Op) 11570 return SDValue(); 11571 if (Ext1.getValueType() != MVT::i32 || 11572 Ext2.getValueType() != MVT::i32) 11573 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 11574 return SDValue(); 11575 11576 int FirstElem = Ext1Op->getZExtValue(); 11577 int SecondElem = Ext2Op->getZExtValue(); 11578 int SubvecIdx; 11579 if (FirstElem == 0 && SecondElem == 1) 11580 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 11581 else if (FirstElem == 2 && SecondElem == 3) 11582 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 11583 else 11584 return SDValue(); 11585 11586 SDValue SrcVec = Ext1.getOperand(0); 11587 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 11588 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 11589 return DAG.getNode(NodeType, dl, MVT::v2f64, 11590 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 11591 } 11592 11593 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 11594 DAGCombinerInfo &DCI) const { 11595 assert((N->getOpcode() == ISD::SINT_TO_FP || 11596 N->getOpcode() == ISD::UINT_TO_FP) && 11597 "Need an int -> FP conversion node here"); 11598 11599 if (useSoftFloat() || !Subtarget.has64BitSupport()) 11600 return SDValue(); 11601 11602 SelectionDAG &DAG = DCI.DAG; 11603 SDLoc dl(N); 11604 SDValue Op(N, 0); 11605 11606 SDValue FirstOperand(Op.getOperand(0)); 11607 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 11608 (FirstOperand.getValueType() == MVT::i8 || 11609 FirstOperand.getValueType() == MVT::i16); 11610 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 11611 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 11612 bool DstDouble = Op.getValueType() == MVT::f64; 11613 unsigned ConvOp = Signed ? 11614 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 11615 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 11616 SDValue WidthConst = 11617 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 11618 dl, false); 11619 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 11620 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 11621 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 11622 DAG.getVTList(MVT::f64, MVT::Other), 11623 Ops, MVT::i8, LDN->getMemOperand()); 11624 11625 // For signed conversion, we need to sign-extend the value in the VSR 11626 if (Signed) { 11627 SDValue ExtOps[] = { Ld, WidthConst }; 11628 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 11629 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 11630 } else 11631 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 11632 } 11633 11634 // Don't handle ppc_fp128 here or i1 conversions. 11635 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 11636 return SDValue(); 11637 if (Op.getOperand(0).getValueType() == MVT::i1) 11638 return SDValue(); 11639 11640 // For i32 intermediate values, unfortunately, the conversion functions 11641 // leave the upper 32 bits of the value are undefined. Within the set of 11642 // scalar instructions, we have no method for zero- or sign-extending the 11643 // value. Thus, we cannot handle i32 intermediate values here. 11644 if (Op.getOperand(0).getValueType() == MVT::i32) 11645 return SDValue(); 11646 11647 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 11648 "UINT_TO_FP is supported only with FPCVT"); 11649 11650 // If we have FCFIDS, then use it when converting to single-precision. 11651 // Otherwise, convert to double-precision and then round. 11652 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11653 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 11654 : PPCISD::FCFIDS) 11655 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 11656 : PPCISD::FCFID); 11657 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11658 ? MVT::f32 11659 : MVT::f64; 11660 11661 // If we're converting from a float, to an int, and back to a float again, 11662 // then we don't need the store/load pair at all. 11663 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 11664 Subtarget.hasFPCVT()) || 11665 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 11666 SDValue Src = Op.getOperand(0).getOperand(0); 11667 if (Src.getValueType() == MVT::f32) { 11668 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 11669 DCI.AddToWorklist(Src.getNode()); 11670 } else if (Src.getValueType() != MVT::f64) { 11671 // Make sure that we don't pick up a ppc_fp128 source value. 11672 return SDValue(); 11673 } 11674 11675 unsigned FCTOp = 11676 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 11677 PPCISD::FCTIDUZ; 11678 11679 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 11680 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 11681 11682 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 11683 FP = DAG.getNode(ISD::FP_ROUND, dl, 11684 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 11685 DCI.AddToWorklist(FP.getNode()); 11686 } 11687 11688 return FP; 11689 } 11690 11691 return SDValue(); 11692 } 11693 11694 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 11695 // builtins) into loads with swaps. 11696 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 11697 DAGCombinerInfo &DCI) const { 11698 SelectionDAG &DAG = DCI.DAG; 11699 SDLoc dl(N); 11700 SDValue Chain; 11701 SDValue Base; 11702 MachineMemOperand *MMO; 11703 11704 switch (N->getOpcode()) { 11705 default: 11706 llvm_unreachable("Unexpected opcode for little endian VSX load"); 11707 case ISD::LOAD: { 11708 LoadSDNode *LD = cast<LoadSDNode>(N); 11709 Chain = LD->getChain(); 11710 Base = LD->getBasePtr(); 11711 MMO = LD->getMemOperand(); 11712 // If the MMO suggests this isn't a load of a full vector, leave 11713 // things alone. For a built-in, we have to make the change for 11714 // correctness, so if there is a size problem that will be a bug. 11715 if (MMO->getSize() < 16) 11716 return SDValue(); 11717 break; 11718 } 11719 case ISD::INTRINSIC_W_CHAIN: { 11720 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11721 Chain = Intrin->getChain(); 11722 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 11723 // us what we want. Get operand 2 instead. 11724 Base = Intrin->getOperand(2); 11725 MMO = Intrin->getMemOperand(); 11726 break; 11727 } 11728 } 11729 11730 MVT VecTy = N->getValueType(0).getSimpleVT(); 11731 11732 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 11733 // aligned and the type is a vector with elements up to 4 bytes 11734 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 11735 && VecTy.getScalarSizeInBits() <= 32 ) { 11736 return SDValue(); 11737 } 11738 11739 SDValue LoadOps[] = { Chain, Base }; 11740 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 11741 DAG.getVTList(MVT::v2f64, MVT::Other), 11742 LoadOps, MVT::v2f64, MMO); 11743 11744 DCI.AddToWorklist(Load.getNode()); 11745 Chain = Load.getValue(1); 11746 SDValue Swap = DAG.getNode( 11747 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 11748 DCI.AddToWorklist(Swap.getNode()); 11749 11750 // Add a bitcast if the resulting load type doesn't match v2f64. 11751 if (VecTy != MVT::v2f64) { 11752 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 11753 DCI.AddToWorklist(N.getNode()); 11754 // Package {bitcast value, swap's chain} to match Load's shape. 11755 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 11756 N, Swap.getValue(1)); 11757 } 11758 11759 return Swap; 11760 } 11761 11762 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 11763 // builtins) into stores with swaps. 11764 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 11765 DAGCombinerInfo &DCI) const { 11766 SelectionDAG &DAG = DCI.DAG; 11767 SDLoc dl(N); 11768 SDValue Chain; 11769 SDValue Base; 11770 unsigned SrcOpnd; 11771 MachineMemOperand *MMO; 11772 11773 switch (N->getOpcode()) { 11774 default: 11775 llvm_unreachable("Unexpected opcode for little endian VSX store"); 11776 case ISD::STORE: { 11777 StoreSDNode *ST = cast<StoreSDNode>(N); 11778 Chain = ST->getChain(); 11779 Base = ST->getBasePtr(); 11780 MMO = ST->getMemOperand(); 11781 SrcOpnd = 1; 11782 // If the MMO suggests this isn't a store of a full vector, leave 11783 // things alone. For a built-in, we have to make the change for 11784 // correctness, so if there is a size problem that will be a bug. 11785 if (MMO->getSize() < 16) 11786 return SDValue(); 11787 break; 11788 } 11789 case ISD::INTRINSIC_VOID: { 11790 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11791 Chain = Intrin->getChain(); 11792 // Intrin->getBasePtr() oddly does not get what we want. 11793 Base = Intrin->getOperand(3); 11794 MMO = Intrin->getMemOperand(); 11795 SrcOpnd = 2; 11796 break; 11797 } 11798 } 11799 11800 SDValue Src = N->getOperand(SrcOpnd); 11801 MVT VecTy = Src.getValueType().getSimpleVT(); 11802 11803 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 11804 // aligned and the type is a vector with elements up to 4 bytes 11805 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 11806 && VecTy.getScalarSizeInBits() <= 32 ) { 11807 return SDValue(); 11808 } 11809 11810 // All stores are done as v2f64 and possible bit cast. 11811 if (VecTy != MVT::v2f64) { 11812 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 11813 DCI.AddToWorklist(Src.getNode()); 11814 } 11815 11816 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 11817 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 11818 DCI.AddToWorklist(Swap.getNode()); 11819 Chain = Swap.getValue(1); 11820 SDValue StoreOps[] = { Chain, Swap, Base }; 11821 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 11822 DAG.getVTList(MVT::Other), 11823 StoreOps, VecTy, MMO); 11824 DCI.AddToWorklist(Store.getNode()); 11825 return Store; 11826 } 11827 11828 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 11829 DAGCombinerInfo &DCI) const { 11830 SelectionDAG &DAG = DCI.DAG; 11831 SDLoc dl(N); 11832 switch (N->getOpcode()) { 11833 default: break; 11834 case ISD::SHL: 11835 return combineSHL(N, DCI); 11836 case ISD::SRA: 11837 return combineSRA(N, DCI); 11838 case ISD::SRL: 11839 return combineSRL(N, DCI); 11840 case PPCISD::SHL: 11841 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 11842 return N->getOperand(0); 11843 break; 11844 case PPCISD::SRL: 11845 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 11846 return N->getOperand(0); 11847 break; 11848 case PPCISD::SRA: 11849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11850 if (C->isNullValue() || // 0 >>s V -> 0. 11851 C->isAllOnesValue()) // -1 >>s V -> -1. 11852 return N->getOperand(0); 11853 } 11854 break; 11855 case ISD::SIGN_EXTEND: 11856 case ISD::ZERO_EXTEND: 11857 case ISD::ANY_EXTEND: 11858 return DAGCombineExtBoolTrunc(N, DCI); 11859 case ISD::TRUNCATE: 11860 case ISD::SETCC: 11861 case ISD::SELECT_CC: 11862 return DAGCombineTruncBoolExt(N, DCI); 11863 case ISD::SINT_TO_FP: 11864 case ISD::UINT_TO_FP: 11865 return combineFPToIntToFP(N, DCI); 11866 case ISD::STORE: { 11867 EVT Op1VT = N->getOperand(1).getValueType(); 11868 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) || 11869 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16)); 11870 11871 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 11872 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 11873 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 11874 ValidTypeForStoreFltAsInt && 11875 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 11876 SDValue Val = N->getOperand(1).getOperand(0); 11877 if (Val.getValueType() == MVT::f32) { 11878 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 11879 DCI.AddToWorklist(Val.getNode()); 11880 } 11881 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 11882 DCI.AddToWorklist(Val.getNode()); 11883 11884 if (Op1VT == MVT::i32) { 11885 SDValue Ops[] = { 11886 N->getOperand(0), Val, N->getOperand(2), 11887 DAG.getValueType(N->getOperand(1).getValueType()) 11888 }; 11889 11890 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 11891 DAG.getVTList(MVT::Other), Ops, 11892 cast<StoreSDNode>(N)->getMemoryVT(), 11893 cast<StoreSDNode>(N)->getMemOperand()); 11894 } else { 11895 unsigned WidthInBytes = 11896 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2; 11897 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false); 11898 11899 SDValue Ops[] = { 11900 N->getOperand(0), Val, N->getOperand(2), WidthConst, 11901 DAG.getValueType(N->getOperand(1).getValueType()) 11902 }; 11903 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl, 11904 DAG.getVTList(MVT::Other), Ops, 11905 cast<StoreSDNode>(N)->getMemoryVT(), 11906 cast<StoreSDNode>(N)->getMemOperand()); 11907 } 11908 11909 DCI.AddToWorklist(Val.getNode()); 11910 return Val; 11911 } 11912 11913 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 11914 if (cast<StoreSDNode>(N)->isUnindexed() && 11915 N->getOperand(1).getOpcode() == ISD::BSWAP && 11916 N->getOperand(1).getNode()->hasOneUse() && 11917 (N->getOperand(1).getValueType() == MVT::i32 || 11918 N->getOperand(1).getValueType() == MVT::i16 || 11919 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 11920 N->getOperand(1).getValueType() == MVT::i64))) { 11921 SDValue BSwapOp = N->getOperand(1).getOperand(0); 11922 // Do an any-extend to 32-bits if this is a half-word input. 11923 if (BSwapOp.getValueType() == MVT::i16) 11924 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 11925 11926 // If the type of BSWAP operand is wider than stored memory width 11927 // it need to be shifted to the right side before STBRX. 11928 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 11929 if (Op1VT.bitsGT(mVT)) { 11930 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 11931 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 11932 DAG.getConstant(Shift, dl, MVT::i32)); 11933 // Need to truncate if this is a bswap of i64 stored as i32/i16. 11934 if (Op1VT == MVT::i64) 11935 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 11936 } 11937 11938 SDValue Ops[] = { 11939 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 11940 }; 11941 return 11942 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 11943 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 11944 cast<StoreSDNode>(N)->getMemOperand()); 11945 } 11946 11947 // For little endian, VSX stores require generating xxswapd/lxvd2x. 11948 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 11949 EVT VT = N->getOperand(1).getValueType(); 11950 if (VT.isSimple()) { 11951 MVT StoreVT = VT.getSimpleVT(); 11952 if (Subtarget.needsSwapsForVSXMemOps() && 11953 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 11954 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 11955 return expandVSXStoreForLE(N, DCI); 11956 } 11957 break; 11958 } 11959 case ISD::LOAD: { 11960 LoadSDNode *LD = cast<LoadSDNode>(N); 11961 EVT VT = LD->getValueType(0); 11962 11963 // For little endian, VSX loads require generating lxvd2x/xxswapd. 11964 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 11965 if (VT.isSimple()) { 11966 MVT LoadVT = VT.getSimpleVT(); 11967 if (Subtarget.needsSwapsForVSXMemOps() && 11968 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 11969 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 11970 return expandVSXLoadForLE(N, DCI); 11971 } 11972 11973 // We sometimes end up with a 64-bit integer load, from which we extract 11974 // two single-precision floating-point numbers. This happens with 11975 // std::complex<float>, and other similar structures, because of the way we 11976 // canonicalize structure copies. However, if we lack direct moves, 11977 // then the final bitcasts from the extracted integer values to the 11978 // floating-point numbers turn into store/load pairs. Even with direct moves, 11979 // just loading the two floating-point numbers is likely better. 11980 auto ReplaceTwoFloatLoad = [&]() { 11981 if (VT != MVT::i64) 11982 return false; 11983 11984 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 11985 LD->isVolatile()) 11986 return false; 11987 11988 // We're looking for a sequence like this: 11989 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 11990 // t16: i64 = srl t13, Constant:i32<32> 11991 // t17: i32 = truncate t16 11992 // t18: f32 = bitcast t17 11993 // t19: i32 = truncate t13 11994 // t20: f32 = bitcast t19 11995 11996 if (!LD->hasNUsesOfValue(2, 0)) 11997 return false; 11998 11999 auto UI = LD->use_begin(); 12000 while (UI.getUse().getResNo() != 0) ++UI; 12001 SDNode *Trunc = *UI++; 12002 while (UI.getUse().getResNo() != 0) ++UI; 12003 SDNode *RightShift = *UI; 12004 if (Trunc->getOpcode() != ISD::TRUNCATE) 12005 std::swap(Trunc, RightShift); 12006 12007 if (Trunc->getOpcode() != ISD::TRUNCATE || 12008 Trunc->getValueType(0) != MVT::i32 || 12009 !Trunc->hasOneUse()) 12010 return false; 12011 if (RightShift->getOpcode() != ISD::SRL || 12012 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12013 RightShift->getConstantOperandVal(1) != 32 || 12014 !RightShift->hasOneUse()) 12015 return false; 12016 12017 SDNode *Trunc2 = *RightShift->use_begin(); 12018 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12019 Trunc2->getValueType(0) != MVT::i32 || 12020 !Trunc2->hasOneUse()) 12021 return false; 12022 12023 SDNode *Bitcast = *Trunc->use_begin(); 12024 SDNode *Bitcast2 = *Trunc2->use_begin(); 12025 12026 if (Bitcast->getOpcode() != ISD::BITCAST || 12027 Bitcast->getValueType(0) != MVT::f32) 12028 return false; 12029 if (Bitcast2->getOpcode() != ISD::BITCAST || 12030 Bitcast2->getValueType(0) != MVT::f32) 12031 return false; 12032 12033 if (Subtarget.isLittleEndian()) 12034 std::swap(Bitcast, Bitcast2); 12035 12036 // Bitcast has the second float (in memory-layout order) and Bitcast2 12037 // has the first one. 12038 12039 SDValue BasePtr = LD->getBasePtr(); 12040 if (LD->isIndexed()) { 12041 assert(LD->getAddressingMode() == ISD::PRE_INC && 12042 "Non-pre-inc AM on PPC?"); 12043 BasePtr = 12044 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12045 LD->getOffset()); 12046 } 12047 12048 auto MMOFlags = 12049 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12050 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12051 LD->getPointerInfo(), LD->getAlignment(), 12052 MMOFlags, LD->getAAInfo()); 12053 SDValue AddPtr = 12054 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12055 BasePtr, DAG.getIntPtrConstant(4, dl)); 12056 SDValue FloatLoad2 = DAG.getLoad( 12057 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12058 LD->getPointerInfo().getWithOffset(4), 12059 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12060 12061 if (LD->isIndexed()) { 12062 // Note that DAGCombine should re-form any pre-increment load(s) from 12063 // what is produced here if that makes sense. 12064 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12065 } 12066 12067 DCI.CombineTo(Bitcast2, FloatLoad); 12068 DCI.CombineTo(Bitcast, FloatLoad2); 12069 12070 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12071 SDValue(FloatLoad2.getNode(), 1)); 12072 return true; 12073 }; 12074 12075 if (ReplaceTwoFloatLoad()) 12076 return SDValue(N, 0); 12077 12078 EVT MemVT = LD->getMemoryVT(); 12079 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12080 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12081 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12082 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12083 if (LD->isUnindexed() && VT.isVector() && 12084 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12085 // P8 and later hardware should just use LOAD. 12086 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12087 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12088 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12089 LD->getAlignment() >= ScalarABIAlignment)) && 12090 LD->getAlignment() < ABIAlignment) { 12091 // This is a type-legal unaligned Altivec or QPX load. 12092 SDValue Chain = LD->getChain(); 12093 SDValue Ptr = LD->getBasePtr(); 12094 bool isLittleEndian = Subtarget.isLittleEndian(); 12095 12096 // This implements the loading of unaligned vectors as described in 12097 // the venerable Apple Velocity Engine overview. Specifically: 12098 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12099 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12100 // 12101 // The general idea is to expand a sequence of one or more unaligned 12102 // loads into an alignment-based permutation-control instruction (lvsl 12103 // or lvsr), a series of regular vector loads (which always truncate 12104 // their input address to an aligned address), and a series of 12105 // permutations. The results of these permutations are the requested 12106 // loaded values. The trick is that the last "extra" load is not taken 12107 // from the address you might suspect (sizeof(vector) bytes after the 12108 // last requested load), but rather sizeof(vector) - 1 bytes after the 12109 // last requested vector. The point of this is to avoid a page fault if 12110 // the base address happened to be aligned. This works because if the 12111 // base address is aligned, then adding less than a full vector length 12112 // will cause the last vector in the sequence to be (re)loaded. 12113 // Otherwise, the next vector will be fetched as you might suspect was 12114 // necessary. 12115 12116 // We might be able to reuse the permutation generation from 12117 // a different base address offset from this one by an aligned amount. 12118 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12119 // optimization later. 12120 Intrinsic::ID Intr, IntrLD, IntrPerm; 12121 MVT PermCntlTy, PermTy, LDTy; 12122 if (Subtarget.hasAltivec()) { 12123 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12124 Intrinsic::ppc_altivec_lvsl; 12125 IntrLD = Intrinsic::ppc_altivec_lvx; 12126 IntrPerm = Intrinsic::ppc_altivec_vperm; 12127 PermCntlTy = MVT::v16i8; 12128 PermTy = MVT::v4i32; 12129 LDTy = MVT::v4i32; 12130 } else { 12131 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12132 Intrinsic::ppc_qpx_qvlpcls; 12133 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12134 Intrinsic::ppc_qpx_qvlfs; 12135 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12136 PermCntlTy = MVT::v4f64; 12137 PermTy = MVT::v4f64; 12138 LDTy = MemVT.getSimpleVT(); 12139 } 12140 12141 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12142 12143 // Create the new MMO for the new base load. It is like the original MMO, 12144 // but represents an area in memory almost twice the vector size centered 12145 // on the original address. If the address is unaligned, we might start 12146 // reading up to (sizeof(vector)-1) bytes below the address of the 12147 // original unaligned load. 12148 MachineFunction &MF = DAG.getMachineFunction(); 12149 MachineMemOperand *BaseMMO = 12150 MF.getMachineMemOperand(LD->getMemOperand(), 12151 -(long)MemVT.getStoreSize()+1, 12152 2*MemVT.getStoreSize()-1); 12153 12154 // Create the new base load. 12155 SDValue LDXIntID = 12156 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12157 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12158 SDValue BaseLoad = 12159 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12160 DAG.getVTList(PermTy, MVT::Other), 12161 BaseLoadOps, LDTy, BaseMMO); 12162 12163 // Note that the value of IncOffset (which is provided to the next 12164 // load's pointer info offset value, and thus used to calculate the 12165 // alignment), and the value of IncValue (which is actually used to 12166 // increment the pointer value) are different! This is because we 12167 // require the next load to appear to be aligned, even though it 12168 // is actually offset from the base pointer by a lesser amount. 12169 int IncOffset = VT.getSizeInBits() / 8; 12170 int IncValue = IncOffset; 12171 12172 // Walk (both up and down) the chain looking for another load at the real 12173 // (aligned) offset (the alignment of the other load does not matter in 12174 // this case). If found, then do not use the offset reduction trick, as 12175 // that will prevent the loads from being later combined (as they would 12176 // otherwise be duplicates). 12177 if (!findConsecutiveLoad(LD, DAG)) 12178 --IncValue; 12179 12180 SDValue Increment = 12181 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12182 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12183 12184 MachineMemOperand *ExtraMMO = 12185 MF.getMachineMemOperand(LD->getMemOperand(), 12186 1, 2*MemVT.getStoreSize()-1); 12187 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12188 SDValue ExtraLoad = 12189 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12190 DAG.getVTList(PermTy, MVT::Other), 12191 ExtraLoadOps, LDTy, ExtraMMO); 12192 12193 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12194 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12195 12196 // Because vperm has a big-endian bias, we must reverse the order 12197 // of the input vectors and complement the permute control vector 12198 // when generating little endian code. We have already handled the 12199 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12200 // and ExtraLoad here. 12201 SDValue Perm; 12202 if (isLittleEndian) 12203 Perm = BuildIntrinsicOp(IntrPerm, 12204 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12205 else 12206 Perm = BuildIntrinsicOp(IntrPerm, 12207 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12208 12209 if (VT != PermTy) 12210 Perm = Subtarget.hasAltivec() ? 12211 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12212 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12213 DAG.getTargetConstant(1, dl, MVT::i64)); 12214 // second argument is 1 because this rounding 12215 // is always exact. 12216 12217 // The output of the permutation is our loaded result, the TokenFactor is 12218 // our new chain. 12219 DCI.CombineTo(N, Perm, TF); 12220 return SDValue(N, 0); 12221 } 12222 } 12223 break; 12224 case ISD::INTRINSIC_WO_CHAIN: { 12225 bool isLittleEndian = Subtarget.isLittleEndian(); 12226 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12227 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12228 : Intrinsic::ppc_altivec_lvsl); 12229 if ((IID == Intr || 12230 IID == Intrinsic::ppc_qpx_qvlpcld || 12231 IID == Intrinsic::ppc_qpx_qvlpcls) && 12232 N->getOperand(1)->getOpcode() == ISD::ADD) { 12233 SDValue Add = N->getOperand(1); 12234 12235 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12236 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12237 12238 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12239 APInt::getAllOnesValue(Bits /* alignment */) 12240 .zext(Add.getScalarValueSizeInBits()))) { 12241 SDNode *BasePtr = Add->getOperand(0).getNode(); 12242 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12243 UE = BasePtr->use_end(); 12244 UI != UE; ++UI) { 12245 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12246 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12247 // We've found another LVSL/LVSR, and this address is an aligned 12248 // multiple of that one. The results will be the same, so use the 12249 // one we've just found instead. 12250 12251 return SDValue(*UI, 0); 12252 } 12253 } 12254 } 12255 12256 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12257 SDNode *BasePtr = Add->getOperand(0).getNode(); 12258 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12259 UE = BasePtr->use_end(); UI != UE; ++UI) { 12260 if (UI->getOpcode() == ISD::ADD && 12261 isa<ConstantSDNode>(UI->getOperand(1)) && 12262 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12263 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12264 (1ULL << Bits) == 0) { 12265 SDNode *OtherAdd = *UI; 12266 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12267 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12268 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12269 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12270 return SDValue(*VI, 0); 12271 } 12272 } 12273 } 12274 } 12275 } 12276 } 12277 } 12278 12279 break; 12280 case ISD::INTRINSIC_W_CHAIN: 12281 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12282 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12283 if (Subtarget.needsSwapsForVSXMemOps()) { 12284 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12285 default: 12286 break; 12287 case Intrinsic::ppc_vsx_lxvw4x: 12288 case Intrinsic::ppc_vsx_lxvd2x: 12289 return expandVSXLoadForLE(N, DCI); 12290 } 12291 } 12292 break; 12293 case ISD::INTRINSIC_VOID: 12294 // For little endian, VSX stores require generating xxswapd/stxvd2x. 12295 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12296 if (Subtarget.needsSwapsForVSXMemOps()) { 12297 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12298 default: 12299 break; 12300 case Intrinsic::ppc_vsx_stxvw4x: 12301 case Intrinsic::ppc_vsx_stxvd2x: 12302 return expandVSXStoreForLE(N, DCI); 12303 } 12304 } 12305 break; 12306 case ISD::BSWAP: 12307 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 12308 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 12309 N->getOperand(0).hasOneUse() && 12310 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 12311 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12312 N->getValueType(0) == MVT::i64))) { 12313 SDValue Load = N->getOperand(0); 12314 LoadSDNode *LD = cast<LoadSDNode>(Load); 12315 // Create the byte-swapping load. 12316 SDValue Ops[] = { 12317 LD->getChain(), // Chain 12318 LD->getBasePtr(), // Ptr 12319 DAG.getValueType(N->getValueType(0)) // VT 12320 }; 12321 SDValue BSLoad = 12322 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 12323 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 12324 MVT::i64 : MVT::i32, MVT::Other), 12325 Ops, LD->getMemoryVT(), LD->getMemOperand()); 12326 12327 // If this is an i16 load, insert the truncate. 12328 SDValue ResVal = BSLoad; 12329 if (N->getValueType(0) == MVT::i16) 12330 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 12331 12332 // First, combine the bswap away. This makes the value produced by the 12333 // load dead. 12334 DCI.CombineTo(N, ResVal); 12335 12336 // Next, combine the load away, we give it a bogus result value but a real 12337 // chain result. The result value is dead because the bswap is dead. 12338 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 12339 12340 // Return N so it doesn't get rechecked! 12341 return SDValue(N, 0); 12342 } 12343 break; 12344 case PPCISD::VCMP: 12345 // If a VCMPo node already exists with exactly the same operands as this 12346 // node, use its result instead of this node (VCMPo computes both a CR6 and 12347 // a normal output). 12348 // 12349 if (!N->getOperand(0).hasOneUse() && 12350 !N->getOperand(1).hasOneUse() && 12351 !N->getOperand(2).hasOneUse()) { 12352 12353 // Scan all of the users of the LHS, looking for VCMPo's that match. 12354 SDNode *VCMPoNode = nullptr; 12355 12356 SDNode *LHSN = N->getOperand(0).getNode(); 12357 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 12358 UI != E; ++UI) 12359 if (UI->getOpcode() == PPCISD::VCMPo && 12360 UI->getOperand(1) == N->getOperand(1) && 12361 UI->getOperand(2) == N->getOperand(2) && 12362 UI->getOperand(0) == N->getOperand(0)) { 12363 VCMPoNode = *UI; 12364 break; 12365 } 12366 12367 // If there is no VCMPo node, or if the flag value has a single use, don't 12368 // transform this. 12369 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 12370 break; 12371 12372 // Look at the (necessarily single) use of the flag value. If it has a 12373 // chain, this transformation is more complex. Note that multiple things 12374 // could use the value result, which we should ignore. 12375 SDNode *FlagUser = nullptr; 12376 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 12377 FlagUser == nullptr; ++UI) { 12378 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 12379 SDNode *User = *UI; 12380 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 12381 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 12382 FlagUser = User; 12383 break; 12384 } 12385 } 12386 } 12387 12388 // If the user is a MFOCRF instruction, we know this is safe. 12389 // Otherwise we give up for right now. 12390 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 12391 return SDValue(VCMPoNode, 0); 12392 } 12393 break; 12394 case ISD::BRCOND: { 12395 SDValue Cond = N->getOperand(1); 12396 SDValue Target = N->getOperand(2); 12397 12398 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12399 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 12400 Intrinsic::ppc_is_decremented_ctr_nonzero) { 12401 12402 // We now need to make the intrinsic dead (it cannot be instruction 12403 // selected). 12404 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 12405 assert(Cond.getNode()->hasOneUse() && 12406 "Counter decrement has more than one use"); 12407 12408 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 12409 N->getOperand(0), Target); 12410 } 12411 } 12412 break; 12413 case ISD::BR_CC: { 12414 // If this is a branch on an altivec predicate comparison, lower this so 12415 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 12416 // lowering is done pre-legalize, because the legalizer lowers the predicate 12417 // compare down to code that is difficult to reassemble. 12418 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 12419 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 12420 12421 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 12422 // value. If so, pass-through the AND to get to the intrinsic. 12423 if (LHS.getOpcode() == ISD::AND && 12424 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 12425 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 12426 Intrinsic::ppc_is_decremented_ctr_nonzero && 12427 isa<ConstantSDNode>(LHS.getOperand(1)) && 12428 !isNullConstant(LHS.getOperand(1))) 12429 LHS = LHS.getOperand(0); 12430 12431 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12432 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 12433 Intrinsic::ppc_is_decremented_ctr_nonzero && 12434 isa<ConstantSDNode>(RHS)) { 12435 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 12436 "Counter decrement comparison is not EQ or NE"); 12437 12438 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12439 bool isBDNZ = (CC == ISD::SETEQ && Val) || 12440 (CC == ISD::SETNE && !Val); 12441 12442 // We now need to make the intrinsic dead (it cannot be instruction 12443 // selected). 12444 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 12445 assert(LHS.getNode()->hasOneUse() && 12446 "Counter decrement has more than one use"); 12447 12448 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 12449 N->getOperand(0), N->getOperand(4)); 12450 } 12451 12452 int CompareOpc; 12453 bool isDot; 12454 12455 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12456 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 12457 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 12458 assert(isDot && "Can't compare against a vector result!"); 12459 12460 // If this is a comparison against something other than 0/1, then we know 12461 // that the condition is never/always true. 12462 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12463 if (Val != 0 && Val != 1) { 12464 if (CC == ISD::SETEQ) // Cond never true, remove branch. 12465 return N->getOperand(0); 12466 // Always !=, turn it into an unconditional branch. 12467 return DAG.getNode(ISD::BR, dl, MVT::Other, 12468 N->getOperand(0), N->getOperand(4)); 12469 } 12470 12471 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 12472 12473 // Create the PPCISD altivec 'dot' comparison node. 12474 SDValue Ops[] = { 12475 LHS.getOperand(2), // LHS of compare 12476 LHS.getOperand(3), // RHS of compare 12477 DAG.getConstant(CompareOpc, dl, MVT::i32) 12478 }; 12479 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 12480 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 12481 12482 // Unpack the result based on how the target uses it. 12483 PPC::Predicate CompOpc; 12484 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 12485 default: // Can't happen, don't crash on invalid number though. 12486 case 0: // Branch on the value of the EQ bit of CR6. 12487 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 12488 break; 12489 case 1: // Branch on the inverted value of the EQ bit of CR6. 12490 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 12491 break; 12492 case 2: // Branch on the value of the LT bit of CR6. 12493 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 12494 break; 12495 case 3: // Branch on the inverted value of the LT bit of CR6. 12496 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 12497 break; 12498 } 12499 12500 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 12501 DAG.getConstant(CompOpc, dl, MVT::i32), 12502 DAG.getRegister(PPC::CR6, MVT::i32), 12503 N->getOperand(4), CompNode.getValue(1)); 12504 } 12505 break; 12506 } 12507 case ISD::BUILD_VECTOR: 12508 return DAGCombineBuildVector(N, DCI); 12509 } 12510 12511 return SDValue(); 12512 } 12513 12514 SDValue 12515 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12516 SelectionDAG &DAG, 12517 std::vector<SDNode *> *Created) const { 12518 // fold (sdiv X, pow2) 12519 EVT VT = N->getValueType(0); 12520 if (VT == MVT::i64 && !Subtarget.isPPC64()) 12521 return SDValue(); 12522 if ((VT != MVT::i32 && VT != MVT::i64) || 12523 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 12524 return SDValue(); 12525 12526 SDLoc DL(N); 12527 SDValue N0 = N->getOperand(0); 12528 12529 bool IsNegPow2 = (-Divisor).isPowerOf2(); 12530 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 12531 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 12532 12533 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 12534 if (Created) 12535 Created->push_back(Op.getNode()); 12536 12537 if (IsNegPow2) { 12538 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 12539 if (Created) 12540 Created->push_back(Op.getNode()); 12541 } 12542 12543 return Op; 12544 } 12545 12546 //===----------------------------------------------------------------------===// 12547 // Inline Assembly Support 12548 //===----------------------------------------------------------------------===// 12549 12550 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12551 KnownBits &Known, 12552 const APInt &DemandedElts, 12553 const SelectionDAG &DAG, 12554 unsigned Depth) const { 12555 Known.resetAll(); 12556 switch (Op.getOpcode()) { 12557 default: break; 12558 case PPCISD::LBRX: { 12559 // lhbrx is known to have the top bits cleared out. 12560 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 12561 Known.Zero = 0xFFFF0000; 12562 break; 12563 } 12564 case ISD::INTRINSIC_WO_CHAIN: { 12565 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 12566 default: break; 12567 case Intrinsic::ppc_altivec_vcmpbfp_p: 12568 case Intrinsic::ppc_altivec_vcmpeqfp_p: 12569 case Intrinsic::ppc_altivec_vcmpequb_p: 12570 case Intrinsic::ppc_altivec_vcmpequh_p: 12571 case Intrinsic::ppc_altivec_vcmpequw_p: 12572 case Intrinsic::ppc_altivec_vcmpequd_p: 12573 case Intrinsic::ppc_altivec_vcmpgefp_p: 12574 case Intrinsic::ppc_altivec_vcmpgtfp_p: 12575 case Intrinsic::ppc_altivec_vcmpgtsb_p: 12576 case Intrinsic::ppc_altivec_vcmpgtsh_p: 12577 case Intrinsic::ppc_altivec_vcmpgtsw_p: 12578 case Intrinsic::ppc_altivec_vcmpgtsd_p: 12579 case Intrinsic::ppc_altivec_vcmpgtub_p: 12580 case Intrinsic::ppc_altivec_vcmpgtuh_p: 12581 case Intrinsic::ppc_altivec_vcmpgtuw_p: 12582 case Intrinsic::ppc_altivec_vcmpgtud_p: 12583 Known.Zero = ~1U; // All bits but the low one are known to be zero. 12584 break; 12585 } 12586 } 12587 } 12588 } 12589 12590 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12591 switch (Subtarget.getDarwinDirective()) { 12592 default: break; 12593 case PPC::DIR_970: 12594 case PPC::DIR_PWR4: 12595 case PPC::DIR_PWR5: 12596 case PPC::DIR_PWR5X: 12597 case PPC::DIR_PWR6: 12598 case PPC::DIR_PWR6X: 12599 case PPC::DIR_PWR7: 12600 case PPC::DIR_PWR8: 12601 case PPC::DIR_PWR9: { 12602 if (!ML) 12603 break; 12604 12605 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 12606 12607 // For small loops (between 5 and 8 instructions), align to a 32-byte 12608 // boundary so that the entire loop fits in one instruction-cache line. 12609 uint64_t LoopSize = 0; 12610 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 12611 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 12612 LoopSize += TII->getInstSizeInBytes(*J); 12613 if (LoopSize > 32) 12614 break; 12615 } 12616 12617 if (LoopSize > 16 && LoopSize <= 32) 12618 return 5; 12619 12620 break; 12621 } 12622 } 12623 12624 return TargetLowering::getPrefLoopAlignment(ML); 12625 } 12626 12627 /// getConstraintType - Given a constraint, return the type of 12628 /// constraint it is for this target. 12629 PPCTargetLowering::ConstraintType 12630 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 12631 if (Constraint.size() == 1) { 12632 switch (Constraint[0]) { 12633 default: break; 12634 case 'b': 12635 case 'r': 12636 case 'f': 12637 case 'd': 12638 case 'v': 12639 case 'y': 12640 return C_RegisterClass; 12641 case 'Z': 12642 // FIXME: While Z does indicate a memory constraint, it specifically 12643 // indicates an r+r address (used in conjunction with the 'y' modifier 12644 // in the replacement string). Currently, we're forcing the base 12645 // register to be r0 in the asm printer (which is interpreted as zero) 12646 // and forming the complete address in the second register. This is 12647 // suboptimal. 12648 return C_Memory; 12649 } 12650 } else if (Constraint == "wc") { // individual CR bits. 12651 return C_RegisterClass; 12652 } else if (Constraint == "wa" || Constraint == "wd" || 12653 Constraint == "wf" || Constraint == "ws") { 12654 return C_RegisterClass; // VSX registers. 12655 } 12656 return TargetLowering::getConstraintType(Constraint); 12657 } 12658 12659 /// Examine constraint type and operand type and determine a weight value. 12660 /// This object must already have been set up with the operand type 12661 /// and the current alternative constraint selected. 12662 TargetLowering::ConstraintWeight 12663 PPCTargetLowering::getSingleConstraintMatchWeight( 12664 AsmOperandInfo &info, const char *constraint) const { 12665 ConstraintWeight weight = CW_Invalid; 12666 Value *CallOperandVal = info.CallOperandVal; 12667 // If we don't have a value, we can't do a match, 12668 // but allow it at the lowest weight. 12669 if (!CallOperandVal) 12670 return CW_Default; 12671 Type *type = CallOperandVal->getType(); 12672 12673 // Look at the constraint type. 12674 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 12675 return CW_Register; // an individual CR bit. 12676 else if ((StringRef(constraint) == "wa" || 12677 StringRef(constraint) == "wd" || 12678 StringRef(constraint) == "wf") && 12679 type->isVectorTy()) 12680 return CW_Register; 12681 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 12682 return CW_Register; 12683 12684 switch (*constraint) { 12685 default: 12686 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12687 break; 12688 case 'b': 12689 if (type->isIntegerTy()) 12690 weight = CW_Register; 12691 break; 12692 case 'f': 12693 if (type->isFloatTy()) 12694 weight = CW_Register; 12695 break; 12696 case 'd': 12697 if (type->isDoubleTy()) 12698 weight = CW_Register; 12699 break; 12700 case 'v': 12701 if (type->isVectorTy()) 12702 weight = CW_Register; 12703 break; 12704 case 'y': 12705 weight = CW_Register; 12706 break; 12707 case 'Z': 12708 weight = CW_Memory; 12709 break; 12710 } 12711 return weight; 12712 } 12713 12714 std::pair<unsigned, const TargetRegisterClass *> 12715 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 12716 StringRef Constraint, 12717 MVT VT) const { 12718 if (Constraint.size() == 1) { 12719 // GCC RS6000 Constraint Letters 12720 switch (Constraint[0]) { 12721 case 'b': // R1-R31 12722 if (VT == MVT::i64 && Subtarget.isPPC64()) 12723 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 12724 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 12725 case 'r': // R0-R31 12726 if (VT == MVT::i64 && Subtarget.isPPC64()) 12727 return std::make_pair(0U, &PPC::G8RCRegClass); 12728 return std::make_pair(0U, &PPC::GPRCRegClass); 12729 // 'd' and 'f' constraints are both defined to be "the floating point 12730 // registers", where one is for 32-bit and the other for 64-bit. We don't 12731 // really care overly much here so just give them all the same reg classes. 12732 case 'd': 12733 case 'f': 12734 if (VT == MVT::f32 || VT == MVT::i32) 12735 return std::make_pair(0U, &PPC::F4RCRegClass); 12736 if (VT == MVT::f64 || VT == MVT::i64) 12737 return std::make_pair(0U, &PPC::F8RCRegClass); 12738 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 12739 return std::make_pair(0U, &PPC::QFRCRegClass); 12740 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 12741 return std::make_pair(0U, &PPC::QSRCRegClass); 12742 break; 12743 case 'v': 12744 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 12745 return std::make_pair(0U, &PPC::QFRCRegClass); 12746 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 12747 return std::make_pair(0U, &PPC::QSRCRegClass); 12748 if (Subtarget.hasAltivec()) 12749 return std::make_pair(0U, &PPC::VRRCRegClass); 12750 case 'y': // crrc 12751 return std::make_pair(0U, &PPC::CRRCRegClass); 12752 } 12753 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 12754 // An individual CR bit. 12755 return std::make_pair(0U, &PPC::CRBITRCRegClass); 12756 } else if ((Constraint == "wa" || Constraint == "wd" || 12757 Constraint == "wf") && Subtarget.hasVSX()) { 12758 return std::make_pair(0U, &PPC::VSRCRegClass); 12759 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 12760 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 12761 return std::make_pair(0U, &PPC::VSSRCRegClass); 12762 else 12763 return std::make_pair(0U, &PPC::VSFRCRegClass); 12764 } 12765 12766 std::pair<unsigned, const TargetRegisterClass *> R = 12767 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12768 12769 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 12770 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 12771 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 12772 // register. 12773 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 12774 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 12775 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 12776 PPC::GPRCRegClass.contains(R.first)) 12777 return std::make_pair(TRI->getMatchingSuperReg(R.first, 12778 PPC::sub_32, &PPC::G8RCRegClass), 12779 &PPC::G8RCRegClass); 12780 12781 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 12782 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 12783 R.first = PPC::CR0; 12784 R.second = &PPC::CRRCRegClass; 12785 } 12786 12787 return R; 12788 } 12789 12790 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12791 /// vector. If it is invalid, don't add anything to Ops. 12792 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12793 std::string &Constraint, 12794 std::vector<SDValue>&Ops, 12795 SelectionDAG &DAG) const { 12796 SDValue Result; 12797 12798 // Only support length 1 constraints. 12799 if (Constraint.length() > 1) return; 12800 12801 char Letter = Constraint[0]; 12802 switch (Letter) { 12803 default: break; 12804 case 'I': 12805 case 'J': 12806 case 'K': 12807 case 'L': 12808 case 'M': 12809 case 'N': 12810 case 'O': 12811 case 'P': { 12812 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 12813 if (!CST) return; // Must be an immediate to match. 12814 SDLoc dl(Op); 12815 int64_t Value = CST->getSExtValue(); 12816 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 12817 // numbers are printed as such. 12818 switch (Letter) { 12819 default: llvm_unreachable("Unknown constraint letter!"); 12820 case 'I': // "I" is a signed 16-bit constant. 12821 if (isInt<16>(Value)) 12822 Result = DAG.getTargetConstant(Value, dl, TCVT); 12823 break; 12824 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 12825 if (isShiftedUInt<16, 16>(Value)) 12826 Result = DAG.getTargetConstant(Value, dl, TCVT); 12827 break; 12828 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 12829 if (isShiftedInt<16, 16>(Value)) 12830 Result = DAG.getTargetConstant(Value, dl, TCVT); 12831 break; 12832 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 12833 if (isUInt<16>(Value)) 12834 Result = DAG.getTargetConstant(Value, dl, TCVT); 12835 break; 12836 case 'M': // "M" is a constant that is greater than 31. 12837 if (Value > 31) 12838 Result = DAG.getTargetConstant(Value, dl, TCVT); 12839 break; 12840 case 'N': // "N" is a positive constant that is an exact power of two. 12841 if (Value > 0 && isPowerOf2_64(Value)) 12842 Result = DAG.getTargetConstant(Value, dl, TCVT); 12843 break; 12844 case 'O': // "O" is the constant zero. 12845 if (Value == 0) 12846 Result = DAG.getTargetConstant(Value, dl, TCVT); 12847 break; 12848 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 12849 if (isInt<16>(-Value)) 12850 Result = DAG.getTargetConstant(Value, dl, TCVT); 12851 break; 12852 } 12853 break; 12854 } 12855 } 12856 12857 if (Result.getNode()) { 12858 Ops.push_back(Result); 12859 return; 12860 } 12861 12862 // Handle standard constraint letters. 12863 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12864 } 12865 12866 // isLegalAddressingMode - Return true if the addressing mode represented 12867 // by AM is legal for this target, for a load/store of the specified type. 12868 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12869 const AddrMode &AM, Type *Ty, 12870 unsigned AS, Instruction *I) const { 12871 // PPC does not allow r+i addressing modes for vectors! 12872 if (Ty->isVectorTy() && AM.BaseOffs != 0) 12873 return false; 12874 12875 // PPC allows a sign-extended 16-bit immediate field. 12876 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 12877 return false; 12878 12879 // No global is ever allowed as a base. 12880 if (AM.BaseGV) 12881 return false; 12882 12883 // PPC only support r+r, 12884 switch (AM.Scale) { 12885 case 0: // "r+i" or just "i", depending on HasBaseReg. 12886 break; 12887 case 1: 12888 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 12889 return false; 12890 // Otherwise we have r+r or r+i. 12891 break; 12892 case 2: 12893 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 12894 return false; 12895 // Allow 2*r as r+r. 12896 break; 12897 default: 12898 // No other scales are supported. 12899 return false; 12900 } 12901 12902 return true; 12903 } 12904 12905 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 12906 SelectionDAG &DAG) const { 12907 MachineFunction &MF = DAG.getMachineFunction(); 12908 MachineFrameInfo &MFI = MF.getFrameInfo(); 12909 MFI.setReturnAddressIsTaken(true); 12910 12911 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 12912 return SDValue(); 12913 12914 SDLoc dl(Op); 12915 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12916 12917 // Make sure the function does not optimize away the store of the RA to 12918 // the stack. 12919 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 12920 FuncInfo->setLRStoreRequired(); 12921 bool isPPC64 = Subtarget.isPPC64(); 12922 auto PtrVT = getPointerTy(MF.getDataLayout()); 12923 12924 if (Depth > 0) { 12925 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 12926 SDValue Offset = 12927 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 12928 isPPC64 ? MVT::i64 : MVT::i32); 12929 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 12930 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 12931 MachinePointerInfo()); 12932 } 12933 12934 // Just load the return address off the stack. 12935 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 12936 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 12937 MachinePointerInfo()); 12938 } 12939 12940 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 12941 SelectionDAG &DAG) const { 12942 SDLoc dl(Op); 12943 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12944 12945 MachineFunction &MF = DAG.getMachineFunction(); 12946 MachineFrameInfo &MFI = MF.getFrameInfo(); 12947 MFI.setFrameAddressIsTaken(true); 12948 12949 EVT PtrVT = getPointerTy(MF.getDataLayout()); 12950 bool isPPC64 = PtrVT == MVT::i64; 12951 12952 // Naked functions never have a frame pointer, and so we use r1. For all 12953 // other functions, this decision must be delayed until during PEI. 12954 unsigned FrameReg; 12955 if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) 12956 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 12957 else 12958 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 12959 12960 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 12961 PtrVT); 12962 while (Depth--) 12963 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 12964 FrameAddr, MachinePointerInfo()); 12965 return FrameAddr; 12966 } 12967 12968 // FIXME? Maybe this could be a TableGen attribute on some registers and 12969 // this table could be generated automatically from RegInfo. 12970 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 12971 SelectionDAG &DAG) const { 12972 bool isPPC64 = Subtarget.isPPC64(); 12973 bool isDarwinABI = Subtarget.isDarwinABI(); 12974 12975 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 12976 (!isPPC64 && VT != MVT::i32)) 12977 report_fatal_error("Invalid register global variable type"); 12978 12979 bool is64Bit = isPPC64 && VT == MVT::i64; 12980 unsigned Reg = StringSwitch<unsigned>(RegName) 12981 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 12982 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 12983 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 12984 (is64Bit ? PPC::X13 : PPC::R13)) 12985 .Default(0); 12986 12987 if (Reg) 12988 return Reg; 12989 report_fatal_error("Invalid register name global variable"); 12990 } 12991 12992 bool 12993 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12994 // The PowerPC target isn't yet aware of offsets. 12995 return false; 12996 } 12997 12998 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12999 const CallInst &I, 13000 unsigned Intrinsic) const { 13001 switch (Intrinsic) { 13002 case Intrinsic::ppc_qpx_qvlfd: 13003 case Intrinsic::ppc_qpx_qvlfs: 13004 case Intrinsic::ppc_qpx_qvlfcd: 13005 case Intrinsic::ppc_qpx_qvlfcs: 13006 case Intrinsic::ppc_qpx_qvlfiwa: 13007 case Intrinsic::ppc_qpx_qvlfiwz: 13008 case Intrinsic::ppc_altivec_lvx: 13009 case Intrinsic::ppc_altivec_lvxl: 13010 case Intrinsic::ppc_altivec_lvebx: 13011 case Intrinsic::ppc_altivec_lvehx: 13012 case Intrinsic::ppc_altivec_lvewx: 13013 case Intrinsic::ppc_vsx_lxvd2x: 13014 case Intrinsic::ppc_vsx_lxvw4x: { 13015 EVT VT; 13016 switch (Intrinsic) { 13017 case Intrinsic::ppc_altivec_lvebx: 13018 VT = MVT::i8; 13019 break; 13020 case Intrinsic::ppc_altivec_lvehx: 13021 VT = MVT::i16; 13022 break; 13023 case Intrinsic::ppc_altivec_lvewx: 13024 VT = MVT::i32; 13025 break; 13026 case Intrinsic::ppc_vsx_lxvd2x: 13027 VT = MVT::v2f64; 13028 break; 13029 case Intrinsic::ppc_qpx_qvlfd: 13030 VT = MVT::v4f64; 13031 break; 13032 case Intrinsic::ppc_qpx_qvlfs: 13033 VT = MVT::v4f32; 13034 break; 13035 case Intrinsic::ppc_qpx_qvlfcd: 13036 VT = MVT::v2f64; 13037 break; 13038 case Intrinsic::ppc_qpx_qvlfcs: 13039 VT = MVT::v2f32; 13040 break; 13041 default: 13042 VT = MVT::v4i32; 13043 break; 13044 } 13045 13046 Info.opc = ISD::INTRINSIC_W_CHAIN; 13047 Info.memVT = VT; 13048 Info.ptrVal = I.getArgOperand(0); 13049 Info.offset = -VT.getStoreSize()+1; 13050 Info.size = 2*VT.getStoreSize()-1; 13051 Info.align = 1; 13052 Info.vol = false; 13053 Info.readMem = true; 13054 Info.writeMem = false; 13055 return true; 13056 } 13057 case Intrinsic::ppc_qpx_qvlfda: 13058 case Intrinsic::ppc_qpx_qvlfsa: 13059 case Intrinsic::ppc_qpx_qvlfcda: 13060 case Intrinsic::ppc_qpx_qvlfcsa: 13061 case Intrinsic::ppc_qpx_qvlfiwaa: 13062 case Intrinsic::ppc_qpx_qvlfiwza: { 13063 EVT VT; 13064 switch (Intrinsic) { 13065 case Intrinsic::ppc_qpx_qvlfda: 13066 VT = MVT::v4f64; 13067 break; 13068 case Intrinsic::ppc_qpx_qvlfsa: 13069 VT = MVT::v4f32; 13070 break; 13071 case Intrinsic::ppc_qpx_qvlfcda: 13072 VT = MVT::v2f64; 13073 break; 13074 case Intrinsic::ppc_qpx_qvlfcsa: 13075 VT = MVT::v2f32; 13076 break; 13077 default: 13078 VT = MVT::v4i32; 13079 break; 13080 } 13081 13082 Info.opc = ISD::INTRINSIC_W_CHAIN; 13083 Info.memVT = VT; 13084 Info.ptrVal = I.getArgOperand(0); 13085 Info.offset = 0; 13086 Info.size = VT.getStoreSize(); 13087 Info.align = 1; 13088 Info.vol = false; 13089 Info.readMem = true; 13090 Info.writeMem = false; 13091 return true; 13092 } 13093 case Intrinsic::ppc_qpx_qvstfd: 13094 case Intrinsic::ppc_qpx_qvstfs: 13095 case Intrinsic::ppc_qpx_qvstfcd: 13096 case Intrinsic::ppc_qpx_qvstfcs: 13097 case Intrinsic::ppc_qpx_qvstfiw: 13098 case Intrinsic::ppc_altivec_stvx: 13099 case Intrinsic::ppc_altivec_stvxl: 13100 case Intrinsic::ppc_altivec_stvebx: 13101 case Intrinsic::ppc_altivec_stvehx: 13102 case Intrinsic::ppc_altivec_stvewx: 13103 case Intrinsic::ppc_vsx_stxvd2x: 13104 case Intrinsic::ppc_vsx_stxvw4x: { 13105 EVT VT; 13106 switch (Intrinsic) { 13107 case Intrinsic::ppc_altivec_stvebx: 13108 VT = MVT::i8; 13109 break; 13110 case Intrinsic::ppc_altivec_stvehx: 13111 VT = MVT::i16; 13112 break; 13113 case Intrinsic::ppc_altivec_stvewx: 13114 VT = MVT::i32; 13115 break; 13116 case Intrinsic::ppc_vsx_stxvd2x: 13117 VT = MVT::v2f64; 13118 break; 13119 case Intrinsic::ppc_qpx_qvstfd: 13120 VT = MVT::v4f64; 13121 break; 13122 case Intrinsic::ppc_qpx_qvstfs: 13123 VT = MVT::v4f32; 13124 break; 13125 case Intrinsic::ppc_qpx_qvstfcd: 13126 VT = MVT::v2f64; 13127 break; 13128 case Intrinsic::ppc_qpx_qvstfcs: 13129 VT = MVT::v2f32; 13130 break; 13131 default: 13132 VT = MVT::v4i32; 13133 break; 13134 } 13135 13136 Info.opc = ISD::INTRINSIC_VOID; 13137 Info.memVT = VT; 13138 Info.ptrVal = I.getArgOperand(1); 13139 Info.offset = -VT.getStoreSize()+1; 13140 Info.size = 2*VT.getStoreSize()-1; 13141 Info.align = 1; 13142 Info.vol = false; 13143 Info.readMem = false; 13144 Info.writeMem = true; 13145 return true; 13146 } 13147 case Intrinsic::ppc_qpx_qvstfda: 13148 case Intrinsic::ppc_qpx_qvstfsa: 13149 case Intrinsic::ppc_qpx_qvstfcda: 13150 case Intrinsic::ppc_qpx_qvstfcsa: 13151 case Intrinsic::ppc_qpx_qvstfiwa: { 13152 EVT VT; 13153 switch (Intrinsic) { 13154 case Intrinsic::ppc_qpx_qvstfda: 13155 VT = MVT::v4f64; 13156 break; 13157 case Intrinsic::ppc_qpx_qvstfsa: 13158 VT = MVT::v4f32; 13159 break; 13160 case Intrinsic::ppc_qpx_qvstfcda: 13161 VT = MVT::v2f64; 13162 break; 13163 case Intrinsic::ppc_qpx_qvstfcsa: 13164 VT = MVT::v2f32; 13165 break; 13166 default: 13167 VT = MVT::v4i32; 13168 break; 13169 } 13170 13171 Info.opc = ISD::INTRINSIC_VOID; 13172 Info.memVT = VT; 13173 Info.ptrVal = I.getArgOperand(1); 13174 Info.offset = 0; 13175 Info.size = VT.getStoreSize(); 13176 Info.align = 1; 13177 Info.vol = false; 13178 Info.readMem = false; 13179 Info.writeMem = true; 13180 return true; 13181 } 13182 default: 13183 break; 13184 } 13185 13186 return false; 13187 } 13188 13189 /// getOptimalMemOpType - Returns the target specific optimal type for load 13190 /// and store operations as a result of memset, memcpy, and memmove 13191 /// lowering. If DstAlign is zero that means it's safe to destination 13192 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13193 /// means there isn't a need to check it against alignment requirement, 13194 /// probably because the source does not need to be loaded. If 'IsMemset' is 13195 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13196 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13197 /// source is constant so it does not need to be loaded. 13198 /// It returns EVT::Other if the type should be determined using generic 13199 /// target-independent logic. 13200 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13201 unsigned DstAlign, unsigned SrcAlign, 13202 bool IsMemset, bool ZeroMemset, 13203 bool MemcpyStrSrc, 13204 MachineFunction &MF) const { 13205 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 13206 const Function *F = MF.getFunction(); 13207 // When expanding a memset, require at least two QPX instructions to cover 13208 // the cost of loading the value to be stored from the constant pool. 13209 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 13210 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 13211 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 13212 return MVT::v4f64; 13213 } 13214 13215 // We should use Altivec/VSX loads and stores when available. For unaligned 13216 // addresses, unaligned VSX loads are only fast starting with the P8. 13217 if (Subtarget.hasAltivec() && Size >= 16 && 13218 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 13219 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 13220 return MVT::v4i32; 13221 } 13222 13223 if (Subtarget.isPPC64()) { 13224 return MVT::i64; 13225 } 13226 13227 return MVT::i32; 13228 } 13229 13230 /// \brief Returns true if it is beneficial to convert a load of a constant 13231 /// to just the constant itself. 13232 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13233 Type *Ty) const { 13234 assert(Ty->isIntegerTy()); 13235 13236 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 13237 return !(BitSize == 0 || BitSize > 64); 13238 } 13239 13240 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13241 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13242 return false; 13243 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13244 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13245 return NumBits1 == 64 && NumBits2 == 32; 13246 } 13247 13248 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13249 if (!VT1.isInteger() || !VT2.isInteger()) 13250 return false; 13251 unsigned NumBits1 = VT1.getSizeInBits(); 13252 unsigned NumBits2 = VT2.getSizeInBits(); 13253 return NumBits1 == 64 && NumBits2 == 32; 13254 } 13255 13256 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13257 // Generally speaking, zexts are not free, but they are free when they can be 13258 // folded with other operations. 13259 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 13260 EVT MemVT = LD->getMemoryVT(); 13261 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 13262 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 13263 (LD->getExtensionType() == ISD::NON_EXTLOAD || 13264 LD->getExtensionType() == ISD::ZEXTLOAD)) 13265 return true; 13266 } 13267 13268 // FIXME: Add other cases... 13269 // - 32-bit shifts with a zext to i64 13270 // - zext after ctlz, bswap, etc. 13271 // - zext after and by a constant mask 13272 13273 return TargetLowering::isZExtFree(Val, VT2); 13274 } 13275 13276 bool PPCTargetLowering::isFPExtFree(EVT VT) const { 13277 assert(VT.isFloatingPoint()); 13278 return true; 13279 } 13280 13281 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13282 return isInt<16>(Imm) || isUInt<16>(Imm); 13283 } 13284 13285 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13286 return isInt<16>(Imm) || isUInt<16>(Imm); 13287 } 13288 13289 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13290 unsigned, 13291 unsigned, 13292 bool *Fast) const { 13293 if (DisablePPCUnaligned) 13294 return false; 13295 13296 // PowerPC supports unaligned memory access for simple non-vector types. 13297 // Although accessing unaligned addresses is not as efficient as accessing 13298 // aligned addresses, it is generally more efficient than manual expansion, 13299 // and generally only traps for software emulation when crossing page 13300 // boundaries. 13301 13302 if (!VT.isSimple()) 13303 return false; 13304 13305 if (VT.getSimpleVT().isVector()) { 13306 if (Subtarget.hasVSX()) { 13307 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 13308 VT != MVT::v4f32 && VT != MVT::v4i32) 13309 return false; 13310 } else { 13311 return false; 13312 } 13313 } 13314 13315 if (VT == MVT::ppcf128) 13316 return false; 13317 13318 if (Fast) 13319 *Fast = true; 13320 13321 return true; 13322 } 13323 13324 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 13325 VT = VT.getScalarType(); 13326 13327 if (!VT.isSimple()) 13328 return false; 13329 13330 switch (VT.getSimpleVT().SimpleTy) { 13331 case MVT::f32: 13332 case MVT::f64: 13333 return true; 13334 default: 13335 break; 13336 } 13337 13338 return false; 13339 } 13340 13341 const MCPhysReg * 13342 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 13343 // LR is a callee-save register, but we must treat it as clobbered by any call 13344 // site. Hence we include LR in the scratch registers, which are in turn added 13345 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 13346 // to CTR, which is used by any indirect call. 13347 static const MCPhysReg ScratchRegs[] = { 13348 PPC::X12, PPC::LR8, PPC::CTR8, 0 13349 }; 13350 13351 return ScratchRegs; 13352 } 13353 13354 unsigned PPCTargetLowering::getExceptionPointerRegister( 13355 const Constant *PersonalityFn) const { 13356 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 13357 } 13358 13359 unsigned PPCTargetLowering::getExceptionSelectorRegister( 13360 const Constant *PersonalityFn) const { 13361 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 13362 } 13363 13364 bool 13365 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 13366 EVT VT , unsigned DefinedValues) const { 13367 if (VT == MVT::v2i64) 13368 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 13369 13370 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 13371 return true; 13372 13373 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 13374 } 13375 13376 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 13377 if (DisableILPPref || Subtarget.enableMachineScheduler()) 13378 return TargetLowering::getSchedulingPreference(N); 13379 13380 return Sched::ILP; 13381 } 13382 13383 // Create a fast isel object. 13384 FastISel * 13385 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 13386 const TargetLibraryInfo *LibInfo) const { 13387 return PPC::createFastISel(FuncInfo, LibInfo); 13388 } 13389 13390 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13391 if (Subtarget.isDarwinABI()) return; 13392 if (!Subtarget.isPPC64()) return; 13393 13394 // Update IsSplitCSR in PPCFunctionInfo 13395 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 13396 PFI->setIsSplitCSR(true); 13397 } 13398 13399 void PPCTargetLowering::insertCopiesSplitCSR( 13400 MachineBasicBlock *Entry, 13401 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13402 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 13403 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13404 if (!IStart) 13405 return; 13406 13407 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 13408 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13409 MachineBasicBlock::iterator MBBI = Entry->begin(); 13410 for (const MCPhysReg *I = IStart; *I; ++I) { 13411 const TargetRegisterClass *RC = nullptr; 13412 if (PPC::G8RCRegClass.contains(*I)) 13413 RC = &PPC::G8RCRegClass; 13414 else if (PPC::F8RCRegClass.contains(*I)) 13415 RC = &PPC::F8RCRegClass; 13416 else if (PPC::CRRCRegClass.contains(*I)) 13417 RC = &PPC::CRRCRegClass; 13418 else if (PPC::VRRCRegClass.contains(*I)) 13419 RC = &PPC::VRRCRegClass; 13420 else 13421 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13422 13423 unsigned NewVR = MRI->createVirtualRegister(RC); 13424 // Create copy from CSR to a virtual register. 13425 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13426 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13427 // nounwind. If we want to generalize this later, we may need to emit 13428 // CFI pseudo-instructions. 13429 assert(Entry->getParent()->getFunction()->hasFnAttribute( 13430 Attribute::NoUnwind) && 13431 "Function should be nounwind in insertCopiesSplitCSR!"); 13432 Entry->addLiveIn(*I); 13433 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13434 .addReg(*I); 13435 13436 // Insert the copy-back instructions right before the terminator 13437 for (auto *Exit : Exits) 13438 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13439 TII->get(TargetOpcode::COPY), *I) 13440 .addReg(NewVR); 13441 } 13442 } 13443 13444 // Override to enable LOAD_STACK_GUARD lowering on Linux. 13445 bool PPCTargetLowering::useLoadStackGuardNode() const { 13446 if (!Subtarget.isTargetLinux()) 13447 return TargetLowering::useLoadStackGuardNode(); 13448 return true; 13449 } 13450 13451 // Override to disable global variable loading on Linux. 13452 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 13453 if (!Subtarget.isTargetLinux()) 13454 return TargetLowering::insertSSPDeclarations(M); 13455 } 13456 13457 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13458 if (!VT.isSimple() || !Subtarget.hasVSX()) 13459 return false; 13460 13461 switch(VT.getSimpleVT().SimpleTy) { 13462 default: 13463 // For FP types that are currently not supported by PPC backend, return 13464 // false. Examples: f16, f80. 13465 return false; 13466 case MVT::f32: 13467 case MVT::f64: 13468 case MVT::ppcf128: 13469 return Imm.isPosZero(); 13470 } 13471 } 13472 13473 // For vector shift operation op, fold 13474 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 13475 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 13476 SelectionDAG &DAG) { 13477 SDValue N0 = N->getOperand(0); 13478 SDValue N1 = N->getOperand(1); 13479 EVT VT = N0.getValueType(); 13480 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 13481 unsigned Opcode = N->getOpcode(); 13482 unsigned TargetOpcode; 13483 13484 switch (Opcode) { 13485 default: 13486 llvm_unreachable("Unexpected shift operation"); 13487 case ISD::SHL: 13488 TargetOpcode = PPCISD::SHL; 13489 break; 13490 case ISD::SRL: 13491 TargetOpcode = PPCISD::SRL; 13492 break; 13493 case ISD::SRA: 13494 TargetOpcode = PPCISD::SRA; 13495 break; 13496 } 13497 13498 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 13499 N1->getOpcode() == ISD::AND) 13500 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 13501 if (Mask->getZExtValue() == OpSizeInBits - 1) 13502 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 13503 13504 return SDValue(); 13505 } 13506 13507 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 13508 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13509 return Value; 13510 13511 return SDValue(); 13512 } 13513 13514 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 13515 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13516 return Value; 13517 13518 return SDValue(); 13519 } 13520 13521 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 13522 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13523 return Value; 13524 13525 return SDValue(); 13526 } 13527